goctl modelgo-zero下的工具模块中的组件之一,目前支持识别mysql ddl进行model层代码生成,通过命令行或者idea插件(即将支持)可以有选择地生成带redis cache或者不带redis cache的代码逻辑。

快速开始

  • 通过ddl生成

    1. $ goctl model mysql ddl -src="./*.sql" -dir="./sql/model" -c

    执行上述命令后即可快速生成CURD代码。

    1. model
    2. ├── error.go
    3. └── usermodel.go
  • 通过datasource生成

    1. $ goctl model mysql datasource -url="user:password@tcp(127.0.0.1:3306)/database" -table="*" -dir="./model"
  • 生成代码示例

D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\model\usermodel.go

  1. package model
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/tal-tech/go-zero/core/stores/cache"
  8. "github.com/tal-tech/go-zero/core/stores/sqlc"
  9. "github.com/tal-tech/go-zero/core/stores/sqlx"
  10. "github.com/tal-tech/go-zero/core/stringx"
  11. "github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
  12. )
  13. var (
  14. userFieldNames = builderx.RawFieldNames(&User{})
  15. userRows = strings.Join(userFieldNames, ",")
  16. userRowsExpectAutoSet = strings.Join(stringx.Remove(userFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
  17. userRowsWithPlaceHolder = strings.Join(stringx.Remove(userFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
  18. cacheUserNamePrefix = "cache#User#name#"
  19. cacheUserMobilePrefix = "cache#User#mobile#"
  20. cacheUserIdPrefix = "cache#User#id#"
  21. cacheUserPrefix = "cache#User#user#"
  22. )
  23. type (
  24. UserModel interface {
  25. Insert(data User) (sql.Result, error)
  26. FindOne(id int64) (*User, error)
  27. FindOneByUser(user string) (*User, error)
  28. FindOneByName(name string) (*User, error)
  29. FindOneByMobile(mobile string) (*User, error)
  30. Update(data User) error
  31. Delete(id int64) error
  32. }
  33. defaultUserModel struct {
  34. sqlc.CachedConn
  35. table string
  36. }
  37. User struct {
  38. Id int64 `db:"id"`
  39. User string `db:"user"` // 用户
  40. Name string `db:"name"` // 用户名称
  41. Password string `db:"password"` // 用户密码
  42. Mobile string `db:"mobile"` // 手机号
  43. Gender string `db:"gender"` // 男|女|未公开
  44. Nickname string `db:"nickname"` // 用户昵称
  45. CreateTime time.Time `db:"create_time"`
  46. UpdateTime time.Time `db:"update_time"`
  47. }
  48. )
  49. func NewUserModel(conn sqlx.SqlConn, c cache.CacheConf) UserModel {
  50. return &defaultUserModel{
  51. CachedConn: sqlc.NewConn(conn, c),
  52. table: "`user`",
  53. }
  54. }
  55. func (m *defaultUserModel) Insert(data User) (sql.Result, error) {
  56. userNameKey := fmt.Sprintf("%s%v", cacheUserNamePrefix, data.Name)
  57. userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, data.Mobile)
  58. userKey := fmt.Sprintf("%s%v", cacheUserPrefix, data.User)
  59. ret, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
  60. query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, userRowsExpectAutoSet)
  61. return conn.Exec(query, data.User, data.Name, data.Password, data.Mobile, data.Gender, data.Nickname)
  62. }, userNameKey, userMobileKey, userKey)
  63. return ret, err
  64. }
  65. func (m *defaultUserModel) FindOne(id int64) (*User, error) {
  66. userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id)
  67. var resp User
  68. err := m.QueryRow(&resp, userIdKey, func(conn sqlx.SqlConn, v interface{}) error {
  69. query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRows, m.table)
  70. return conn.QueryRow(v, query, id)
  71. })
  72. switch err {
  73. case nil:
  74. return &resp, nil
  75. case sqlc.ErrNotFound:
  76. return nil, ErrNotFound
  77. default:
  78. return nil, err
  79. }
  80. }
  81. func (m *defaultUserModel) FindOneByUser(user string) (*User, error) {
  82. userKey := fmt.Sprintf("%s%v", cacheUserPrefix, user)
  83. var resp User
  84. err := m.QueryRowIndex(&resp, userKey, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
  85. query := fmt.Sprintf("select %s from %s where `user` = ? limit 1", userRows, m.table)
  86. if err := conn.QueryRow(&resp, query, user); err != nil {
  87. return nil, err
  88. }
  89. return resp.Id, nil
  90. }, m.queryPrimary)
  91. switch err {
  92. case nil:
  93. return &resp, nil
  94. case sqlc.ErrNotFound:
  95. return nil, ErrNotFound
  96. default:
  97. return nil, err
  98. }
  99. }
  100. func (m *defaultUserModel) FindOneByName(name string) (*User, error) {
  101. userNameKey := fmt.Sprintf("%s%v", cacheUserNamePrefix, name)
  102. var resp User
  103. err := m.QueryRowIndex(&resp, userNameKey, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
  104. query := fmt.Sprintf("select %s from %s where `name` = ? limit 1", userRows, m.table)
  105. if err := conn.QueryRow(&resp, query, name); err != nil {
  106. return nil, err
  107. }
  108. return resp.Id, nil
  109. }, m.queryPrimary)
  110. switch err {
  111. case nil:
  112. return &resp, nil
  113. case sqlc.ErrNotFound:
  114. return nil, ErrNotFound
  115. default:
  116. return nil, err
  117. }
  118. }
  119. func (m *defaultUserModel) FindOneByMobile(mobile string) (*User, error) {
  120. userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, mobile)
  121. var resp User
  122. err := m.QueryRowIndex(&resp, userMobileKey, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
  123. query := fmt.Sprintf("select %s from %s where `mobile` = ? limit 1", userRows, m.table)
  124. if err := conn.QueryRow(&resp, query, mobile); err != nil {
  125. return nil, err
  126. }
  127. return resp.Id, nil
  128. }, m.queryPrimary)
  129. switch err {
  130. case nil:
  131. return &resp, nil
  132. case sqlc.ErrNotFound:
  133. return nil, ErrNotFound
  134. default:
  135. return nil, err
  136. }
  137. }
  138. func (m *defaultUserModel) Update(data User) error {
  139. userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, data.Id)
  140. _, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
  141. query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRowsWithPlaceHolder)
  142. return conn.Exec(query, data.User, data.Name, data.Password, data.Mobile, data.Gender, data.Nickname, data.Id)
  143. }, userIdKey)
  144. return err
  145. }
  146. func (m *defaultUserModel) Delete(id int64) error {
  147. data, err := m.FindOne(id)
  148. if err != nil {
  149. return err
  150. }
  151. userNameKey := fmt.Sprintf("%s%v", cacheUserNamePrefix, data.Name)
  152. userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, data.Mobile)
  153. userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id)
  154. userKey := fmt.Sprintf("%s%v", cacheUserPrefix, data.User)
  155. _, err = m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
  156. query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
  157. return conn.Exec(query, id)
  158. }, userNameKey, userMobileKey, userIdKey, userKey)
  159. return err
  160. }
  161. func (m *defaultUserModel) formatPrimary(primary interface{}) string {
  162. return fmt.Sprintf("%s%v", cacheUserIdPrefix, primary)
  163. }
  164. func (m *defaultUserModel) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
  165. query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRows, m.table)
  166. return conn.QueryRow(v, query, primary)
  167. }

