콘텐츠로 이동

goctl Model

Terminal window
$ goctl model --help
Generate model code
Usage:
goctl model [command]
Available 명령s:
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.
Terminal window
$ 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
매개변수 필드 매개변수 타입 필수? 기본값 value 매개변수 설명
branchstring없음Empty string원격 템플릿 name is 사용됨 만 경우 remote has value
캐시boolean없음falseWhether 또는 아님 로 생성 code 사용하여 캐시
dirstring없음Current 작동 디렉터리생성 Code 출력 디렉터리
easyboolean없음falseExposure pool name variable
homestring없음${HOME}/.goctl로컬 템플릿 파일 디렉터리
원격string없음Empty string해당 항목의 동작과 사용법을 설명합니다.
스타일string없음gozeroNamed 스타일 symbols 위한 출력 파일과 디렉터리, see 파일 스타일
타입[]stringYESnilStructure 타입 Name

Below은 예제 의 generating user structure입니다.

1 Whether 또는 아님 로 생성 code 사용하여 캐시

Terminal window
# 예시입니다
$ cd ~
# 예시입니다
$ mkdir demo && cd demo
# 예시입니다
$ goctl model mongo --type User --dir cache --cache
# 예시입니다
$ tree
.
└── cache
├── error.go
├── usermodel.go
├── usermodelgen.go
└── usertypes.go
1 directory, 4 files

View code

오류.go

package model
import (
"errors"
"github.com/zeromicro/go-zero/core/stores/mon"
)
var (
ErrNotFound = mon.ErrNotFound
ErrInvalidObjectId = errors.New("invalid objectId")
)

usermodel.go

package model
import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/monc"
)
var _ UserModel = (*customUserModel)(nil)
type (
// 사용합니다
// 예시입니다
UserModel interface {
userModel
}
customUserModel struct {
*defaultUserModel
}
)
// NewUserModel 예시입니다
func NewUserModel(url, db, collection string, c cache.CacheConf) UserModel {
conn := monc.MustNewModel(url, db, collection, c)
return &customUserModel{
defaultUserModel: newDefaultUserModel(conn),
}
}

usermodelgen.go

// 이 코드는 직접 수정하지 마세요
package model
import (
"context"
"time"
"github.com/zeromicro/go-zero/core/stores/monc"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var prefixUserCacheKey = "cache:user:"
type userModel interface {
Insert(ctx context.Context, data *User) error
FindOne(ctx context.Context, id string) (*User, error)
Update(ctx context.Context, data *User) error
Delete(ctx context.Context, id string) error
}
type defaultUserModel struct {
conn *monc.Model
}
func newDefaultUserModel(conn *monc.Model) *defaultUserModel {
return &defaultUserModel{conn: conn}
}
func (m *defaultUserModel) Insert(ctx context.Context, data *User) error {
if data.ID.IsZero() {
data.ID = primitive.NewObjectID()
data.CreateAt = time.Now()
data.UpdateAt = time.Now()
}
key := prefixUserCacheKey + data.ID.Hex()
_, err := m.conn.InsertOne(ctx, key, data)
return err
}
func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, ErrInvalidObjectId
}
var data User
key := prefixUserCacheKey + id
err = m.conn.FindOne(ctx, key, &data, bson.M{"_id": oid})
switch err {
case nil:
return &data, nil
case monc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserModel) Update(ctx context.Context, data *User) error {
data.UpdateAt = time.Now()
key := prefixUserCacheKey + data.ID.Hex()
_, err := m.conn.ReplaceOne(ctx, key, bson.M{"_id": data.ID}, data)
return err
}
func (m *defaultUserModel) Delete(ctx context.Context, id string) error {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return ErrInvalidObjectId
}
key := prefixUserCacheKey + id
_, err = m.conn.DeleteOne(ctx, key, bson.M{"_id": oid})
return err
}

usertypes.go

