|
| 1 | +# Goctl Model |
| 2 | + |
| 3 | +goctl model 为go-zero下的工具模块中的组件之一,目前支持识别mysql ddl进行model层代码生成,通过命令行或者idea插件(即将支持)可以有选择地生成带redis cache或者不带redis cache的代码逻辑。 |
| 4 | + |
| 5 | +# 快速开始 |
| 6 | + |
| 7 | +* 通过ddl生成 |
| 8 | + |
| 9 | + ```shell script |
| 10 | + $ goctl model mysql ddl -src="./sql/user.sql" -dir="./sql/model" -c=true |
| 11 | + ``` |
| 12 | + |
| 13 | + 执行上述命令后即可快速生成CURD代码。 |
| 14 | + |
| 15 | + ``` |
| 16 | + model |
| 17 | + │ ├── error.go |
| 18 | + │ └── usermodel.go |
| 19 | + ``` |
| 20 | +* 通过datasource生成 |
| 21 | + |
| 22 | + ```shell script |
| 23 | + $ goctl model mysql datasource -url="user:password@tcp(127.0.0.1:3306)/database" -table="table1,table2" -dir="./model" |
| 24 | + ``` |
| 25 | + |
| 26 | + |
| 27 | +* 生成代码示例 |
| 28 | + |
| 29 | + ``` go |
| 30 | + package model |
| 31 | + |
| 32 | + import ( |
| 33 | + "database/sql" |
| 34 | + "fmt" |
| 35 | + "strings" |
| 36 | + "time" |
| 37 | + |
| 38 | + "github.com/tal-tech/go-zero/core/stores/cache" |
| 39 | + "github.com/tal-tech/go-zero/core/stores/sqlc" |
| 40 | + "github.com/tal-tech/go-zero/core/stores/sqlx" |
| 41 | + "github.com/tal-tech/go-zero/core/stringx" |
| 42 | + "github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx" |
| 43 | + ) |
| 44 | + |
| 45 | + var ( |
| 46 | + userFieldNames = builderx.FieldNames(&User{}) |
| 47 | + userRows = strings.Join(userFieldNames, ",") |
| 48 | + userRowsExpectAutoSet = strings.Join(stringx.Remove(userFieldNames, "id", "create_time", "update_time"), ",") |
| 49 | + userRowsWithPlaceHolder = strings.Join(stringx.Remove(userFieldNames, "id", "create_time", "update_time"), "=?,") + "=?" |
| 50 | + |
| 51 | + cacheUserMobilePrefix = "cache#User#mobile#" |
| 52 | + cacheUserIdPrefix = "cache#User#id#" |
| 53 | + cacheUserNamePrefix = "cache#User#name#" |
| 54 | + ) |
| 55 | + |
| 56 | + type ( |
| 57 | + UserModel struct { |
| 58 | + sqlc.CachedConn |
| 59 | + table string |
| 60 | + } |
| 61 | + |
| 62 | + User struct { |
| 63 | + Id int64 `db:"id"` |
| 64 | + Name string `db:"name"` // 用户名称 |
| 65 | + Password string `db:"password"` // 用户密码 |
| 66 | + Mobile string `db:"mobile"` // 手机号 |
| 67 | + Gender string `db:"gender"` // 男|女|未公开 |
| 68 | + Nickname string `db:"nickname"` // 用户昵称 |
| 69 | + CreateTime time.Time `db:"create_time"` |
| 70 | + UpdateTime time.Time `db:"update_time"` |
| 71 | + } |
| 72 | + ) |
| 73 | + |
| 74 | + func NewUserModel(conn sqlx.SqlConn, c cache.CacheConf, table string) *UserModel { |
| 75 | + return &UserModel{ |
| 76 | + CachedConn: sqlc.NewConn(conn, c), |
| 77 | + table: table, |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + func (m *UserModel) Insert(data User) (sql.Result, error) { |
| 82 | + query := `insert into ` + m.table + `(` + userRowsExpectAutoSet + `) value (?, ?, ?, ?, ?)` |
| 83 | + return m.ExecNoCache(query, data.Name, data.Password, data.Mobile, data.Gender, data.Nickname) |
| 84 | + } |
| 85 | + |
| 86 | + func (m *UserModel) FindOne(id int64) (*User, error) { |
| 87 | + userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id) |
| 88 | + var resp User |
| 89 | + err := m.QueryRow(&resp, userIdKey, func(conn sqlx.SqlConn, v interface{}) error { |
| 90 | + query := `select ` + userRows + ` from ` + m.table + ` where id = ? limit 1` |
| 91 | + return conn.QueryRow(v, query, id) |
| 92 | + }) |
| 93 | + switch err { |
| 94 | + case nil: |
| 95 | + return &resp, nil |
| 96 | + case sqlc.ErrNotFound: |
| 97 | + return nil, ErrNotFound |
| 98 | + default: |
| 99 | + return nil, err |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + func (m *UserModel) FindOneByName(name string) (*User, error) { |
| 104 | + userNameKey := fmt.Sprintf("%s%v", cacheUserNamePrefix, name) |
| 105 | + var resp User |
| 106 | + err := m.QueryRowIndex(&resp, userNameKey, func(primary interface{}) string { |
| 107 | + return fmt.Sprintf("%s%v", cacheUserIdPrefix, primary) |
| 108 | + }, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) { |
| 109 | + query := `select ` + userRows + ` from ` + m.table + ` where name = ? limit 1` |
| 110 | + if err := conn.QueryRow(&resp, query, name); err != nil { |
| 111 | + return nil, err |
| 112 | + } |
| 113 | + return resp.Id, nil |
| 114 | + }, func(conn sqlx.SqlConn, v, primary interface{}) error { |
| 115 | + query := `select ` + userRows + ` from ` + m.table + ` where id = ? limit 1` |
| 116 | + return conn.QueryRow(v, query, primary) |
| 117 | + }) |
| 118 | + switch err { |
| 119 | + case nil: |
| 120 | + return &resp, nil |
| 121 | + case sqlc.ErrNotFound: |
| 122 | + return nil, ErrNotFound |
| 123 | + default: |
| 124 | + return nil, err |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + func (m *UserModel) FindOneByMobile(mobile string) (*User, error) { |
| 129 | + userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, mobile) |
| 130 | + var resp User |
| 131 | + err := m.QueryRowIndex(&resp, userMobileKey, func(primary interface{}) string { |
| 132 | + return fmt.Sprintf("%s%v", cacheUserIdPrefix, primary) |
| 133 | + }, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) { |
| 134 | + query := `select ` + userRows + ` from ` + m.table + ` where mobile = ? limit 1` |
| 135 | + if err := conn.QueryRow(&resp, query, mobile); err != nil { |
| 136 | + return nil, err |
| 137 | + } |
| 138 | + return resp.Id, nil |
| 139 | + }, func(conn sqlx.SqlConn, v, primary interface{}) error { |
| 140 | + query := `select ` + userRows + ` from ` + m.table + ` where id = ? limit 1` |
| 141 | + return conn.QueryRow(v, query, primary) |
| 142 | + }) |
| 143 | + switch err { |
| 144 | + case nil: |
| 145 | + return &resp, nil |
| 146 | + case sqlc.ErrNotFound: |
| 147 | + return nil, ErrNotFound |
| 148 | + default: |
| 149 | + return nil, err |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + func (m *UserModel) Update(data User) error { |
| 154 | + userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, data.Id) |
| 155 | + _, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) { |
| 156 | + query := `update ` + m.table + ` set ` + userRowsWithPlaceHolder + ` where id = ?` |
| 157 | + return conn.Exec(query, data.Name, data.Password, data.Mobile, data.Gender, data.Nickname, data.Id) |
| 158 | + }, userIdKey) |
| 159 | + return err |
| 160 | + } |
| 161 | + |
| 162 | + func (m *UserModel) Delete(id int64) error { |
| 163 | + data, err := m.FindOne(id) |
| 164 | + if err != nil { |
| 165 | + return err |
| 166 | + } |
| 167 | + userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id) |
| 168 | + userNameKey := fmt.Sprintf("%s%v", cacheUserNamePrefix, data.Name) |
| 169 | + userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, data.Mobile) |
| 170 | + _, err = m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) { |
| 171 | + query := `delete from ` + m.table + ` where id = ?` |
| 172 | + return conn.Exec(query, id) |
| 173 | + }, userIdKey, userNameKey, userMobileKey) |
| 174 | + return err |
| 175 | + } |
| 176 | + ``` |
| 177 | +
|
| 178 | +# 用法 |
| 179 | +
|
| 180 | +``` |
| 181 | +$ goctl model mysql -h |
| 182 | +``` |
| 183 | +
|
| 184 | +``` |
| 185 | +NAME: |
| 186 | + goctl model mysql - generate mysql model" |
| 187 | +
|
| 188 | +USAGE: |
| 189 | + goctl model mysql command [command options] [arguments...] |
| 190 | +
|
| 191 | +COMMANDS: |
| 192 | + ddl generate mysql model from ddl" |
| 193 | + datasource generate model from datasource" |
| 194 | +
|
| 195 | +OPTIONS: |
| 196 | + --help, -h show help |
| 197 | +``` |
| 198 | +
|
| 199 | +# 生成规则 |
| 200 | +
|
| 201 | +* 默认规则 |
| 202 | + |
| 203 | + 我们默认用户在建表时会创建createTime、updateTime字段(忽略大小写、下划线命名风格)且默认值均为`CURRENT_TIMESTAMP`,而updateTime支持`ON UPDATE CURRENT_TIMESTAMP`,对于这两个字段生成`insert`、`update`时会被移除,不在赋值范畴内,当然,如果你不需要这两个字段那也无大碍。 |
| 204 | +* 带缓存模式 |
| 205 | + * ddl |
| 206 | + |
| 207 | + ```shell script |
| 208 | + $ goctl model mysql -src={filename} -dir={dir} -cache=true |
| 209 | + ``` |
| 210 | + * datasource |
| 211 | + |
| 212 | + ```shell script |
| 213 | + $ goctl model mysql datasource -url={datasource} -table={tables} -dir={dir} -cache=true |
| 214 | + ``` |
| 215 | + |
| 216 | + 目前仅支持redis缓存,如果选择带缓存模式,即生成的`FindOne(ByXxx)`&`Delete`代码会生成带缓存逻辑的代码,目前仅支持单索引字段(除全文索引外),对于联合索引我们默认认为不需要带缓存,且不属于通用型代码,因此没有放在代码生成行列,如example中user表中的`id`、`name`、`mobile`字段均属于单字段索引。 |
| 217 | +
|
| 218 | +* 不带缓存模式 |
| 219 | + |
| 220 | + * ddl |
| 221 | + |
| 222 | + ```shell script |
| 223 | + $ goctl model -src={filename} -dir={dir} |
| 224 | + ``` |
| 225 | + * datasource |
| 226 | + |
| 227 | + ```shell script |
| 228 | + $ goctl model mysql datasource -url={datasource} -table={tables} -dir={dir} |
| 229 | + ``` |
| 230 | + or |
| 231 | + * ddl |
| 232 | + |
| 233 | + ```shell script |
| 234 | + $ goctl model -src={filename} -dir={dir} -cache=false |
| 235 | + ``` |
| 236 | + * datasource |
| 237 | + |
| 238 | + ```shell script |
| 239 | + $ goctl model mysql datasource -url={datasource} -table={tables} -dir={dir} -cache=false |
| 240 | + ``` |
| 241 | + |
| 242 | + 生成代码仅基本的CURD结构。 |
| 243 | +
|
| 244 | +# 缓存 |
| 245 | +
|
| 246 | + 对于缓存这一块我选择用一问一答的形式进行罗列。我想这样能够更清晰的描述model中缓存的功能。 |
| 247 | +
|
| 248 | +* 缓存会缓存哪些信息? |
| 249 | +
|
| 250 | + 对于主键字段缓存,会缓存整个结构体信息,而对于单索引字段(除全文索引)则缓存主键字段值。 |
| 251 | +
|
| 252 | +* 数据有更新(`update`)操作会清空缓存吗? |
| 253 | + |
| 254 | + 会,但仅清空主键缓存的信息,why?这里就不做详细赘述了。 |
| 255 | +
|
| 256 | +* 为什么不按照单索引字段生成`updateByXxx`和`deleteByXxx`的代码? |
| 257 | + |
| 258 | + 理论上是没任何问题,但是我们认为,对于model层的数据操作均是以整个结构体为单位,包括查询,我不建议只查询某部分字段(不反对),否则我们的缓存就没有意义了。 |
| 259 | +
|
| 260 | +* 为什么不支持`findPageLimit`、`findAll`这么模式代码生层? |
| 261 | + |
| 262 | + 目前,我认为除了基本的CURD外,其他的代码均属于<i>业务型</i>代码,这个我觉得开发人员根据业务需要进行编写更好。 |
| 263 | +
|
| 264 | +# QA |
| 265 | +
|
| 266 | +* goctl model除了命令行模式,支持插件模式吗? |
| 267 | +
|
| 268 | + 很快支持idea插件。 |
| 269 | +
|
| 270 | +
|
| 271 | + |
| 272 | +
|
| 273 | +
|
| 274 | + |
0 commit comments