gorm's automation tool gen
official
https://gorm.io/zh_CN/gen/
Assume the database structure is as follows
Use gen-tool here
Install
go install gorm.io/gen/tools/gentool@latest
usage
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
How to add gobin to PATH in ubuntu
Personally speaking, gentool has not been added to PATH. Here, I manually add GOPATH to PATH. I use
zsh, so add the environment variables to ~/.zshrc, refer to the following command
echo 'export PATH=$PATH:~/go/bin' | tee -a ~/.zshrc
Now gentool can be called from anywhere
Example
Write the content in the Xinjiang gentool file in the project root directory
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
Then use gentool to specify -c
As a result, the corresponding models and query are generated under the dao package.