gorm的自动化工具gen

gorm的自动化工具gen

官方

https://gorm.io/zh_CN/gen/

假设数据库结构如

gorm的自动化工具gen_第1张图片

这里使用gen-tool

安装

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

用法

gentool -h

Usage of gentool:
 -c string
       配置文件名、默认值 “”、命令行选项的优先级高于配置文件。 
 -db string
       指定Driver,默认值“mysql”,referer:https://gorm.io/docs/connecting_to_the_database.html
 -dsn string
       用于连接数据库的DSN reference: https://gorm.io/docs/connecting_to_the_database.html
 -fieldNullable
       当字段允许空时用指针生成
 -fieldWithIndexTag
       生成带有gorm index 标签的字段
 -fieldWithTypeTag
       生成带有gorm type标签的字段
 -modelPkgName string
       生成模型代码包名称。
 -outFile string
       Genrated 查询代码文件名称,默认值:gen.go
 -outPath string
       指定输出目录(默认 “./dao/query”)
 -tables string
       指定要生成的表名称,默认所有表。
 -onlyModel
       指生成Models不生成对应的query
 -withUnitTest
       生成单元测试,默认值 false, 选项: false / true
 -fieldSignable
       detect integer field's unsigned type, adjust generated data type

Example

gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor"

gentool -c "./gen.tool" # 配置文件像下面
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"
  # 选择mysql或者其他引擎,比方sqlserver
  db  : "mysql"
  # 指定要生成的table,流控则全部
  tables  : "user"
  # 指定输出目录
  outPath :  "./dao/query"
  # 输出的代码,默认gen.go
  outFile :  ""
  # 是否生成单元测试
  withUnitTest  : false
  # generated model code's package name
  # 生成的model的代码的包名
  modelPkgName  : ""
  # 使用指针当字段是空的
  fieldNullable : false
  # 生成的字段带有gorm tag
  fieldWithIndexTag : false
  # 生成的字段时候带有gorm type 标签
  fieldWithTypeTag  : false

ubuntu将gobin加入到PATH的做法

个人来说,gentool没有被加入到PATH中,这边手动把GOPATH加入到PATH中,我用的是

zsh,所以把环境变量加入到~/.zshrc中,参考下面的命令

gorm的自动化工具gen_第2张图片

echo 'export PATH=$PATH:~/go/bin' | tee -a ~/.zshrc

现在gentool可以在任意地方被调用了

gorm的自动化工具gen_第3张图片

实例

在项目根目录新疆gentool文件里面写入内容

version: "0.1"
database:
  # consult[https://gorm.io/docs/connecting_to_the_database.html]"
  dsn : "root:root@tcp(127.0.0.1:3306)/school?charset=utf8mb4&parseTime=true&loc=Local"
  # 选择mysql或者其他引擎,比方sqlserver
  db  : "mysql"
  # 指定要生成的table,流控则全部
  # 指定输出目录
  outPath :  "./dao/query"
  # 输出的代码,默认gen.go
  outFile :  ""
  # 是否生成单元测试
  withUnitTest  : false
  # generated model code's package name
  # 生成的model的代码的包名
  modelPkgName  : "models"
  # 使用指针当字段是空的
  fieldNullable : false
  # 生成的字段带有gorm tag
  fieldWithIndexTag : false
  # 生成的字段时候带有gorm type 标签
  fieldWithTypeTag  : false

然后使用gentool指定-c

结果如在dao包下生成了对应的models和query

gorm的自动化工具gen_第4张图片

你可能感兴趣的:(go,web开发,自动化,log4j,运维,go1.19)