package model
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
// TODO: 필요한 로직을 작성하세요
UpdateAt time.Time `bson:"updateAt,omitempty" json:"updateAt,omitempty"`
CreateAt time.Time `bson:"createAt,omitempty" json:"createAt,omitempty"`
}

2 생성 code 없이 캐시

Terminal window
# 예시입니다
$ cd ~
# 예시입니다
$ mkdir demo && cd demo
# 예시입니다
$ goctl model mongo --type User --dir nocache
# 예시입니다
$ tree
.
└── nocache
├── error.go
├── usermodel.go
├── usermodelgen.go
└── usertypes.go
1 directory, 4 files

View code

오류.go

package model
import (
"errors"
"github.com/zeromicro/go-zero/core/stores/mon"
)
var (
ErrNotFound = mon.ErrNotFound
ErrInvalidObjectId = errors.New("invalid objectId")
)

usermodel.go

package model
import "github.com/zeromicro/go-zero/core/stores/mon"
var _ UserModel = (*customUserModel)(nil)
type (
// 사용합니다
// 예시입니다
UserModel interface {
userModel
}
customUserModel struct {
*defaultUserModel
}
)
// NewUserModel 예시입니다
func NewUserModel(url, db, collection string) UserModel {
conn := mon.MustNewModel(url, db, collection)
return &customUserModel{
defaultUserModel: newDefaultUserModel(conn),
}
}

usermodelgen.go

// 이 코드는 직접 수정하지 마세요
package model
import (
"context"
"time"
"github.com/zeromicro/go-zero/core/stores/mon"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type userModel interface {
Insert(ctx context.Context, data *User) error
FindOne(ctx context.Context, id string) (*User, error)
Update(ctx context.Context, data *User) error
Delete(ctx context.Context, id string) error
}
type defaultUserModel struct {
conn *mon.Model
}
func newDefaultUserModel(conn *mon.Model) *defaultUserModel {
return &defaultUserModel{conn: conn}
}
func (m *defaultUserModel) Insert(ctx context.Context, data *User) error {
if data.ID.IsZero() {
data.ID = primitive.NewObjectID()
data.CreateAt = time.Now()
data.UpdateAt = time.Now()
}
_, err := m.conn.InsertOne(ctx, data)
return err
}
func (m *defaultUserModel) FindOne(ctx context.Context, id string) (*User, error) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, ErrInvalidObjectId
}
var data User
err = m.conn.FindOne(ctx, &data, bson.M{"_id": oid})
switch err {
case nil:
return &data, nil
case mon.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserModel) Update(ctx context.Context, data *User) error {
data.UpdateAt = time.Now()
_, err := m.conn.ReplaceOne(ctx, bson.M{"_id": data.ID}, data)
return err
}
func (m *defaultUserModel) Delete(ctx context.Context, id string) error {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return ErrInvalidObjectId
}
_, err = m.conn.DeleteOne(ctx, bson.M{"_id": oid})
return err
}

usertypes.go

package model
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
// TODO: 필요한 로직을 작성하세요
UpdateAt time.Time `bson:"updateAt,omitempty" json:"updateAt,omitempty"`
CreateAt time.Time `bson:"createAt,omitempty" json:"createAt,omitempty"`
}
Terminal window
$ goctl model mysql --help
Generate mysql model
Usage:
goctl model mysql [command]
Available 명령s:
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
-p, --prefix string The cache prefix, effective when --cache is true (default "cache")
Use "goctl model mysql [command] --help" for more information about a command.

goctl 모델 mysql datasource instructions은 사용되어 생성 모델 code 에서 데이터베이스 connections입니다.

