github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/internal/ddl/exec.go (about) 1 package ddl 2 3 import ( 4 "context" 5 "fmt" 6 "github.com/pkg/errors" 7 "github.com/sirupsen/logrus" 8 "github.com/unionj-cloud/go-doudou/toolkit/caller" 9 "os" 10 "path/filepath" 11 "strings" 12 "time" 13 14 // here must import mysql 15 _ "github.com/go-sql-driver/mysql" 16 "github.com/iancoleman/strcase" 17 "github.com/jmoiron/sqlx" 18 "github.com/unionj-cloud/go-doudou/cmd/internal/ddl/codegen" 19 "github.com/unionj-cloud/go-doudou/cmd/internal/ddl/config" 20 "github.com/unionj-cloud/go-doudou/cmd/internal/ddl/table" 21 ) 22 23 // Ddl is for ddl command 24 type Ddl struct { 25 Dir string 26 Reverse bool 27 Dao bool 28 Pre string 29 Df string 30 Conf config.DbConfig 31 } 32 33 // Exec executes the logic for ddl command 34 // if Reverse is true, it will generate code from database tables, 35 // otherwise it will update database tables from structs defined in domain pkg 36 func (d Ddl) Exec() { 37 var db *sqlx.DB 38 var err error 39 conf := d.Conf 40 conn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", 41 conf.User, 42 conf.Passwd, 43 conf.Host, 44 conf.Port, 45 conf.Schema, 46 conf.Charset) 47 conn += `&loc=Asia%2FShanghai&parseTime=True` 48 db, err = sqlx.Connect("mysql", conn) 49 if err != nil { 50 panic(errors.Wrap(err, caller.NewCaller().String())) 51 } 52 defer db.Close() 53 db.MapperFunc(strcase.ToSnake) 54 db = db.Unsafe() 55 56 var existTables []string 57 if err = db.Select(&existTables, "show tables"); err != nil { 58 panic(errors.Wrap(err, caller.NewCaller().String())) 59 } 60 61 var tables []table.Table 62 timeoutCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 63 defer cancel() 64 _ = os.MkdirAll(d.Dir, os.ModePerm) 65 if !d.Reverse { 66 tables = table.Struct2Table(timeoutCtx, d.Dir, d.Pre, existTables, db, d.Conf.Schema) 67 } else { 68 tables = table.Table2struct(timeoutCtx, d.Pre, d.Conf.Schema, existTables, db) 69 for _, item := range tables { 70 dfile := filepath.Join(d.Dir, strings.ToLower(item.Meta.Name)+".go") 71 if _, err = os.Stat(dfile); os.IsNotExist(err) { 72 if err = codegen.GenDomainGo(d.Dir, item.Meta); err != nil { 73 panic(errors.Wrap(err, caller.NewCaller().String())) 74 } 75 } else { 76 logrus.Warnf("file %s already exists", dfile) 77 } 78 } 79 } 80 81 if d.Dao { 82 genDao(d, tables) 83 } 84 } 85 86 func genDao(d Ddl, tables []table.Table) { 87 var err error 88 for _, t := range tables { 89 if err = codegen.GenDaoGo(d.Dir, t, d.Df); err != nil { 90 panic(errors.Wrap(err, caller.NewCaller().String())) 91 } 92 if err = codegen.GenDaoSQL(d.Dir, t, d.Df); err != nil { 93 panic(errors.Wrap(err, caller.NewCaller().String())) 94 } 95 } 96 }