添加AllModels

This commit is contained in:
eson 2023-06-21 11:29:09 +08:00
parent edeb2bb5f1
commit 389f12b8c5
8 changed files with 143 additions and 28 deletions

View File

@ -7,6 +7,10 @@ import (
) )
func TestXMain(t *testing.T) { 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 // Now you can use the generated GORM model to interact with the database
} }

View File

@ -65,6 +65,106 @@ func GetColsFromTable(tname string, db *sql.DB) (result []Column, tableName, tab
return ParserDDL(ddl) 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() { func main() {
var mysqluri string var mysqluri string
var name string // 需要序列化的单独文件名 var name string // 需要序列化的单独文件名
@ -85,13 +185,20 @@ func main() {
panic(err) panic(err)
} }
defer db.Close() defer db.Close()
var tmcs []TableNameComment
if name == "-" { if name == "-" {
tablenames := GetAllTableNames(mysqluri) tablenames := GetAllTableNames(mysqluri)
for _, testName := range tablenames { for _, testName := range tablenames {
cols, tname, tcomment := GetColsFromTable(testName, db) cols, tname, tcomment := GetColsFromTable(testName, db)
GenFromPath(testGenDir, cols, tname, tcomment) GenFromPath(testGenDir, cols, tname, tcomment)
tmcs = append(tmcs, TableNameComment{
Name: tname,
GoName: toPascalCase(tname),
Comment: tcomment,
})
} }
} else { } else {
if name != "" { if name != "" {
testName = name testName = name
@ -100,8 +207,16 @@ func main() {
// log.Println(testName) // log.Println(testName)
cols, tname, tcomment := GetColsFromTable(testName, db) cols, tname, tcomment := GetColsFromTable(testName, db)
GenFromPath(testGenDir, cols, tname, tcomment) GenFromPath(testGenDir, cols, tname, tcomment)
tmcs = append(tmcs, TableNameComment{
Name: tname,
GoName: toPascalCase(tname),
Comment: tcomment,
})
} }
GenAllModels(testGenDir, tmcs...)
// tablenames := GetAllTableNames(mysqluri) // tablenames := GetAllTableNames(mysqluri)
// log.Println(tablenames) // log.Println(tablenames)
@ -162,10 +277,6 @@ func GenFromPath(mdir string, cols []Column, tableName string, tableComment stri
typeName = typeName[1:] typeName = typeName[1:]
} }
if col.AutoIncrement {
}
tagstr := "`gorm:" tagstr := "`gorm:"
gormTag := "" gormTag := ""
@ -178,9 +289,6 @@ func GenFromPath(mdir string, cols []Column, tableName string, tableComment stri
if col.AutoIncrement { if col.AutoIncrement {
gormTag += "auto_increment;" gormTag += "auto_increment;"
} }
// if col.DefaultValue == "" {
// log.Panic(col, "需要默认值")
// }
tagstr += fmt.Sprintf("\"%s\"", gormTag) tagstr += fmt.Sprintf("\"%s\"", gormTag)

View File

@ -9,6 +9,5 @@ func TestMain(t *testing.T) {
testGenDir = "../" + testGenDir testGenDir = "../" + testGenDir
// os.Args = []string{"cmd", "-name=fs_guest"} // os.Args = []string{"cmd", "-name=fs_guest"}
main() main()
} }

View File

@ -6,16 +6,7 @@ import (
// TODO: 使用model的属性做你想做的 // TODO: 使用model的属性做你想做的
func (m *FsFontModel) FindAllOrderSortByDesc(ctx context.Context) ([]*FsFont, error) { func (m *FsFontModel) FindAllOrderSortByDesc(ctx context.Context) (fonts []*FsFont, err error) {
err = m.db.Model(&FsFont{}).Order("sort desc").Find(&fonts).Error
var fonts []*FsFont return fonts, err
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
}
} }

View File

@ -1,5 +0,0 @@
package gmodel
import "gorm.io/gorm"
var ErrRecordNotFound = gorm.ErrRecordNotFound

14
model/gmodel/var_gen.go Normal file
View File

@ -0,0 +1,14 @@
package gmodel
import "gorm.io/gorm"
type AllModelsGen struct {
}
func NewAllModels(gdb *gorm.DB) *AllModelsGen {
models := &AllModelsGen{
}
return models
}

View File

@ -10,6 +10,7 @@ import (
"fusenapi/utils/basic" "fusenapi/utils/basic"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
) )
type UserSaveBasicInfoLogic struct { type UserSaveBasicInfoLogic struct {
@ -51,7 +52,7 @@ func (l *UserSaveBasicInfoLogic) UserSaveBasicInfo(req *types.RequestBasicInfoFo
if err != nil { if err != nil {
logx.Error(err) logx.Error(err)
switch err { switch err {
case gmodel.ErrRecordNotFound: case gorm.ErrRecordNotFound:
return resp.SetStatus(basic.CodeUserIdNotFoundErr) return resp.SetStatus(basic.CodeUserIdNotFoundErr)
default: default:
return resp.SetStatusWithMessage(basic.CodeDbUpdateErr, err.Error()) return resp.SetStatusWithMessage(basic.CodeDbUpdateErr, err.Error())

View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"fusenapi/initalize" "fusenapi/initalize"
"fusenapi/model/gmodel"
"fusenapi/server/home-user-auth/internal/config" "fusenapi/server/home-user-auth/internal/config"
"net/http" "net/http"
@ -14,12 +15,14 @@ import (
type ServiceContext struct { type ServiceContext struct {
Config config.Config Config config.Config
MysqlConn *gorm.DB MysqlConn *gorm.DB
AllModels *gmodel.AllModelsGen
} }
func NewServiceContext(c config.Config) *ServiceContext { func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{ return &ServiceContext{
Config: c, Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql), MysqlConn: initalize.InitMysql(c.SourceMysql),
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
} }
} }