From 37907c21725d19cdcd51fef32e376068404b8271 Mon Sep 17 00:00:00 2001 From: cat13 <1273014435@qq.com> Date: Fri, 1 Dec 2023 11:30:35 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81redis=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- readme.md | 120 +++++++++++++++++++++++--- tools/goctl/api/gogen/component.tpl | 2 +- tools/goctl/api/gogen/components.go | 20 +++-- tools/goctl/api/gogen/config-type.tpl | 8 +- tools/goctl/api/gogen/config.tpl | 4 + tools/goctl/api/gogen/etc.tpl | 9 ++ tools/goctl/api/gogen/gorm-mysql.tpl | 4 +- tools/goctl/api/gogen/redis.tpl | 85 ++++++++++++++++++ tools/goctl/api/gogen/template.go | 6 ++ 9 files changed, 233 insertions(+), 25 deletions(-) diff --git a/readme.md b/readme.md index cff38b59fec9..016889bb121d 100644 --- a/readme.md +++ b/readme.md @@ -1,23 +1,121 @@ ## change -`gozero` 的作者不打算支持`gorm` +### 支持`gorm`风格的`model`生成 -自己实现`gorm` 风格的`model` +- ddl -用法 + ```bash + goctl model mysql ddl --src /path/user.sql --dir /path/model -m gorm + ``` -```bash -goctl model mysql ddl --src /path/user.sql --dir /path/model -m gorm -``` +- datasource + + ````bash + goctl model mysql datasource --url "root:12345678@tcp(127.0.0.1:3306)/user" --dir ./model -t "*" -m gorm + ```` + + + +生成的样例 + +```go +// Code generated by goctl. DO NOT EDIT. +package model + +import ( + "gorm.io/gorm" + "time" +) + +const ( + UserProfileTName = "user.user_profile" +) + +type ( + UserProfile struct { + Id int64 `gorm:"column:id"` + Nick string `gorm:"column:nick"` + Pwd string `gorm:"column:pwd"` + Email string `gorm:"column:email"` + CreateTime time.Time `gorm:"column:create_time"` + UpdateTime time.Time `gorm:"column:update_time"` + UserId string `gorm:"column:user_id"` + VipTime time.Time `gorm:"column:vip_time"` + UserStatus int64 `gorm:"column:user_status"` // 0正常 1禁用 + RegisterFrom int64 `gorm:"column:register_from"` + } +) + +func (m *UserProfile) TableName() string { + return UserProfileTName +} +func (m *UserProfile) Create(db *gorm.DB) error { + // m.CreateTime = time.Now() + // m.UpdateTime = time.Now() + return db.Table(m.TableName()).Create(m).Error +} +func (m *UserProfile) FindByPrimary(db *gorm.DB, primary int64) error { + return IgnoreRecordNotFound(db.Table(m.TableName()).Where(" id = ?", primary).Find(m).Error) +} +func (m *UserProfile) UpdateByPrimary(db *gorm.DB, primary int64) error { + return db.Table(m.TableName()).Where("id = ?", primary).Updates(m).Error +} + +func (m *UserProfile) UpdateFieldsByPrimary(db *gorm.DB, primary int64, fields map[string]interface{}) error { + return db.Table(m.TableName()).Where("id = ?", primary).Updates(fields).Error +} +func (m *UserProfile) DeleteByPrimary(db *gorm.DB, primary int64) error { + return db.Table(m.TableName()).Where("id = ?", primary).Delete(m).Error +} + +type UserProfileList []UserProfile + +func (l *UserProfileList) FindByPrimarys(db *gorm.DB, primarys []int64) (err error) { + if len(primarys) == 0 { + return + } + err = db.Table(UserProfileTName).Where(" id in (?)", primarys).Find(l).Error + return +} + +func (l *UserProfileList) FindByPage(db *gorm.DB, page int, size int) (total int64, err error) { + if page <= 0 { + page = 1 + } + if size <= 0 { + size = 10 + } + db = db.Table(UserProfileTName) + //conditions + err = db.Count(&total).Error + if err != nil { + return + } + err = db.Offset((page - 1) * size).Limit(size).Find(&l).Error + return +} + +func (l *UserProfileList) Create(db *gorm.DB, batchSize int) error { + return db.CreateInBatches(l, batchSize).Error +} +func (m *UserProfile) FindByUserId(db *gorm.DB, key string) error { + return IgnoreRecordNotFound(db.Table(m.TableName()).Where(" user_id = ?", key).Find(m).Error) +} +func (m *UserProfile) FindByEmail(db *gorm.DB, key string) error { + return IgnoreRecordNotFound(db.Table(m.TableName()).Where(" email = ?", key).Find(m).Error) +} ``` -goctl model mysql ddl -h -Generate mysql model from ddl -........... - -m, --mode string chose gorm style -................. + + +### 支持组件的初始化,配置。 + +```bash +goctl api new demo -c "mysql,redis" ``` + + diff --git a/tools/goctl/api/gogen/component.tpl b/tools/goctl/api/gogen/component.tpl index e4b202ac1e4d..6b396c7c53e7 100644 --- a/tools/goctl/api/gogen/component.tpl +++ b/tools/goctl/api/gogen/component.tpl @@ -1,5 +1,5 @@ package {{.pkgName}} -func Init() error { +func Init() (err error) { {{.initCode}} return nil } diff --git a/tools/goctl/api/gogen/components.go b/tools/goctl/api/gogen/components.go index 644cd465a38f..877c9303bda3 100644 --- a/tools/goctl/api/gogen/components.go +++ b/tools/goctl/api/gogen/components.go @@ -14,7 +14,6 @@ const ( mysqlComponent = "mysql" redisComponent = "redis" componentPackageName = "component" - componentFile = "component.go" ) type componentStruct struct { @@ -39,7 +38,7 @@ var ( initComponent: { fileName: "component.go", templateName: "componentTemplate", - templateFile: "component.tpl", + templateFile: componentTemplateFile, data: map[string]any{ "pkgName": componentPackageName, }, @@ -49,7 +48,7 @@ var ( initFuncCode: "initMysql", fileName: "mysql.go", templateName: "mysqlTemplate", - templateFile: "gorm-mysql.tpl", + templateFile: gormMysqlTemplateFile, exportVar: "DB", data: map[string]any{ "pkgName": componentPackageName, @@ -59,10 +58,15 @@ var ( builtinTemplate: gormMysqlTemplate, }, redisComponent: { - fileName: "redis.go", - templateName: "redisTemplate", - templateFile: "redis.tpl", - data: map[string]any{}, + initFuncCode: "initRedisPool", + fileName: "redis.go", + templateName: "redisTemplate", + templateFile: redisTemplateFile, + data: map[string]any{ + "pkgName": componentPackageName, + "initCode": "initRedisPool", + "exportVar": "RedisPool", + }, builtinTemplate: redisTemplate, }, } @@ -94,7 +98,7 @@ func genComponents(dir string, rootPkg string, cfg *config.Config, api *spec.Api return code } code += fmt.Sprintf(` - err:=%s () + err =%s () if err !=nil{ return err } diff --git a/tools/goctl/api/gogen/config-type.tpl b/tools/goctl/api/gogen/config-type.tpl index a785bf8bded3..244d2385efa5 100644 --- a/tools/goctl/api/gogen/config-type.tpl +++ b/tools/goctl/api/gogen/config-type.tpl @@ -12,8 +12,10 @@ type DBConfig struct { {{end}} {{if .redis}} -type CacheConfig struct{ - Ip string - Port int +type RedisConfig struct { + Ip string + Port int + Pwd string + Db []int } {{end}} \ No newline at end of file diff --git a/tools/goctl/api/gogen/config.tpl b/tools/goctl/api/gogen/config.tpl index 4d45f2018374..f2e83e43a0a2 100644 --- a/tools/goctl/api/gogen/config.tpl +++ b/tools/goctl/api/gogen/config.tpl @@ -13,4 +13,8 @@ type Config struct { {{if .mysql}} DbConfig DBConfig {{end}} + + {{if .redis}} + Redis RedisConfig + {{end}} } diff --git a/tools/goctl/api/gogen/etc.tpl b/tools/goctl/api/gogen/etc.tpl index c1f8f823e943..77da312918ba 100644 --- a/tools/goctl/api/gogen/etc.tpl +++ b/tools/goctl/api/gogen/etc.tpl @@ -9,4 +9,13 @@ DbConfig: User: root ConnectPoolSize: 100 SetLog: true +{{end}} + +{{if .redis}} +Redis: + Ip: 127.0.0.1 + Port: 6379 + Pwd: "redis-hahah@123" + Db: + - 0 {{end}} \ No newline at end of file diff --git a/tools/goctl/api/gogen/gorm-mysql.tpl b/tools/goctl/api/gogen/gorm-mysql.tpl index bb2e463bc8cf..a952158f295f 100644 --- a/tools/goctl/api/gogen/gorm-mysql.tpl +++ b/tools/goctl/api/gogen/gorm-mysql.tpl @@ -32,7 +32,7 @@ func {{.initCode}}() error { if err != nil { return err } - if true { + if config.AppConf.DbConfig.SetLog { newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer logger.Config{ @@ -47,4 +47,4 @@ func {{.initCode}}() error { } DB = myDb return err -} \ No newline at end of file +} diff --git a/tools/goctl/api/gogen/redis.tpl b/tools/goctl/api/gogen/redis.tpl index e69de29bb2d1..007974c33c61 100644 --- a/tools/goctl/api/gogen/redis.tpl +++ b/tools/goctl/api/gogen/redis.tpl @@ -0,0 +1,85 @@ +package {{.pkgName}} + +import ( + "context" + "errors" + "fmt" + "{{.configPkg}}" + "github.com/go-redis/redis/v8" +) + +var ( + {{.exportVar}} *redisClientPool +) + +type redisClientPool struct { + clients map[int]*redis.Client +} +type clientConf struct { + Options *redis.Options + DB []int +} + +func newRedisClients(c *clientConf) (*redisClientPool, error) { + r := redisClientPool{ + clients: make(map[int]*redis.Client), + } + + for i := 0; i < len(c.DB); i++ { + client := redis.NewClient(&redis.Options{ + Network: c.Options.Network, + Addr: c.Options.Addr, + Dialer: c.Options.Dialer, + OnConnect: c.Options.OnConnect, + Username: c.Options.Username, + Password: c.Options.Password, + DB: c.DB[i], + MaxRetries: c.Options.MaxRetries, + MinRetryBackoff: c.Options.MinRetryBackoff, + MaxRetryBackoff: c.Options.MaxRetryBackoff, + DialTimeout: c.Options.DialTimeout, + ReadTimeout: c.Options.ReadTimeout, + WriteTimeout: c.Options.WriteTimeout, + PoolFIFO: c.Options.PoolFIFO, + PoolSize: c.Options.PoolSize, + MinIdleConns: c.Options.MinIdleConns, + MaxConnAge: c.Options.MaxConnAge, + PoolTimeout: c.Options.PoolTimeout, + IdleTimeout: c.Options.IdleTimeout, + IdleCheckFrequency: c.Options.IdleCheckFrequency, + TLSConfig: c.Options.TLSConfig, + Limiter: c.Options.Limiter, + }) + if client == nil { + return nil, errors.New("client nil") + } + _, err := client.Ping(context.Background()).Result() + if err != nil { + panic(err) + } + r.clients[c.DB[i]] = client + } + return &r, nil +} +func (r *redisClientPool) Select(args ...int) *redis.Client { + db := 0 + if len(args) != 0 { + db = args[0] + } + tmp := r.clients[db] + if tmp == nil { + panic("invalid db index") + } + return tmp +} + +func {{.initCode}}() (err error) { + RedisPool, err = newRedisClients(&clientConf{ + Options: &redis.Options{ + Addr: fmt.Sprintf("%s:%d", config.AppConf.Redis.Ip, config.AppConf.Redis.Port), + Password: config.AppConf.Redis.Pwd, + }, + DB: config.AppConf.Redis.Db, + }) + return +} \ No newline at end of file diff --git a/tools/goctl/api/gogen/template.go b/tools/goctl/api/gogen/template.go index 3c3a8135b6f1..b1266c9e9861 100644 --- a/tools/goctl/api/gogen/template.go +++ b/tools/goctl/api/gogen/template.go @@ -19,6 +19,9 @@ const ( routesAdditionTemplateFile = "route-addition.tpl" typesTemplateFile = "types.tpl" configTypeTemplateFile = "config-type.tpl" + componentTemplateFile = "component.tpl" + gormMysqlTemplateFile = "gorm-mysql.tpl" + redisTemplateFile = "redis.tpl" ) var templates = map[string]string{ @@ -33,6 +36,9 @@ var templates = map[string]string{ routesAdditionTemplateFile: routesAdditionTemplate, typesTemplateFile: typesTemplate, configTypeTemplateFile: configTypeTemplate, + componentTemplateFile: componentTemplate, + gormMysqlTemplateFile: gormMysqlTemplate, + redisTemplateFile: redisTemplate, } // Category returns the category of the api files.