前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >gorm 教程三 gen自动代码生成工具

gorm 教程三 gen自动代码生成工具

原创
作者头像
onenewcode
发布2024-01-31 19:39:11
6090
发布2024-01-31 19:39:11
举报
文章被收录于专栏:gowebgoweb

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 from `orders`

--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

我正在参与2024腾讯技术创作特训营第五期有奖征文,快来和我瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • gorm gen
    • gorm 例子
      • 模板方法
        • 自定义表名称
          • Field Options
            • 全局生成选项
              • 数据类型映射
                • Gen Tool
                  • Install
                  • Usage
                  • 例子
              • 我正在参与2024腾讯技术创作特训营第五期有奖征文,快来和我瓜分大奖!
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
              http://www.vxiaotou.com