|
| 1 | +{{ define "GORM_OPEN" }} |
| 2 | + {{ .GormOpen }} |
| 3 | + if err != nil { |
| 4 | + log.Fatal("open db fail: ", err) |
| 5 | + } |
| 6 | +{{ end }} |
| 7 | + |
| 8 | +{{ define "GEN_CONFIG" }} |
| 9 | + genConfig := gen.Config{ |
| 10 | + OutPath: {{ printf "%q" .OutPath }}, |
| 11 | + OutFile: {{ printf "%q" .OutFile }}, |
| 12 | + ModelPkgPath: {{ printf "%q" .ModelPkgPath }}, |
| 13 | + WithUnitTest: {{ .WithUnitTest }}, |
| 14 | + FieldNullable: {{ .FieldNullable }}, |
| 15 | + FieldSignable: {{ .FieldSignable }}, |
| 16 | + FieldWithIndexTag: {{ .FieldWithIndexTag }}, |
| 17 | + FieldWithTypeTag: {{ .FieldWithTypeTag }}, |
| 18 | + Mode: {{ .Mode }}, |
| 19 | + } |
| 20 | +{{ end }} |
| 21 | + |
| 22 | +{{ define "TABLE_STRATEGY" }} |
| 23 | + {{if or (gt (len .ExcludeTables) 0) (eq .Type "sqlite") }} |
| 24 | + genConfig.WithTableNameStrategy(func(tableName string) string { |
| 25 | + {{if eq .Type "sqlite" -}} |
| 26 | + if strings.HasPrefix(tableName, "sqlite") { |
| 27 | + return "" |
| 28 | + } |
| 29 | + {{end -}} |
| 30 | + {{if gt (len .ExcludeTables) 0 -}} |
| 31 | + switch tableName { |
| 32 | + {{range $table := .ExcludeTables -}} |
| 33 | + case "{{ $table }}": |
| 34 | + return "" |
| 35 | + {{end -}} |
| 36 | + } |
| 37 | + {{end -}} |
| 38 | + return tableName |
| 39 | + }) |
| 40 | + {{end}} |
| 41 | +{{ end }} |
| 42 | + |
| 43 | +package main |
| 44 | + |
| 45 | +import ( |
| 46 | + "fmt" |
| 47 | + "log" |
| 48 | + |
| 49 | + "gorm.io/gorm" |
| 50 | + "gorm.io/gen" |
| 51 | + {{if .UseRawSQL }} "gorm.io/rawsql" {{end}} |
| 52 | +) |
| 53 | + |
| 54 | +func main() { |
| 55 | + {{ template "GORM_OPEN" . }} |
| 56 | + {{ template "GEN_CONFIG" .Config }} |
| 57 | + {{ template "TABLE_STRATEGY" .StrategyParams }} |
| 58 | + |
| 59 | + g := gen.NewGenerator(genConfig) |
| 60 | + g.UseDB(db) |
| 61 | + models, err := genModels(g, db, []string{ {{- range $index, $element := .Tables }} |
| 62 | + {{- if $index }}, {{ end }}"{{$element}}"{{- end }} }) |
| 63 | + if err != nil { |
| 64 | + log.Fatal("gen models fail: ", err) |
| 65 | + } |
| 66 | + {{if not .OnlyModel}} |
| 67 | + g.ApplyBasic(models...) |
| 68 | + {{end}} |
| 69 | + g.Execute() |
| 70 | +} |
| 71 | + |
| 72 | +func genModels(g *gen.Generator, db *gorm.DB, tables []string) (models []interface{}, err error) { |
| 73 | + var tablesNameList []string |
| 74 | + if len(tables) == 0 { |
| 75 | + tablesNameList, err = db.Migrator().GetTables() |
| 76 | + if err != nil { |
| 77 | + return nil, fmt.Errorf("migrator get all tables fail: %w", err) |
| 78 | + } |
| 79 | + } else { |
| 80 | + tablesNameList = tables |
| 81 | + } |
| 82 | + |
| 83 | + models = make([]interface{}, len(tablesNameList)) |
| 84 | + for i, tableName := range tablesNameList { |
| 85 | + models[i] = g.GenerateModel(tableName) |
| 86 | + } |
| 87 | + return models, nil |
| 88 | +} |
0 commit comments