package main import ( _ "embed" "flag" "fmt" "git.diulo.com/mogfee/kit/cmd/mysql-kit/core" "git.diulo.com/mogfee/kit/core/pathx" "git.diulo.com/mogfee/kit/mysql/ddl" "os" "os/exec" "strings" ) //go:embed template.tpl var templateContent string //go:embed custom.tpl var customContent string func main() { sqlFile := flag.String("f", "/Users/mogfee/web/sendmail_server_new/test_gozero.sql", "数据库创建mysqldump文件") savePath := flag.String("s", "./model", "数据库存储路径") flag.Parse() fmt.Println("sqlfile:", *sqlFile) fmt.Println("savePath:", *savePath) if *sqlFile == "" { return } os.MkdirAll(*savePath, os.ModePerm) if err := core.VarsFile(*savePath); err != nil { panic(err) } err := ddl.Parser(*sqlFile, func(table *ddl.Table) error { //table.Imports = append(table.Imports, "git.diulo.com/mogfee/kit/errors") //modelFileName := fmt.Sprintf("%s/%s_model_gen.go", strings.TrimRight(*savePath, "/"), table.Name) modelGenFile := fmt.Sprintf("%s/%smodel_gen.go", strings.TrimRight(*savePath, "/"), filename(table.Name)) modelFile := fmt.Sprintf("%s/%smodel.go", strings.TrimRight(*savePath, "/"), filename(table.Name)) table.Imports = append(table.Imports, "gorm.io/gorm") table.Imports = append(table.Imports, "context") table.Indexes = filterIndex(table.Indexes) if err := saveFile(modelGenFile, templateContent, table, false); err != nil { return err } if err := saveFile(modelFile, customContent, table, true); err != nil { return err } return nil }) if err != nil { panic(err) } exec.Command("gofmt", "-l", "-w", *savePath+"/..").Run() } func filename(tableName string) string { return strings.ToLower(strings.Join(strings.Split(tableName, "_"), "")) } func filterIndex(index []*ddl.TableIndex) []*ddl.TableIndex { idxs := make([]*ddl.TableIndex, 0) for _, v := range index { if v.IsUnique { idxs = append(idxs, v) } } return idxs } func saveFile(fileName string, templateContent string, table *ddl.Table, isOnce bool) error { if isOnce { if pathx.Exists(fileName) { return nil } } f, err := os.Create(fileName) if err != nil { return err } defer f.Close() return core.SaveFile(f, templateContent, table) }