Skip to content

Commit

Permalink
支持redis配置生成
Browse files Browse the repository at this point in the history
  • Loading branch information
cat3306 committed Dec 1, 2023
1 parent 14d24f6 commit 37907c2
Show file tree
Hide file tree
Showing 9 changed files with 233 additions and 25 deletions.
120 changes: 109 additions & 11 deletions readme.md
Original file line number Diff line number Diff line change
@@ -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"
```



2 changes: 1 addition & 1 deletion tools/goctl/api/gogen/component.tpl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package {{.pkgName}}
func Init() error {
func Init() (err error) {
{{.initCode}}
return nil
}
20 changes: 12 additions & 8 deletions tools/goctl/api/gogen/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const (
mysqlComponent = "mysql"
redisComponent = "redis"
componentPackageName = "component"
componentFile = "component.go"
)

type componentStruct struct {
Expand All @@ -39,7 +38,7 @@ var (
initComponent: {
fileName: "component.go",
templateName: "componentTemplate",
templateFile: "component.tpl",
templateFile: componentTemplateFile,
data: map[string]any{
"pkgName": componentPackageName,
},
Expand All @@ -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,
Expand All @@ -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,
},
}
Expand Down Expand Up @@ -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
}
Expand Down
8 changes: 5 additions & 3 deletions tools/goctl/api/gogen/config-type.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
4 changes: 4 additions & 0 deletions tools/goctl/api/gogen/config.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ type Config struct {
{{if .mysql}}
DbConfig DBConfig
{{end}}

{{if .redis}}
Redis RedisConfig
{{end}}
}
9 changes: 9 additions & 0 deletions tools/goctl/api/gogen/etc.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -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}}
4 changes: 2 additions & 2 deletions tools/goctl/api/gogen/gorm-mysql.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -47,4 +47,4 @@ func {{.initCode}}() error {
}
DB = myDb
return err
}
}
85 changes: 85 additions & 0 deletions tools/goctl/api/gogen/redis.tpl
Original file line number Diff line number Diff line change
@@ -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
}
6 changes: 6 additions & 0 deletions tools/goctl/api/gogen/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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.
Expand Down

0 comments on commit 37907c2

Please sign in to comment.