gorm 教程三 gen代码生成框架

gorm gen

gorm 例子

Gen 支持所有GORM Driver从数据库生成结构, 使用示例: ```go package main

import "gorm.io/gen"

func main() { g := gen.NewGenerator(gen.Config{ // 设置输出路径 OutPath: "../query", Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // 选择生成模式 }) // 建立数据库连接 gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local")) g.UseDB(gormdb) // 选择数据库连接

// 为结构模型生成基本类型安全的 DAO API。用户的以下约定

g.ApplyBasic( // Generate struct User based on table users g.GenerateModel("users"),

// Generate struct Employee based on table users g.GenerateModelAs("users", "Employee"),

// Generate struct User based on table users and generating options g.GenerateModel("users", gen.FieldIgnore("address"), gen.FieldType("id", "int64")),

) g.ApplyBasic( // 从当前数据库的所有表生成结构 g.GenerateAllTable()..., ) // 生成代码 g.Execute() }

```

模板方法

当从数据库生成结构时,您也可以通过面的方式,给生成的model添加模板方法,例如: ```go type CommonMethod struct { ID int32 Name *string }

func (m *CommonMethod) IsEmpty() bool { if m == nil { return true } return m.ID == 0 }

func (m *CommonMethod) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name }

// 将 IsEmpty 方法添加到生成的“People”结构中 g.GenerateModel("people", gen.WithMethod(CommonMethod{}.IsEmpty))

// 将CommonMethod上定义的所有方法添加到生成的“User”结构中 g.GenerateModel("user", gen.WithMethod(CommonMethod)) ```

生成的代码如下所示: ```go type Person struct { // ... }

func (m *Person) IsEmpty() bool { if m == nil { return true } return m.ID == 0 }

// Generated User struct type User struct { // ... }

func (m *User) IsEmpty() bool { if m == nil { return true } return m.ID == 0 }

func (m *User) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name }

```

自定义表名称

当从数据库生成结构时,您也可以通过实现自己的TableName方法,例如: ```go

type CommonMethod struct { ID int32 Name *string }

// TableName func (m CommonMethod) TableName() string { return "@@table" }

// TableName table name with gorm NamingStrategy func (m CommonMethod) TableName(namer schema.Namer) string { if namer == nil { return "@@table" } return namer.TableName("@@table") }

// 生成的“user”结构的表名方法 g.GenerateModel("user", gen.WithMethod(CommonMethod{}.TableName))

// 自定义生成的所有结构的表名方法 g.WithOpts(gen.WithMethod(CommonMethod{}.TableName))

// 为生成的所有结构设置默认 DIY 表名方法 g.WithOpts(gen.WithMethod(gen.DefaultMethodTableWithNamer)) ```

Field Options

以下是可以在生成模型/生成模型期间使用的选项

FieldNew // 创建一个新字段 FieldIgnore // 忽略一个字段 FieldIgnoreReg // 正则匹配的方法忽略字段 FieldRename // 重命名结构体的字段 FieldComment // 在生成的结构中指定字段注释 FieldType // 指定字段类型 FieldTypeReg // specify field type (match with regexp) FieldGenType // 指定字段生成类型 FieldGenTypeReg // specify field gen type (match with regexp) FieldTag // 指定 gorm 和 JSON 标记 FieldJSONTag // specify json tag FieldJSONTagWithNS // 使用名称策略指定 JSON 标记 FieldGORMTag // specify gorm tag FieldNewTag // 追加一个新字段 FieldNewTagWithNS // 使用名称策略指定新标记 FieldTrimPrefix // 修剪列前缀 FieldTrimSuffix // 修剪列后缀 FieldAddPrefix // 将前缀添加到结构字段的名称 FieldAddSuffix // 将后缀添加到结构字段的名称 FieldRelate // 指定与其他表的关系 FieldRelateModel // 确定与现有模型的关系

全局生成选项

