goctl model

Overview

The database model code generation instruction provided by goctl model for goctl is currently supported by MySQL, PostgreSQL, Mongo code generation, MySQL support from sql files and database connections and PostgreSQL support from database connections only.

goctl model directive

  1. $ goctl model --help
  2. Generate model code
  3. Usage:
  4. goctl model [command]
  5. Available Commands:
  6. mongo Generate mongo model
  7. mysql Generate mysql model
  8. pg Generate postgresql model
  9. Flags:
  10. -h, --help help for model
  11. Use "goctl model [command] --help" for more information about a command.

goctl model mono directive

Mongo is generated different than MySQL. MySQL and MySQL can read a table of information (field name, data type, index, etc.) from the scheme_information library, while Mongo is a document type database, we are temporarily unable to read a record from the db to get the field information, even if it is not necessarily complete (some fields may be omitempty modifications, if any) where type type is self-writing+ code generated.

  1. $ goctl model mongo --help
  2. Generate mongo model
  3. Usage:
  4. goctl model mongo [flags]
  5. Flags:
  6. --branch string The branch of the remote repo, it does work with --remote
  7. -c, --cache Generate code with cache [optional]
  8. -d, --dir string The target dir
  9. -e, --easy Generate code with auto generated CollectionName for easy declare [optional]
  10. -h, --help help for mongo
  11. --home string The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  12. --remote string The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  13. The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
  14. --style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
  15. -t, --type strings Specified model type name
goctl model - 图1 Parameter fieldgoctl model - 图2 Parameter Typegoctl model - 图3 Required?goctl model - 图4 Default valuegoctl model - 图5 Parameter Description
branchstringNOEmpty stringRemote template name is used only if remote has value
cachebooleanNOfalseWhether or not to generate code with cache
dirstringNOCurrent working directoryGenerate Code Output Directory
easybooleanNOfalseExposure pool name variable
homestringNO${HOME}/.goctlLocal Template File Directory
remotestringNOEmpty stringRemote template is a git repository address. Priority is higher than home field value when this field is passed
stylestringNOgozeroNamed style symbols for output files and directories, seefile style
type[]stringYESnilStructure Type Name

Examples

Below are examples of generating a user structure.

  1. Whether or not to generate code with cache
  1. # enter user home
  2. $ cd ~
  3. # make dir named demo
  4. $ mkdir demo && cd demo
  5. # generate mongo code by goctl
  6. $ goctl model mongo --type User --dir cache --cache
  7. # view layout
  8. $ tree
  9. .
  10. └── cache
  11. ├── error.go
  12. ├── usermodel.go
  13. ├── usermodelgen.go
  14. └── usertypes.go
  15. 1 directory, 4 files

