From 389f12b8c5f2e9f21ab5ded6073fb4874ddc525d Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Wed, 21 Jun 2023 11:29:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0AllModels?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generator/gorm_gen_test.go | 6 +- generator/main.go | 124 ++++++++++++++++-- generator/main_test.go | 1 - model/gmodel/fs_font_logic.go | 15 +-- model/gmodel/var.go | 5 - model/gmodel/var_gen.go | 14 ++ .../internal/logic/usersavebasicinfologic.go | 3 +- .../internal/svc/servicecontext.go | 3 + 8 files changed, 143 insertions(+), 28 deletions(-) delete mode 100644 model/gmodel/var.go create mode 100644 model/gmodel/var_gen.go diff --git a/generator/gorm_gen_test.go b/generator/gorm_gen_test.go index e286504c..4aab2982 100644 --- a/generator/gorm_gen_test.go +++ b/generator/gorm_gen_test.go @@ -7,6 +7,10 @@ import ( ) func TestXMain(t *testing.T) { - + testGenDir = "../" + testGenDir + GenAllModels(testGenDir, TableNameComment{ + Name: "FsFont", + Comment: "测试", + }) // Now you can use the generated GORM model to interact with the database } diff --git a/generator/main.go b/generator/main.go index c40af7d5..1929934d 100644 --- a/generator/main.go +++ b/generator/main.go @@ -65,6 +65,106 @@ func GetColsFromTable(tname string, db *sql.DB) (result []Column, tableName, tab return ParserDDL(ddl) } +var gmodelVarStr = ` +package gmodel + +import "gorm.io/gorm" + +type AllModelsGen struct { +} + +func NewAllModels(gdb *gorm.DB) *AllModelsGen { + models := &AllModelsGen{ + } + return models +} +` + +var gmodelVarStrFormat = ` +package gmodel + +import "gorm.io/gorm" + +type AllModelsGen struct { + %s +} + +func NewAllModels(gdb *gorm.DB) *AllModelsGen { + models := &AllModelsGen{ + %s + } + return models +} +` + +type TableNameComment struct { + Name string + GoName string + Comment string +} + +func GenAllModels(filedir string, tmcs ...TableNameComment) { + fileName := filedir + "/var_gen.go" + if _, err := os.Stat(fileName); err == nil { + data, err := os.ReadFile(fileName) + if err != nil { + panic(err) + } + filestr := string(data) + filelines := strings.Split(filestr, "\n") + re := regexp.MustCompile(` +([^:]+)[^/]+ // ([^ ]+) (.?)$`) + for _, line := range filelines { + result := re.FindStringSubmatch(line) + if len(result) > 0 { + // key := result[0] + log.Println(result) + tmcs = append(tmcs, TableNameComment{ + Name: result[1], + GoName: result[0], + Comment: result[2], + }) + + } + } + + structStr := "" + newModelsStr := "" + for _, tmc := range tmcs { + fsline := fmt.Sprintf("%s %sModel // %s %s\n", tmc.GoName, tmc.GoName, tmc.Name, tmc.Comment) + structStr += fsline + nmline := fmt.Sprintf("%s: New%sModel(gdb),\n", tmc.GoName, tmc.GoName) + newModelsStr += nmline + } + + content := fmt.Sprintf(gmodelVarStrFormat, structStr, newModelsStr) + f, err := os.OpenFile(fileName, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + panic(err) + } + _, err = f.WriteString(content) + if err != nil { + panic(err) + } + + } else if os.IsExist(err) { + f, err := os.Create(fileName) + if err != nil { + panic(err) + } + _, err = f.WriteString(gmodelVarStr) + if err != nil { + panic(err) + } + } else { + panic(err) + } + + err := exec.Command("gofmt", "-w", fileName).Run() + if err != nil { + panic(err) + } +} + func main() { var mysqluri string var name string // 需要序列化的单独文件名 @@ -85,13 +185,20 @@ func main() { panic(err) } defer db.Close() - + var tmcs []TableNameComment if name == "-" { tablenames := GetAllTableNames(mysqluri) for _, testName := range tablenames { cols, tname, tcomment := GetColsFromTable(testName, db) GenFromPath(testGenDir, cols, tname, tcomment) + + tmcs = append(tmcs, TableNameComment{ + Name: tname, + GoName: toPascalCase(tname), + Comment: tcomment, + }) } + } else { if name != "" { testName = name @@ -100,8 +207,16 @@ func main() { // log.Println(testName) cols, tname, tcomment := GetColsFromTable(testName, db) GenFromPath(testGenDir, cols, tname, tcomment) + + tmcs = append(tmcs, TableNameComment{ + Name: tname, + GoName: toPascalCase(tname), + Comment: tcomment, + }) } + GenAllModels(testGenDir, tmcs...) + // tablenames := GetAllTableNames(mysqluri) // log.Println(tablenames) @@ -162,10 +277,6 @@ func GenFromPath(mdir string, cols []Column, tableName string, tableComment stri typeName = typeName[1:] } - if col.AutoIncrement { - - } - tagstr := "`gorm:" gormTag := "" @@ -178,9 +289,6 @@ func GenFromPath(mdir string, cols []Column, tableName string, tableComment stri if col.AutoIncrement { gormTag += "auto_increment;" } - // if col.DefaultValue == "" { - // log.Panic(col, "需要默认值") - // } tagstr += fmt.Sprintf("\"%s\"", gormTag) diff --git a/generator/main_test.go b/generator/main_test.go index 4c41af2c..24133354 100644 --- a/generator/main_test.go +++ b/generator/main_test.go @@ -9,6 +9,5 @@ func TestMain(t *testing.T) { testGenDir = "../" + testGenDir // os.Args = []string{"cmd", "-name=fs_guest"} - main() } diff --git a/model/gmodel/fs_font_logic.go b/model/gmodel/fs_font_logic.go index ca9e30d6..375355b1 100644 --- a/model/gmodel/fs_font_logic.go +++ b/model/gmodel/fs_font_logic.go @@ -6,16 +6,7 @@ import ( // TODO: 使用model的属性做你想做的 -func (m *FsFontModel) FindAllOrderSortByDesc(ctx context.Context) ([]*FsFont, error) { - - var fonts []*FsFont - err := m.db.Model(&FsFont{}).Order("sort desc").Find(&fonts).Error - switch err { - case nil: - return fonts, nil - case ErrRecordNotFound: - return nil, nil - default: - return nil, err - } +func (m *FsFontModel) FindAllOrderSortByDesc(ctx context.Context) (fonts []*FsFont, err error) { + err = m.db.Model(&FsFont{}).Order("sort desc").Find(&fonts).Error + return fonts, err } diff --git a/model/gmodel/var.go b/model/gmodel/var.go deleted file mode 100644 index d2e7bd33..00000000 --- a/model/gmodel/var.go +++ /dev/null @@ -1,5 +0,0 @@ -package gmodel - -import "gorm.io/gorm" - -var ErrRecordNotFound = gorm.ErrRecordNotFound diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go new file mode 100644 index 00000000..7f292624 --- /dev/null +++ b/model/gmodel/var_gen.go @@ -0,0 +1,14 @@ + +package gmodel + +import "gorm.io/gorm" + +type AllModelsGen struct { + +} + +func NewAllModels(gdb *gorm.DB) *AllModelsGen { + models := &AllModelsGen{ + } + return models +} diff --git a/server/home-user-auth/internal/logic/usersavebasicinfologic.go b/server/home-user-auth/internal/logic/usersavebasicinfologic.go index bd1ac35a..590e7923 100644 --- a/server/home-user-auth/internal/logic/usersavebasicinfologic.go +++ b/server/home-user-auth/internal/logic/usersavebasicinfologic.go @@ -10,6 +10,7 @@ import ( "fusenapi/utils/basic" "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" ) type UserSaveBasicInfoLogic struct { @@ -51,7 +52,7 @@ func (l *UserSaveBasicInfoLogic) UserSaveBasicInfo(req *types.RequestBasicInfoFo if err != nil { logx.Error(err) switch err { - case gmodel.ErrRecordNotFound: + case gorm.ErrRecordNotFound: return resp.SetStatus(basic.CodeUserIdNotFoundErr) default: return resp.SetStatusWithMessage(basic.CodeDbUpdateErr, err.Error()) diff --git a/server/home-user-auth/internal/svc/servicecontext.go b/server/home-user-auth/internal/svc/servicecontext.go index 0a127e7c..1f902c4a 100644 --- a/server/home-user-auth/internal/svc/servicecontext.go +++ b/server/home-user-auth/internal/svc/servicecontext.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "fusenapi/initalize" + "fusenapi/model/gmodel" "fusenapi/server/home-user-auth/internal/config" "net/http" @@ -14,12 +15,14 @@ import ( type ServiceContext struct { Config config.Config MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen } func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), } }