Skip to main content

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

$ goctl model  --help
Generate model code

Usage:
goctl model [command]

Available Commands:
mongo Generate mongo model
mysql Generate mysql model
pg Generate postgresql model

Flags:
-h, --help help for model


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.

$ goctl model mongo --help
Generate mongo model

Usage:
goctl model mongo [flags]

Flags:
--branch string The branch of the remote repo, it does work with --remote
-c, --cache Generate code with cache [optional]
-d, --dir string The target dir
-e, --easy Generate code with auto generated CollectionName for easy declare [optional]
-h, --help help for mongo
--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
--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
The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
--style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
-t, --type strings Specified model type name
Parameter field Parameter Type Required? Default value 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, see file style
type[]stringYESnilStructure Type Name

Examples

Below are examples of generating a user structure.

1 Whether or not to generate code with cache

# enter user home
$ cd ~

# make dir named demo
$ mkdir demo && cd demo

# generate mongo code by goctl
$ goctl model mongo --type User --dir cache --cache

# view layout
$ tree
.
└── cache
├── error.go
├── usermodel.go
├── usermodelgen.go
└── usertypes.go

1 directory, 4 files

View code

package model

import (
"errors"

"github.com/zeromicro/go-zero/core/stores/mon"
)

var (
ErrNotFound = mon.ErrNotFound
ErrInvalidObjectId = errors.New("invalid objectId")
)

2 Generate code without cache

# enter user home
$ cd ~

# make dir named demo
$ mkdir demo && cd demo

# generate mongo code by goctl
$ goctl model mongo --type User --dir nocache

# view layout
$ tree
.
└── nocache
├── error.go
├── usermodel.go
├── usermodelgen.go
└── usertypes.go

1 directory, 4 files

View code

package model

import (
"errors"

"github.com/zeromicro/go-zero/core/stores/mon"
)

var (
ErrNotFound = mon.ErrNotFound
ErrInvalidObjectId = errors.New("invalid objectId")
)

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.

$ goctl model mysql --help
Generate mysql model

Usage:
goctl model mysql [command]

Available Commands:
datasource Generate model from datasource
ddl Generate mysql model from ddl

Flags:
-h, --help help for mysql
-i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
--strict Generate model in strict mode


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.

$ goctl model mysql datasource --help
Generate model from datasource

Usage:
goctl model mysql datasource [flags]

Flags:
--branch string The branch of the remote repo, it does work with --remote
-c, --cache Generate code with cache [optional]
-d, --dir string The target dir
-h, --help help for datasource
--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
--idea For idea plugin [optional]
--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
The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
--style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
-t, --table strings The table or table globbing patterns in the database
--url string The data source of database,like "root:password@tcp(127.0.0.1:3306)/database"


Global Flags:
-i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
--strict Generate model in strict mode
Parameter field Parameter Type Required? Default value 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, see file 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.

$ goctl model mysql ddl --help
Generate mysql model from ddl

Usage:
goctl model mysql ddl [flags]

Flags:
--branch string The branch of the remote repo, it does work with --remote
-c, --cache Generate code with cache [optional]
--database string The name of database [optional]
-d, --dir string The target dir
-h, --help help for ddl
--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
--idea For idea plugin [optional]
--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
The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
-s, --src string The path or path globbing patterns of the ddl
--style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]


Global Flags:
-i, --ignore-columns strings Ignore columns while creating or updating rows (default [create_at,created_at,create_time,update_at,updated_at,update_time])
--strict Generate model in strict mode
Parameter field Parameter Type Required? Default value 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, see file 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

MySQL DataType is null constraint? 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 pg directive

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

$ goctl model pg --help
Generate postgresql model

Usage:
goctl model pg [flags]
goctl model pg [command]

Available Commands:
datasource Generate model from datasource

Flags:
-h, --help help for pg


Use "goctl model pg [command] --help" for more information about a command.

goctl model pg datasource directive