View code

  • error.go
  • usermodel.go
  • usermodelgen.go
  • usertypes.go
  1. package model
  2. import (
  3. "errors"
  4. "github.com/zeromicro/go-zero/core/stores/mon"
  5. )
  6. var (
  7. ErrNotFound = mon.ErrNotFound
  8. ErrInvalidObjectId = errors.New("invalid objectId")
  9. )
  1. package model
  2. import (
  3. "github.com/zeromicro/go-zero/core/stores/cache"
  4. "github.com/zeromicro/go-zero/core/stores/monc"
  5. )
  6. var _ UserModel = (*customUserModel)(nil)
  7. type (
  8. // UserModel is an interface to be customized, add more methods here,
  9. // and implement the added methods in customUserModel.
  10. UserModel interface {
  11. userModel
  12. }
  13. customUserModel struct {
  14. *defaultUserModel
  15. }
  16. )
  17. // NewUserModel returns a model for the mongo.
  18. func NewUserModel(url, db, collection string, c cache.CacheConf) UserModel {
  19. conn := monc.MustNewModel(url, db, collection, c)
  20. return &customUserModel{
  21. defaultUserModel: newDefaultUserModel(conn),
  22. }
  23. }
  1. // Code generated by goctl. DO NOT EDIT.
  2. package model
  3. import (
  4. "context"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/stores/monc"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. )
  10. var prefixUserCacheKey = "cache:user:"
  11. type userModel interface {
  12. Insert(ctx context.Context, data *User) error
  13. FindOne(ctx context.Context, id string) (*User, error)
  14. Update(ctx context.Context, data *User) error
  15. Delete(ctx context.Context, id string) error
  16. }
  17. type defaultUserModel struct {
  18. conn *monc.Model
  19. }
  20. func newDefaultUserModel(conn *monc.Model) *defaultUserModel {
  21. return &defaultUserModel{conn: conn}
  22. }
  23. func (m *defaultUserModel) Insert(ctx context.Context, data *User) error {
  24. if data.ID.IsZero() {
  25. data.ID = primitive.NewObjectID()
  26. data.CreateAt = time.Now()
  27. data.UpdateAt = time.Now()
  28. }
  29. key := prefixUserCacheKey + data.ID.Hex()
  30. _, err := m.conn.InsertOne(ctx, key, data)
  31. return err
  32. }
  33. func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) {
  34. oid, err := primitive.ObjectIDFromHex(id)
  35. if err != nil {
  36. return nil, ErrInvalidObjectId
  37. }
  38. var data User
  39. key := prefixUserCacheKey + id
  40. err = m.conn.FindOne(ctx, key, &data, bson.M{"_id": oid})
  41. switch err {
  42. case nil:
  43. return &data, nil
  44. case monc.ErrNotFound:
  45. return nil, ErrNotFound
  46. default:
  47. return nil, err
  48. }
  49. }
  50. func (m *defaultUserModel) Update(ctx context.Context, data *User) error {
  51. data.UpdateAt = time.Now()
  52. key := prefixUserCacheKey + data.ID.Hex()
  53. _, err := m.conn.ReplaceOne(ctx, key, bson.M{"_id": data.ID}, data)
  54. return err
  55. }
  56. func (m *defaultUserModel) Delete(ctx context.Context, id string) error {
  57. oid, err := primitive.ObjectIDFromHex(id)
  58. if err != nil {
  59. return ErrInvalidObjectId
  60. }
  61. key := prefixUserCacheKey + id
  62. _, err = m.conn.DeleteOne(ctx, key, bson.M{"_id": oid})
  63. return err
  64. }
  1. package model
  2. import (
  3. "time"
  4. "go.mongodb.org/mongo-driver/bson/primitive"
  5. )
  6. type User struct {
  7. ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
  8. // TODO: Fill your own fields
  9. UpdateAt time.Time `bson:"updateAt,omitempty" json:"updateAt,omitempty"`
  10. CreateAt time.Time `bson:"createAt,omitempty" json:"createAt,omitempty"`
  11. }
  1. Generate code without cache
  1. # enter user home
  2. $ cd ~
  3. # make dir named demo
  4. $ mkdir demo && cd demo
  5. # generate mongo code by goctl
  6. $ goctl model mongo --type User --dir nocache
  7. # view layout
  8. $ tree
  9. .
  10. └── nocache
  11. ├── error.go
  12. ├── usermodel.go
  13. ├── usermodelgen.go
  14. └── usertypes.go
  15. 1 directory, 4 files

