Skip to content

Commit

Permalink
gentool accept config file go-gorm#252 (go-gorm#275)
Browse files Browse the repository at this point in the history
* feat(gentool):"gentool accept config file go-gorm#252"

* fix(gen.yml):add new line

* fix(go.mod,gentool):"update yaml to v3 and cmd first"

* update("README"):"The command line is the highest priority"
  • Loading branch information
dino-ma authored Dec 6, 2021
1 parent 10b96a8 commit 1328240
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 13 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
golang.org/x/mod v0.5.1 // indirect
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b // indirect
golang.org/x/tools v0.1.7
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
gorm.io/datatypes v1.0.3
gorm.io/driver/mysql v1.2.0
gorm.io/driver/postgres v1.2.3
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,9 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/datatypes v1.0.3 h1:cbFm8OiE50PZK1Zj9+bROQQpsFipE9bPFxxxkKgj3e4=
gorm.io/datatypes v1.0.3/go.mod h1:bi/3zc2D4dyUkiB+xhrirAv95+u4CXI+OE/YK43Jntg=
gorm.io/driver/mysql v1.1.3/go.mod h1:4P/X9vSc3WTrhTLZ259cpFd6xKNYiSSdSZngkSBGIMM=
Expand Down
6 changes: 6 additions & 0 deletions tools/gentool/README.ZH_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
```
#### c
default ""
可以指定配置文件gen.yml的路径。
用配置文件来代替命令行。
命令行是最高优先级。
#### db
默认值:mysql
Expand Down
6 changes: 6 additions & 0 deletions tools/gentool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ Install GEN as a binary tool
generate unit test for query code
```
#### c
default ""
Is path for gen.yml
Replace the command line with a configuration file
The command line is the highest priority
#### db
Expand Down
22 changes: 22 additions & 0 deletions tools/gentool/gen.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
version: "0.1"
database:
# consult[https://gorm.io/docs/connecting_to_the_database.html]"
dsn : "user:pass@tcp(127.0.0.1:3306)/dbname?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 : ""
# 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
114 changes: 102 additions & 12 deletions tools/gentool/gentool.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"flag"
"fmt"
"log"
"os"
"strings"