Gen 有一些全局选项可以在 gen.Config中设置: ```go

g := gen.NewGenerator(gen.Config{ // 如果希望可为空字段生成属性为指针类型,请将 FieldNullable 设置为 true FieldNullable: true, // 如果要分配在“创建”API 中具有默认值的字段,请将 FieldCoverable 设置为 true FieldCoverable: true, // 如果要生成具有无符号整数类型的字段,请将字段可签名设置为 true FieldSignable: true, // 如果要从数据库生成索引标记,请将 FieldWithIndexTag 设置为 true FieldWithIndexTag: true, // 如果要从数据库生成类型标记,请将 FieldWithTypeTag 设置为 true FieldWithTypeTag: true, // if you need unit tests for query code, set WithUnitTest true WithUnitTest: true, }) go // 设置获取数据库名称函数 WithDbNameOpts(opts ...model.SchemaNameOpt)

// 指定表名命名策略,仅在从数据库同步表时有效 WithTableNameStrategy(ns func(tableName string) (targetTableName string))

// 指定模型结构名称命名策略,仅在从数据库同步表时有效 // 如果返回空字符串,则将忽略该表 WithModelNameStrategy(ns func(tableName string) (modelName string))

// 指定文件名命名策略,仅在从数据库同步表时有效 WithFileNameStrategy(ns func(tableName string) (fileName string))

// 指定 JSON 标记命名策略 WithJSONTagNameStrategy(ns func(columnName string) (tagContent string))

// 指定数据类型映射关系,仅在从 DB 同步表时工作 WithDataTypeMap(newMap map[string]func(gorm.ColumnType) (dataType string))

// 指定导入包路径 WithImportPkgPath(paths ...string)

// 指定全局模型选项 WithOpts(opts ...ModelOpt)

```

数据类型映射

指定model属性类型和 db 字段类型之间的映射关系。 ```go

var dataMap = map[string]func(gorm.ColumnType) (dataType string){ // int mapping "int": func(columnType gorm.ColumnType) (dataType string) { if n, ok := columnType.Nullable(); ok && n { return "*int32" } return "int32" },

// bool mapping
"tinyint": func(columnType gorm.ColumnType) (dataType string) {
    ct, _ := columnType.ColumnType()
    if strings.HasPrefix(ct, "tinyint(1)") {
        return "bool"
    }
    return "byte"
},

}

g.WithDataTypeMap(dataMap)

```

Gen Tool

Gen Tool 是一个没有依赖关系的二进制文件,可以用来从数据库生成结构

Install

go go install gorm.io/gen/tools/gentool@latest

Usage

gentool -h ```cmd

Usage of gentool: -c string 配置文件路径 -db string 选择数据库种类 -dsn string 设置数据库连接地址 -fieldNullable 当字段可为空时,使用指针生成 -fieldWithIndexTag 使用 GORM 索引标签生成字段 -fieldWithTypeTag 生成带有 GORM 列类型标记的字段 -modelPkgName string 生成的模型代码的包名称 -outFile string 查询代码文件名,默认:gen.go -outPath string 指定输出目录 -tables string 输入所需的数据表或将其留空 -onlyModel 仅生成模型 -withUnitTest 为查询代码生成单元测试 -fieldSignable 检测整数字段的无符号类型,调整生成的数据类型 ```

c 配置文件名、默认值 “”、命令行选项的优先级高于配置文件。

db 指定Driver,默认值“mysql”

dsn 用于连接数据库的DSN 例子:"root:password@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=True"

fieldNullable 当字段允许空时用指针生成

fieldWithIndexTag 生成带有gorm index 标签的字段

fieldWithTypeTag 生成带有gorm type标签的字段

modelPkgName 生成模型代码包名称。

outFile Genrated 查询代码文件名称,默认值:gen.go

outPath 指定输出目录(默认 “./dao/query”)

tables 指定要生成的表名称,默认所有表。

eg : ``p --tables="orders" # generate fromorders`

--tables="orders,users" # generate from orders and users

--tables="" # generate from all tables ``` Generate some tables code.

withUnitTest 生成单元测试,默认值 false, 选项: false / true

fieldSignable Use signable datatype as field type, default value false, options: false / true

例子

gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor" gentool -c "./gen.tool" yaml version: "0.1" database: # consult[https://gorm.io/docs/connecting_to_the_database.html]" dsn : "username:password@tcp(address:port)/db?charset=utf8mb4&parseTime=true&loc=Local" # input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] db : "mysql" # enter the required data table or leave it blank.You can input : orders,users,goods tables : "user" # specify a directory for output outPath : "./dao/query" # query code file name, default: gen.go outFile : "" # generate unit test for query code withUnitTest : false # generated model code's package name modelPkgName : "" # generate with pointer when field is nullable fieldNullable : false # generate field with gorm index tag fieldWithIndexTag : false # generate field with gorm column type tag fieldWithTypeTag : false

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

过去日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值