View code

  • error.go
  • usermodel.go
  • usermodelgen.go
  • usertypes.go
  1. package model
  2. import (
  3. "errors"
  4. "github.com/zeromicro/go-zero/core/stores/mon"
  5. )
  6. var (
  7. ErrNotFound = mon.ErrNotFound
  8. ErrInvalidObjectId = errors.New("invalid objectId")
  9. )
  1. package model
  2. import "github.com/zeromicro/go-zero/core/stores/mon"
  3. var _ UserModel = (*customUserModel)(nil)
  4. type (
  5. // UserModel is an interface to be customized, add more methods here,
  6. // and implement the added methods in customUserModel.
  7. UserModel interface {
  8. userModel
  9. }
  10. customUserModel struct {
  11. *defaultUserModel
  12. }
  13. )
  14. // NewUserModel returns a model for the mongo.
  15. func NewUserModel(url, db, collection string) UserModel {
  16. conn := mon.MustNewModel(url, db, collection)
  17. return &customUserModel{
  18. defaultUserModel: newDefaultUserModel(conn),
  19. }
  20. }
  1. // Code generated by goctl. DO NOT EDIT.
  2. package model
  3. import (
  4. "context"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/stores/mon"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. )
  10. type userModel interface {
  11. Insert(ctx context.Context, data *User) error
  12. FindOne(ctx context.Context, id string) (*User, error)
  13. Update(ctx context.Context, data *User) error
  14. Delete(ctx context.Context, id string) error
  15. }
  16. type defaultUserModel struct {
  17. conn *mon.Model
  18. }
  19. func newDefaultUserModel(conn *mon.Model) *defaultUserModel {
  20. return &defaultUserModel{conn: conn}
  21. }
  22. func (m *defaultUserModel) Insert(ctx context.Context, data *User) error {
  23. if data.ID.IsZero() {
  24. data.ID = primitive.NewObjectID()
  25. data.CreateAt = time.Now()
  26. data.UpdateAt = time.Now()
  27. }
  28. _, err := m.conn.InsertOne(ctx, data)
  29. return err
  30. }
  31. func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) {
  32. oid, err := primitive.ObjectIDFromHex(id)
  33. if err != nil {
  34. return nil, ErrInvalidObjectId
  35. }
  36. var data User
  37. err = m.conn.FindOne(ctx, &data, bson.M{"_id": oid})
  38. switch err {
  39. case nil:
  40. return &data, nil
  41. case mon.ErrNotFound:
  42. return nil, ErrNotFound
  43. default:
  44. return nil, err
  45. }
  46. }
  47. func (m *defaultUserModel) Update(ctx context.Context, data *User) error {
  48. data.UpdateAt = time.Now()
  49. _, err := m.conn.ReplaceOne(ctx, bson.M{"_id": data.ID}, data)
  50. return err
  51. }
  52. func (m *defaultUserModel) Delete(ctx context.Context, id string) error {
  53. oid, err := primitive.ObjectIDFromHex(id)
  54. if err != nil {
  55. return ErrInvalidObjectId
  56. }
  57. _, err = m.conn.DeleteOne(ctx, bson.M{"_id": oid})
  58. return err
  59. }
  1. package model
  2. import (
  3. "time"
  4. "go.mongodb.org/mongo-driver/bson/primitive"
  5. )
  6. type User struct {
  7. ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
  8. // TODO: Fill your own fields
  9. UpdateAt time.Time `bson:"updateAt,omitempty" json:"updateAt,omitempty"`
  10. CreateAt time.Time `bson:"createAt,omitempty" json:"createAt,omitempty"`
  11. }

goctl model mysql directive

The goctl model mysql directive is used to generate MySQL based model code that supports the generation of cached and non-cached code.MySQL code generation support from sql files. Database connection to two sources to generate code.

  1. $ goctl model mysql --help
  2. Generate mysql model
  3. Usage:
  4. goctl model mysql [command]
  5. Available Commands:
  6. datasource Generate model from datasource
  7. ddl Generate mysql model from ddl
  8. Flags:
  9. -h, --help help for mysql
  10. -i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
  11. --strict Generate model in strict mode
  12. Use "goctl model mysql [command] --help" for more information about a command.

goctl model mysql datasource directive

goctl model mysql datasource instructions are used to generate model code from database connections.

  1. $ goctl model mysql datasource --help
  2. Generate model from datasource
  3. Usage:
  4. goctl model mysql datasource [flags]
  5. Flags:
  6. --branch string The branch of the remote repo, it does work with --remote
  7. -c, --cache Generate code with cache [optional]
  8. -d, --dir string The target dir
  9. -h, --help help for datasource
  10. --home string The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  11. --idea For idea plugin [optional]
  12. --remote string The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  13. The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
  14. --style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
  15. -t, --table strings The table or table globbing patterns in the database
  16. --url string The data source of database,like "root:password@tcp(127.0.0.1:3306)/database"
  17. Global Flags:
  18. -i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
  19. --strict Generate model in strict mode
goctl model - 图6 Parameter fieldgoctl model - 图7 Parameter Typegoctl model - 图8 Required?goctl model - 图9 Default valuegoctl model - 图10 Parameter Description
branchstringNOEmpty stringRemote template name is used only if remote has value
cachebooleanNOfalseWhether or not to generate code with cache
dirstringNOCurrent working directoryGenerate Code Output Directory
easybooleanNOfalseExposure pool name variable
homestringNO${HOME}/.goctlLocal Template File Directory
remotestringNOEmpty stringRemote template is a git repository address. Priority is higher than home field value when this field is passed
stylestringNOgozeroNamed style symbols for output files and directories, seefile style
table[]stringYESnilTable to generate code
urlstringYESEmpty stringDatabase connection,format{{username}}:{{password}}@tcp({{host_port}}) /{{db}}
ignore-columns[]stringNOnilFields that need to be ignored, inserted or updated, such as create_time
strictbooleanNOfalseWhether it is a strict mode and, if it is rigid, the modified field unsigned will be converted to the corresponding data type, primarily for numerical types, e.g.:if the name of the database indicates bigint type, The result isunsigned modifies the corresponding golang data type to int64, For uint64, if strict is false, no modification to unsigned

