diff --git a/generator.go b/generator.go index 36def1fb..93b42bd3 100644 --- a/generator.go +++ b/generator.go @@ -3,6 +3,7 @@ package gen import ( "bytes" "context" + "database/sql" "fmt" "io" "io/ioutil" @@ -33,6 +34,15 @@ type T interface{} // M map[string]interface{} type M map[string]interface{} +// SQLResult sql.result +type SQLResult sql.Result + +// SQLRow sql.Row +type SQLRow sql.Row + +// SQLRows sql.Rows +type SQLRows sql.Rows + // RowsAffected execute affected raws type RowsAffected int64 @@ -200,12 +210,12 @@ func (g *Generator) genModelObjConfig() *model.Config { } } -// ApplyBasic specify models which will implement basic method +// ApplyBasic specify models which will implement basic .diy_method func (g *Generator) ApplyBasic(models ...interface{}) { g.ApplyInterface(func() {}, models...) } -// ApplyInterface specifies method interfaces on structures, implment codes will be generated after calling g.Execute() +// ApplyInterface specifies .diy_method interfaces on structures, implment codes will be generated after calling g.Execute() // eg: g.ApplyInterface(func(model.Method){}, model.User{}, model.Company{}) func (g *Generator) ApplyInterface(fc interface{}, models ...interface{}) { structs, err := generate.ConvertStructs(g.db, models...) diff --git a/internal/generate/interface.go b/internal/generate/interface.go index 43eeef86..85a1957f 100644 --- a/internal/generate/interface.go +++ b/internal/generate/interface.go @@ -57,6 +57,46 @@ func (m *InterfaceMethod) GormRunMethodName() string { return "Take" } +// ReturnSQLResult return sql result +func (m *InterfaceMethod) ReturnSQLResult() bool { + for _, res := range m.Result { + if res.IsSQLResult() { + return true + } + } + return false +} + +// ReturnSQLRow return sql result +func (m *InterfaceMethod) ReturnSQLRow() bool { + for _, res := range m.Result { + if res.IsSQLRow() { + return true + } + } + return false +} + +// ReturnSQLRows return sql result +func (m *InterfaceMethod) ReturnSQLRows() bool { + for _, res := range m.Result { + if res.IsSQLRows() { + return true + } + } + return false +} + +// ReturnNothing not return error and rowAffected +func (m *InterfaceMethod) ReturnNothing() bool { + for _, res := range m.Result { + if res.IsError() || res.Name == "rowsAffected" { + return false + } + } + return true +} + // ReturnRowsAffected return rows affected func (m *InterfaceMethod) ReturnRowsAffected() bool { for _, res := range m.Result { @@ -113,7 +153,7 @@ func paramToString(params []parser.Param) string { // DocComment return comment sql add "//" every line func (m *InterfaceMethod) DocComment() string { - return strings.Replace(strings.TrimSpace(m.Doc), "\n", "\n//", -1) + return strings.Replace(strings.Replace(strings.TrimSpace(m.Doc), "\n", "\n// ", -1), "// ", "// ", -1) } // checkParams check all parameters @@ -196,6 +236,23 @@ func (m *InterfaceMethod) checkResult(result []parser.Param) (err error) { param.Package = "" param.SetName("rowsAffected") m.GormOption = "Exec" + case param.IsSQLResult(): + param.Type = "Result" + param.Package = "sql" + param.SetName("result") + m.GormOption = "Statement.ConnPool.ExecContext" + case param.IsSQLRow(): + param.Type = "Row" + param.Package = "sql" + param.SetName("row") + m.GormOption = "Raw" + param.IsPointer = true + case param.IsSQLRows(): + param.Type = "Rows" + param.Package = "sql" + param.SetName("rows") + m.GormOption = "Raw" + param.IsPointer = true default: if !m.ResultData.IsNull() { return fmt.Errorf("query method cannot return more than 1 data value in [%s.%s]", m.InterfaceName, m.MethodName) diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 7c384cf3..a3447774 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -181,6 +181,21 @@ func (p *Param) IsTime() bool { return p.Package == "time" && p.Type == "Time" } +// IsSQLResult ... +func (p *Param) IsSQLResult() bool { + return (p.Package == "sql" && p.Type == "Result") || (p.Package == "gen" && p.Type == "SQLResult") +} + +// IsSQLRow ... +func (p *Param) IsSQLRow() bool { + return (p.Package == "sql" && p.Type == "Row") || (p.Package == "gen" && p.Type == "SQLRow") +} + +// IsSQLRows ... +func (p *Param) IsSQLRows() bool { + return (p.Package == "sql" && p.Type == "Rows") || (p.Package == "gen" && p.Type == "SQLRows") +} + // SetName ... func (p *Param) SetName(name string) { p.Name = name diff --git a/internal/template/method.go b/internal/template/method.go index d99629c1..a562d0e0 100644 --- a/internal/template/method.go +++ b/internal/template/method.go @@ -3,7 +3,7 @@ package template // DIYMethod DIY method const DIYMethod = ` -//{{.DocComment }} +// {{.DocComment }} func ({{.S}} {{.TargetStruct}}Do){{.FuncSign}}{ {{if .HasSQLData}}var params []interface{} @@ -12,12 +12,17 @@ func ({{.S}} {{.TargetStruct}}Do){{.FuncSign}}{ {{end}} {{if .HasNeedNewResult}}result ={{if .ResultData.IsMap}}make{{else}}new{{end}}({{if ne .ResultData.Package ""}}{{.ResultData.Package}}.{{end}}{{.ResultData.Type}}){{end}} - {{if or .ReturnRowsAffected .ReturnError}}var executeSQL *gorm.DB - {{end}} - {{if or .ReturnRowsAffected .ReturnError}}executeSQL{{else}}_{{end}} = {{.S}}.UnderlyingDB().{{.GormOption}}(generateSQL.String(){{if .HasSQLData}},params...{{end}}){{if not .ResultData.IsNull}}.{{.GormRunMethodName}}({{if .HasGotPoint}}&{{end}}{{.ResultData.Name}}){{end}} + {{if .ReturnSQLResult}}stmt := {{.S}}.UnderlyingDB().Statement + result,{{if .ReturnError}}err{{else}}_{{end}} = stmt.ConnPool.ExecContext(stmt.Context,generateSQL.String(){{if .HasSQLData}},params...{{end}}) // ignore_security_alert + {{else if .ReturnSQLRow}}row = {{.S}}.UnderlyingDB().Raw(generateSQL.String(){{if .HasSQLData}},params...{{end}}).Row() // ignore_security_alert + {{else if .ReturnSQLRows}}rows,{{if .ReturnError}}err{{else}}_{{end}} = {{.S}}.UnderlyingDB().Raw(generateSQL.String(){{if .HasSQLData}},params...{{end}}).Rows() // ignore_security_alert + {{else}}var executeSQL *gorm.DB + executeSQL = {{.S}}.UnderlyingDB().{{.GormOption}}(generateSQL.String(){{if .HasSQLData}},params...{{end}}){{if not .ResultData.IsNull}}.{{.GormRunMethodName}}({{if .HasGotPoint}}&{{end}}{{.ResultData.Name}}){{end}} // ignore_security_alert {{if .ReturnRowsAffected}}rowsAffected = executeSQL.RowsAffected {{end}}{{if .ReturnError}}err = executeSQL.Error - {{end}}return + {{end}}{{if .ReturnNothing}}_ = executeSQL + {{end}}{{end}} + return } ` diff --git a/tests/.expect/dal_4/model/banks.gen.go b/tests/.expect/dal_4/model/banks.gen.go new file mode 100644 index 00000000..47ce6f40 --- /dev/null +++ b/tests/.expect/dal_4/model/banks.gen.go @@ -0,0 +1,20 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +const TableNameBank = "banks" + +// Bank mapped from table +type Bank struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"-"` + Name *string `gorm:"column:name" json:"-"` + Address *string `gorm:"column:address" json:"-"` + Scale *int64 `gorm:"column:scale" json:"-"` +} + +// TableName Bank's table name +func (*Bank) TableName() string { + return TableNameBank +} diff --git a/tests/.expect/dal_4/model/credit_cards.gen.go b/tests/.expect/dal_4/model/credit_cards.gen.go new file mode 100644 index 00000000..7a7d0202 --- /dev/null +++ b/tests/.expect/dal_4/model/credit_cards.gen.go @@ -0,0 +1,29 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +import ( + "time" + + "gorm.io/gorm" +) + +const TableNameCreditCard = "credit_cards" + +// CreditCard mapped from table +type CreditCard struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"-"` + CreatedAt *time.Time `gorm:"column:created_at" json:"-"` + UpdatedAt *time.Time `gorm:"column:updated_at" json:"-"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index:idx_credit_cards_deleted_at,priority:1" json:"-"` + Number *string `gorm:"column:number" json:"-"` + CustomerRefer *int64 `gorm:"column:customer_refer" json:"-"` + BankID *int64 `gorm:"column:bank_id" json:"-"` +} + +// TableName CreditCard's table name +func (*CreditCard) TableName() string { + return TableNameCreditCard +} diff --git a/tests/.expect/dal_4/model/customers.gen.go b/tests/.expect/dal_4/model/customers.gen.go new file mode 100644 index 00000000..0b0800fb --- /dev/null +++ b/tests/.expect/dal_4/model/customers.gen.go @@ -0,0 +1,27 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +import ( + "time" + + "gorm.io/gorm" +) + +const TableNameCustomer = "customers" + +// Customer mapped from table +type Customer struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"-"` + CreatedAt *time.Time `gorm:"column:created_at" json:"-"` + UpdatedAt *time.Time `gorm:"column:updated_at" json:"-"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index:idx_customers_deleted_at,priority:1" json:"-"` + BankID *int64 `gorm:"column:bank_id" json:"-"` +} + +// TableName Customer's table name +func (*Customer) TableName() string { + return TableNameCustomer +} diff --git a/tests/.expect/dal_4/model/people.gen.go b/tests/.expect/dal_4/model/people.gen.go new file mode 100644 index 00000000..72f8d1c7 --- /dev/null +++ b/tests/.expect/dal_4/model/people.gen.go @@ -0,0 +1,43 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +import ( + "time" + + "gorm.io/gorm" +) + +const TableNamePerson = "people" + +// Person mapped from table +type Person struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"-"` + Name *string `gorm:"column:name" json:"-"` + Alias_ *string `gorm:"column:alias" json:"-"` + Age *int32 `gorm:"column:age" json:"-"` + Flag *bool `gorm:"column:flag" json:"-"` + AnotherFlag *int32 `gorm:"column:another_flag" json:"-"` + Commit *string `gorm:"column:commit" json:"-"` + First *bool `gorm:"column:First" json:"-"` + Bit *[]uint8 `gorm:"column:bit" json:"-"` + Small *int32 `gorm:"column:small" json:"-"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"-"` + Score *float64 `gorm:"column:score" json:"-"` + Number *int32 `gorm:"column:number" json:"-"` + Birth *time.Time `gorm:"column:birth;default:CURRENT_TIMESTAMP" json:"-"` + XMLHTTPRequest *string `gorm:"column:xmlHTTPRequest;default:' '" json:"-"` + JStr *string `gorm:"column:jStr" json:"-"` + Geo *string `gorm:"column:geo" json:"-"` + Mint *int32 `gorm:"column:mint" json:"-"` + Blank *string `gorm:"column:blank;default:' '" json:"-"` + Remark *string `gorm:"column:remark" json:"-"` + LongRemark *string `gorm:"column:long_remark" json:"-"` +} + +// TableName Person's table name +func (*Person) TableName() string { + return TableNamePerson +} diff --git a/tests/.expect/dal_4/model/users.gen.go b/tests/.expect/dal_4/model/users.gen.go new file mode 100644 index 00000000..b9df6533 --- /dev/null +++ b/tests/.expect/dal_4/model/users.gen.go @@ -0,0 +1,33 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +import ( + "time" +) + +const TableNameUser = "users" + +// User mapped from table +type User struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"-"` + CreatedAt *time.Time `gorm:"column:created_at" json:"-"` + Name *string `gorm:"column:name;index:idx_name,priority:1" json:"-"` // oneline + Address *string `gorm:"column:address" json:"-"` + RegisterTime *time.Time `gorm:"column:register_time" json:"-"` + /* + multiline + line1 + line2 + */ + Alive *bool `gorm:"column:alive" json:"-"` + CompanyID *int64 `gorm:"column:company_id;default:666" json:"-"` + PrivateURL *string `gorm:"column:private_url;default:https://a.b.c" json:"-"` +} + +// TableName User's table name +func (*User) TableName() string { + return TableNameUser +} diff --git a/tests/.expect/dal_4/query/banks.gen.go b/tests/.expect/dal_4/query/banks.gen.go new file mode 100644 index 00000000..cdf9111b --- /dev/null +++ b/tests/.expect/dal_4/query/banks.gen.go @@ -0,0 +1,402 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "gorm.io/gen/tests/.gen/dal_4/model" +) + +func newBank(db *gorm.DB, opts ...gen.DOOption) bank { + _bank := bank{} + + _bank.bankDo.UseDB(db, opts...) + _bank.bankDo.UseModel(&model.Bank{}) + + tableName := _bank.bankDo.TableName() + _bank.ALL = field.NewAsterisk(tableName) + _bank.ID = field.NewInt64(tableName, "id") + _bank.Name = field.NewString(tableName, "name") + _bank.Address = field.NewString(tableName, "address") + _bank.Scale = field.NewInt64(tableName, "scale") + + _bank.fillFieldMap() + + return _bank +} + +type bank struct { + bankDo bankDo + + ALL field.Asterisk + ID field.Int64 + Name field.String + Address field.String + Scale field.Int64 + + fieldMap map[string]field.Expr +} + +func (b bank) Table(newTableName string) *bank { + b.bankDo.UseTable(newTableName) + return b.updateTableName(newTableName) +} + +func (b bank) As(alias string) *bank { + b.bankDo.DO = *(b.bankDo.As(alias).(*gen.DO)) + return b.updateTableName(alias) +} + +func (b *bank) updateTableName(table string) *bank { + b.ALL = field.NewAsterisk(table) + b.ID = field.NewInt64(table, "id") + b.Name = field.NewString(table, "name") + b.Address = field.NewString(table, "address") + b.Scale = field.NewInt64(table, "scale") + + b.fillFieldMap() + + return b +} + +func (b *bank) WithContext(ctx context.Context) IBankDo { return b.bankDo.WithContext(ctx) } + +func (b bank) TableName() string { return b.bankDo.TableName() } + +func (b bank) Alias() string { return b.bankDo.Alias() } + +func (b *bank) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := b.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (b *bank) fillFieldMap() { + b.fieldMap = make(map[string]field.Expr, 4) + b.fieldMap["id"] = b.ID + b.fieldMap["name"] = b.Name + b.fieldMap["address"] = b.Address + b.fieldMap["scale"] = b.Scale +} + +func (b bank) clone(db *gorm.DB) bank { + b.bankDo.ReplaceConnPool(db.Statement.ConnPool) + return b +} + +func (b bank) replaceDB(db *gorm.DB) bank { + b.bankDo.ReplaceDB(db) + return b +} + +type bankDo struct{ gen.DO } + +type IBankDo interface { + gen.SubQuery + Debug() IBankDo + WithContext(ctx context.Context) IBankDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IBankDo + WriteDB() IBankDo + As(alias string) gen.Dao + Session(config *gorm.Session) IBankDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IBankDo + Not(conds ...gen.Condition) IBankDo + Or(conds ...gen.Condition) IBankDo + Select(conds ...field.Expr) IBankDo + Where(conds ...gen.Condition) IBankDo + Order(conds ...field.Expr) IBankDo + Distinct(cols ...field.Expr) IBankDo + Omit(cols ...field.Expr) IBankDo + Join(table schema.Tabler, on ...field.Expr) IBankDo + LeftJoin(table schema.Tabler, on ...field.Expr) IBankDo + RightJoin(table schema.Tabler, on ...field.Expr) IBankDo + Group(cols ...field.Expr) IBankDo + Having(conds ...gen.Condition) IBankDo + Limit(limit int) IBankDo + Offset(offset int) IBankDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IBankDo + Unscoped() IBankDo + Create(values ...*model.Bank) error + CreateInBatches(values []*model.Bank, batchSize int) error + Save(values ...*model.Bank) error + First() (*model.Bank, error) + Take() (*model.Bank, error) + Last() (*model.Bank, error) + Find() ([]*model.Bank, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Bank, err error) + FindInBatches(result *[]*model.Bank, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*model.Bank) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) IBankDo + Assign(attrs ...field.AssignExpr) IBankDo + Joins(fields ...field.RelationField) IBankDo + Preload(fields ...field.RelationField) IBankDo + FirstOrInit() (*model.Bank, error) + FirstOrCreate() (*model.Bank, error) + FindByPage(offset int, limit int) (result []*model.Bank, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) IBankDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (b bankDo) Debug() IBankDo { + return b.withDO(b.DO.Debug()) +} + +func (b bankDo) WithContext(ctx context.Context) IBankDo { + return b.withDO(b.DO.WithContext(ctx)) +} + +func (b bankDo) ReadDB() IBankDo { + return b.Clauses(dbresolver.Read) +} + +func (b bankDo) WriteDB() IBankDo { + return b.Clauses(dbresolver.Write) +} + +func (b bankDo) Session(config *gorm.Session) IBankDo { + return b.withDO(b.DO.Session(config)) +} + +func (b bankDo) Clauses(conds ...clause.Expression) IBankDo { + return b.withDO(b.DO.Clauses(conds...)) +} + +func (b bankDo) Returning(value interface{}, columns ...string) IBankDo { + return b.withDO(b.DO.Returning(value, columns...)) +} + +func (b bankDo) Not(conds ...gen.Condition) IBankDo { + return b.withDO(b.DO.Not(conds...)) +} + +func (b bankDo) Or(conds ...gen.Condition) IBankDo { + return b.withDO(b.DO.Or(conds...)) +} + +func (b bankDo) Select(conds ...field.Expr) IBankDo { + return b.withDO(b.DO.Select(conds...)) +} + +func (b bankDo) Where(conds ...gen.Condition) IBankDo { + return b.withDO(b.DO.Where(conds...)) +} + +func (b bankDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IBankDo { + return b.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) +} + +func (b bankDo) Order(conds ...field.Expr) IBankDo { + return b.withDO(b.DO.Order(conds...)) +} + +func (b bankDo) Distinct(cols ...field.Expr) IBankDo { + return b.withDO(b.DO.Distinct(cols...)) +} + +func (b bankDo) Omit(cols ...field.Expr) IBankDo { + return b.withDO(b.DO.Omit(cols...)) +} + +func (b bankDo) Join(table schema.Tabler, on ...field.Expr) IBankDo { + return b.withDO(b.DO.Join(table, on...)) +} + +func (b bankDo) LeftJoin(table schema.Tabler, on ...field.Expr) IBankDo { + return b.withDO(b.DO.LeftJoin(table, on...)) +} + +func (b bankDo) RightJoin(table schema.Tabler, on ...field.Expr) IBankDo { + return b.withDO(b.DO.RightJoin(table, on...)) +} + +func (b bankDo) Group(cols ...field.Expr) IBankDo { + return b.withDO(b.DO.Group(cols...)) +} + +func (b bankDo) Having(conds ...gen.Condition) IBankDo { + return b.withDO(b.DO.Having(conds...)) +} + +func (b bankDo) Limit(limit int) IBankDo { + return b.withDO(b.DO.Limit(limit)) +} + +func (b bankDo) Offset(offset int) IBankDo { + return b.withDO(b.DO.Offset(offset)) +} + +func (b bankDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IBankDo { + return b.withDO(b.DO.Scopes(funcs...)) +} + +func (b bankDo) Unscoped() IBankDo { + return b.withDO(b.DO.Unscoped()) +} + +func (b bankDo) Create(values ...*model.Bank) error { + if len(values) == 0 { + return nil + } + return b.DO.Create(values) +} + +func (b bankDo) CreateInBatches(values []*model.Bank, batchSize int) error { + return b.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (b bankDo) Save(values ...*model.Bank) error { + if len(values) == 0 { + return nil + } + return b.DO.Save(values) +} + +func (b bankDo) First() (*model.Bank, error) { + if result, err := b.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Bank), nil + } +} + +func (b bankDo) Take() (*model.Bank, error) { + if result, err := b.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Bank), nil + } +} + +func (b bankDo) Last() (*model.Bank, error) { + if result, err := b.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Bank), nil + } +} + +func (b bankDo) Find() ([]*model.Bank, error) { + result, err := b.DO.Find() + return result.([]*model.Bank), err +} + +func (b bankDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Bank, err error) { + buf := make([]*model.Bank, 0, batchSize) + err = b.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (b bankDo) FindInBatches(result *[]*model.Bank, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return b.DO.FindInBatches(result, batchSize, fc) +} + +func (b bankDo) Attrs(attrs ...field.AssignExpr) IBankDo { + return b.withDO(b.DO.Attrs(attrs...)) +} + +func (b bankDo) Assign(attrs ...field.AssignExpr) IBankDo { + return b.withDO(b.DO.Assign(attrs...)) +} + +func (b bankDo) Joins(fields ...field.RelationField) IBankDo { + for _, _f := range fields { + b = *b.withDO(b.DO.Joins(_f)) + } + return &b +} + +func (b bankDo) Preload(fields ...field.RelationField) IBankDo { + for _, _f := range fields { + b = *b.withDO(b.DO.Preload(_f)) + } + return &b +} + +func (b bankDo) FirstOrInit() (*model.Bank, error) { + if result, err := b.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Bank), nil + } +} + +func (b bankDo) FirstOrCreate() (*model.Bank, error) { + if result, err := b.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Bank), nil + } +} + +func (b bankDo) FindByPage(offset int, limit int) (result []*model.Bank, count int64, err error) { + result, err = b.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = b.Offset(-1).Limit(-1).Count() + return +} + +func (b bankDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = b.Count() + if err != nil { + return + } + + err = b.Offset(offset).Limit(limit).Scan(result) + return +} + +func (b bankDo) Scan(result interface{}) (err error) { + return b.DO.Scan(result) +} + +func (b bankDo) Delete(models ...*model.Bank) (result gen.ResultInfo, err error) { + return b.DO.Delete(models) +} + +func (b *bankDo) withDO(do gen.Dao) *bankDo { + b.DO = *do.(*gen.DO) + return b +} diff --git a/tests/.expect/dal_4/query/banks.gen_test.go b/tests/.expect/dal_4/query/banks.gen_test.go new file mode 100644 index 00000000..e7aee2e2 --- /dev/null +++ b/tests/.expect/dal_4/query/banks.gen_test.go @@ -0,0 +1,145 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "testing" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/tests/.gen/dal_4/model" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.Bank{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.Bank{}) fail: %s", err) + } +} + +func Test_bankQuery(t *testing.T) { + bank := newBank(db) + bank = *bank.As(bank.TableName()) + _do := bank.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(bank.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := bank.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from bank success") + } + + err = _do.Create(&model.Bank{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.Bank{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.Bank{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(bank.ALL).Take() + if err != nil { + t.Error("Take() on table fail:", err) + } + + _, err = _do.First() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Last() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatch() on table fail:", err) + } + + err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.Bank{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(bank.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find() + if err != nil { + t.Error("Find() on table fail:", err) + } + + _, err = _do.Distinct(primaryKey).Take() + if err != nil { + t.Error("select Distinct() on table fail:", err) + } + + _, err = _do.Select(bank.ALL).Omit(primaryKey).Take() + if err != nil { + t.Error("Omit() on table fail:", err) + } + + _, err = _do.Group(primaryKey).Find() + if err != nil { + t.Error("Group() on table fail:", err) + } + + _, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find() + if err != nil { + t.Error("Scopes() on table fail:", err) + } + + _, _, err = _do.FindByPage(0, 1) + if err != nil { + t.Error("FindByPage() on table fail:", err) + } + + _, err = _do.ScanByPage(&model.Bank{}, 0, 1) + if err != nil { + t.Error("ScanByPage() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit() + if err != nil { + t.Error("FirstOrInit() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate() + if err != nil { + t.Error("FirstOrCreate() on table fail:", err) + } + + var _a _another + var _aPK = field.NewString(_a.TableName(), clause.PrimaryKey) + + err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("Join() on table fail:", err) + } + + err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("LeftJoin() on table fail:", err) + } + + _, err = _do.Not().Or().Clauses().Take() + if err != nil { + t.Error("Not/Or/Clauses on table fail:", err) + } +} diff --git a/tests/.expect/dal_4/query/credit_cards.gen.go b/tests/.expect/dal_4/query/credit_cards.gen.go new file mode 100644 index 00000000..b6552a8a --- /dev/null +++ b/tests/.expect/dal_4/query/credit_cards.gen.go @@ -0,0 +1,416 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "gorm.io/gen/tests/.gen/dal_4/model" +) + +func newCreditCard(db *gorm.DB, opts ...gen.DOOption) creditCard { + _creditCard := creditCard{} + + _creditCard.creditCardDo.UseDB(db, opts...) + _creditCard.creditCardDo.UseModel(&model.CreditCard{}) + + tableName := _creditCard.creditCardDo.TableName() + _creditCard.ALL = field.NewAsterisk(tableName) + _creditCard.ID = field.NewInt64(tableName, "id") + _creditCard.CreatedAt = field.NewTime(tableName, "created_at") + _creditCard.UpdatedAt = field.NewTime(tableName, "updated_at") + _creditCard.DeletedAt = field.NewField(tableName, "deleted_at") + _creditCard.Number = field.NewString(tableName, "number") + _creditCard.CustomerRefer = field.NewInt64(tableName, "customer_refer") + _creditCard.BankID = field.NewInt64(tableName, "bank_id") + + _creditCard.fillFieldMap() + + return _creditCard +} + +type creditCard struct { + creditCardDo creditCardDo + + ALL field.Asterisk + ID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Number field.String + CustomerRefer field.Int64 + BankID field.Int64 + + fieldMap map[string]field.Expr +} + +func (c creditCard) Table(newTableName string) *creditCard { + c.creditCardDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c creditCard) As(alias string) *creditCard { + c.creditCardDo.DO = *(c.creditCardDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *creditCard) updateTableName(table string) *creditCard { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + c.Number = field.NewString(table, "number") + c.CustomerRefer = field.NewInt64(table, "customer_refer") + c.BankID = field.NewInt64(table, "bank_id") + + c.fillFieldMap() + + return c +} + +func (c *creditCard) WithContext(ctx context.Context) ICreditCardDo { + return c.creditCardDo.WithContext(ctx) +} + +func (c creditCard) TableName() string { return c.creditCardDo.TableName() } + +func (c creditCard) Alias() string { return c.creditCardDo.Alias() } + +func (c *creditCard) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *creditCard) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 7) + c.fieldMap["id"] = c.ID + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt + c.fieldMap["number"] = c.Number + c.fieldMap["customer_refer"] = c.CustomerRefer + c.fieldMap["bank_id"] = c.BankID +} + +func (c creditCard) clone(db *gorm.DB) creditCard { + c.creditCardDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c creditCard) replaceDB(db *gorm.DB) creditCard { + c.creditCardDo.ReplaceDB(db) + return c +} + +type creditCardDo struct{ gen.DO } + +type ICreditCardDo interface { + gen.SubQuery + Debug() ICreditCardDo + WithContext(ctx context.Context) ICreditCardDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() ICreditCardDo + WriteDB() ICreditCardDo + As(alias string) gen.Dao + Session(config *gorm.Session) ICreditCardDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) ICreditCardDo + Not(conds ...gen.Condition) ICreditCardDo + Or(conds ...gen.Condition) ICreditCardDo + Select(conds ...field.Expr) ICreditCardDo + Where(conds ...gen.Condition) ICreditCardDo + Order(conds ...field.Expr) ICreditCardDo + Distinct(cols ...field.Expr) ICreditCardDo + Omit(cols ...field.Expr) ICreditCardDo + Join(table schema.Tabler, on ...field.Expr) ICreditCardDo + LeftJoin(table schema.Tabler, on ...field.Expr) ICreditCardDo + RightJoin(table schema.Tabler, on ...field.Expr) ICreditCardDo + Group(cols ...field.Expr) ICreditCardDo + Having(conds ...gen.Condition) ICreditCardDo + Limit(limit int) ICreditCardDo + Offset(offset int) ICreditCardDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) ICreditCardDo + Unscoped() ICreditCardDo + Create(values ...*model.CreditCard) error + CreateInBatches(values []*model.CreditCard, batchSize int) error + Save(values ...*model.CreditCard) error + First() (*model.CreditCard, error) + Take() (*model.CreditCard, error) + Last() (*model.CreditCard, error) + Find() ([]*model.CreditCard, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.CreditCard, err error) + FindInBatches(result *[]*model.CreditCard, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*model.CreditCard) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) ICreditCardDo + Assign(attrs ...field.AssignExpr) ICreditCardDo + Joins(fields ...field.RelationField) ICreditCardDo + Preload(fields ...field.RelationField) ICreditCardDo + FirstOrInit() (*model.CreditCard, error) + FirstOrCreate() (*model.CreditCard, error) + FindByPage(offset int, limit int) (result []*model.CreditCard, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) ICreditCardDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (c creditCardDo) Debug() ICreditCardDo { + return c.withDO(c.DO.Debug()) +} + +func (c creditCardDo) WithContext(ctx context.Context) ICreditCardDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c creditCardDo) ReadDB() ICreditCardDo { + return c.Clauses(dbresolver.Read) +} + +func (c creditCardDo) WriteDB() ICreditCardDo { + return c.Clauses(dbresolver.Write) +} + +func (c creditCardDo) Session(config *gorm.Session) ICreditCardDo { + return c.withDO(c.DO.Session(config)) +} + +func (c creditCardDo) Clauses(conds ...clause.Expression) ICreditCardDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c creditCardDo) Returning(value interface{}, columns ...string) ICreditCardDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c creditCardDo) Not(conds ...gen.Condition) ICreditCardDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c creditCardDo) Or(conds ...gen.Condition) ICreditCardDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c creditCardDo) Select(conds ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c creditCardDo) Where(conds ...gen.Condition) ICreditCardDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c creditCardDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ICreditCardDo { + return c.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) +} + +func (c creditCardDo) Order(conds ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c creditCardDo) Distinct(cols ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c creditCardDo) Omit(cols ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c creditCardDo) Join(table schema.Tabler, on ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c creditCardDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c creditCardDo) RightJoin(table schema.Tabler, on ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c creditCardDo) Group(cols ...field.Expr) ICreditCardDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c creditCardDo) Having(conds ...gen.Condition) ICreditCardDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c creditCardDo) Limit(limit int) ICreditCardDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c creditCardDo) Offset(offset int) ICreditCardDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c creditCardDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICreditCardDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c creditCardDo) Unscoped() ICreditCardDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c creditCardDo) Create(values ...*model.CreditCard) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c creditCardDo) CreateInBatches(values []*model.CreditCard, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c creditCardDo) Save(values ...*model.CreditCard) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c creditCardDo) First() (*model.CreditCard, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.CreditCard), nil + } +} + +func (c creditCardDo) Take() (*model.CreditCard, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.CreditCard), nil + } +} + +func (c creditCardDo) Last() (*model.CreditCard, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.CreditCard), nil + } +} + +func (c creditCardDo) Find() ([]*model.CreditCard, error) { + result, err := c.DO.Find() + return result.([]*model.CreditCard), err +} + +func (c creditCardDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.CreditCard, err error) { + buf := make([]*model.CreditCard, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c creditCardDo) FindInBatches(result *[]*model.CreditCard, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c creditCardDo) Attrs(attrs ...field.AssignExpr) ICreditCardDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c creditCardDo) Assign(attrs ...field.AssignExpr) ICreditCardDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c creditCardDo) Joins(fields ...field.RelationField) ICreditCardDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c creditCardDo) Preload(fields ...field.RelationField) ICreditCardDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c creditCardDo) FirstOrInit() (*model.CreditCard, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.CreditCard), nil + } +} + +func (c creditCardDo) FirstOrCreate() (*model.CreditCard, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.CreditCard), nil + } +} + +func (c creditCardDo) FindByPage(offset int, limit int) (result []*model.CreditCard, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c creditCardDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c creditCardDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c creditCardDo) Delete(models ...*model.CreditCard) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +func (c *creditCardDo) withDO(do gen.Dao) *creditCardDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/tests/.expect/dal_4/query/credit_cards.gen_test.go b/tests/.expect/dal_4/query/credit_cards.gen_test.go new file mode 100644 index 00000000..c5ce2519 --- /dev/null +++ b/tests/.expect/dal_4/query/credit_cards.gen_test.go @@ -0,0 +1,145 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "testing" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/tests/.gen/dal_4/model" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.CreditCard{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.CreditCard{}) fail: %s", err) + } +} + +func Test_creditCardQuery(t *testing.T) { + creditCard := newCreditCard(db) + creditCard = *creditCard.As(creditCard.TableName()) + _do := creditCard.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(creditCard.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := creditCard.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from creditCard success") + } + + err = _do.Create(&model.CreditCard{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.CreditCard{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.CreditCard{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(creditCard.ALL).Take() + if err != nil { + t.Error("Take() on table fail:", err) + } + + _, err = _do.First() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Last() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatch() on table fail:", err) + } + + err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.CreditCard{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(creditCard.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find() + if err != nil { + t.Error("Find() on table fail:", err) + } + + _, err = _do.Distinct(primaryKey).Take() + if err != nil { + t.Error("select Distinct() on table fail:", err) + } + + _, err = _do.Select(creditCard.ALL).Omit(primaryKey).Take() + if err != nil { + t.Error("Omit() on table fail:", err) + } + + _, err = _do.Group(primaryKey).Find() + if err != nil { + t.Error("Group() on table fail:", err) + } + + _, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find() + if err != nil { + t.Error("Scopes() on table fail:", err) + } + + _, _, err = _do.FindByPage(0, 1) + if err != nil { + t.Error("FindByPage() on table fail:", err) + } + + _, err = _do.ScanByPage(&model.CreditCard{}, 0, 1) + if err != nil { + t.Error("ScanByPage() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit() + if err != nil { + t.Error("FirstOrInit() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate() + if err != nil { + t.Error("FirstOrCreate() on table fail:", err) + } + + var _a _another + var _aPK = field.NewString(_a.TableName(), clause.PrimaryKey) + + err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("Join() on table fail:", err) + } + + err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("LeftJoin() on table fail:", err) + } + + _, err = _do.Not().Or().Clauses().Take() + if err != nil { + t.Error("Not/Or/Clauses on table fail:", err) + } +} diff --git a/tests/.expect/dal_4/query/customers.gen.go b/tests/.expect/dal_4/query/customers.gen.go new file mode 100644 index 00000000..9b726e65 --- /dev/null +++ b/tests/.expect/dal_4/query/customers.gen.go @@ -0,0 +1,406 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "gorm.io/gen/tests/.gen/dal_4/model" +) + +func newCustomer(db *gorm.DB, opts ...gen.DOOption) customer { + _customer := customer{} + + _customer.customerDo.UseDB(db, opts...) + _customer.customerDo.UseModel(&model.Customer{}) + + tableName := _customer.customerDo.TableName() + _customer.ALL = field.NewAsterisk(tableName) + _customer.ID = field.NewInt64(tableName, "id") + _customer.CreatedAt = field.NewTime(tableName, "created_at") + _customer.UpdatedAt = field.NewTime(tableName, "updated_at") + _customer.DeletedAt = field.NewField(tableName, "deleted_at") + _customer.BankID = field.NewInt64(tableName, "bank_id") + + _customer.fillFieldMap() + + return _customer +} + +type customer struct { + customerDo customerDo + + ALL field.Asterisk + ID field.Int64 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + BankID field.Int64 + + fieldMap map[string]field.Expr +} + +func (c customer) Table(newTableName string) *customer { + c.customerDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c customer) As(alias string) *customer { + c.customerDo.DO = *(c.customerDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *customer) updateTableName(table string) *customer { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewInt64(table, "id") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + c.BankID = field.NewInt64(table, "bank_id") + + c.fillFieldMap() + + return c +} + +func (c *customer) WithContext(ctx context.Context) ICustomerDo { return c.customerDo.WithContext(ctx) } + +func (c customer) TableName() string { return c.customerDo.TableName() } + +func (c customer) Alias() string { return c.customerDo.Alias() } + +func (c *customer) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *customer) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 5) + c.fieldMap["id"] = c.ID + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt + c.fieldMap["bank_id"] = c.BankID +} + +func (c customer) clone(db *gorm.DB) customer { + c.customerDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c customer) replaceDB(db *gorm.DB) customer { + c.customerDo.ReplaceDB(db) + return c +} + +type customerDo struct{ gen.DO } + +type ICustomerDo interface { + gen.SubQuery + Debug() ICustomerDo + WithContext(ctx context.Context) ICustomerDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() ICustomerDo + WriteDB() ICustomerDo + As(alias string) gen.Dao + Session(config *gorm.Session) ICustomerDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) ICustomerDo + Not(conds ...gen.Condition) ICustomerDo + Or(conds ...gen.Condition) ICustomerDo + Select(conds ...field.Expr) ICustomerDo + Where(conds ...gen.Condition) ICustomerDo + Order(conds ...field.Expr) ICustomerDo + Distinct(cols ...field.Expr) ICustomerDo + Omit(cols ...field.Expr) ICustomerDo + Join(table schema.Tabler, on ...field.Expr) ICustomerDo + LeftJoin(table schema.Tabler, on ...field.Expr) ICustomerDo + RightJoin(table schema.Tabler, on ...field.Expr) ICustomerDo + Group(cols ...field.Expr) ICustomerDo + Having(conds ...gen.Condition) ICustomerDo + Limit(limit int) ICustomerDo + Offset(offset int) ICustomerDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) ICustomerDo + Unscoped() ICustomerDo + Create(values ...*model.Customer) error + CreateInBatches(values []*model.Customer, batchSize int) error + Save(values ...*model.Customer) error + First() (*model.Customer, error) + Take() (*model.Customer, error) + Last() (*model.Customer, error) + Find() ([]*model.Customer, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Customer, err error) + FindInBatches(result *[]*model.Customer, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*model.Customer) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) ICustomerDo + Assign(attrs ...field.AssignExpr) ICustomerDo + Joins(fields ...field.RelationField) ICustomerDo + Preload(fields ...field.RelationField) ICustomerDo + FirstOrInit() (*model.Customer, error) + FirstOrCreate() (*model.Customer, error) + FindByPage(offset int, limit int) (result []*model.Customer, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) ICustomerDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (c customerDo) Debug() ICustomerDo { + return c.withDO(c.DO.Debug()) +} + +func (c customerDo) WithContext(ctx context.Context) ICustomerDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c customerDo) ReadDB() ICustomerDo { + return c.Clauses(dbresolver.Read) +} + +func (c customerDo) WriteDB() ICustomerDo { + return c.Clauses(dbresolver.Write) +} + +func (c customerDo) Session(config *gorm.Session) ICustomerDo { + return c.withDO(c.DO.Session(config)) +} + +func (c customerDo) Clauses(conds ...clause.Expression) ICustomerDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c customerDo) Returning(value interface{}, columns ...string) ICustomerDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c customerDo) Not(conds ...gen.Condition) ICustomerDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c customerDo) Or(conds ...gen.Condition) ICustomerDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c customerDo) Select(conds ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c customerDo) Where(conds ...gen.Condition) ICustomerDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c customerDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ICustomerDo { + return c.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) +} + +func (c customerDo) Order(conds ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c customerDo) Distinct(cols ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c customerDo) Omit(cols ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c customerDo) Join(table schema.Tabler, on ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c customerDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICustomerDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c customerDo) RightJoin(table schema.Tabler, on ...field.Expr) ICustomerDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c customerDo) Group(cols ...field.Expr) ICustomerDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c customerDo) Having(conds ...gen.Condition) ICustomerDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c customerDo) Limit(limit int) ICustomerDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c customerDo) Offset(offset int) ICustomerDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c customerDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICustomerDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c customerDo) Unscoped() ICustomerDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c customerDo) Create(values ...*model.Customer) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c customerDo) CreateInBatches(values []*model.Customer, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c customerDo) Save(values ...*model.Customer) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c customerDo) First() (*model.Customer, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Customer), nil + } +} + +func (c customerDo) Take() (*model.Customer, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Customer), nil + } +} + +func (c customerDo) Last() (*model.Customer, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Customer), nil + } +} + +func (c customerDo) Find() ([]*model.Customer, error) { + result, err := c.DO.Find() + return result.([]*model.Customer), err +} + +func (c customerDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Customer, err error) { + buf := make([]*model.Customer, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c customerDo) FindInBatches(result *[]*model.Customer, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c customerDo) Attrs(attrs ...field.AssignExpr) ICustomerDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c customerDo) Assign(attrs ...field.AssignExpr) ICustomerDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c customerDo) Joins(fields ...field.RelationField) ICustomerDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c customerDo) Preload(fields ...field.RelationField) ICustomerDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c customerDo) FirstOrInit() (*model.Customer, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Customer), nil + } +} + +func (c customerDo) FirstOrCreate() (*model.Customer, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Customer), nil + } +} + +func (c customerDo) FindByPage(offset int, limit int) (result []*model.Customer, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c customerDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c customerDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c customerDo) Delete(models ...*model.Customer) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +func (c *customerDo) withDO(do gen.Dao) *customerDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/tests/.expect/dal_4/query/customers.gen_test.go b/tests/.expect/dal_4/query/customers.gen_test.go new file mode 100644 index 00000000..04b85e28 --- /dev/null +++ b/tests/.expect/dal_4/query/customers.gen_test.go @@ -0,0 +1,145 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "testing" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/tests/.gen/dal_4/model" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.Customer{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.Customer{}) fail: %s", err) + } +} + +func Test_customerQuery(t *testing.T) { + customer := newCustomer(db) + customer = *customer.As(customer.TableName()) + _do := customer.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(customer.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := customer.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from customer success") + } + + err = _do.Create(&model.Customer{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.Customer{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.Customer{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(customer.ALL).Take() + if err != nil { + t.Error("Take() on table fail:", err) + } + + _, err = _do.First() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Last() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatch() on table fail:", err) + } + + err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.Customer{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(customer.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find() + if err != nil { + t.Error("Find() on table fail:", err) + } + + _, err = _do.Distinct(primaryKey).Take() + if err != nil { + t.Error("select Distinct() on table fail:", err) + } + + _, err = _do.Select(customer.ALL).Omit(primaryKey).Take() + if err != nil { + t.Error("Omit() on table fail:", err) + } + + _, err = _do.Group(primaryKey).Find() + if err != nil { + t.Error("Group() on table fail:", err) + } + + _, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find() + if err != nil { + t.Error("Scopes() on table fail:", err) + } + + _, _, err = _do.FindByPage(0, 1) + if err != nil { + t.Error("FindByPage() on table fail:", err) + } + + _, err = _do.ScanByPage(&model.Customer{}, 0, 1) + if err != nil { + t.Error("ScanByPage() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit() + if err != nil { + t.Error("FirstOrInit() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate() + if err != nil { + t.Error("FirstOrCreate() on table fail:", err) + } + + var _a _another + var _aPK = field.NewString(_a.TableName(), clause.PrimaryKey) + + err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("Join() on table fail:", err) + } + + err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("LeftJoin() on table fail:", err) + } + + _, err = _do.Not().Or().Clauses().Take() + if err != nil { + t.Error("Not/Or/Clauses on table fail:", err) + } +} diff --git a/tests/.expect/dal_4/query/gen.go b/tests/.expect/dal_4/query/gen.go new file mode 100644 index 00000000..53b8245e --- /dev/null +++ b/tests/.expect/dal_4/query/gen.go @@ -0,0 +1,131 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "database/sql" + + "gorm.io/gorm" + + "gorm.io/gen" + + "gorm.io/plugin/dbresolver" +) + +var ( + Q = new(Query) + Bank *bank + CreditCard *creditCard + Customer *customer + Person *person + User *user +) + +func SetDefault(db *gorm.DB, opts ...gen.DOOption) { + *Q = *Use(db, opts...) + Bank = &Q.Bank + CreditCard = &Q.CreditCard + Customer = &Q.Customer + Person = &Q.Person + User = &Q.User +} + +func Use(db *gorm.DB, opts ...gen.DOOption) *Query { + return &Query{ + db: db, + Bank: newBank(db, opts...), + CreditCard: newCreditCard(db, opts...), + Customer: newCustomer(db, opts...), + Person: newPerson(db, opts...), + User: newUser(db, opts...), + } +} + +type Query struct { + db *gorm.DB + + Bank bank + CreditCard creditCard + Customer customer + Person person + User user +} + +func (q *Query) Available() bool { return q.db != nil } + +func (q *Query) clone(db *gorm.DB) *Query { + return &Query{ + db: db, + Bank: q.Bank.clone(db), + CreditCard: q.CreditCard.clone(db), + Customer: q.Customer.clone(db), + Person: q.Person.clone(db), + User: q.User.clone(db), + } +} + +func (q *Query) ReadDB() *Query { + return q.ReplaceDB(q.db.Clauses(dbresolver.Read)) +} + +func (q *Query) WriteDB() *Query { + return q.ReplaceDB(q.db.Clauses(dbresolver.Write)) +} + +func (q *Query) ReplaceDB(db *gorm.DB) *Query { + return &Query{ + db: db, + Bank: q.Bank.replaceDB(db), + CreditCard: q.CreditCard.replaceDB(db), + Customer: q.Customer.replaceDB(db), + Person: q.Person.replaceDB(db), + User: q.User.replaceDB(db), + } +} + +type queryCtx struct { + Bank IBankDo + CreditCard ICreditCardDo + Customer ICustomerDo + Person IPersonDo + User IUserDo +} + +func (q *Query) WithContext(ctx context.Context) *queryCtx { + return &queryCtx{ + Bank: q.Bank.WithContext(ctx), + CreditCard: q.CreditCard.WithContext(ctx), + Customer: q.Customer.WithContext(ctx), + Person: q.Person.WithContext(ctx), + User: q.User.WithContext(ctx), + } +} + +func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error { + return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...) +} + +func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx { + return &QueryTx{q.clone(q.db.Begin(opts...))} +} + +type QueryTx struct{ *Query } + +func (q *QueryTx) Commit() error { + return q.db.Commit().Error +} + +func (q *QueryTx) Rollback() error { + return q.db.Rollback().Error +} + +func (q *QueryTx) SavePoint(name string) error { + return q.db.SavePoint(name).Error +} + +func (q *QueryTx) RollbackTo(name string) error { + return q.db.RollbackTo(name).Error +} diff --git a/tests/.expect/dal_4/query/gen_test.go b/tests/.expect/dal_4/query/gen_test.go new file mode 100644 index 00000000..9416fe5f --- /dev/null +++ b/tests/.expect/dal_4/query/gen_test.go @@ -0,0 +1,122 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "reflect" + "sync" + "testing" + + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +type Input struct { + Args []interface{} +} + +type Expectation struct { + Ret []interface{} +} + +type TestCase struct { + Input + Expectation +} + +const dbName = "gen_test.db" + +var db *gorm.DB +var once sync.Once + +func init() { + InitializeDB() + db.AutoMigrate(&_another{}) +} + +func InitializeDB() { + once.Do(func() { + var err error + db, err = gorm.Open(sqlite.Open(dbName), &gorm.Config{}) + if err != nil { + panic(fmt.Errorf("open sqlite %q fail: %w", dbName, err)) + } + }) +} + +func assert(t *testing.T, methodName string, res, exp interface{}) { + if !reflect.DeepEqual(res, exp) { + t.Errorf("%v() gotResult = %v, want %v", methodName, res, exp) + } +} + +type _another struct { + ID uint64 `gorm:"primaryKey"` +} + +func (*_another) TableName() string { return "another_for_unit_test" } + +func Test_Available(t *testing.T) { + if !Use(db).Available() { + t.Errorf("query.Available() == false") + } +} + +func Test_WithContext(t *testing.T) { + query := Use(db) + if !query.Available() { + t.Errorf("query Use(db) fail: query.Available() == false") + } + + type Content string + var key, value Content = "gen_tag", "unit_test" + qCtx := query.WithContext(context.WithValue(context.Background(), key, value)) + + for _, ctx := range []context.Context{ + qCtx.Bank.UnderlyingDB().Statement.Context, + qCtx.CreditCard.UnderlyingDB().Statement.Context, + qCtx.Customer.UnderlyingDB().Statement.Context, + qCtx.Person.UnderlyingDB().Statement.Context, + qCtx.User.UnderlyingDB().Statement.Context, + } { + if v := ctx.Value(key); v != value { + t.Errorf("get value from context fail, expect %q, got %q", value, v) + } + } +} + +func Test_Transaction(t *testing.T) { + query := Use(db) + if !query.Available() { + t.Errorf("query Use(db) fail: query.Available() == false") + } + + err := query.Transaction(func(tx *Query) error { return nil }) + if err != nil { + t.Errorf("query.Transaction execute fail: %s", err) + } + + tx := query.Begin() + + err = tx.SavePoint("point") + if err != nil { + t.Errorf("query tx SavePoint fail: %s", err) + } + err = tx.RollbackTo("point") + if err != nil { + t.Errorf("query tx RollbackTo fail: %s", err) + } + err = tx.Commit() + if err != nil { + t.Errorf("query tx Commit fail: %s", err) + } + + err = query.Begin().Rollback() + if err != nil { + t.Errorf("query tx Rollback fail: %s", err) + } +} diff --git a/tests/.expect/dal_4/query/people.gen.go b/tests/.expect/dal_4/query/people.gen.go new file mode 100644 index 00000000..103ab9e3 --- /dev/null +++ b/tests/.expect/dal_4/query/people.gen.go @@ -0,0 +1,470 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "gorm.io/gen/tests/.gen/dal_4/model" +) + +func newPerson(db *gorm.DB, opts ...gen.DOOption) person { + _person := person{} + + _person.personDo.UseDB(db, opts...) + _person.personDo.UseModel(&model.Person{}) + + tableName := _person.personDo.TableName() + _person.ALL = field.NewAsterisk(tableName) + _person.ID = field.NewInt64(tableName, "id") + _person.Name = field.NewString(tableName, "name") + _person.Alias_ = field.NewString(tableName, "alias") + _person.Age = field.NewInt32(tableName, "age") + _person.Flag = field.NewBool(tableName, "flag") + _person.AnotherFlag = field.NewInt32(tableName, "another_flag") + _person.Commit = field.NewString(tableName, "commit") + _person.First = field.NewBool(tableName, "First") + _person.Bit = field.NewField(tableName, "bit") + _person.Small = field.NewInt32(tableName, "small") + _person.DeletedAt = field.NewField(tableName, "deleted_at") + _person.Score = field.NewFloat64(tableName, "score") + _person.Number = field.NewInt32(tableName, "number") + _person.Birth = field.NewTime(tableName, "birth") + _person.XMLHTTPRequest = field.NewString(tableName, "xmlHTTPRequest") + _person.JStr = field.NewString(tableName, "jStr") + _person.Geo = field.NewString(tableName, "geo") + _person.Mint = field.NewInt32(tableName, "mint") + _person.Blank = field.NewString(tableName, "blank") + _person.Remark = field.NewString(tableName, "remark") + _person.LongRemark = field.NewString(tableName, "long_remark") + + _person.fillFieldMap() + + return _person +} + +type person struct { + personDo personDo + + ALL field.Asterisk + ID field.Int64 + Name field.String + Alias_ field.String + Age field.Int32 + Flag field.Bool + AnotherFlag field.Int32 + Commit field.String + First field.Bool + Bit field.Field + Small field.Int32 + DeletedAt field.Field + Score field.Float64 + Number field.Int32 + Birth field.Time + XMLHTTPRequest field.String + JStr field.String + Geo field.String + Mint field.Int32 + Blank field.String + Remark field.String + LongRemark field.String + + fieldMap map[string]field.Expr +} + +func (p person) Table(newTableName string) *person { + p.personDo.UseTable(newTableName) + return p.updateTableName(newTableName) +} + +func (p person) As(alias string) *person { + p.personDo.DO = *(p.personDo.As(alias).(*gen.DO)) + return p.updateTableName(alias) +} + +func (p *person) updateTableName(table string) *person { + p.ALL = field.NewAsterisk(table) + p.ID = field.NewInt64(table, "id") + p.Name = field.NewString(table, "name") + p.Alias_ = field.NewString(table, "alias") + p.Age = field.NewInt32(table, "age") + p.Flag = field.NewBool(table, "flag") + p.AnotherFlag = field.NewInt32(table, "another_flag") + p.Commit = field.NewString(table, "commit") + p.First = field.NewBool(table, "First") + p.Bit = field.NewField(table, "bit") + p.Small = field.NewInt32(table, "small") + p.DeletedAt = field.NewField(table, "deleted_at") + p.Score = field.NewFloat64(table, "score") + p.Number = field.NewInt32(table, "number") + p.Birth = field.NewTime(table, "birth") + p.XMLHTTPRequest = field.NewString(table, "xmlHTTPRequest") + p.JStr = field.NewString(table, "jStr") + p.Geo = field.NewString(table, "geo") + p.Mint = field.NewInt32(table, "mint") + p.Blank = field.NewString(table, "blank") + p.Remark = field.NewString(table, "remark") + p.LongRemark = field.NewString(table, "long_remark") + + p.fillFieldMap() + + return p +} + +func (p *person) WithContext(ctx context.Context) IPersonDo { return p.personDo.WithContext(ctx) } + +func (p person) TableName() string { return p.personDo.TableName() } + +func (p person) Alias() string { return p.personDo.Alias() } + +func (p *person) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := p.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (p *person) fillFieldMap() { + p.fieldMap = make(map[string]field.Expr, 21) + p.fieldMap["id"] = p.ID + p.fieldMap["name"] = p.Name + p.fieldMap["alias"] = p.Alias_ + p.fieldMap["age"] = p.Age + p.fieldMap["flag"] = p.Flag + p.fieldMap["another_flag"] = p.AnotherFlag + p.fieldMap["commit"] = p.Commit + p.fieldMap["First"] = p.First + p.fieldMap["bit"] = p.Bit + p.fieldMap["small"] = p.Small + p.fieldMap["deleted_at"] = p.DeletedAt + p.fieldMap["score"] = p.Score + p.fieldMap["number"] = p.Number + p.fieldMap["birth"] = p.Birth + p.fieldMap["xmlHTTPRequest"] = p.XMLHTTPRequest + p.fieldMap["jStr"] = p.JStr + p.fieldMap["geo"] = p.Geo + p.fieldMap["mint"] = p.Mint + p.fieldMap["blank"] = p.Blank + p.fieldMap["remark"] = p.Remark + p.fieldMap["long_remark"] = p.LongRemark +} + +func (p person) clone(db *gorm.DB) person { + p.personDo.ReplaceConnPool(db.Statement.ConnPool) + return p +} + +func (p person) replaceDB(db *gorm.DB) person { + p.personDo.ReplaceDB(db) + return p +} + +type personDo struct{ gen.DO } + +type IPersonDo interface { + gen.SubQuery + Debug() IPersonDo + WithContext(ctx context.Context) IPersonDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IPersonDo + WriteDB() IPersonDo + As(alias string) gen.Dao + Session(config *gorm.Session) IPersonDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IPersonDo + Not(conds ...gen.Condition) IPersonDo + Or(conds ...gen.Condition) IPersonDo + Select(conds ...field.Expr) IPersonDo + Where(conds ...gen.Condition) IPersonDo + Order(conds ...field.Expr) IPersonDo + Distinct(cols ...field.Expr) IPersonDo + Omit(cols ...field.Expr) IPersonDo + Join(table schema.Tabler, on ...field.Expr) IPersonDo + LeftJoin(table schema.Tabler, on ...field.Expr) IPersonDo + RightJoin(table schema.Tabler, on ...field.Expr) IPersonDo + Group(cols ...field.Expr) IPersonDo + Having(conds ...gen.Condition) IPersonDo + Limit(limit int) IPersonDo + Offset(offset int) IPersonDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IPersonDo + Unscoped() IPersonDo + Create(values ...*model.Person) error + CreateInBatches(values []*model.Person, batchSize int) error + Save(values ...*model.Person) error + First() (*model.Person, error) + Take() (*model.Person, error) + Last() (*model.Person, error) + Find() ([]*model.Person, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Person, err error) + FindInBatches(result *[]*model.Person, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*model.Person) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) IPersonDo + Assign(attrs ...field.AssignExpr) IPersonDo + Joins(fields ...field.RelationField) IPersonDo + Preload(fields ...field.RelationField) IPersonDo + FirstOrInit() (*model.Person, error) + FirstOrCreate() (*model.Person, error) + FindByPage(offset int, limit int) (result []*model.Person, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) IPersonDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (p personDo) Debug() IPersonDo { + return p.withDO(p.DO.Debug()) +} + +func (p personDo) WithContext(ctx context.Context) IPersonDo { + return p.withDO(p.DO.WithContext(ctx)) +} + +func (p personDo) ReadDB() IPersonDo { + return p.Clauses(dbresolver.Read) +} + +func (p personDo) WriteDB() IPersonDo { + return p.Clauses(dbresolver.Write) +} + +func (p personDo) Session(config *gorm.Session) IPersonDo { + return p.withDO(p.DO.Session(config)) +} + +func (p personDo) Clauses(conds ...clause.Expression) IPersonDo { + return p.withDO(p.DO.Clauses(conds...)) +} + +func (p personDo) Returning(value interface{}, columns ...string) IPersonDo { + return p.withDO(p.DO.Returning(value, columns...)) +} + +func (p personDo) Not(conds ...gen.Condition) IPersonDo { + return p.withDO(p.DO.Not(conds...)) +} + +func (p personDo) Or(conds ...gen.Condition) IPersonDo { + return p.withDO(p.DO.Or(conds...)) +} + +func (p personDo) Select(conds ...field.Expr) IPersonDo { + return p.withDO(p.DO.Select(conds...)) +} + +func (p personDo) Where(conds ...gen.Condition) IPersonDo { + return p.withDO(p.DO.Where(conds...)) +} + +func (p personDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IPersonDo { + return p.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) +} + +func (p personDo) Order(conds ...field.Expr) IPersonDo { + return p.withDO(p.DO.Order(conds...)) +} + +func (p personDo) Distinct(cols ...field.Expr) IPersonDo { + return p.withDO(p.DO.Distinct(cols...)) +} + +func (p personDo) Omit(cols ...field.Expr) IPersonDo { + return p.withDO(p.DO.Omit(cols...)) +} + +func (p personDo) Join(table schema.Tabler, on ...field.Expr) IPersonDo { + return p.withDO(p.DO.Join(table, on...)) +} + +func (p personDo) LeftJoin(table schema.Tabler, on ...field.Expr) IPersonDo { + return p.withDO(p.DO.LeftJoin(table, on...)) +} + +func (p personDo) RightJoin(table schema.Tabler, on ...field.Expr) IPersonDo { + return p.withDO(p.DO.RightJoin(table, on...)) +} + +func (p personDo) Group(cols ...field.Expr) IPersonDo { + return p.withDO(p.DO.Group(cols...)) +} + +func (p personDo) Having(conds ...gen.Condition) IPersonDo { + return p.withDO(p.DO.Having(conds...)) +} + +func (p personDo) Limit(limit int) IPersonDo { + return p.withDO(p.DO.Limit(limit)) +} + +func (p personDo) Offset(offset int) IPersonDo { + return p.withDO(p.DO.Offset(offset)) +} + +func (p personDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IPersonDo { + return p.withDO(p.DO.Scopes(funcs...)) +} + +func (p personDo) Unscoped() IPersonDo { + return p.withDO(p.DO.Unscoped()) +} + +func (p personDo) Create(values ...*model.Person) error { + if len(values) == 0 { + return nil + } + return p.DO.Create(values) +} + +func (p personDo) CreateInBatches(values []*model.Person, batchSize int) error { + return p.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (p personDo) Save(values ...*model.Person) error { + if len(values) == 0 { + return nil + } + return p.DO.Save(values) +} + +func (p personDo) First() (*model.Person, error) { + if result, err := p.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Person), nil + } +} + +func (p personDo) Take() (*model.Person, error) { + if result, err := p.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Person), nil + } +} + +func (p personDo) Last() (*model.Person, error) { + if result, err := p.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Person), nil + } +} + +func (p personDo) Find() ([]*model.Person, error) { + result, err := p.DO.Find() + return result.([]*model.Person), err +} + +func (p personDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Person, err error) { + buf := make([]*model.Person, 0, batchSize) + err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (p personDo) FindInBatches(result *[]*model.Person, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return p.DO.FindInBatches(result, batchSize, fc) +} + +func (p personDo) Attrs(attrs ...field.AssignExpr) IPersonDo { + return p.withDO(p.DO.Attrs(attrs...)) +} + +func (p personDo) Assign(attrs ...field.AssignExpr) IPersonDo { + return p.withDO(p.DO.Assign(attrs...)) +} + +func (p personDo) Joins(fields ...field.RelationField) IPersonDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Joins(_f)) + } + return &p +} + +func (p personDo) Preload(fields ...field.RelationField) IPersonDo { + for _, _f := range fields { + p = *p.withDO(p.DO.Preload(_f)) + } + return &p +} + +func (p personDo) FirstOrInit() (*model.Person, error) { + if result, err := p.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Person), nil + } +} + +func (p personDo) FirstOrCreate() (*model.Person, error) { + if result, err := p.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Person), nil + } +} + +func (p personDo) FindByPage(offset int, limit int) (result []*model.Person, count int64, err error) { + result, err = p.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = p.Offset(-1).Limit(-1).Count() + return +} + +func (p personDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = p.Count() + if err != nil { + return + } + + err = p.Offset(offset).Limit(limit).Scan(result) + return +} + +func (p personDo) Scan(result interface{}) (err error) { + return p.DO.Scan(result) +} + +func (p personDo) Delete(models ...*model.Person) (result gen.ResultInfo, err error) { + return p.DO.Delete(models) +} + +func (p *personDo) withDO(do gen.Dao) *personDo { + p.DO = *do.(*gen.DO) + return p +} diff --git a/tests/.expect/dal_4/query/people.gen_test.go b/tests/.expect/dal_4/query/people.gen_test.go new file mode 100644 index 00000000..6ebb566a --- /dev/null +++ b/tests/.expect/dal_4/query/people.gen_test.go @@ -0,0 +1,145 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "testing" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/tests/.gen/dal_4/model" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.Person{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.Person{}) fail: %s", err) + } +} + +func Test_personQuery(t *testing.T) { + person := newPerson(db) + person = *person.As(person.TableName()) + _do := person.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(person.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := person.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from person success") + } + + err = _do.Create(&model.Person{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.Person{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.Person{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(person.ALL).Take() + if err != nil { + t.Error("Take() on table fail:", err) + } + + _, err = _do.First() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Last() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatch() on table fail:", err) + } + + err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.Person{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(person.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find() + if err != nil { + t.Error("Find() on table fail:", err) + } + + _, err = _do.Distinct(primaryKey).Take() + if err != nil { + t.Error("select Distinct() on table fail:", err) + } + + _, err = _do.Select(person.ALL).Omit(primaryKey).Take() + if err != nil { + t.Error("Omit() on table fail:", err) + } + + _, err = _do.Group(primaryKey).Find() + if err != nil { + t.Error("Group() on table fail:", err) + } + + _, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find() + if err != nil { + t.Error("Scopes() on table fail:", err) + } + + _, _, err = _do.FindByPage(0, 1) + if err != nil { + t.Error("FindByPage() on table fail:", err) + } + + _, err = _do.ScanByPage(&model.Person{}, 0, 1) + if err != nil { + t.Error("ScanByPage() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit() + if err != nil { + t.Error("FirstOrInit() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate() + if err != nil { + t.Error("FirstOrCreate() on table fail:", err) + } + + var _a _another + var _aPK = field.NewString(_a.TableName(), clause.PrimaryKey) + + err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("Join() on table fail:", err) + } + + err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("LeftJoin() on table fail:", err) + } + + _, err = _do.Not().Or().Clauses().Take() + if err != nil { + t.Error("Not/Or/Clauses on table fail:", err) + } +} diff --git a/tests/.expect/dal_4/query/users.gen.go b/tests/.expect/dal_4/query/users.gen.go new file mode 100644 index 00000000..3726d50c --- /dev/null +++ b/tests/.expect/dal_4/query/users.gen.go @@ -0,0 +1,1192 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "database/sql" + "strings" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/helper" + + "gorm.io/plugin/dbresolver" + + "gorm.io/gen/tests/.gen/dal_4/model" + + "time" +) + +func newUser(db *gorm.DB, opts ...gen.DOOption) user { + _user := user{} + + _user.userDo.UseDB(db, opts...) + _user.userDo.UseModel(&model.User{}) + + tableName := _user.userDo.TableName() + _user.ALL = field.NewAsterisk(tableName) + _user.ID = field.NewInt64(tableName, "id") + _user.CreatedAt = field.NewTime(tableName, "created_at") + _user.Name = field.NewString(tableName, "name") + _user.Address = field.NewString(tableName, "address") + _user.RegisterTime = field.NewTime(tableName, "register_time") + _user.Alive = field.NewBool(tableName, "alive") + _user.CompanyID = field.NewInt64(tableName, "company_id") + _user.PrivateURL = field.NewString(tableName, "private_url") + + _user.fillFieldMap() + + return _user +} + +type user struct { + userDo userDo + + ALL field.Asterisk + ID field.Int64 + CreatedAt field.Time + Name field.String // oneline + Address field.String + RegisterTime field.Time + /* + multiline + line1 + line2 + */ + Alive field.Bool + CompanyID field.Int64 + PrivateURL field.String + + fieldMap map[string]field.Expr +} + +func (u user) Table(newTableName string) *user { + u.userDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u user) As(alias string) *user { + u.userDo.DO = *(u.userDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *user) updateTableName(table string) *user { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewInt64(table, "id") + u.CreatedAt = field.NewTime(table, "created_at") + u.Name = field.NewString(table, "name") + u.Address = field.NewString(table, "address") + u.RegisterTime = field.NewTime(table, "register_time") + u.Alive = field.NewBool(table, "alive") + u.CompanyID = field.NewInt64(table, "company_id") + u.PrivateURL = field.NewString(table, "private_url") + + u.fillFieldMap() + + return u +} + +func (u *user) WithContext(ctx context.Context) IUserDo { return u.userDo.WithContext(ctx) } + +func (u user) TableName() string { return u.userDo.TableName() } + +func (u user) Alias() string { return u.userDo.Alias() } + +func (u *user) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := u.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (u *user) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 8) + u.fieldMap["id"] = u.ID + u.fieldMap["created_at"] = u.CreatedAt + u.fieldMap["name"] = u.Name + u.fieldMap["address"] = u.Address + u.fieldMap["register_time"] = u.RegisterTime + u.fieldMap["alive"] = u.Alive + u.fieldMap["company_id"] = u.CompanyID + u.fieldMap["private_url"] = u.PrivateURL +} + +func (u user) clone(db *gorm.DB) user { + u.userDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u user) replaceDB(db *gorm.DB) user { + u.userDo.ReplaceDB(db) + return u +} + +type userDo struct{ gen.DO } + +type IUserDo interface { + gen.SubQuery + Debug() IUserDo + WithContext(ctx context.Context) IUserDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IUserDo + WriteDB() IUserDo + As(alias string) gen.Dao + Session(config *gorm.Session) IUserDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IUserDo + Not(conds ...gen.Condition) IUserDo + Or(conds ...gen.Condition) IUserDo + Select(conds ...field.Expr) IUserDo + Where(conds ...gen.Condition) IUserDo + Order(conds ...field.Expr) IUserDo + Distinct(cols ...field.Expr) IUserDo + Omit(cols ...field.Expr) IUserDo + Join(table schema.Tabler, on ...field.Expr) IUserDo + LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo + RightJoin(table schema.Tabler, on ...field.Expr) IUserDo + Group(cols ...field.Expr) IUserDo + Having(conds ...gen.Condition) IUserDo + Limit(limit int) IUserDo + Offset(offset int) IUserDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo + Unscoped() IUserDo + Create(values ...*model.User) error + CreateInBatches(values []*model.User, batchSize int) error + Save(values ...*model.User) error + First() (*model.User, error) + Take() (*model.User, error) + Last() (*model.User, error) + Find() ([]*model.User, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.User, err error) + FindInBatches(result *[]*model.User, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*model.User) (info gen.ResultInfo, err error) + Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + Updates(value interface{}) (info gen.ResultInfo, err error) + UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) + UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) + UpdateColumns(value interface{}) (info gen.ResultInfo, err error) + UpdateFrom(q gen.SubQuery) gen.Dao + Attrs(attrs ...field.AssignExpr) IUserDo + Assign(attrs ...field.AssignExpr) IUserDo + Joins(fields ...field.RelationField) IUserDo + Preload(fields ...field.RelationField) IUserDo + FirstOrInit() (*model.User, error) + FirstOrCreate() (*model.User, error) + FindByPage(offset int, limit int) (result []*model.User, count int64, err error) + ScanByPage(result interface{}, offset int, limit int) (count int64, err error) + Scan(result interface{}) (err error) + Returning(value interface{}, columns ...string) IUserDo + UnderlyingDB() *gorm.DB + schema.Tabler + + FindByUsers(user model.User) (result []model.User) + FindByComplexIf(user *model.User) (result []model.User) + FindByIfTime(start time.Time) (result []model.User) + TestFor(names []string) (result model.User, err error) + TestForKey(names []string, name string, value string) (result model.User, err error) + TestForOr(names []string) (result model.User, err error) + TestIfInFor(names []string, name string) (result model.User, err error) + TestForInIf(names []string, name string) (result model.User, err error) + TestForInWhere(names []string, name string, forName string) (result model.User, err error) + TestForUserList(users []*model.User, name string) (result model.User, err error) + TestForMap(param map[string]string, name string) (result model.User, err error) + TestIfInIf(name string) (result model.User) + TestMoreFor(names []string, ids []int) (result []model.User) + TestMoreFor2(names []string, ids []int) (result []model.User) + TestForInSet(users []model.User) (err error) + TestInsertMoreInfo(users []model.User) (err error) + TestIfElseFor(name string, users []model.User) (err error) + TestForLike(names []string) (result []model.User) + AddUser(name string, age int) (result sql.Result, err error) + AddUser1(name string, age int) (rowsAffected int64, err error) + AddUser2(name string, age int) (rowsAffected int64) + AddUser3(name string, age int) (result sql.Result) + AddUser4(name string, age int) (row *sql.Row) + AddUser5(name string, age int) (rows *sql.Rows) + AddUser6(name string, age int) (rows *sql.Rows, err error) + FindByID(id int) (result model.User) + LikeSearch(name string) (result *model.User) + InSearch(names []string) (result []*model.User) + ColumnSearch(name string, names []string) (result []*model.User) +} + +// FindByUsers +// +// select * from @@table +// {{where}} +// {{if user.Name !=""}} +// name=@user.Name +// {{end}} +// {{end}} +func (u userDo) FindByUsers(user model.User) (result []model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + if user.Name != "" { + params = append(params, user.Name) + whereSQL0.WriteString("name=? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// FindByComplexIf +// +// select * from @@table +// {{where}} +// {{if user != nil && user.Name !=""}} +// name=@user.Name +// {{end}} +// {{end}} +func (u userDo) FindByComplexIf(user *model.User) (result []model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + if user != nil && user.Name != "" { + params = append(params, user.Name) + whereSQL0.WriteString("name=? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// FindByIfTime +// +// select * from @@table +// {{if !start.IsZero()}} +// created_at > start +// {{end}} +func (u userDo) FindByIfTime(start time.Time) (result []model.User) { + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + if !start.IsZero() { + generateSQL.WriteString("created_at > start ") + } + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String()).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// TestFor +// +// select * from @@table where +// {{for _,name:=range names}} +// name = @name and +// {{end}} +// 1=1 +func (u userDo) TestFor(names []string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users where ") + for _, name := range names { + params = append(params, name) + generateSQL.WriteString("name = ? and ") + } + generateSQL.WriteString("1=1 ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForKey +// +// select * from @@table where +// {{for _,name:=range names}} +// or @@name = @value +// {{end}} +// and 1=1 +func (u userDo) TestForKey(names []string, name string, value string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users where ") + for _, name := range names { + params = append(params, value) + generateSQL.WriteString("or " + u.Quote(name) + " = ? ") + } + generateSQL.WriteString("and 1=1 ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForOr +// +// select * from @@table +// {{where}} +// ( +// {{for _,name:=range names}} +// name = @name or +// {{end}} +// {{end}} +// ) +func (u userDo) TestForOr(names []string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + whereSQL0.WriteString("( ") + for _, name := range names { + params = append(params, name) + whereSQL0.WriteString("name = ? or ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + generateSQL.WriteString(") ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestIfInFor +// +// select * from @@table where +// {{for _,name:=range names}} +// {{if name !=""}} +// name = @name or +// {{end}} +// {{end}} +// 1=2 +func (u userDo) TestIfInFor(names []string, name string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users where ") + for _, name := range names { + if name != "" { + params = append(params, name) + generateSQL.WriteString("name = ? or ") + } + } + generateSQL.WriteString("1=2 ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForInIf +// +// select * from @@table where +// {{if name !="" }} +// {{for _,forName:=range names}} +// name = @forName or +// {{end}} +// {{end}} +// 1=2 +func (u userDo) TestForInIf(names []string, name string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users where ") + if name != "" { + for _, forName := range names { + params = append(params, forName) + generateSQL.WriteString("name = ? or ") + } + } + generateSQL.WriteString("1=2 ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForInWhere +// +// select * from @@table +// {{where}} +// {{for _,forName:=range names}} +// or name = @forName +// {{end}} +// {{end}} +func (u userDo) TestForInWhere(names []string, name string, forName string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for _, forName := range names { + params = append(params, forName) + whereSQL0.WriteString("or name = ? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForUserList +// +// select * from users +// {{where}} +// {{for _,user :=range users}} +// name=@user.Name +// {{end}} +// {{end}} +func (u userDo) TestForUserList(users []*model.User, name string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for _, user := range users { + params = append(params, user.Name) + whereSQL0.WriteString("name=? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForMap +// +// select * from users +// {{where}} +// {{for key,value :=range param}} +// @@key=@value +// {{end}} +// {{end}} +func (u userDo) TestForMap(param map[string]string, name string) (result model.User, err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for key, value := range param { + params = append(params, value) + whereSQL0.WriteString(u.Quote(key) + "=? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestIfInIf +// +// select * from users +// {{where}} +// {{if name !="xx"}} +// {{if name !="xx"}} +// name=@name +// {{end}} +// {{end}} +// {{end}} +func (u userDo) TestIfInIf(name string) (result model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + if name != "xx" { + if name != "xx" { + params = append(params, name) + whereSQL0.WriteString("name=? ") + } + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// TestMoreFor +// +// select * from @@table +// {{where}} +// {{for _,name := range names}} +// and name=@name +// {{end}} +// {{for _,id:=range ids}} +// and id=@id +// {{end}} +// {{end}} +func (u userDo) TestMoreFor(names []string, ids []int) (result []model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for _, name := range names { + params = append(params, name) + whereSQL0.WriteString("and name=? ") + } + for _, id := range ids { + params = append(params, id) + whereSQL0.WriteString("and id=? ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// TestMoreFor2 +// +// select * from @@table +// {{where}} +// {{for _,name := range names}} +// OR (name=@name +// {{for _,id:=range ids}} +// and id=@id +// {{end}} +// and title !=@name) +// {{end}} +// {{end}} +func (u userDo) TestMoreFor2(names []string, ids []int) (result []model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for _, name := range names { + params = append(params, name) + whereSQL0.WriteString("OR (name=? ") + for _, id := range ids { + params = append(params, id) + whereSQL0.WriteString("and id=? ") + } + params = append(params, name) + whereSQL0.WriteString("and title !=?) ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// TestForInSet +// +// update @@table +// {{set}} +// {{for _,user:=range users}} +// name=@user.Name, +// {{end}} +// {{end}} where +func (u userDo) TestForInSet(users []model.User) (err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("update users ") + var setSQL0 strings.Builder + for _, user := range users { + params = append(params, user.Name) + setSQL0.WriteString("name=?, ") + } + helper.JoinSetBuilder(&generateSQL, setSQL0) + generateSQL.WriteString("where ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestInsertMoreInfo +// +// insert into @@table(name,age)values +// {{for index ,user:=range users}} +// {{if index >0}} +// , +// {{end}} +// (@user.Name,@user.Age) +// {{end}} +func (u userDo) TestInsertMoreInfo(users []model.User) (err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("insert into users(name,age)values ") + for index, user := range users { + if index > 0 { + generateSQL.WriteString(", ") + } + params = append(params, user.Name) + params = append(params, user.Age) + generateSQL.WriteString("(?,?) ") + } + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestIfElseFor +// +// select * from @@table +// {{where}} +// {{if name =="admin"}} +// ( +// {{for index,user:=range users}} +// {{if index !=0}} +// and +// {{end}} +// name like @user.Name +// {{end}} +// ) +// {{else if name !="guest"}} +// {{for index,guser:=range users}} +// {{if index ==0}} +// ( +// {{else}} +// and +// {{end}} +// name = @guser.Name +// {{end}} +// ) +// {{else}} +// name ="guest" +// {{end}} +// {{end}} +func (u userDo) TestIfElseFor(name string, users []model.User) (err error) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + if name == "admin" { + whereSQL0.WriteString("( ") + for index, user := range users { + if index != 0 { + whereSQL0.WriteString("and ") + } + params = append(params, user.Name) + whereSQL0.WriteString("name like ? ") + } + whereSQL0.WriteString(") ") + } else if name != "guest" { + for index, guser := range users { + if index == 0 { + whereSQL0.WriteString("( ") + } else { + whereSQL0.WriteString("and ") + } + params = append(params, guser.Name) + whereSQL0.WriteString("name = ? ") + } + whereSQL0.WriteString(") ") + } else { + whereSQL0.WriteString("name =\"guest\" ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert + err = executeSQL.Error + + return +} + +// TestForLike +// +// select * from @@table +// {{where}} +// {{for _,name:=range names}} +// name like concat("%",@name,"%") or +// {{end}} +// {{end}} +func (u userDo) TestForLike(names []string) (result []model.User) { + var params []interface{} + + var generateSQL strings.Builder + generateSQL.WriteString("select * from users ") + var whereSQL0 strings.Builder + for _, name := range names { + params = append(params, name) + whereSQL0.WriteString("name like concat(\"%\",?,\"%\") or ") + } + helper.JoinWhereBuilder(&generateSQL, whereSQL0) + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// AddUser +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser(name string, age int) (result sql.Result, err error) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + stmt := u.UnderlyingDB().Statement + result, err = stmt.ConnPool.ExecContext(stmt.Context, generateSQL.String(), params...) // ignore_security_alert + + return +} + +// AddUser1 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser1(name string, age int) (rowsAffected int64, err error) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert + rowsAffected = executeSQL.RowsAffected + err = executeSQL.Error + + return +} + +// AddUser2 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser2(name string, age int) (rowsAffected int64) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert + rowsAffected = executeSQL.RowsAffected + + return +} + +// AddUser3 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser3(name string, age int) (result sql.Result) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + stmt := u.UnderlyingDB().Statement + result, _ = stmt.ConnPool.ExecContext(stmt.Context, generateSQL.String(), params...) // ignore_security_alert + + return +} + +// AddUser4 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser4(name string, age int) (row *sql.Row) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + row = u.UnderlyingDB().Raw(generateSQL.String(), params...).Row() // ignore_security_alert + + return +} + +// AddUser5 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser5(name string, age int) (rows *sql.Rows) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + rows, _ = u.UnderlyingDB().Raw(generateSQL.String(), params...).Rows() // ignore_security_alert + + return +} + +// AddUser6 +// +// INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) +func (u userDo) AddUser6(name string, age int) (rows *sql.Rows, err error) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + params = append(params, age) + generateSQL.WriteString("INSERT INTO users (name,age) VALUES (?,?) ON DUPLICATE KEY UPDATE age=VALUES(age) ") + + rows, err = u.UnderlyingDB().Raw(generateSQL.String(), params...).Rows() // ignore_security_alert + + return +} + +// FindByID +// +// select * from users where id=@id +func (u userDo) FindByID(id int) (result model.User) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, id) + generateSQL.WriteString("select * from users where id=? ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// LikeSearch +// +// SELECT * FROM @@table where name LIKE concat('%',@name,'%') +func (u userDo) LikeSearch(name string) (result *model.User) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, name) + generateSQL.WriteString("SELECT * FROM users where name LIKE concat('%',?,'%') ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Take(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// InSearch +// +// select * from @@table where name in @names +func (u userDo) InSearch(names []string) (result []*model.User) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, names) + generateSQL.WriteString("select * from users where name in ? ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +// ColumnSearch +// +// select * from @@table where @@name in @names +func (u userDo) ColumnSearch(name string, names []string) (result []*model.User) { + var params []interface{} + + var generateSQL strings.Builder + params = append(params, names) + generateSQL.WriteString("select * from users where " + u.Quote(name) + " in ? ") + + var executeSQL *gorm.DB + executeSQL = u.UnderlyingDB().Raw(generateSQL.String(), params...).Find(&result) // ignore_security_alert + _ = executeSQL + + return +} + +func (u userDo) Debug() IUserDo { + return u.withDO(u.DO.Debug()) +} + +func (u userDo) WithContext(ctx context.Context) IUserDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userDo) ReadDB() IUserDo { + return u.Clauses(dbresolver.Read) +} + +func (u userDo) WriteDB() IUserDo { + return u.Clauses(dbresolver.Write) +} + +func (u userDo) Session(config *gorm.Session) IUserDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userDo) Clauses(conds ...clause.Expression) IUserDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userDo) Returning(value interface{}, columns ...string) IUserDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userDo) Not(conds ...gen.Condition) IUserDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userDo) Or(conds ...gen.Condition) IUserDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userDo) Select(conds ...field.Expr) IUserDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userDo) Where(conds ...gen.Condition) IUserDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IUserDo { + return u.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) +} + +func (u userDo) Order(conds ...field.Expr) IUserDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userDo) Distinct(cols ...field.Expr) IUserDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userDo) Omit(cols ...field.Expr) IUserDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userDo) Join(table schema.Tabler, on ...field.Expr) IUserDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userDo) LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userDo) RightJoin(table schema.Tabler, on ...field.Expr) IUserDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userDo) Group(cols ...field.Expr) IUserDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userDo) Having(conds ...gen.Condition) IUserDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userDo) Limit(limit int) IUserDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userDo) Offset(offset int) IUserDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userDo) Unscoped() IUserDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userDo) Create(values ...*model.User) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userDo) CreateInBatches(values []*model.User, batchSize int) error { + return u.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (u userDo) Save(values ...*model.User) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userDo) First() (*model.User, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.User), nil + } +} + +func (u userDo) Take() (*model.User, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.User), nil + } +} + +func (u userDo) Last() (*model.User, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.User), nil + } +} + +func (u userDo) Find() ([]*model.User, error) { + result, err := u.DO.Find() + return result.([]*model.User), err +} + +func (u userDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.User, err error) { + buf := make([]*model.User, 0, batchSize) + err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (u userDo) FindInBatches(result *[]*model.User, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userDo) Attrs(attrs ...field.AssignExpr) IUserDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userDo) Assign(attrs ...field.AssignExpr) IUserDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userDo) Joins(fields ...field.RelationField) IUserDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userDo) Preload(fields ...field.RelationField) IUserDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userDo) FirstOrInit() (*model.User, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.User), nil + } +} + +func (u userDo) FirstOrCreate() (*model.User, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.User), nil + } +} + +func (u userDo) FindByPage(offset int, limit int) (result []*model.User, count int64, err error) { + result, err = u.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = u.Offset(-1).Limit(-1).Count() + return +} + +func (u userDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = u.Count() + if err != nil { + return + } + + err = u.Offset(offset).Limit(limit).Scan(result) + return +} + +func (u userDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userDo) Delete(models ...*model.User) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +func (u *userDo) withDO(do gen.Dao) *userDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/tests/.expect/dal_4/query/users.gen_test.go b/tests/.expect/dal_4/query/users.gen_test.go new file mode 100644 index 00000000..2b533f99 --- /dev/null +++ b/tests/.expect/dal_4/query/users.gen_test.go @@ -0,0 +1,564 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + "fmt" + "strconv" + "testing" + "time" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gen/tests/.gen/dal_4/model" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.User{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.User{}) fail: %s", err) + } +} + +func Test_userQuery(t *testing.T) { + user := newUser(db) + user = *user.As(user.TableName()) + _do := user.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(user.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := user.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from user success") + } + + err = _do.Create(&model.User{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.User{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.User{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(user.ALL).Take() + if err != nil { + t.Error("Take() on table fail:", err) + } + + _, err = _do.First() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Last() + if err != nil { + t.Error("First() on table fail:", err) + } + + _, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatch() on table fail:", err) + } + + err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*model.User{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(user.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find() + if err != nil { + t.Error("Find() on table fail:", err) + } + + _, err = _do.Distinct(primaryKey).Take() + if err != nil { + t.Error("select Distinct() on table fail:", err) + } + + _, err = _do.Select(user.ALL).Omit(primaryKey).Take() + if err != nil { + t.Error("Omit() on table fail:", err) + } + + _, err = _do.Group(primaryKey).Find() + if err != nil { + t.Error("Group() on table fail:", err) + } + + _, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find() + if err != nil { + t.Error("Scopes() on table fail:", err) + } + + _, _, err = _do.FindByPage(0, 1) + if err != nil { + t.Error("FindByPage() on table fail:", err) + } + + _, err = _do.ScanByPage(&model.User{}, 0, 1) + if err != nil { + t.Error("ScanByPage() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit() + if err != nil { + t.Error("FirstOrInit() on table fail:", err) + } + + _, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate() + if err != nil { + t.Error("FirstOrCreate() on table fail:", err) + } + + var _a _another + var _aPK = field.NewString(_a.TableName(), clause.PrimaryKey) + + err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("Join() on table fail:", err) + } + + err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{}) + if err != nil { + t.Error("LeftJoin() on table fail:", err) + } + + _, err = _do.Not().Or().Clauses().Take() + if err != nil { + t.Error("Not/Or/Clauses on table fail:", err) + } +} + +var UserFindByUsersTestCase = []TestCase{} + +func Test_user_FindByUsers(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserFindByUsersTestCase { + t.Run("FindByUsers_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.FindByUsers(tt.Input.Args[0].(model.User)) + assert(t, "FindByUsers", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserFindByComplexIfTestCase = []TestCase{} + +func Test_user_FindByComplexIf(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserFindByComplexIfTestCase { + t.Run("FindByComplexIf_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.FindByComplexIf(tt.Input.Args[0].(*model.User)) + assert(t, "FindByComplexIf", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserFindByIfTimeTestCase = []TestCase{} + +func Test_user_FindByIfTime(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserFindByIfTimeTestCase { + t.Run("FindByIfTime_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.FindByIfTime(tt.Input.Args[0].(time.Time)) + assert(t, "FindByIfTime", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestForTestCase = []TestCase{} + +func Test_user_TestFor(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForTestCase { + t.Run("TestFor_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestFor(tt.Input.Args[0].([]string)) + assert(t, "TestFor", res1, tt.Expectation.Ret[0]) + assert(t, "TestFor", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForKeyTestCase = []TestCase{} + +func Test_user_TestForKey(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForKeyTestCase { + t.Run("TestForKey_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForKey(tt.Input.Args[0].([]string), tt.Input.Args[1].(string), tt.Input.Args[2].(string)) + assert(t, "TestForKey", res1, tt.Expectation.Ret[0]) + assert(t, "TestForKey", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForOrTestCase = []TestCase{} + +func Test_user_TestForOr(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForOrTestCase { + t.Run("TestForOr_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForOr(tt.Input.Args[0].([]string)) + assert(t, "TestForOr", res1, tt.Expectation.Ret[0]) + assert(t, "TestForOr", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestIfInForTestCase = []TestCase{} + +func Test_user_TestIfInFor(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestIfInForTestCase { + t.Run("TestIfInFor_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestIfInFor(tt.Input.Args[0].([]string), tt.Input.Args[1].(string)) + assert(t, "TestIfInFor", res1, tt.Expectation.Ret[0]) + assert(t, "TestIfInFor", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForInIfTestCase = []TestCase{} + +func Test_user_TestForInIf(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForInIfTestCase { + t.Run("TestForInIf_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForInIf(tt.Input.Args[0].([]string), tt.Input.Args[1].(string)) + assert(t, "TestForInIf", res1, tt.Expectation.Ret[0]) + assert(t, "TestForInIf", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForInWhereTestCase = []TestCase{} + +func Test_user_TestForInWhere(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForInWhereTestCase { + t.Run("TestForInWhere_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForInWhere(tt.Input.Args[0].([]string), tt.Input.Args[1].(string), tt.Input.Args[2].(string)) + assert(t, "TestForInWhere", res1, tt.Expectation.Ret[0]) + assert(t, "TestForInWhere", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForUserListTestCase = []TestCase{} + +func Test_user_TestForUserList(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForUserListTestCase { + t.Run("TestForUserList_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForUserList(tt.Input.Args[0].(*[]model.User), tt.Input.Args[1].(string)) + assert(t, "TestForUserList", res1, tt.Expectation.Ret[0]) + assert(t, "TestForUserList", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestForMapTestCase = []TestCase{} + +func Test_user_TestForMap(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForMapTestCase { + t.Run("TestForMap_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.TestForMap(tt.Input.Args[0].(map[string]string), tt.Input.Args[1].(string)) + assert(t, "TestForMap", res1, tt.Expectation.Ret[0]) + assert(t, "TestForMap", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserTestIfInIfTestCase = []TestCase{} + +func Test_user_TestIfInIf(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestIfInIfTestCase { + t.Run("TestIfInIf_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestIfInIf(tt.Input.Args[0].(string)) + assert(t, "TestIfInIf", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestMoreForTestCase = []TestCase{} + +func Test_user_TestMoreFor(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestMoreForTestCase { + t.Run("TestMoreFor_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestMoreFor(tt.Input.Args[0].([]string), tt.Input.Args[1].([]int)) + assert(t, "TestMoreFor", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestMoreFor2TestCase = []TestCase{} + +func Test_user_TestMoreFor2(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestMoreFor2TestCase { + t.Run("TestMoreFor2_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestMoreFor2(tt.Input.Args[0].([]string), tt.Input.Args[1].([]int)) + assert(t, "TestMoreFor2", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestForInSetTestCase = []TestCase{} + +func Test_user_TestForInSet(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForInSetTestCase { + t.Run("TestForInSet_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestForInSet(tt.Input.Args[0].([]model.User)) + assert(t, "TestForInSet", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestInsertMoreInfoTestCase = []TestCase{} + +func Test_user_TestInsertMoreInfo(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestInsertMoreInfoTestCase { + t.Run("TestInsertMoreInfo_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestInsertMoreInfo(tt.Input.Args[0].([]model.User)) + assert(t, "TestInsertMoreInfo", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestIfElseForTestCase = []TestCase{} + +func Test_user_TestIfElseFor(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestIfElseForTestCase { + t.Run("TestIfElseFor_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestIfElseFor(tt.Input.Args[0].(string), tt.Input.Args[1].([]model.User)) + assert(t, "TestIfElseFor", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserTestForLikeTestCase = []TestCase{} + +func Test_user_TestForLike(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserTestForLikeTestCase { + t.Run("TestForLike_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.TestForLike(tt.Input.Args[0].([]string)) + assert(t, "TestForLike", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserAddUserTestCase = []TestCase{} + +func Test_user_AddUser(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUserTestCase { + t.Run("AddUser_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.AddUser(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser", res1, tt.Expectation.Ret[0]) + assert(t, "AddUser", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserAddUser1TestCase = []TestCase{} + +func Test_user_AddUser1(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser1TestCase { + t.Run("AddUser1_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.AddUser1(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser1", res1, tt.Expectation.Ret[0]) + assert(t, "AddUser1", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserAddUser2TestCase = []TestCase{} + +func Test_user_AddUser2(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser2TestCase { + t.Run("AddUser2_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.AddUser2(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser2", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserAddUser3TestCase = []TestCase{} + +func Test_user_AddUser3(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser3TestCase { + t.Run("AddUser3_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.AddUser3(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser3", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserAddUser4TestCase = []TestCase{} + +func Test_user_AddUser4(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser4TestCase { + t.Run("AddUser4_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.AddUser4(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser4", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserAddUser5TestCase = []TestCase{} + +func Test_user_AddUser5(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser5TestCase { + t.Run("AddUser5_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.AddUser5(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser5", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserAddUser6TestCase = []TestCase{} + +func Test_user_AddUser6(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserAddUser6TestCase { + t.Run("AddUser6_"+strconv.Itoa(i), func(t *testing.T) { + res1, res2 := do.AddUser6(tt.Input.Args[0].(string), tt.Input.Args[1].(int)) + assert(t, "AddUser6", res1, tt.Expectation.Ret[0]) + assert(t, "AddUser6", res2, tt.Expectation.Ret[1]) + }) + } +} + +var UserFindByIDTestCase = []TestCase{} + +func Test_user_FindByID(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserFindByIDTestCase { + t.Run("FindByID_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.FindByID(tt.Input.Args[0].(int)) + assert(t, "FindByID", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserLikeSearchTestCase = []TestCase{} + +func Test_user_LikeSearch(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserLikeSearchTestCase { + t.Run("LikeSearch_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.LikeSearch(tt.Input.Args[0].(string)) + assert(t, "LikeSearch", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserInSearchTestCase = []TestCase{} + +func Test_user_InSearch(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserInSearchTestCase { + t.Run("InSearch_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.InSearch(tt.Input.Args[0].([]string)) + assert(t, "InSearch", res1, tt.Expectation.Ret[0]) + }) + } +} + +var UserColumnSearchTestCase = []TestCase{} + +func Test_user_ColumnSearch(t *testing.T) { + user := newUser(db) + do := user.WithContext(context.Background()).Debug() + + for i, tt := range UserColumnSearchTestCase { + t.Run("ColumnSearch_"+strconv.Itoa(i), func(t *testing.T) { + res1 := do.ColumnSearch(tt.Input.Args[0].(string), tt.Input.Args[1].([]string)) + assert(t, "ColumnSearch", res1, tt.Expectation.Ret[0]) + }) + } +} diff --git a/tests/diy_method/method.go b/tests/diy_method/method.go new file mode 100644 index 00000000..54e41312 --- /dev/null +++ b/tests/diy_method/method.go @@ -0,0 +1,315 @@ +package diy_method + +import ( + "gorm.io/gen" + "time" +) + +type InsertMethod interface { + + // AddUser + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser(name string, age int) (gen.SQLResult, error) + + // AddUser1 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser1(name string, age int) (gen.RowsAffected, error) + + // AddUser2 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser2(name string, age int) gen.RowsAffected + + // AddUser3 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser3(name string, age int) gen.SQLResult + + // AddUser4 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser4(name string, age int) gen.SQLRow + + // AddUser5 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser5(name string, age int) gen.SQLRows + + // AddUser6 + // + // INSERT INTO users (name,age) VALUES (@name,@age) ON DUPLICATE KEY UPDATE age=VALUES(age) + AddUser6(name string, age int) (gen.SQLRows, error) +} + +type SelectMethod interface { + + // FindByID + // + // select * from users where id=@id + FindByID(id int) gen.T + + // LikeSearch + // + // SELECT * FROM @@table where name LIKE concat('%',@name,'%') + LikeSearch(name string) *gen.T + + // InSearch + // + // select * from @@table where name in @names + InSearch(names []string) []*gen.T + + // ColumnSearch + // + // select * from @@table where @@name in @names + ColumnSearch(name string, names []string) []*gen.T +} + +type TrimTest interface { + + // TestTrim + // + // select * from @@table where + // {{trim}} + // {{for _,name :=range list}} + // name = @name or + // {{end}} + // {{end}} + TestTrim(list []string) []gen.T + + // TestTrimInWhere + // + // select * from @@table + // {{where}} + // {{trim}} + // {{for _,name :=range list}} + // name = @name or + // {{end}} + // {{end}} + // {{end}} + TestTrimInWhere(list []string) []gen.T + + // TestInsert + // + // insert into users (name,age) values + // {{trim}} + // {{for key,value :=range data}} + // (@key,@value), + // {{end}} + // {{end}} + TestInsert(data gen.M) error +} + +type TestIF interface { + // FindByUsers + // + //select * from @@table + //{{where}} + //{{if user.Name !=""}} + //name=@user.Name + //{{end}} + //{{end}} + FindByUsers(user gen.T) []gen.T + + // FindByComplexIf + // + //select * from @@table + //{{where}} + //{{if user != nil && user.Name !=""}} + //name=@user.Name + //{{end}} + //{{end}} + FindByComplexIf(user *gen.T) []gen.T + + // FindByIfTime + // + // select * from @@table + //{{if !start.IsZero()}} + //created_at > start + //{{end}} + FindByIfTime(start time.Time) []gen.T +} + +type TestFor interface { + // TestFor + // + //select * from @@table where + //{{for _,name:=range names}} + //name = @name and + //{{end}} + //1=1 + TestFor(names []string) (gen.T, error) + + // TestForKey + // + // select * from @@table where + //{{for _,name:=range names}} + //or @@name = @value + //{{end}} + //and 1=1 + TestForKey(names []string, name, value string) (gen.T, error) + + // TestForOr + // + //select * from @@table + //{{where}} + //( + //{{for _,name:=range names}} + //name = @name or + //{{end}} + //{{end}} + //) + TestForOr(names []string) (gen.T, error) + + // TestIfInFor + // + //select * from @@table where + //{{for _,name:=range names}} + //{{if name !=""}} + //name = @name or + //{{end}} + //{{end}} + //1=2 + TestIfInFor(names []string, name string) (gen.T, error) + + // TestForInIf + // + //select * from @@table where + //{{if name !="" }} + //{{for _,forName:=range names}} + //name = @forName or + //{{end}} + //{{end}} + //1=2 + TestForInIf(names []string, name string) (gen.T, error) + + // TestForInWhere + // + //select * from @@table + //{{where}} + //{{for _,forName:=range names}} + //or name = @forName + //{{end}} + //{{end}} + TestForInWhere(names []string, name, forName string) (gen.T, error) + + // TestForUserList + // + //select * from users + //{{where}} + //{{for _,user :=range users}} + //name=@user.Name + //{{end}} + //{{end}} + TestForUserList(users []*gen.T, name string) (gen.T, error) + + // TestForMap + // + //select * from users + //{{where}} + //{{for key,value :=range param}} + //@@key=@value + //{{end}} + //{{end}} + TestForMap(param map[string]string, name string) (gen.T, error) + + // TestIfInIf + // + //select * from users + //{{where}} + //{{if name !="xx"}} + //{{if name !="xx"}} + //name=@name + //{{end}} + //{{end}} + //{{end}} + TestIfInIf(name string) gen.T + + // TestMoreFor + // + //select * from @@table + //{{where}} + //{{for _,name := range names}} + //and name=@name + //{{end}} + //{{for _,id:=range ids}} + //and id=@id + //{{end}} + //{{end}} + TestMoreFor(names []string, ids []int) []gen.T + + // TestMoreFor2 + // + //select * from @@table + //{{where}} + //{{for _,name := range names}} + //OR (name=@name + //{{for _,id:=range ids}} + //and id=@id + //{{end}} + // and title !=@name) + //{{end}} + // {{end}} + TestMoreFor2(names []string, ids []int) []gen.T + + // TestForInSet + // + // update @@table + //{{set}} + //{{for _,user:=range users}} + //name=@user.Name, + //{{end}} + // {{end}} where + TestForInSet(users []gen.T) error + + // TestInsertMoreInfo + // + // insert into @@table(name,age)values + //{{for index ,user:=range users}} + //{{if index >0}} + //, + //{{end}} + //(@user.Name,@user.Age) + //{{end}} + TestInsertMoreInfo(users []gen.T) error + + // TestIfElseFor + // + // select * from @@table + // {{where}} + //{{if name =="admin"}} + //( + //{{for index,user:=range users}} + //{{if index !=0}} + //and + //{{end}} + //name like @user.Name + //{{end}} + //) + //{{else if name !="guest"}} + //{{for index,guser:=range users}} + //{{if index ==0}} + //( + //{{else}} + //and + //{{end}} + //name = @guser.Name + //{{end}} + //) + //{{else}} + //name ="guest" + //{{end}} + // {{end}} + TestIfElseFor(name string, users []gen.T) error + + // TestForLike + // + // select * from @@table + // {{where}} + //{{for _,name:=range names}} + //name like concat("%",@name,"%") or + //{{end}} + // {{end}} + TestForLike(names []string) []gen.T +} diff --git a/tests/generate_test.go b/tests/generate_test.go index cd5f31e9..4cfab569 100644 --- a/tests/generate_test.go +++ b/tests/generate_test.go @@ -10,6 +10,8 @@ import ( "time" "gorm.io/gen" + + "gorm.io/gen/tests/diy_method" ) const ( @@ -61,6 +63,24 @@ var generateCase = map[string]func(dir string) *gen.Generator{ g.ApplyBasic(g.GenerateAllTable()...) return g }, + generateDirPrefix + "dal_4": func(dir string) *gen.Generator { + g := gen.NewGenerator(gen.Config{ + OutPath: dir + "/query", + Mode: gen.WithDefaultQuery | gen.WithQueryInterface, + + WithUnitTest: true, + + FieldNullable: true, + FieldCoverable: true, + FieldWithIndexTag: true, + }) + g.UseDB(DB) + g.WithJSONTagNameStrategy(func(c string) string { return "-" }) + g.ApplyBasic(g.GenerateAllTable()...) + g.ApplyInterface(func(testIF diy_method.TestIF, testFor diy_method.TestFor, method diy_method.InsertMethod, selectMethod diy_method.SelectMethod) { + }, g.GenerateModel("users")) + return g + }, } func TestGenerate(t *testing.T) {