$ goctl model pg datasource --help
Generate model from datasource

Usage:
goctl model pg datasource [flags]

Flags:
--branch string The branch of the remote repo, it does work with --remote
-c, --cache Generate code with cache [optional]
-d, --dir string The target dir
-h, --help help for datasource
--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
--idea For idea plugin [optional]
--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
The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
-s, --schema string The table schema (default "public")
--strict Generate model in strict mode
--style string The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
-t, --table string The table or table globbing patterns in the database
--url string The data source of database,like "postgres://root:password@127.0.0.1:5432/database?sslmode=disable"
Parameter field Parameter Type Required? Default value 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, see file style
table[]stringYESnilTable to generate code
urlstringYESEmpty stringDatabase connection,format postprogres://{{username}}:{{password}}@{{host_port}}/{{db}}?sslmode=disabled

PostgreSQL Type Map Relationships

PostgreSQL Type 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

type mapping customization

Type mapping customization can only be used in the experimental version. For how to enable the experimental version, please refer to goctl env,For configuration use, please refer to goctl config

Example 1. Modify decimal to decimal. Decimal type

  1. Initialize configuration in projects that need to generate models
$ goctl config init
goctl.yaml generated in ~/workspace/go-zero/tools/goctl/goctl.yaml
  1. Modify the type mapping relationship

The grey shading is a custom mapping type.

model:
types_map:
bigint:
null_type: sql.NullInt64
type: int64
unsigned_type: uint64
dec:
null_type: sql.NullFloat64
type: float64
decimal:
null_type: decimal.NullDecimal
pkg: github.com/shopspring/decimal
type: decimal.Decimal
...

Add type mappings not supported by goctl built-in

We have a pg in the table with data type inet.

-- auto-generated definition
create table student
(
id integer not null
constraint student_pk
primary key,
name varchar default ''::character varying not null,
age integer default 0 not null,
description integer not null,
ip_address inet default '0.0.0.0'::inet not null
);

alter table student
owner to postgres;

Currently goctl built-in type mappings do not support types, so goctl will report an error as follows:

$ goctl model pg datasource --url="postgres://postgres:postgrespw@127.0.0.1:55000/postgres?sslmode=disable" --table="user,student" --dir . 
Error: unsupported database type: inet

To solve the above problem, in the past, the goctl version was not supported. You could only add rules to the built-in type mapping rules, and then send the version, but now you only need to add a type mapping rule in the configuration file.

Provided that the goctl version is greater than or equal to 1.6.5, and the experimental function is started

  1. Check if the goctl version meets the conditions
$ goctl env
GOCTL_OS=darwin
GOCTL_ARCH=arm64
GOCTL_HOME=/Users/sh00414ml/.goctl
GOCTL_DEBUG=False
GOCTL_CACHE=/Users/sh00414ml/.goctl/cache
GOCTL_EXPERIMENTAL=on # If the experimental function tube is off, it needs to be turned on. The opening command is goctl env -w GOCTL_EXPERIMENTAL = on
GOCTL_VERSION=1.6.5 # goctl version
PROTOC_VERSION=3.19.4
PROTOC_GEN_GO_VERSION=v1.28.0
PROTO_GEN_GO_GRPC_VERSION=1.2.0
  1. Initialize goctl configuration in the target project
$ goctl config
goctl.yaml generated in ~/demo/goctl-config/goctl.yaml # This is based on the output of your own computer, which is for reference only.
  1. Modify goctl.yaml

To increase the target data type and mapping relationship, add an inet mapping here. The example is as follows: Grey shading

model:
types_map:
bigint:
null_type: sql.NullInt64
type: int64
unsigned_type: uint64
...
inet:
null_type: sql.NullString
type: string
  1. Generate model code again
goctl model pg datasource --url="postgres://postgres:postgrespw@127.0.0.1:55000/postgres?sslmode=disable" --table="user,student" --dir . 
Done.