goctl model mysql ddl directive

goctl model mysql ddl instructions are used to generate model code from sql files.

  1. $ goctl model mysql ddl --help
  2. Generate mysql model from ddl
  3. Usage:
  4. goctl model mysql ddl [flags]
  5. Flags:
  6. --branch string The branch of the remote repo, it does work with --remote
  7. -c, --cache Generate code with cache [optional]
  8. --database string The name of database [optional]
  9. -d, --dir string The target dir
  10. -h, --help help for ddl
  11. --home string The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  12. --idea For idea plugin [optional]
  13. --remote string The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  14. The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
  15. -s, --src string The path or path globbing patterns of the ddl
  16. --style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
  17. Global Flags:
  18. -i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
  19. --strict Generate model in strict mode
goctl model - 图11 Parameter fieldgoctl model - 图12 Parameter Typegoctl model - 图13 Required?goctl model - 图14 Default valuegoctl model - 图15 Parameter Description
branchstringNOEmpty stringRemote template name is used only if remote has value
cachebooleanNOfalseWhether or not to generate code with cache
dirstringNOCurrent working directoryGenerate Code Output Directory
easybooleanNOfalseExposure pool name variable
homestringNO${HOME}/.goctlLocal Template File Directory
remotestringNOEmpty stringRemote template is a git repository address. Priority is higher than home field value when this field is passed
srcstringYESEmpty stringsql file path
stylestringNOgozeroNamed style symbols for output files and directories, seefile style
ignore-columns[]stringNOnilFields that need to be ignored, inserted or updated, such as create_time
strictbooleanNOfalseWhether it is a strict mode and, if it is rigid, the modified field unsigned will be converted to the corresponding data type, primarily for numerical types, e.g.:if the name of the database indicates bigint type, The result isunsigned modifies the corresponding golang data type to int64, For uint64, if strict is false, no modification to unsigned

MySQL type mapping relationships

  • strict 为 true 时,且 unsigned 修饰
  • strict 不为 true 时
goctl model - 图16 MySQL DataTypegoctl model - 图17 is null constraint?goctl model - 图18 Golang DataType
bitNObyte
tinyintNOuint64
tinyintYESsql.NullInt64
smallintNOuint64
smallintYESsql.NullInt64
mediumintNOuint64
mediumintYESsql.NullInt64
intNOuint64
intYESsql.NullInt64
middleintNOuint64
middleintYESsql.NullInt64
int1NOuint64
int1YESsql.NullInt64
int2NOuint64
int2YESsql.NullInt64
int3NOuint64
int3YESsql.NullInt64
int4NOuint64
int4YESsql.NullInt64
int8NOiunt64
int8YESsql.NullInt64
integerNOuint64
integerYESsql.NullInt64
bigintNOuint64
bigintYESsql.NullInt64
floatNOfloat64
floatYESsql.NullFloat64
float4NOfloat64
float4YESsql.NullFloat64
float8NOfloat64
float8YESsql.NullFloat64
dateNOtime.Time
datetimeNOtime.Time
timstampNOtime.Time
timeNOstring
yearNOint64
charNOstring
varcharNOstring
nvarcharNOstring
ncharNOstring
characterNOstring
longvarcharNOstring
linestringNOstring
multilinestringNOstring
binaryNOstring
varbinaryNOstring
tinytextNOstring
textNOstring
mediumtextNOstring
longtextNOstring
enumNOstring
setNOstring
jsonNOstring
blobNOstring
longblobNOstring
mediumblobNOstring
tinyblobNOstring
boolNObool
blleanNObool
goctl model - 图19 MySQL 类型goctl model - 图20 是否为 null 约束goctl model - 图21 Golang 类型
bitNObyte
tinyintNOint64
tinyintYESsql.NullInt64
smallintNOint64
smallintYESsql.NullInt64
mediumintNOint64
mediumintYESsql.NullInt64
intNOint64
intYESsql.NullInt64
middleintNOint64
middleintYESsql.NullInt64
int1NOint64
int1YESsql.NullInt64
int2NOint64
int2YESsql.NullInt64
int3NOint64
int3YESsql.NullInt64
int4NOint64
int4YESsql.NullInt64
int8NOint64
int8YESsql.NullInt64
integerNOint64
integerYESsql.NullInt64
bigintNOint64
bigintYESsql.NullInt64
floatNOfloat64
floatYESsql.NullFloat64
float4NOfloat64
float4YESsql.NullFloat64
float8NOfloat64
float8YESsql.NullFloat64
dateNOtime.Time
datetimeNOtime.Time
timstampNOtime.Time
timeNOstring
yearNOint64
charNOstring
varcharNOstring
nvarcharNOstring
ncharNOstring
characterNOstring
longvarcharNOstring
linestringNOstring
multilinestringNOstring
binaryNOstring
varbinaryNOstring
tinytextNOstring
textNOstring
mediumtextNOstring
longtextNOstring
enumNOstring
setNOstring
jsonNOstring
blobNOstring
longblobNOstring
mediumblobNOstring
tinyblobNOstring
boolNObool
blleanNObool