用法

  1. $ goctl model mysql -h
  1. PS D:\Projects\Github\NoobWu\go-zero-demo\book\service\user\model> goctl model mysql -h
  2. NAME:
  3. goctl.exe model mysql - generate mysql model
  4. USAGE:
  5. goctl.exe model mysql command [command options] [arguments...]
  6. COMMANDS:
  7. ddl generate mysql model from ddl
  8. datasource generate model from datasource
  9. OPTIONS:
  10. --help, -h show help

生成规则

  • 默认规则我们默认用户在建表时会创建createTimeupdateTime字段(忽略大小写、下划线命名风格)且默认值均为CURRENT_TIMESTAMP,而updateTime支持ON UPDATE CURRENT_TIMESTAMP,对于这两个字段生成insertupdate时会被移除,不在赋值范畴内,当然,如果你不需要这两个字段那也无大碍。

  • 带缓存模式

    • ddl
      1. $ goctl model mysql -src={patterns} -dir={dir} -cache
      help ```bash NAME: goctl model mysql ddl - generate mysql model from ddl

USAGE: goctl model mysql ddl [command options] [arguments…]

OPTIONS: —src value, -s value the path or path globbing patterns of the ddl —dir value, -d value the target dir —style value the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md] —cache, -c generate code with cache [optional] —idea for idea plugin [optional]

  1. - datasource
  2. ```bash
  3. $ goctl model mysql datasource -url={datasource} -table={patterns} -dir={dir} -cache=true

