Gen 工具

Gen 工具是一个无需依赖的单一二进制文件,可用于从数据库生成结构体。

安装

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

用法

gentool -h

Usage of gentool:
-c string
config file path
-db string
input mysql or postgres or sqlite or sqlserver. consult[https://gorm.golang.ac.cn/docs/connecting_to_the_database.html] (default "mysql")
-dsn string
consult[https://gorm.golang.ac.cn/docs/connecting_to_the_database.html]
-fieldNullable
generate with pointer when field is nullable
-fieldWithIndexTag
generate field with gorm index tag
-fieldWithTypeTag
generate field with gorm column type tag
-modelPkgName string
generated model code's package name
-outFile string
query code file name, default: gen.go
-outPath string
specify a directory for output (default "./dao/query")
-tables string
enter the required data table or leave it blank
-onlyModel
only generate models (without query file)
-withUnitTest
generate unit test for query code
-fieldSignable
detect integer field's unsigned type, adjust generated data type

c

配置文件名,默认值为空字符串,命令行选项优先级高于配置文件。

数据库

指定驱动程序方言,默认值为“mysql”,参考:https://gorm.golang.ac.cn/docs/connecting_to_the_database.html

数据源名称

用于连接数据库的数据源名称,参考:https://gorm.golang.ac.cn/docs/connecting_to_the_database.html

字段可空

当字段可空时,使用指针生成。

字段带索引标签

生成带有 gorm 索引标签的字段。

字段带类型标签

生成带有 gorm 列类型标签的字段。

模型包名

生成的模型代码的包名。

输出文件名

生成的查询代码文件名,默认值:gen.go

输出路径

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

指定要从中生成的表,默认为所有表。

例如:

--tables="orders"       # generate from `orders`

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

--tables=""             # generate from all tables

生成一些表的代码。

带单元测试

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

字段可签名

使用可签名数据类型作为字段类型,默认值为 false,选项:false / true

示例

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.golang.ac.cn/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.golang.ac.cn/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

铂金赞助商

黄金赞助商

铂金赞助商

黄金赞助商