goctl model pg directive

goctl model pg instructions are used to generate Go language code from PostgreSQL database.

  1. $ goctl model pg --help
  2. Generate postgresql model
  3. Usage:
  4. goctl model pg [flags]
  5. goctl model pg [command]
  6. Available Commands:
  7. datasource Generate model from datasource
  8. Flags:
  9. -h, --help help for pg
  10. Use "goctl model pg [command] --help" for more information about a command.

goctl model pg datasource directive

  1. $ goctl model pg datasource --help
  2. Generate model from datasource
  3. Usage:
  4. goctl model pg datasource [flags]
  5. Flags:
  6. --branch string The branch of the remote repo, it does work with --remote
  7. -c, --cache Generate code with cache [optional]
  8. -d, --dir string The target dir
  9. -h, --help help for datasource
  10. --home string The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  11. --idea For idea plugin [optional]
  12. --remote string The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
  13. The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
  14. -s, --schema string The table schema (default "public")
  15. --strict Generate model in strict mode
  16. --style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
  17. -t, --table string The table or table globbing patterns in the database
  18. --url string The data source of database,like "postgres://root:password@127.0.0.1:5432/database?sslmode=disable"
goctl model - 图22 Parameter fieldgoctl model - 图23 Parameter Typegoctl model - 图24 Required?goctl model - 图25 Default valuegoctl model - 图26 Parameter Description
branchstringNOEmpty stringRemote template name is used only if remote has value
cachebooleanNOfalseWhether or not to generate code with cache
dirstringNOCurrent working directoryGenerate Code Output Directory
easybooleanNOfalseExposure pool name variable
homestringNO${HOME}/.goctlLocal Template File Directory
ideabooleanNOfalseWhether to use as idea, please ignore this field
remotestringNOEmpty stringRemote template is a git repository address. Priority is higher than home field value when this field is passed
strictbooleanNOfalseWhether it is a strict mode and, if it is rigid, the modified field unsigned will be converted to the corresponding data type, primarily for numerical types, e.g.:if the name of the database indicates bigint type, The result isunsigned modifies the corresponding golang data type to int64, For uint64, if strict is false, no modification to unsigned
stylestringNOgozeroNamed style symbols for output files and directories, seefile style
table[]stringYESnilTable to generate code
urlstringYESEmpty stringDatabase connection,format postprogres://{{username}}:{{password}}@{{host_port}}/{{db}}?sslmode=disabled

PostgreSQL Type Map Relationships

goctl model - 图27 PostgreSQL Typegoctl model - 图28 Golang Type
boolbool
_boolpq.BoolArray
booleanbool
tinyintint64
smallintint64
mediumintint64
intint64
int1int64
int2int64
_int2pq.Int64Array
int3int64
int4int64
_int4pq.Int64Array
int8int64
_int8pq.Int64Array
integerint64
_integerpq.Int64Array
bigintint64
floatfloat64
float4float64
_float4pq.Float64Array
float8float64
_float8pq.Float64Array
doublefloat64
decimalfloat64
decfloat64
fixedfloat64
realfloat64
bitbyte
datetime.Time
datetimetime.Time
timestamptime.Time
timestring
yearint64
linestringstring
multilinestringstring
nvarcharstring
ncharstring
charstring
_charpq.StringArray
characterstring
varcharstring
_varcharpq.StringArray
binarystring
byteastring
longvarbinarystring
varbinarystring
tinytextstring
textstring
_textpq.StringArray
mediumtextstring
longtextstring
enumstring
setstring
jsonstring
jsonbstring
blobstring
longblobstring
mediumblobstring
tinyblobstring
ltree[]byte