github.com/unionj-cloud/go-doudou/v2@v2.3.5/toolkit/gormgen/internal/generate/generate.go (about) 1 package generate 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 "gorm.io/gorm" 9 "gorm.io/gorm/schema" 10 11 "github.com/unionj-cloud/go-doudou/v2/toolkit/gormgen/internal/model" 12 ) 13 14 /* 15 ** The feature of mapping table from database server to Golang struct 16 ** Provided by @qqxhb 17 */ 18 19 func getFields(db *gorm.DB, conf *model.Config, columns []*model.Column) (fields []*model.Field) { 20 for _, col := range columns { 21 col.SetDataTypeMap(conf.DataTypeMap) 22 col.WithNS(conf.FieldJSONTagNS) 23 24 m := col.ToField(conf.FieldNullable, conf.FieldCoverable, conf.FieldSignable) 25 26 if filterField(m, conf.FilterOpts) == nil { 27 continue 28 } 29 if _, ok := col.ColumnType.ColumnType(); ok && !conf.FieldWithTypeTag { // remove type tag if FieldWithTypeTag == false 30 m.GORMTag.Remove("type") 31 } 32 33 m = modifyField(m, conf.ModifyOpts) 34 if ns, ok := db.NamingStrategy.(schema.NamingStrategy); ok { 35 ns.SingularTable = true 36 m.Name = ns.SchemaName(ns.TablePrefix + m.Name) 37 } else if db.NamingStrategy != nil { 38 m.Name = db.NamingStrategy.SchemaName(m.Name) 39 } 40 41 fields = append(fields, m) 42 } 43 for _, create := range conf.CreateOpts { 44 m := create.Operator()(nil) 45 if m.Relation != nil { 46 if m.Relation.Model() != nil { 47 stmt := gorm.Statement{DB: db} 48 _ = stmt.Parse(m.Relation.Model()) 49 if stmt.Schema != nil { 50 m.Relation.AppendChildRelation(ParseStructRelationShip(&stmt.Schema.Relationships)...) 51 } 52 } 53 m.Type = strings.ReplaceAll(m.Type, conf.ModelPkg+".", "") // remove modelPkg in field's Type, avoid import error 54 } 55 56 fields = append(fields, m) 57 } 58 return fields 59 } 60 61 func filterField(m *model.Field, opts []model.FieldOption) *model.Field { 62 for _, opt := range opts { 63 if opt.Operator()(m) == nil { 64 return nil 65 } 66 } 67 return m 68 } 69 70 func modifyField(m *model.Field, opts []model.FieldOption) *model.Field { 71 for _, opt := range opts { 72 m = opt.Operator()(m) 73 } 74 return m 75 } 76 77 // get mysql db' name 78 var modelNameReg = regexp.MustCompile(`^\w+$`) 79 80 func checkStructName(name string) error { 81 if name == "" { 82 return nil 83 } 84 if !modelNameReg.MatchString(name) { 85 return fmt.Errorf("model name cannot contains invalid character") 86 } 87 if name[0] < 'A' || name[0] > 'Z' { 88 return fmt.Errorf("model name must be initial capital") 89 } 90 return nil 91 }