动态 SQL

Gen 允许从原始 SQL 生成完全类型安全的惯用 Go 代码,它在接口上使用注解,这些接口可以在代码生成期间应用于多个模型。

不仅可以共享和重用经过调整的 SQL 查询,还可以共享和重用 SQL 代码片段,让我们来看一个例子

原始 SQL

type Querier interface {
// SELECT * FROM @@table WHERE id=@id
GetByID(id int) (gen.T, error) // GetByID query data by id and return it as *struct*

// GetByRoles query data by roles and return it as *slice of pointer*
// (The below blank line is required to comment for the generated method)
//
// SELECT * FROM @@table WHERE role IN @rolesName
GetByRoles(rolesName ...string) ([]*gen.T, error)

// InsertValue insert value
//
// INSERT INTO @@table (name, age) VALUES (@name, @age)
InsertValue(name string, age int) error
}

g := gen.NewGenerator(gen.Config{
// ... some config
})

// Apply the interface to existing `User` and generated `Employee`
g.ApplyInterface(func(Querier) {}, model.User{}, g.GenerateModel("employee"))

g.Execute()

运行上述配置程序,为您的应用程序生成查询接口代码,并像下面这样使用生成的代码

import "your_project/query"

func main() {
user, err := query.User.GetByID(10)

employees, err := query.Employee.GetByRoles("admin", "manager")

err := query.User.InsertValue("modi", 18)
}

代码片段

代码片段通常与 DAO 接口 一起使用

type Querier interface {
// FindByNameAndAge query data by name and age and return it as map
//
// where("name=@name AND age=@age")
FindByNameAndAge(name string, age int) (gen.M, error)
}

g := gen.NewGenerator(gen.Config{
// ... some config
})

// Apply the interface to existing `User` and generated `Employee`
g.ApplyInterface(func(Querier) {}, model.User{}, g.GenerateModel("employee"))

g.Execute()

用法

import "your_project/query"

func main() {
userMap, err := query.User.Where(query.User.Name.Eq("modi")).FilterWithNameAndRole("modi", "admin")
}

更多控制

Gen 支持条件注解和自定义返回结果,请参阅 注解 了解更多信息

铂金赞助商

黄金赞助商

铂金赞助商

黄金赞助商