Terminal window
$ 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
-p, --prefix string The cache prefix, effective when --cache is true (default "cache")
매개변수 필드 매개변수 타입 필수? 기본값 value 매개변수 설명
branchstring없음Empty string원격 템플릿 name is 사용됨 만 경우 remote has value
캐시boolean없음falseWhether 또는 아님 로 생성 code 사용하여 캐시
dirstring없음Current 작동 디렉터리생성 Code 출력 디렉터리
easyboolean없음falseExposure pool name variable
homestring없음${HOME}/.goctl로컬 템플릿 파일 디렉터리
원격string없음Empty string해당 항목의 동작과 사용법을 설명합니다.
스타일string없음gozeroNamed 스타일 symbols 위한 출력 파일과 디렉터리, see 파일 스타일
table[]stringYESnilTable 로 생성 code
URLstringYESEmpty string데이터베이스 연결,format{{username}}:{{password}}@tcp({{host_port}}) /{{db}}
ignore-columns[]string없음nil해당 항목의 동작과 사용법을 설명합니다.
strictboolean없음false해당 항목의 동작과 사용법을 설명합니다.
prefixstring없음cache캐시 prefix, effective 때 —cache is true (기본값 “캐시”), goctl 버전 > 1.7.6
Terminal window
$ 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
-p, --prefix string The cache prefix, effective when --cache is true (default "cache")
매개변수 필드 매개변수 타입 필수? 기본값 value 매개변수 설명
branchstring없음Empty string원격 템플릿 name is 사용됨 만 경우 remote has value
캐시boolean없음falseWhether 또는 아님 로 생성 code 사용하여 캐시
dirstring없음Current 작동 디렉터리생성 Code 출력 디렉터리
easyboolean없음falseExposure pool name variable
homestring없음${HOME}/.goctl로컬 템플릿 파일 디렉터리
원격string없음Empty string해당 항목의 동작과 사용법을 설명합니다.
srcstringYESEmpty stringsql 파일 경로
스타일string없음gozeroNamed 스타일 symbols 위한 출력 파일과 디렉터리, see 파일 스타일
ignore-columns[]string없음nil해당 항목의 동작과 사용법을 설명합니다.
strictboolean없음false해당 항목의 동작과 사용법을 설명합니다.
prefixstring없음cache캐시 prefix, effective 때 —cache is true (기본값 “캐시”), goctl 버전 > 1.7.6

strict 为 true 时,且 unsigned 修饰

MySQL DataType is null constraint? Golang DataType
bit없음byte
tinyint없음uint64
tinyintYESsql.NullInt64
smallint없음uint64
smallintYESsql.NullInt64
mediumint없음uint64
mediumintYESsql.NullInt64
int없음uint64
intYESsql.NullInt64
middleint없음uint64
middleintYESsql.NullInt64
int1없음uint64
int1YESsql.NullInt64
int2없음uint64
int2YESsql.NullInt64
int3없음uint64
int3YESsql.NullInt64
int4없음uint64
int4YESsql.NullInt64
int8없음iunt64
int8YESsql.NullInt64
integer없음uint64
integerYESsql.NullInt64
bigint없음uint64
bigintYESsql.NullInt64
float없음float64
floatYESsql.NullFloat64
float4없음float64
float4YESsql.NullFloat64
float8없음float64
float8YESsql.NullFloat64
date없음time.Time
datetime없음time.Time
timstamp없음time.Time
time없음string
year없음int64
char없음string
varchar없음string
nvarchar없음string
nchar없음string
character없음string
longvarchar없음string
linestring없음string
multilinestring없음string
바이너리없음string
varbinary없음string
tinytext없음string
text없음string
mediumtext없음string
longtext없음string
enum없음string
set없음string
json없음string
blob없음string
longblob없음string
mediumblob없음string
tinyblob없음string
bool없음bool
bllean없음bool

strict 不为 true 时

