Skip to content

支持自定义接口生成 #1349

@WqyJh

Description

@WqyJh

Describe the feature

为接口添加 gen:skip 注释,带有该注释的方法只会生成在接口定义中,而不会生成默认的实现,需要用户自行实现。

例如定义以下接口:

type TestSkipImpl interface {
	// gen:skip
	SkipMethod(id int) (gen.T, error)

	// NoSkipMethod
	// select * from users where id=@id
	NoSkipMethod(id int) (gen.T, error)
}

在生成的接口中会包含两个接口函数

type IUserDo interface {
	// ......
	SkipMethod(id int) (result model.User, err error)
	NoSkipMethod(id int) (result model.User, err error)
}

但是只会生成一个实现函数

// NoSkipMethod
// select * from users where id=@id
func (u userDo) NoSkipMethod(id int) (result model.User, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("select * from users where id=? ")

	var executeSQL *gorm.DB
	executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert
	err = executeSQL.Error

	return
}

此时代码是无法编译的状态,用户必须添加对应的实现才能编译。生成的代码均位于 query/*.gen.go 中,而自定义的实现可以写到 query/*.go 中。调用的时候使用 query interface 直接调用即可。

这个方案可以提升编码效率,尤其是对于写代码比写 template 更简单的场景。

Motivation

当前支持以下代码生成方式:

  1. 基于一条简单的 sql
  2. 基于 template:支持 if/else, where, set, for 等流程控制

存在以下问题:

  1. template 的编写比较抽象,没有代码直观。如果不是通用逻辑,只为某一个 model 的某一个查询来编写 template,工作量比写代码更大。
  2. 如果某个查询被多次用到,需要封装一下以减少重复。当前无法直接扩展 DO 层的接口,因此只能封装在另一个地方,代码的内聚性比较低。

Related Issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions