github.com/profzone/eden-framework@v1.0.10/pkg/sqlx/generator/sql_func_generator.go (about) 1 package generator 2 3 import ( 4 "github.com/profzone/eden-framework/internal/generator" 5 "github.com/profzone/eden-framework/pkg/codegen" 6 "github.com/profzone/eden-framework/pkg/packagex" 7 "github.com/sirupsen/logrus" 8 "go/types" 9 "os" 10 "path" 11 "path/filepath" 12 ) 13 14 func NewSqlFuncGenerator() *SqlFuncGenerator { 15 return &SqlFuncGenerator{} 16 } 17 18 type SqlFuncGenerator struct { 19 Config 20 pkg *packagex.Package 21 model *Model 22 } 23 24 func (g *SqlFuncGenerator) Load(cwd string) { 25 var err error 26 if len(cwd) == 0 { 27 cwd, err = os.Getwd() 28 if err != nil { 29 logrus.Panicf("get current working directory err: %v, cwd: %s", err, cwd) 30 } 31 } 32 _, err = os.Stat(cwd) 33 if err != nil { 34 if !os.IsExist(err) { 35 logrus.Panicf("entry path does not exist: %s", cwd) 36 } 37 } 38 pkg, err := packagex.Load(cwd) 39 if err != nil { 40 logrus.Panic(err) 41 } 42 43 g.pkg = pkg 44 45 } 46 47 func (g *SqlFuncGenerator) Pick() { 48 for ident, obj := range g.pkg.TypesInfo.Defs { 49 if typeName, ok := obj.(*types.TypeName); ok { 50 if typeName.Name() == g.StructName { 51 if _, ok := typeName.Type().Underlying().(*types.Struct); ok { 52 g.model = NewModel(g.pkg, typeName, g.pkg.CommentsOf(ident), &g.Config) 53 } 54 } 55 } 56 } 57 } 58 59 func (g *SqlFuncGenerator) Output(outputPath string) generator.Outputs { 60 if g.model == nil { 61 return nil 62 } 63 64 dir, _ := filepath.Rel(outputPath, filepath.Dir(g.pkg.GoFiles[0])) 65 filename := codegen.GeneratedFileSuffix(codegen.LowerSnakeCase(g.StructName) + ".go") 66 67 file := codegen.NewFile(g.pkg.Name, filename) 68 g.model.WriteTo(file) 69 70 return generator.Outputs{ 71 path.Join(dir, filename): string(file.Bytes()), 72 } 73 } 74 75 type Config struct { 76 StructName string 77 TableName string 78 Database string 79 80 WithComments bool 81 WithTableName bool 82 WithTableInterfaces bool 83 WithMethods bool 84 85 FieldPrimaryKey string 86 FieldKeyDeletedAt string 87 FieldKeyCreatedAt string 88 FieldKeyUpdatedAt string 89 } 90 91 func (g *Config) SetDefaults() { 92 if g.FieldKeyDeletedAt == "" { 93 g.FieldKeyDeletedAt = "DeletedAt" 94 } 95 96 if g.FieldKeyCreatedAt == "" { 97 g.FieldKeyCreatedAt = "CreatedAt" 98 } 99 100 if g.FieldKeyUpdatedAt == "" { 101 g.FieldKeyUpdatedAt = "UpdatedAt" 102 } 103 104 if g.TableName == "" { 105 g.TableName = toDefaultTableName(g.StructName) 106 } 107 }