MySQL 类型 是否为 null 约束 Golang 类型
bit없음byte
tinyint없음int64
tinyintYESsql.NullInt64
smallint없음int64
smallintYESsql.NullInt64
mediumint없음int64
mediumintYESsql.NullInt64
int없음int64
intYESsql.NullInt64
middleint없음int64
middleintYESsql.NullInt64
int1없음int64
int1YESsql.NullInt64
int2없음int64
int2YESsql.NullInt64
int3없음int64
int3YESsql.NullInt64
int4없음int64
int4YESsql.NullInt64
int8없음int64
int8YESsql.NullInt64
integer없음int64
integerYESsql.NullInt64
bigint없음int64
bigintYESsql.NullInt64
float없음float64
floatYESsql.NullFloat64
float4없음float64
float4YESsql.NullFloat64
float8없음float64
float8YESsql.NullFloat64
date없음time.Time
datetime없음time.Time
timstamp없음time.Time
time없음string
year없음int64
char없음string
varchar없음string
nvarchar없음string
nchar없음string
character없음string
longvarchar없음string
linestring없음string
multilinestring없음string
바이너리없음string
varbinary없음string
tinytext없음string
text없음string
mediumtext없음string
longtext없음string
enum없음string
set없음string
json없음string
blob없음string
longblob없음string
mediumblob없음string
tinyblob없음string
bool없음bool
bllean없음bool

goctl 모델 pg instructions은 사용되어 생성 Go language code 에서 PostgreSQL 데이터베이스입니다.

Terminal window
$ goctl model pg --help
Generate postgresql model
Usage:
goctl model pg [flags]
goctl model pg [command]
Available 명령s:
datasource Generate model from datasource
Flags:
-h, --help help for pg
Use "goctl model pg [command] --help" for more information about a command.
Terminal window
$ 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:// 예시입니다
매개변수 필드 매개변수 타입 필수? 기본값 value 매개변수 설명
branchstring없음Empty string원격 템플릿 name is 사용됨 만 경우 remote has value
캐시boolean없음falseWhether 또는 아님 로 생성 code 사용하여 캐시
dirstring없음Current 작동 디렉터리생성 Code 출력 디렉터리
easyboolean없음falseExposure pool name variable
homestring없음${HOME}/.goctl로컬 템플릿 파일 디렉터리
ideaboolean없음falseWhether 로 사용 로서 idea, please ignore this 필드
원격string없음Empty string해당 항목의 동작과 사용법을 설명합니다.
strictboolean없음false해당 항목의 동작과 사용법을 설명합니다.
스타일string없음gozeroNamed 스타일 symbols 위한 출력 파일과 디렉터리, see 파일 스타일
table[]stringYESnilTable 로 생성 code
URLstringYESEmpty string이 항목은 해당 기능의 사용 방법, 설정, 주의 사항을 설명합니다.
PostgreSQL 타입 Golang 타입
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
바이너리string
byteastring
longvarbinarystring
varbinarystring
tinytextstring
textstring
_textpq.StringArray
mediumtextstring
longtextstring
enumstring
setstring
jsonstring
jsonbstring
blobstring
longblobstring
mediumblobstring
tinyblobstring
ltree[]byte

예제 1. Modify decimal 로 decimal. Decimal 타입

  1. Initialize 설정 에서 projects that need 로 생성 모델
Terminal window
$ goctl config init
goctl.yaml generated in ~/workspace/go-zero/tools/goctl/goctl.yaml
  1. Modify 타입 mapping relationship

grey shading은 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
...

추가 타입 mappings 아님 supported 통해 goctl built-in

섹션 제목: “추가 타입 mappings 아님 supported 통해 goctl built-in”

We have pg 에서 table 사용하여 데이터 타입 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;
Terminal window
$ goctl model pg datasource --url="postgres:// 예시입니다
Error: unsupported database type: inet
  1. 체크 경우 goctl 버전 meets conditions
Terminal window
$ 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, GOCTL_EXPERIMENTAL 예시입니다
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 설정 에서 target 프로젝트
Terminal window
$ goctl config
goctl.yaml generated in ~/demo/goctl-config/goctl.yaml # 예시입니다
  1. Modify goctl.yaml
model:
types_map:
bigint:
null_type: sql.NullInt64
type: int64
unsigned_type: uint64
...
inet:
null_type: sql.NullString
type: string
  1. 생성 모델 code again
Terminal window
goctl model pg datasource --url="postgres:// 예시입니다
Done.