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