forked from go-gorm/gen
/
config.go
116 lines (92 loc) · 2.49 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package model
import (
"path/filepath"
"strings"
"gorm.io/gorm"
)
// Config model configuration
type Config struct {
ModelPkg string
TablePrefix string
TableName string
ModelName string
ImportPkgPaths []string
ModelOpts []Option
NameStrategy
FieldConfig
MethodConfig
}
// NameStrategy name strategy
type NameStrategy struct {
SchemaNameOpts []SchemaNameOpt
TableNameNS func(tableName string) string
ModelNameNS func(tableName string) string
FileNameNS func(tableName string) string
}
// FieldConfig field configuration
type FieldConfig struct {
DataTypeMap map[string]func(detailType string) (dataType string)
FieldNullable bool // generate pointer when field is nullable
FieldCoverable bool // generate pointer when field has default value
FieldSignable bool // detect integer field's unsigned type, adjust generated data type
FieldWithIndexTag bool // generate with gorm index tag
FieldWithTypeTag bool // generate with gorm column type tag
FieldJSONTagNS func(columnName string) string
FieldNewTagNS func(columnName string) string
ModifyOpts []FieldOption
FilterOpts []FieldOption
CreateOpts []FieldOption
}
// MethodConfig method configuration
type MethodConfig struct {
MethodOpts []MethodOption
}
// Preprocess revise invalid field
func (cfg *Config) Preprocess() *Config {
if cfg.ModelPkg == "" {
cfg.ModelPkg = DefaultModelPkg
}
cfg.ModelPkg = filepath.Base(cfg.ModelPkg)
cfg.ModifyOpts, cfg.FilterOpts, cfg.CreateOpts, cfg.MethodOpts = sortOptions(cfg.ModelOpts)
return cfg
}
// GetNames get names
func (cfg *Config) GetNames() (tableName, structName, fileName string) {
tableName, structName = cfg.TableName, cfg.ModelName
if cfg.ModelNameNS != nil {
structName = cfg.ModelNameNS(tableName)
}
if cfg.TableNameNS != nil {
tableName = cfg.TableNameNS(tableName)
}
if !strings.HasPrefix(tableName, cfg.TablePrefix) {
tableName = cfg.TablePrefix + tableName
}
fileName = strings.ToLower(tableName)
if cfg.FileNameNS != nil {
fileName = cfg.FileNameNS(cfg.TableName)
}
return
}
// GetModelMethods get diy method from option
func (cfg *Config) GetModelMethods() (methods []interface{}) {
if cfg == nil {
return
}
for _, opt := range cfg.MethodOpts {
methods = append(methods, opt.Methods()...)
}
return
}
// GetSchemaName get schema name
func (cfg *Config) GetSchemaName(db *gorm.DB) string {
if cfg == nil {
return ""
}
for _, opt := range cfg.SchemaNameOpts {
if name := opt(db); name != "" {
return name
}
}
return ""
}