"gopkg.in/yaml.v3"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
Expand All @@ -18,13 +20,38 @@ import (
type DBType string

const (
// Gorm Drivers mysql || postgres || sqlite || sqlserver
// DBMySQL Gorm Drivers mysql || postgres || sqlite || sqlserver
DBMySQL DBType = "mysql"
DBPostgres DBType = "postgres"
DBSQLite DBType = "sqlite"
DBSQLServer DBType = "sqlserver"
)
const (
// DefaultOutPath default path
DefaultOutPath = "./dao/query"
)

// CmdParams is command line parameters
type CmdParams struct {
DSN string `yaml:"dsn"` //consult[https://gorm.io/docs/connecting_to_the_database.html]"
DB string `yaml:"db"` //input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html]
Tables string `yaml:"tables"` //enter the required data table or leave it blank
OutPath string `yaml:"outPath"` //specify a directory for output
OutFile string `yaml:"outFile"` //query code file name, default: gen.go
WithUnitTest bool `yaml:"withUnitTest"` //generate unit test for query code
ModelPkgName string `yaml:"modelPkgName"` //generated model code's package name
FieldNullable bool `yaml:"fieldNullable"` //generate with pointer when field is nullable
FieldWithIndexTag bool `yaml:"fieldWithIndexTag"` // generate field with gorm index tag
FieldWithTypeTag bool `yaml:"fieldWithTypeTag"` //generate field with gorm column type tag
}

// YamlConfig is yaml config struct
type YamlConfig struct {
Version string `yaml:"version"` //
Database *CmdParams `yaml:"database"` //
}

// connectDB choose db type for connection to database
func connectDB(t DBType, dsn string) (*gorm.DB, error) {
if dsn == "" {
return nil, fmt.Errorf("dsn cannot be empty")
Expand All @@ -44,6 +71,7 @@ func connectDB(t DBType, dsn string) (*gorm.DB, error) {
}
}

// getModels is gorm/gen generated models
func getModels(g *gen.Generator, db *gorm.DB, tables []string) (models []interface{}, err error) {
if len(tables) == 0 {
//Execute tasks for all tables in the database
Expand All @@ -61,9 +89,26 @@ func getModels(g *gen.Generator, db *gorm.DB, tables []string) (models []interfa
return models, nil
}

func main() {
// loadConfigFile load config file from path
func loadConfigFile(path string) (*CmdParams, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var yamlConfig YamlConfig
if cmdErr := yaml.NewDecoder(file).Decode(&yamlConfig); cmdErr != nil {
return nil, cmdErr
}
return yamlConfig.Database, nil
}

// cmdParse is parser for cmd
func cmdParser() (*CmdParams, error) {
//choose is file or flag
genPath := flag.String("c", "", "is path for gen.yml")
dsn := flag.String("dsn", "", "consult[https://gorm.io/docs/connecting_to_the_database.html]")
dbType := flag.String("db", "mysql", "input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html]")
db := flag.String("db", "mysql", "input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html]")
tableList := flag.String("tables", "", "enter the required data table or leave it blank")
outPath := flag.String("outPath", "./dao/query", "specify a directory for output")
outFile := flag.String("outFile", "", "query code file name, default: gen.go")
Expand All @@ -73,25 +118,70 @@ func main() {
fieldWithIndexTag := flag.Bool("fieldWithIndexTag", false, "generate field with gorm index tag")
fieldWithTypeTag := flag.Bool("fieldWithTypeTag", false, "generate field with gorm column type tag")
flag.Parse()
var cmdParse CmdParams
if *genPath != "" {
if configFileParams, err := loadConfigFile(*genPath); err == nil && configFileParams != nil {
cmdParse = *configFileParams
}
}
//cmd first
if *dsn != "" {
cmdParse.DSN = *dsn
}
if *db != "" {
cmdParse.DB = *db
}
if *tableList != "" {
cmdParse.Tables = *tableList
}
if *outPath != DefaultOutPath {
cmdParse.OutPath = *outPath
}
if *outFile != "" {
cmdParse.OutFile = *outFile
}
if *withUnitTest {
cmdParse.WithUnitTest = *withUnitTest
}
if *modelPkgName != "" {
cmdParse.ModelPkgName = *modelPkgName
}
if *fieldNullable {
cmdParse.FieldNullable = *fieldNullable
}
if *fieldWithIndexTag {
cmdParse.FieldWithIndexTag = *fieldWithIndexTag
}
if *fieldWithTypeTag {
cmdParse.FieldWithTypeTag = *fieldWithTypeTag
}
return &cmdParse, nil
}

db, err := connectDB(DBType(*dbType), *dsn)
func main() {
//cmdParse
config, cmdErr := cmdParser()
if cmdErr != nil || config == nil {
log.Fatalln("cmdParse config is failed:", cmdErr)
}
db, err := connectDB(DBType(config.DB), config.DSN)
if err != nil {
log.Fatalln("connect db server fail:", err)
}

g := gen.NewGenerator(gen.Config{
OutPath: *outPath,
OutFile: *outFile,
ModelPkgPath: *modelPkgName,
WithUnitTest: *withUnitTest,
FieldNullable: *fieldNullable,
FieldWithIndexTag: *fieldWithIndexTag,
FieldWithTypeTag: *fieldWithTypeTag,
OutPath: config.OutPath,
OutFile: config.OutFile,
ModelPkgPath: config.ModelPkgName,
WithUnitTest: config.WithUnitTest,
FieldNullable: config.FieldNullable,
FieldWithIndexTag: config.FieldWithIndexTag,
FieldWithTypeTag: config.FieldWithTypeTag,
})

g.UseDB(db)

models, err := getModels(g, db, strings.Split(*tableList, ","))
models, err := getModels(g, db, strings.Split(config.Tables, ","))
if err != nil {
log.Fatalln("get tables info fail:", err)
}
Expand Down

0 comments on commit 1328240

Please sign in to comment.