help

  1. NAME:
  2. goctl model mysql datasource - generate model from datasource
  3. USAGE:
  4. goctl model mysql datasource [command options] [arguments...]
  5. OPTIONS:
  6. --url value the data source of database,like "root:password@tcp(127.0.0.1:3306)/database
  7. --table value, -t value the table or table globbing patterns in the database
  8. --cache, -c generate code with cache [optional]
  9. --dir value, -d value the target dir
  10. --style value the file naming format, see [https://github.com/tal-tech/go-zero/tree/master/tools/goctl/config/readme.md]
  11. --idea for idea plugin [optional]

Tip goctl model mysql ddl/datasource 均新增了一个—style参数,用于标记文件命名风格。

目前仅支持redis缓存,如果选择带缓存模式,即生成的FindOne(ByXxx)&Delete代码会生成带缓存逻辑的代码,目前仅支持单索引字段(除全文索引外),对于联合索引我们默认认为不需要带缓存,且不属于通用型代码,因此没有放在代码生成行列,如exampleuser表中的idnamemobile字段均属于单字段索引。


  • 不带缓存模式

    • ddl

      1. $ goctl model -src={patterns} -dir={dir}
    • datasource

      1. $ goctl model mysql datasource -url={datasource} -table={patterns} -dir={dir}

      or

    • ddl

      1. $ goctl model -src={patterns} -dir={dir}
    • datasource

      1. $ goctl model mysql datasource -url={datasource} -table={patterns} -dir={dir}

      生成代码仅基本的CURD结构。

缓存

对于缓存这一块我选择用一问一答的形式进行罗列。我想这样能够更清晰的描述model中缓存的功能。

  • 缓存会缓存哪些信息?对于主键字段缓存,会缓存整个结构体信息,而对于单索引字段(除全文索引)则缓存主键字段值。

  • 数据有更新(update)操作会清空缓存吗?会,但仅清空主键缓存的信息,why?这里就不做详细赘述了。

  • 为什么不按照单索引字段生成updateByXxxdeleteByXxx的代码?理论上是没任何问题,但是我们认为,对于model层的数据操作均是以整个结构体为单位,包括查询,我不建议只查询某部分字段(不反对),否则我们的缓存就没有意义了。

  • 为什么不支持findPageLimitfindAll这么模式代码生层?目前,我认为除了基本的CURD外,其他的代码均属于业务型代码,这个我觉得开发人员根据业务需要进行编写更好。


    类型转换规则

    | mysql dataType | golang dataType | golang dataType(if null&&default null) | | —- | —- | —- | | bool | int64 | sql.NullInt64 | | boolean | int64 | sql.NullInt64 | | tinyint | int64 | sql.NullInt64 | | smallint | int64 | sql.NullInt64 | | mediumint | int64 | sql.NullInt64 | | int | int64 | sql.NullInt64 | | integer | int64 | sql.NullInt64 | | bigint | int64 | sql.NullInt64 | | float | float64 | sql.NullFloat64 | | double | float64 | sql.NullFloat64 | | decimal | float64 | sql.NullFloat64 | | date | time.Time | sql.NullTime | | datetime | time.Time | sql.NullTime | | timestamp | time.Time | sql.NullTime | | time | string | sql.NullString | | year | time.Time | sql.NullInt64 | | char | string | sql.NullString | | varchar | string | sql.NullString | | binary | string | sql.NullString | | varbinary | string | sql.NullString | | tinytext | string | sql.NullString | | text | string | sql.NullString | | mediumtext | string | sql.NullString | | longtext | string | sql.NullString | | enum | string | sql.NullString | | set | string | sql.NullString | | json | string | sql.NullString |

原文链接

https://go-zero.dev/cn/goctl-model.html