From c3be071296c53eabf8492ec4b0dffa4fe41e3fbb Mon Sep 17 00:00:00 2001 From: lz-freedom <632339942@qq.com> Date: Thu, 7 Nov 2024 15:33:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A4=8D=E7=8E=B0=E5=85=B3=E8=81=94?= =?UTF-8?q?=E5=85=B3=E7=B3=BBbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dal/query/accounts.gen.go | 421 ++++++++++++++ dal/query/accounts.gen_test.go | 146 +++++ dal/query/companies.gen.go | 343 +++++++++++ dal/query/companies.gen_test.go | 146 +++++ dal/query/gen.go | 135 +++++ dal/query/gen_test.go | 122 ++++ dal/query/user_account_relations.gen.go | 572 ++++++++++++++++++ dal/query/user_account_relations.gen_test.go | 146 +++++ dal/query/user_exts.gen.go | 485 ++++++++++++++++ dal/query/user_exts.gen_test.go | 146 +++++ dal/query/users.gen.go | 580 +++++++++++++++++++ dal/query/users.gen_test.go | 146 +++++ db.go | 108 ---- gen.go | 8 +- gen_test.go | 35 ++ go.mod | 4 +- main_test.go | 20 - model/models.go | 43 ++ models.go | 60 -- 19 files changed, 3473 insertions(+), 193 deletions(-) create mode 100644 dal/query/accounts.gen.go create mode 100644 dal/query/accounts.gen_test.go create mode 100644 dal/query/companies.gen.go create mode 100644 dal/query/companies.gen_test.go create mode 100644 dal/query/gen.go create mode 100644 dal/query/gen_test.go create mode 100644 dal/query/user_account_relations.gen.go create mode 100644 dal/query/user_account_relations.gen_test.go create mode 100644 dal/query/user_exts.gen.go create mode 100644 dal/query/user_exts.gen_test.go create mode 100644 dal/query/users.gen.go create mode 100644 dal/query/users.gen_test.go delete mode 100644 db.go create mode 100644 gen_test.go delete mode 100644 main_test.go create mode 100644 model/models.go delete mode 100644 models.go diff --git a/dal/query/accounts.gen.go b/dal/query/accounts.gen.go new file mode 100644 index 00000000..480508a4 --- /dev/null +++ b/dal/query/accounts.gen.go @@ -0,0 +1,421 @@ +// 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" + + "playground/model" +) + +func newAccount(db *gorm.DB, opts ...gen.DOOption) account { + _account := account{} + + _account.accountDo.UseDB(db, opts...) + _account.accountDo.UseModel(&model.Account{}) + + tableName := _account.accountDo.TableName() + _account.ALL = field.NewAsterisk(tableName) + _account.ID = field.NewUint(tableName, "id") + _account.CreatedAt = field.NewTime(tableName, "created_at") + _account.UpdatedAt = field.NewTime(tableName, "updated_at") + _account.DeletedAt = field.NewField(tableName, "deleted_at") + _account.CompanyID = field.NewUint(tableName, "company_id") + _account.CompanyInfo = accountBelongsToCompanyInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("CompanyInfo", "model.Company"), + } + + _account.fillFieldMap() + + return _account +} + +type account struct { + accountDo accountDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + CompanyID field.Uint + CompanyInfo accountBelongsToCompanyInfo + + fieldMap map[string]field.Expr +} + +func (a account) Table(newTableName string) *account { + a.accountDo.UseTable(newTableName) + return a.updateTableName(newTableName) +} + +func (a account) As(alias string) *account { + a.accountDo.DO = *(a.accountDo.As(alias).(*gen.DO)) + return a.updateTableName(alias) +} + +func (a *account) updateTableName(table string) *account { + a.ALL = field.NewAsterisk(table) + a.ID = field.NewUint(table, "id") + a.CreatedAt = field.NewTime(table, "created_at") + a.UpdatedAt = field.NewTime(table, "updated_at") + a.DeletedAt = field.NewField(table, "deleted_at") + a.CompanyID = field.NewUint(table, "company_id") + + a.fillFieldMap() + + return a +} + +func (a *account) WithContext(ctx context.Context) *accountDo { return a.accountDo.WithContext(ctx) } + +func (a account) TableName() string { return a.accountDo.TableName() } + +func (a account) Alias() string { return a.accountDo.Alias() } + +func (a account) Columns(cols ...field.Expr) gen.Columns { return a.accountDo.Columns(cols...) } + +func (a *account) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := a.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (a *account) fillFieldMap() { + a.fieldMap = make(map[string]field.Expr, 6) + a.fieldMap["id"] = a.ID + a.fieldMap["created_at"] = a.CreatedAt + a.fieldMap["updated_at"] = a.UpdatedAt + a.fieldMap["deleted_at"] = a.DeletedAt + a.fieldMap["company_id"] = a.CompanyID + +} + +func (a account) clone(db *gorm.DB) account { + a.accountDo.ReplaceConnPool(db.Statement.ConnPool) + return a +} + +func (a account) replaceDB(db *gorm.DB) account { + a.accountDo.ReplaceDB(db) + return a +} + +type accountBelongsToCompanyInfo struct { + db *gorm.DB + + field.RelationField +} + +func (a accountBelongsToCompanyInfo) Where(conds ...field.Expr) *accountBelongsToCompanyInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a accountBelongsToCompanyInfo) WithContext(ctx context.Context) *accountBelongsToCompanyInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a accountBelongsToCompanyInfo) Session(session *gorm.Session) *accountBelongsToCompanyInfo { + a.db = a.db.Session(session) + return &a +} + +func (a accountBelongsToCompanyInfo) Model(m *model.Account) *accountBelongsToCompanyInfoTx { + return &accountBelongsToCompanyInfoTx{a.db.Model(m).Association(a.Name())} +} + +type accountBelongsToCompanyInfoTx struct{ tx *gorm.Association } + +func (a accountBelongsToCompanyInfoTx) Find() (result *model.Company, err error) { + return result, a.tx.Find(&result) +} + +func (a accountBelongsToCompanyInfoTx) Append(values ...*model.Company) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a accountBelongsToCompanyInfoTx) Replace(values ...*model.Company) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a accountBelongsToCompanyInfoTx) Delete(values ...*model.Company) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a accountBelongsToCompanyInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a accountBelongsToCompanyInfoTx) Count() int64 { + return a.tx.Count() +} + +type accountDo struct{ gen.DO } + +func (a accountDo) Debug() *accountDo { + return a.withDO(a.DO.Debug()) +} + +func (a accountDo) WithContext(ctx context.Context) *accountDo { + return a.withDO(a.DO.WithContext(ctx)) +} + +func (a accountDo) ReadDB() *accountDo { + return a.Clauses(dbresolver.Read) +} + +func (a accountDo) WriteDB() *accountDo { + return a.Clauses(dbresolver.Write) +} + +func (a accountDo) Session(config *gorm.Session) *accountDo { + return a.withDO(a.DO.Session(config)) +} + +func (a accountDo) Clauses(conds ...clause.Expression) *accountDo { + return a.withDO(a.DO.Clauses(conds...)) +} + +func (a accountDo) Returning(value interface{}, columns ...string) *accountDo { + return a.withDO(a.DO.Returning(value, columns...)) +} + +func (a accountDo) Not(conds ...gen.Condition) *accountDo { + return a.withDO(a.DO.Not(conds...)) +} + +func (a accountDo) Or(conds ...gen.Condition) *accountDo { + return a.withDO(a.DO.Or(conds...)) +} + +func (a accountDo) Select(conds ...field.Expr) *accountDo { + return a.withDO(a.DO.Select(conds...)) +} + +func (a accountDo) Where(conds ...gen.Condition) *accountDo { + return a.withDO(a.DO.Where(conds...)) +} + +func (a accountDo) Order(conds ...field.Expr) *accountDo { + return a.withDO(a.DO.Order(conds...)) +} + +func (a accountDo) Distinct(cols ...field.Expr) *accountDo { + return a.withDO(a.DO.Distinct(cols...)) +} + +func (a accountDo) Omit(cols ...field.Expr) *accountDo { + return a.withDO(a.DO.Omit(cols...)) +} + +func (a accountDo) Join(table schema.Tabler, on ...field.Expr) *accountDo { + return a.withDO(a.DO.Join(table, on...)) +} + +func (a accountDo) LeftJoin(table schema.Tabler, on ...field.Expr) *accountDo { + return a.withDO(a.DO.LeftJoin(table, on...)) +} + +func (a accountDo) RightJoin(table schema.Tabler, on ...field.Expr) *accountDo { + return a.withDO(a.DO.RightJoin(table, on...)) +} + +func (a accountDo) Group(cols ...field.Expr) *accountDo { + return a.withDO(a.DO.Group(cols...)) +} + +func (a accountDo) Having(conds ...gen.Condition) *accountDo { + return a.withDO(a.DO.Having(conds...)) +} + +func (a accountDo) Limit(limit int) *accountDo { + return a.withDO(a.DO.Limit(limit)) +} + +func (a accountDo) Offset(offset int) *accountDo { + return a.withDO(a.DO.Offset(offset)) +} + +func (a accountDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *accountDo { + return a.withDO(a.DO.Scopes(funcs...)) +} + +func (a accountDo) Unscoped() *accountDo { + return a.withDO(a.DO.Unscoped()) +} + +func (a accountDo) Create(values ...*model.Account) error { + if len(values) == 0 { + return nil + } + return a.DO.Create(values) +} + +func (a accountDo) CreateInBatches(values []*model.Account, batchSize int) error { + return a.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 (a accountDo) Save(values ...*model.Account) error { + if len(values) == 0 { + return nil + } + return a.DO.Save(values) +} + +func (a accountDo) First() (*model.Account, error) { + if result, err := a.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Account), nil + } +} + +func (a accountDo) Take() (*model.Account, error) { + if result, err := a.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Account), nil + } +} + +func (a accountDo) Last() (*model.Account, error) { + if result, err := a.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Account), nil + } +} + +func (a accountDo) Find() ([]*model.Account, error) { + result, err := a.DO.Find() + return result.([]*model.Account), err +} + +func (a accountDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Account, err error) { + buf := make([]*model.Account, 0, batchSize) + err = a.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 (a accountDo) FindInBatches(result *[]*model.Account, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return a.DO.FindInBatches(result, batchSize, fc) +} + +func (a accountDo) Attrs(attrs ...field.AssignExpr) *accountDo { + return a.withDO(a.DO.Attrs(attrs...)) +} + +func (a accountDo) Assign(attrs ...field.AssignExpr) *accountDo { + return a.withDO(a.DO.Assign(attrs...)) +} + +func (a accountDo) Joins(fields ...field.RelationField) *accountDo { + for _, _f := range fields { + a = *a.withDO(a.DO.Joins(_f)) + } + return &a +} + +func (a accountDo) Preload(fields ...field.RelationField) *accountDo { + for _, _f := range fields { + a = *a.withDO(a.DO.Preload(_f)) + } + return &a +} + +func (a accountDo) FirstOrInit() (*model.Account, error) { + if result, err := a.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Account), nil + } +} + +func (a accountDo) FirstOrCreate() (*model.Account, error) { + if result, err := a.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Account), nil + } +} + +func (a accountDo) FindByPage(offset int, limit int) (result []*model.Account, count int64, err error) { + result, err = a.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 = a.Offset(-1).Limit(-1).Count() + return +} + +func (a accountDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = a.Count() + if err != nil { + return + } + + err = a.Offset(offset).Limit(limit).Scan(result) + return +} + +func (a accountDo) Scan(result interface{}) (err error) { + return a.DO.Scan(result) +} + +func (a accountDo) Delete(models ...*model.Account) (result gen.ResultInfo, err error) { + return a.DO.Delete(models) +} + +func (a *accountDo) withDO(do gen.Dao) *accountDo { + a.DO = *do.(*gen.DO) + return a +} diff --git a/dal/query/accounts.gen_test.go b/dal/query/accounts.gen_test.go new file mode 100644 index 00000000..2464dcb5 --- /dev/null +++ b/dal/query/accounts.gen_test.go @@ -0,0 +1,146 @@ +// 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" + + "playground/model" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.Account{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.Account{}) fail: %s", err) + } +} + +func Test_accountQuery(t *testing.T) { + account := newAccount(db) + account = *account.As(account.TableName()) + _do := account.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(account.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := account.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from account success") + } + + err = _do.Create(&model.Account{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.Account{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.Account{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(account.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.Account{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(account.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(account.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.Account{}, 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(), "id") + + 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/dal/query/companies.gen.go b/dal/query/companies.gen.go new file mode 100644 index 00000000..ceaa031d --- /dev/null +++ b/dal/query/companies.gen.go @@ -0,0 +1,343 @@ +// 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" + + "playground/model" +) + +func newCompany(db *gorm.DB, opts ...gen.DOOption) company { + _company := company{} + + _company.companyDo.UseDB(db, opts...) + _company.companyDo.UseModel(&model.Company{}) + + tableName := _company.companyDo.TableName() + _company.ALL = field.NewAsterisk(tableName) + _company.ID = field.NewUint(tableName, "id") + _company.CreatedAt = field.NewTime(tableName, "created_at") + _company.UpdatedAt = field.NewTime(tableName, "updated_at") + _company.DeletedAt = field.NewField(tableName, "deleted_at") + _company.Name = field.NewString(tableName, "name") + + _company.fillFieldMap() + + return _company +} + +type company struct { + companyDo companyDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Name field.String + + fieldMap map[string]field.Expr +} + +func (c company) Table(newTableName string) *company { + c.companyDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c company) As(alias string) *company { + c.companyDo.DO = *(c.companyDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *company) updateTableName(table string) *company { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewUint(table, "id") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + c.Name = field.NewString(table, "name") + + c.fillFieldMap() + + return c +} + +func (c *company) WithContext(ctx context.Context) *companyDo { return c.companyDo.WithContext(ctx) } + +func (c company) TableName() string { return c.companyDo.TableName() } + +func (c company) Alias() string { return c.companyDo.Alias() } + +func (c company) Columns(cols ...field.Expr) gen.Columns { return c.companyDo.Columns(cols...) } + +func (c *company) 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 *company) 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["name"] = c.Name +} + +func (c company) clone(db *gorm.DB) company { + c.companyDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c company) replaceDB(db *gorm.DB) company { + c.companyDo.ReplaceDB(db) + return c +} + +type companyDo struct{ gen.DO } + +func (c companyDo) Debug() *companyDo { + return c.withDO(c.DO.Debug()) +} + +func (c companyDo) WithContext(ctx context.Context) *companyDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c companyDo) ReadDB() *companyDo { + return c.Clauses(dbresolver.Read) +} + +func (c companyDo) WriteDB() *companyDo { + return c.Clauses(dbresolver.Write) +} + +func (c companyDo) Session(config *gorm.Session) *companyDo { + return c.withDO(c.DO.Session(config)) +} + +func (c companyDo) Clauses(conds ...clause.Expression) *companyDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c companyDo) Returning(value interface{}, columns ...string) *companyDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c companyDo) Not(conds ...gen.Condition) *companyDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c companyDo) Or(conds ...gen.Condition) *companyDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c companyDo) Select(conds ...field.Expr) *companyDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c companyDo) Where(conds ...gen.Condition) *companyDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c companyDo) Order(conds ...field.Expr) *companyDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c companyDo) Distinct(cols ...field.Expr) *companyDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c companyDo) Omit(cols ...field.Expr) *companyDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c companyDo) Join(table schema.Tabler, on ...field.Expr) *companyDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c companyDo) LeftJoin(table schema.Tabler, on ...field.Expr) *companyDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c companyDo) RightJoin(table schema.Tabler, on ...field.Expr) *companyDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c companyDo) Group(cols ...field.Expr) *companyDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c companyDo) Having(conds ...gen.Condition) *companyDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c companyDo) Limit(limit int) *companyDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c companyDo) Offset(offset int) *companyDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c companyDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *companyDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c companyDo) Unscoped() *companyDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c companyDo) Create(values ...*model.Company) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c companyDo) CreateInBatches(values []*model.Company, 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 companyDo) Save(values ...*model.Company) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c companyDo) First() (*model.Company, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Company), nil + } +} + +func (c companyDo) Take() (*model.Company, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Company), nil + } +} + +func (c companyDo) Last() (*model.Company, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Company), nil + } +} + +func (c companyDo) Find() ([]*model.Company, error) { + result, err := c.DO.Find() + return result.([]*model.Company), err +} + +func (c companyDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Company, err error) { + buf := make([]*model.Company, 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 companyDo) FindInBatches(result *[]*model.Company, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c companyDo) Attrs(attrs ...field.AssignExpr) *companyDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c companyDo) Assign(attrs ...field.AssignExpr) *companyDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c companyDo) Joins(fields ...field.RelationField) *companyDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c companyDo) Preload(fields ...field.RelationField) *companyDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c companyDo) FirstOrInit() (*model.Company, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Company), nil + } +} + +func (c companyDo) FirstOrCreate() (*model.Company, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Company), nil + } +} + +func (c companyDo) FindByPage(offset int, limit int) (result []*model.Company, 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 companyDo) 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 companyDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c companyDo) Delete(models ...*model.Company) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +func (c *companyDo) withDO(do gen.Dao) *companyDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/dal/query/companies.gen_test.go b/dal/query/companies.gen_test.go new file mode 100644 index 00000000..353cffbf --- /dev/null +++ b/dal/query/companies.gen_test.go @@ -0,0 +1,146 @@ +// 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" + + "playground/model" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.Company{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.Company{}) fail: %s", err) + } +} + +func Test_companyQuery(t *testing.T) { + company := newCompany(db) + company = *company.As(company.TableName()) + _do := company.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(company.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := company.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from company success") + } + + err = _do.Create(&model.Company{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.Company{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.Company{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(company.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.Company{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(company.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(company.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.Company{}, 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(), "id") + + 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/dal/query/gen.go b/dal/query/gen.go new file mode 100644 index 00000000..606db5a1 --- /dev/null +++ b/dal/query/gen.go @@ -0,0 +1,135 @@ +// 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) + Account *account + Company *company + User *user + UserAccountRelation *userAccountRelation + UserExt *userExt +) + +func SetDefault(db *gorm.DB, opts ...gen.DOOption) { + *Q = *Use(db, opts...) + Account = &Q.Account + Company = &Q.Company + User = &Q.User + UserAccountRelation = &Q.UserAccountRelation + UserExt = &Q.UserExt +} + +func Use(db *gorm.DB, opts ...gen.DOOption) *Query { + return &Query{ + db: db, + Account: newAccount(db, opts...), + Company: newCompany(db, opts...), + User: newUser(db, opts...), + UserAccountRelation: newUserAccountRelation(db, opts...), + UserExt: newUserExt(db, opts...), + } +} + +type Query struct { + db *gorm.DB + + Account account + Company company + User user + UserAccountRelation userAccountRelation + UserExt userExt +} + +func (q *Query) Available() bool { return q.db != nil } + +func (q *Query) clone(db *gorm.DB) *Query { + return &Query{ + db: db, + Account: q.Account.clone(db), + Company: q.Company.clone(db), + User: q.User.clone(db), + UserAccountRelation: q.UserAccountRelation.clone(db), + UserExt: q.UserExt.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, + Account: q.Account.replaceDB(db), + Company: q.Company.replaceDB(db), + User: q.User.replaceDB(db), + UserAccountRelation: q.UserAccountRelation.replaceDB(db), + UserExt: q.UserExt.replaceDB(db), + } +} + +type queryCtx struct { + Account *accountDo + Company *companyDo + User *userDo + UserAccountRelation *userAccountRelationDo + UserExt *userExtDo +} + +func (q *Query) WithContext(ctx context.Context) *queryCtx { + return &queryCtx{ + Account: q.Account.WithContext(ctx), + Company: q.Company.WithContext(ctx), + User: q.User.WithContext(ctx), + UserAccountRelation: q.UserAccountRelation.WithContext(ctx), + UserExt: q.UserExt.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 { + tx := q.db.Begin(opts...) + return &QueryTx{Query: q.clone(tx), Error: tx.Error} +} + +type QueryTx struct { + *Query + Error error +} + +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/dal/query/gen_test.go b/dal/query/gen_test.go new file mode 100644 index 00000000..e532508d --- /dev/null +++ b/dal/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.Account.UnderlyingDB().Statement.Context, + qCtx.Company.UnderlyingDB().Statement.Context, + qCtx.User.UnderlyingDB().Statement.Context, + qCtx.UserAccountRelation.UnderlyingDB().Statement.Context, + qCtx.UserExt.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/dal/query/user_account_relations.gen.go b/dal/query/user_account_relations.gen.go new file mode 100644 index 00000000..7dc7158c --- /dev/null +++ b/dal/query/user_account_relations.gen.go @@ -0,0 +1,572 @@ +// 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" + + "playground/model" +) + +func newUserAccountRelation(db *gorm.DB, opts ...gen.DOOption) userAccountRelation { + _userAccountRelation := userAccountRelation{} + + _userAccountRelation.userAccountRelationDo.UseDB(db, opts...) + _userAccountRelation.userAccountRelationDo.UseModel(&model.UserAccountRelation{}) + + tableName := _userAccountRelation.userAccountRelationDo.TableName() + _userAccountRelation.ALL = field.NewAsterisk(tableName) + _userAccountRelation.ID = field.NewUint(tableName, "id") + _userAccountRelation.CreatedAt = field.NewTime(tableName, "created_at") + _userAccountRelation.UpdatedAt = field.NewTime(tableName, "updated_at") + _userAccountRelation.DeletedAt = field.NewField(tableName, "deleted_at") + _userAccountRelation.UserID = field.NewUint(tableName, "user_id") + _userAccountRelation.AccountID = field.NewUint(tableName, "account_id") + _userAccountRelation.UserInfo = userAccountRelationBelongsToUserInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("UserInfo", "model.User"), + UserExtInfo: struct { + field.RelationField + UserInfo struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("UserInfo.UserExtInfo", "model.UserExt"), + UserInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserExtInfo.UserInfo", "model.User"), + }, + }, + UserAccountRelationInfo: struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo", "model.UserAccountRelation"), + UserInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.UserInfo", "model.User"), + }, + AccountInfo: struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.AccountInfo", "model.Account"), + CompanyInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.AccountInfo.CompanyInfo", "model.Company"), + }, + }, + }, + } + + _userAccountRelation.AccountInfo = userAccountRelationBelongsToAccountInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("AccountInfo", "model.Account"), + } + + _userAccountRelation.fillFieldMap() + + return _userAccountRelation +} + +type userAccountRelation struct { + userAccountRelationDo userAccountRelationDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + UserID field.Uint + AccountID field.Uint + UserInfo userAccountRelationBelongsToUserInfo + + AccountInfo userAccountRelationBelongsToAccountInfo + + fieldMap map[string]field.Expr +} + +func (u userAccountRelation) Table(newTableName string) *userAccountRelation { + u.userAccountRelationDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userAccountRelation) As(alias string) *userAccountRelation { + u.userAccountRelationDo.DO = *(u.userAccountRelationDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userAccountRelation) updateTableName(table string) *userAccountRelation { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewUint(table, "id") + u.CreatedAt = field.NewTime(table, "created_at") + u.UpdatedAt = field.NewTime(table, "updated_at") + u.DeletedAt = field.NewField(table, "deleted_at") + u.UserID = field.NewUint(table, "user_id") + u.AccountID = field.NewUint(table, "account_id") + + u.fillFieldMap() + + return u +} + +func (u *userAccountRelation) WithContext(ctx context.Context) *userAccountRelationDo { + return u.userAccountRelationDo.WithContext(ctx) +} + +func (u userAccountRelation) TableName() string { return u.userAccountRelationDo.TableName() } + +func (u userAccountRelation) Alias() string { return u.userAccountRelationDo.Alias() } + +func (u userAccountRelation) Columns(cols ...field.Expr) gen.Columns { + return u.userAccountRelationDo.Columns(cols...) +} + +func (u *userAccountRelation) 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 *userAccountRelation) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 8) + u.fieldMap["id"] = u.ID + u.fieldMap["created_at"] = u.CreatedAt + u.fieldMap["updated_at"] = u.UpdatedAt + u.fieldMap["deleted_at"] = u.DeletedAt + u.fieldMap["user_id"] = u.UserID + u.fieldMap["account_id"] = u.AccountID + +} + +func (u userAccountRelation) clone(db *gorm.DB) userAccountRelation { + u.userAccountRelationDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userAccountRelation) replaceDB(db *gorm.DB) userAccountRelation { + u.userAccountRelationDo.ReplaceDB(db) + return u +} + +type userAccountRelationBelongsToUserInfo struct { + db *gorm.DB + + field.RelationField + + UserExtInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + } + UserAccountRelationInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + } +} + +func (a userAccountRelationBelongsToUserInfo) Where(conds ...field.Expr) *userAccountRelationBelongsToUserInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a userAccountRelationBelongsToUserInfo) WithContext(ctx context.Context) *userAccountRelationBelongsToUserInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a userAccountRelationBelongsToUserInfo) Session(session *gorm.Session) *userAccountRelationBelongsToUserInfo { + a.db = a.db.Session(session) + return &a +} + +func (a userAccountRelationBelongsToUserInfo) Model(m *model.UserAccountRelation) *userAccountRelationBelongsToUserInfoTx { + return &userAccountRelationBelongsToUserInfoTx{a.db.Model(m).Association(a.Name())} +} + +type userAccountRelationBelongsToUserInfoTx struct{ tx *gorm.Association } + +func (a userAccountRelationBelongsToUserInfoTx) Find() (result *model.User, err error) { + return result, a.tx.Find(&result) +} + +func (a userAccountRelationBelongsToUserInfoTx) Append(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a userAccountRelationBelongsToUserInfoTx) Replace(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a userAccountRelationBelongsToUserInfoTx) Delete(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a userAccountRelationBelongsToUserInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a userAccountRelationBelongsToUserInfoTx) Count() int64 { + return a.tx.Count() +} + +type userAccountRelationBelongsToAccountInfo struct { + db *gorm.DB + + field.RelationField +} + +func (a userAccountRelationBelongsToAccountInfo) Where(conds ...field.Expr) *userAccountRelationBelongsToAccountInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a userAccountRelationBelongsToAccountInfo) WithContext(ctx context.Context) *userAccountRelationBelongsToAccountInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a userAccountRelationBelongsToAccountInfo) Session(session *gorm.Session) *userAccountRelationBelongsToAccountInfo { + a.db = a.db.Session(session) + return &a +} + +func (a userAccountRelationBelongsToAccountInfo) Model(m *model.UserAccountRelation) *userAccountRelationBelongsToAccountInfoTx { + return &userAccountRelationBelongsToAccountInfoTx{a.db.Model(m).Association(a.Name())} +} + +type userAccountRelationBelongsToAccountInfoTx struct{ tx *gorm.Association } + +func (a userAccountRelationBelongsToAccountInfoTx) Find() (result *model.Account, err error) { + return result, a.tx.Find(&result) +} + +func (a userAccountRelationBelongsToAccountInfoTx) Append(values ...*model.Account) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a userAccountRelationBelongsToAccountInfoTx) Replace(values ...*model.Account) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a userAccountRelationBelongsToAccountInfoTx) Delete(values ...*model.Account) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a userAccountRelationBelongsToAccountInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a userAccountRelationBelongsToAccountInfoTx) Count() int64 { + return a.tx.Count() +} + +type userAccountRelationDo struct{ gen.DO } + +func (u userAccountRelationDo) Debug() *userAccountRelationDo { + return u.withDO(u.DO.Debug()) +} + +func (u userAccountRelationDo) WithContext(ctx context.Context) *userAccountRelationDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userAccountRelationDo) ReadDB() *userAccountRelationDo { + return u.Clauses(dbresolver.Read) +} + +func (u userAccountRelationDo) WriteDB() *userAccountRelationDo { + return u.Clauses(dbresolver.Write) +} + +func (u userAccountRelationDo) Session(config *gorm.Session) *userAccountRelationDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userAccountRelationDo) Clauses(conds ...clause.Expression) *userAccountRelationDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userAccountRelationDo) Returning(value interface{}, columns ...string) *userAccountRelationDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userAccountRelationDo) Not(conds ...gen.Condition) *userAccountRelationDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userAccountRelationDo) Or(conds ...gen.Condition) *userAccountRelationDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userAccountRelationDo) Select(conds ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userAccountRelationDo) Where(conds ...gen.Condition) *userAccountRelationDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userAccountRelationDo) Order(conds ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userAccountRelationDo) Distinct(cols ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userAccountRelationDo) Omit(cols ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userAccountRelationDo) Join(table schema.Tabler, on ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userAccountRelationDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userAccountRelationDo) RightJoin(table schema.Tabler, on ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userAccountRelationDo) Group(cols ...field.Expr) *userAccountRelationDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userAccountRelationDo) Having(conds ...gen.Condition) *userAccountRelationDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userAccountRelationDo) Limit(limit int) *userAccountRelationDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userAccountRelationDo) Offset(offset int) *userAccountRelationDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userAccountRelationDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userAccountRelationDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userAccountRelationDo) Unscoped() *userAccountRelationDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userAccountRelationDo) Create(values ...*model.UserAccountRelation) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userAccountRelationDo) CreateInBatches(values []*model.UserAccountRelation, 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 userAccountRelationDo) Save(values ...*model.UserAccountRelation) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userAccountRelationDo) First() (*model.UserAccountRelation, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.UserAccountRelation), nil + } +} + +func (u userAccountRelationDo) Take() (*model.UserAccountRelation, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.UserAccountRelation), nil + } +} + +func (u userAccountRelationDo) Last() (*model.UserAccountRelation, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.UserAccountRelation), nil + } +} + +func (u userAccountRelationDo) Find() ([]*model.UserAccountRelation, error) { + result, err := u.DO.Find() + return result.([]*model.UserAccountRelation), err +} + +func (u userAccountRelationDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.UserAccountRelation, err error) { + buf := make([]*model.UserAccountRelation, 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 userAccountRelationDo) FindInBatches(result *[]*model.UserAccountRelation, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userAccountRelationDo) Attrs(attrs ...field.AssignExpr) *userAccountRelationDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userAccountRelationDo) Assign(attrs ...field.AssignExpr) *userAccountRelationDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userAccountRelationDo) Joins(fields ...field.RelationField) *userAccountRelationDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userAccountRelationDo) Preload(fields ...field.RelationField) *userAccountRelationDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userAccountRelationDo) FirstOrInit() (*model.UserAccountRelation, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.UserAccountRelation), nil + } +} + +func (u userAccountRelationDo) FirstOrCreate() (*model.UserAccountRelation, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.UserAccountRelation), nil + } +} + +func (u userAccountRelationDo) FindByPage(offset int, limit int) (result []*model.UserAccountRelation, 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 userAccountRelationDo) 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 userAccountRelationDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userAccountRelationDo) Delete(models ...*model.UserAccountRelation) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +func (u *userAccountRelationDo) withDO(do gen.Dao) *userAccountRelationDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/dal/query/user_account_relations.gen_test.go b/dal/query/user_account_relations.gen_test.go new file mode 100644 index 00000000..271b7092 --- /dev/null +++ b/dal/query/user_account_relations.gen_test.go @@ -0,0 +1,146 @@ +// 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" + + "playground/model" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.UserAccountRelation{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.UserAccountRelation{}) fail: %s", err) + } +} + +func Test_userAccountRelationQuery(t *testing.T) { + userAccountRelation := newUserAccountRelation(db) + userAccountRelation = *userAccountRelation.As(userAccountRelation.TableName()) + _do := userAccountRelation.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(userAccountRelation.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := userAccountRelation.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from userAccountRelation success") + } + + err = _do.Create(&model.UserAccountRelation{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.UserAccountRelation{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.UserAccountRelation{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(userAccountRelation.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.UserAccountRelation{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(userAccountRelation.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(userAccountRelation.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.UserAccountRelation{}, 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(), "id") + + 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/dal/query/user_exts.gen.go b/dal/query/user_exts.gen.go new file mode 100644 index 00000000..752734b5 --- /dev/null +++ b/dal/query/user_exts.gen.go @@ -0,0 +1,485 @@ +// 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" + + "playground/model" +) + +func newUserExt(db *gorm.DB, opts ...gen.DOOption) userExt { + _userExt := userExt{} + + _userExt.userExtDo.UseDB(db, opts...) + _userExt.userExtDo.UseModel(&model.UserExt{}) + + tableName := _userExt.userExtDo.TableName() + _userExt.ALL = field.NewAsterisk(tableName) + _userExt.ID = field.NewUint(tableName, "id") + _userExt.CreatedAt = field.NewTime(tableName, "created_at") + _userExt.UpdatedAt = field.NewTime(tableName, "updated_at") + _userExt.DeletedAt = field.NewField(tableName, "deleted_at") + _userExt.UserID = field.NewUint(tableName, "user_id") + _userExt.UserInfo = userExtBelongsToUserInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("UserInfo", "model.User"), + UserExtInfo: struct { + field.RelationField + UserInfo struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("UserInfo.UserExtInfo", "model.UserExt"), + UserInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserExtInfo.UserInfo", "model.User"), + }, + }, + UserAccountRelationInfo: struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo", "model.UserAccountRelation"), + UserInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.UserInfo", "model.User"), + }, + AccountInfo: struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.AccountInfo", "model.Account"), + CompanyInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserInfo.UserAccountRelationInfo.AccountInfo.CompanyInfo", "model.Company"), + }, + }, + }, + } + + _userExt.fillFieldMap() + + return _userExt +} + +type userExt struct { + userExtDo userExtDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + UserID field.Uint + UserInfo userExtBelongsToUserInfo + + fieldMap map[string]field.Expr +} + +func (u userExt) Table(newTableName string) *userExt { + u.userExtDo.UseTable(newTableName) + return u.updateTableName(newTableName) +} + +func (u userExt) As(alias string) *userExt { + u.userExtDo.DO = *(u.userExtDo.As(alias).(*gen.DO)) + return u.updateTableName(alias) +} + +func (u *userExt) updateTableName(table string) *userExt { + u.ALL = field.NewAsterisk(table) + u.ID = field.NewUint(table, "id") + u.CreatedAt = field.NewTime(table, "created_at") + u.UpdatedAt = field.NewTime(table, "updated_at") + u.DeletedAt = field.NewField(table, "deleted_at") + u.UserID = field.NewUint(table, "user_id") + + u.fillFieldMap() + + return u +} + +func (u *userExt) WithContext(ctx context.Context) *userExtDo { return u.userExtDo.WithContext(ctx) } + +func (u userExt) TableName() string { return u.userExtDo.TableName() } + +func (u userExt) Alias() string { return u.userExtDo.Alias() } + +func (u userExt) Columns(cols ...field.Expr) gen.Columns { return u.userExtDo.Columns(cols...) } + +func (u *userExt) 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 *userExt) fillFieldMap() { + u.fieldMap = make(map[string]field.Expr, 6) + u.fieldMap["id"] = u.ID + u.fieldMap["created_at"] = u.CreatedAt + u.fieldMap["updated_at"] = u.UpdatedAt + u.fieldMap["deleted_at"] = u.DeletedAt + u.fieldMap["user_id"] = u.UserID + +} + +func (u userExt) clone(db *gorm.DB) userExt { + u.userExtDo.ReplaceConnPool(db.Statement.ConnPool) + return u +} + +func (u userExt) replaceDB(db *gorm.DB) userExt { + u.userExtDo.ReplaceDB(db) + return u +} + +type userExtBelongsToUserInfo struct { + db *gorm.DB + + field.RelationField + + UserExtInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + } + UserAccountRelationInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + } +} + +func (a userExtBelongsToUserInfo) Where(conds ...field.Expr) *userExtBelongsToUserInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a userExtBelongsToUserInfo) WithContext(ctx context.Context) *userExtBelongsToUserInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a userExtBelongsToUserInfo) Session(session *gorm.Session) *userExtBelongsToUserInfo { + a.db = a.db.Session(session) + return &a +} + +func (a userExtBelongsToUserInfo) Model(m *model.UserExt) *userExtBelongsToUserInfoTx { + return &userExtBelongsToUserInfoTx{a.db.Model(m).Association(a.Name())} +} + +type userExtBelongsToUserInfoTx struct{ tx *gorm.Association } + +func (a userExtBelongsToUserInfoTx) Find() (result *model.User, err error) { + return result, a.tx.Find(&result) +} + +func (a userExtBelongsToUserInfoTx) Append(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a userExtBelongsToUserInfoTx) Replace(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a userExtBelongsToUserInfoTx) Delete(values ...*model.User) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a userExtBelongsToUserInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a userExtBelongsToUserInfoTx) Count() int64 { + return a.tx.Count() +} + +type userExtDo struct{ gen.DO } + +func (u userExtDo) Debug() *userExtDo { + return u.withDO(u.DO.Debug()) +} + +func (u userExtDo) WithContext(ctx context.Context) *userExtDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userExtDo) ReadDB() *userExtDo { + return u.Clauses(dbresolver.Read) +} + +func (u userExtDo) WriteDB() *userExtDo { + return u.Clauses(dbresolver.Write) +} + +func (u userExtDo) Session(config *gorm.Session) *userExtDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userExtDo) Clauses(conds ...clause.Expression) *userExtDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userExtDo) Returning(value interface{}, columns ...string) *userExtDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userExtDo) Not(conds ...gen.Condition) *userExtDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userExtDo) Or(conds ...gen.Condition) *userExtDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userExtDo) Select(conds ...field.Expr) *userExtDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userExtDo) Where(conds ...gen.Condition) *userExtDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userExtDo) Order(conds ...field.Expr) *userExtDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userExtDo) Distinct(cols ...field.Expr) *userExtDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userExtDo) Omit(cols ...field.Expr) *userExtDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userExtDo) Join(table schema.Tabler, on ...field.Expr) *userExtDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userExtDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userExtDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userExtDo) RightJoin(table schema.Tabler, on ...field.Expr) *userExtDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userExtDo) Group(cols ...field.Expr) *userExtDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userExtDo) Having(conds ...gen.Condition) *userExtDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userExtDo) Limit(limit int) *userExtDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userExtDo) Offset(offset int) *userExtDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userExtDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userExtDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userExtDo) Unscoped() *userExtDo { + return u.withDO(u.DO.Unscoped()) +} + +func (u userExtDo) Create(values ...*model.UserExt) error { + if len(values) == 0 { + return nil + } + return u.DO.Create(values) +} + +func (u userExtDo) CreateInBatches(values []*model.UserExt, 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 userExtDo) Save(values ...*model.UserExt) error { + if len(values) == 0 { + return nil + } + return u.DO.Save(values) +} + +func (u userExtDo) First() (*model.UserExt, error) { + if result, err := u.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.UserExt), nil + } +} + +func (u userExtDo) Take() (*model.UserExt, error) { + if result, err := u.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.UserExt), nil + } +} + +func (u userExtDo) Last() (*model.UserExt, error) { + if result, err := u.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.UserExt), nil + } +} + +func (u userExtDo) Find() ([]*model.UserExt, error) { + result, err := u.DO.Find() + return result.([]*model.UserExt), err +} + +func (u userExtDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.UserExt, err error) { + buf := make([]*model.UserExt, 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 userExtDo) FindInBatches(result *[]*model.UserExt, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return u.DO.FindInBatches(result, batchSize, fc) +} + +func (u userExtDo) Attrs(attrs ...field.AssignExpr) *userExtDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userExtDo) Assign(attrs ...field.AssignExpr) *userExtDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userExtDo) Joins(fields ...field.RelationField) *userExtDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userExtDo) Preload(fields ...field.RelationField) *userExtDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Preload(_f)) + } + return &u +} + +func (u userExtDo) FirstOrInit() (*model.UserExt, error) { + if result, err := u.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.UserExt), nil + } +} + +func (u userExtDo) FirstOrCreate() (*model.UserExt, error) { + if result, err := u.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.UserExt), nil + } +} + +func (u userExtDo) FindByPage(offset int, limit int) (result []*model.UserExt, 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 userExtDo) 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 userExtDo) Scan(result interface{}) (err error) { + return u.DO.Scan(result) +} + +func (u userExtDo) Delete(models ...*model.UserExt) (result gen.ResultInfo, err error) { + return u.DO.Delete(models) +} + +func (u *userExtDo) withDO(do gen.Dao) *userExtDo { + u.DO = *do.(*gen.DO) + return u +} diff --git a/dal/query/user_exts.gen_test.go b/dal/query/user_exts.gen_test.go new file mode 100644 index 00000000..26877934 --- /dev/null +++ b/dal/query/user_exts.gen_test.go @@ -0,0 +1,146 @@ +// 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" + + "playground/model" + + "gorm.io/gen" + "gorm.io/gen/field" + "gorm.io/gorm/clause" +) + +func init() { + InitializeDB() + err := db.AutoMigrate(&model.UserExt{}) + if err != nil { + fmt.Printf("Error: AutoMigrate(&model.UserExt{}) fail: %s", err) + } +} + +func Test_userExtQuery(t *testing.T) { + userExt := newUserExt(db) + userExt = *userExt.As(userExt.TableName()) + _do := userExt.WithContext(context.Background()).Debug() + + primaryKey := field.NewString(userExt.TableName(), clause.PrimaryKey) + _, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete() + if err != nil { + t.Error("clean table fail:", err) + return + } + + _, ok := userExt.GetFieldByName("") + if ok { + t.Error("GetFieldByName(\"\") from userExt success") + } + + err = _do.Create(&model.UserExt{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.Save(&model.UserExt{}) + if err != nil { + t.Error("create item in table fail:", err) + } + + err = _do.CreateInBatches([]*model.UserExt{{}, {}}, 10) + if err != nil { + t.Error("create item in table fail:", err) + } + + _, err = _do.Select(userExt.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.UserExt{}, 10, func(tx gen.Dao, batch int) error { return nil }) + if err != nil { + t.Error("FindInBatches() on table fail:", err) + } + + _, err = _do.Select(userExt.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(userExt.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.UserExt{}, 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(), "id") + + 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/dal/query/users.gen.go b/dal/query/users.gen.go new file mode 100644 index 00000000..dee92803 --- /dev/null +++ b/dal/query/users.gen.go @@ -0,0 +1,580 @@ +// 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" + + "playground/model" +) + +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.NewUint(tableName, "id") + _user.CreatedAt = field.NewTime(tableName, "created_at") + _user.UpdatedAt = field.NewTime(tableName, "updated_at") + _user.DeletedAt = field.NewField(tableName, "deleted_at") + _user.UserMainID = field.NewUint(tableName, "user_main_id") + _user.Username = field.NewString(tableName, "username") + _user.UserExtInfo = userHasOneUserExtInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("UserExtInfo", "model.UserExt"), + UserInfo: struct { + field.RelationField + UserExtInfo struct { + field.RelationField + } + UserAccountRelationInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + } + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo", "model.User"), + UserExtInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo.UserExtInfo", "model.UserExt"), + }, + UserAccountRelationInfo: struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo.UserAccountRelationInfo", "model.UserAccountRelation"), + UserInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo.UserAccountRelationInfo.UserInfo", "model.User"), + }, + AccountInfo: struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo.UserAccountRelationInfo.AccountInfo", "model.Account"), + CompanyInfo: struct { + field.RelationField + }{ + RelationField: field.NewRelation("UserExtInfo.UserInfo.UserAccountRelationInfo.AccountInfo.CompanyInfo", "model.Company"), + }, + }, + }, + }, + } + + _user.UserAccountRelationInfo = userHasOneUserAccountRelationInfo{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("UserAccountRelationInfo", "model.UserAccountRelation"), + } + + _user.fillFieldMap() + + return _user +} + +type user struct { + userDo userDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + UserMainID field.Uint + Username field.String + UserExtInfo userHasOneUserExtInfo + + UserAccountRelationInfo userHasOneUserAccountRelationInfo + + 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.NewUint(table, "id") + u.CreatedAt = field.NewTime(table, "created_at") + u.UpdatedAt = field.NewTime(table, "updated_at") + u.DeletedAt = field.NewField(table, "deleted_at") + u.UserMainID = field.NewUint(table, "user_main_id") + u.Username = field.NewString(table, "username") + + u.fillFieldMap() + + return u +} + +func (u *user) WithContext(ctx context.Context) *userDo { 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) Columns(cols ...field.Expr) gen.Columns { return u.userDo.Columns(cols...) } + +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["updated_at"] = u.UpdatedAt + u.fieldMap["deleted_at"] = u.DeletedAt + u.fieldMap["user_main_id"] = u.UserMainID + u.fieldMap["username"] = u.Username + +} + +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 userHasOneUserExtInfo struct { + db *gorm.DB + + field.RelationField + + UserInfo struct { + field.RelationField + UserExtInfo struct { + field.RelationField + } + UserAccountRelationInfo struct { + field.RelationField + UserInfo struct { + field.RelationField + } + AccountInfo struct { + field.RelationField + CompanyInfo struct { + field.RelationField + } + } + } + } +} + +func (a userHasOneUserExtInfo) Where(conds ...field.Expr) *userHasOneUserExtInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a userHasOneUserExtInfo) WithContext(ctx context.Context) *userHasOneUserExtInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a userHasOneUserExtInfo) Session(session *gorm.Session) *userHasOneUserExtInfo { + a.db = a.db.Session(session) + return &a +} + +func (a userHasOneUserExtInfo) Model(m *model.User) *userHasOneUserExtInfoTx { + return &userHasOneUserExtInfoTx{a.db.Model(m).Association(a.Name())} +} + +type userHasOneUserExtInfoTx struct{ tx *gorm.Association } + +func (a userHasOneUserExtInfoTx) Find() (result *model.UserExt, err error) { + return result, a.tx.Find(&result) +} + +func (a userHasOneUserExtInfoTx) Append(values ...*model.UserExt) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a userHasOneUserExtInfoTx) Replace(values ...*model.UserExt) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a userHasOneUserExtInfoTx) Delete(values ...*model.UserExt) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a userHasOneUserExtInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a userHasOneUserExtInfoTx) Count() int64 { + return a.tx.Count() +} + +type userHasOneUserAccountRelationInfo struct { + db *gorm.DB + + field.RelationField +} + +func (a userHasOneUserAccountRelationInfo) Where(conds ...field.Expr) *userHasOneUserAccountRelationInfo { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a userHasOneUserAccountRelationInfo) WithContext(ctx context.Context) *userHasOneUserAccountRelationInfo { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a userHasOneUserAccountRelationInfo) Session(session *gorm.Session) *userHasOneUserAccountRelationInfo { + a.db = a.db.Session(session) + return &a +} + +func (a userHasOneUserAccountRelationInfo) Model(m *model.User) *userHasOneUserAccountRelationInfoTx { + return &userHasOneUserAccountRelationInfoTx{a.db.Model(m).Association(a.Name())} +} + +type userHasOneUserAccountRelationInfoTx struct{ tx *gorm.Association } + +func (a userHasOneUserAccountRelationInfoTx) Find() (result *model.UserAccountRelation, err error) { + return result, a.tx.Find(&result) +} + +func (a userHasOneUserAccountRelationInfoTx) Append(values ...*model.UserAccountRelation) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a userHasOneUserAccountRelationInfoTx) Replace(values ...*model.UserAccountRelation) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a userHasOneUserAccountRelationInfoTx) Delete(values ...*model.UserAccountRelation) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a userHasOneUserAccountRelationInfoTx) Clear() error { + return a.tx.Clear() +} + +func (a userHasOneUserAccountRelationInfoTx) Count() int64 { + return a.tx.Count() +} + +type userDo struct{ gen.DO } + +func (u userDo) Debug() *userDo { + return u.withDO(u.DO.Debug()) +} + +func (u userDo) WithContext(ctx context.Context) *userDo { + return u.withDO(u.DO.WithContext(ctx)) +} + +func (u userDo) ReadDB() *userDo { + return u.Clauses(dbresolver.Read) +} + +func (u userDo) WriteDB() *userDo { + return u.Clauses(dbresolver.Write) +} + +func (u userDo) Session(config *gorm.Session) *userDo { + return u.withDO(u.DO.Session(config)) +} + +func (u userDo) Clauses(conds ...clause.Expression) *userDo { + return u.withDO(u.DO.Clauses(conds...)) +} + +func (u userDo) Returning(value interface{}, columns ...string) *userDo { + return u.withDO(u.DO.Returning(value, columns...)) +} + +func (u userDo) Not(conds ...gen.Condition) *userDo { + return u.withDO(u.DO.Not(conds...)) +} + +func (u userDo) Or(conds ...gen.Condition) *userDo { + return u.withDO(u.DO.Or(conds...)) +} + +func (u userDo) Select(conds ...field.Expr) *userDo { + return u.withDO(u.DO.Select(conds...)) +} + +func (u userDo) Where(conds ...gen.Condition) *userDo { + return u.withDO(u.DO.Where(conds...)) +} + +func (u userDo) Order(conds ...field.Expr) *userDo { + return u.withDO(u.DO.Order(conds...)) +} + +func (u userDo) Distinct(cols ...field.Expr) *userDo { + return u.withDO(u.DO.Distinct(cols...)) +} + +func (u userDo) Omit(cols ...field.Expr) *userDo { + return u.withDO(u.DO.Omit(cols...)) +} + +func (u userDo) Join(table schema.Tabler, on ...field.Expr) *userDo { + return u.withDO(u.DO.Join(table, on...)) +} + +func (u userDo) LeftJoin(table schema.Tabler, on ...field.Expr) *userDo { + return u.withDO(u.DO.LeftJoin(table, on...)) +} + +func (u userDo) RightJoin(table schema.Tabler, on ...field.Expr) *userDo { + return u.withDO(u.DO.RightJoin(table, on...)) +} + +func (u userDo) Group(cols ...field.Expr) *userDo { + return u.withDO(u.DO.Group(cols...)) +} + +func (u userDo) Having(conds ...gen.Condition) *userDo { + return u.withDO(u.DO.Having(conds...)) +} + +func (u userDo) Limit(limit int) *userDo { + return u.withDO(u.DO.Limit(limit)) +} + +func (u userDo) Offset(offset int) *userDo { + return u.withDO(u.DO.Offset(offset)) +} + +func (u userDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userDo { + return u.withDO(u.DO.Scopes(funcs...)) +} + +func (u userDo) Unscoped() *userDo { + 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) *userDo { + return u.withDO(u.DO.Attrs(attrs...)) +} + +func (u userDo) Assign(attrs ...field.AssignExpr) *userDo { + return u.withDO(u.DO.Assign(attrs...)) +} + +func (u userDo) Joins(fields ...field.RelationField) *userDo { + for _, _f := range fields { + u = *u.withDO(u.DO.Joins(_f)) + } + return &u +} + +func (u userDo) Preload(fields ...field.RelationField) *userDo { + 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/dal/query/users.gen_test.go b/dal/query/users.gen_test.go new file mode 100644 index 00000000..2d2cf378 --- /dev/null +++ b/dal/query/users.gen_test.go @@ -0,0 +1,146 @@ +// 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" + + "playground/model" + + "gorm.io/gen" + "gorm.io/gen/field" + "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(), "id") + + 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/db.go b/db.go deleted file mode 100644 index ccab03ed..00000000 --- a/db.go +++ /dev/null @@ -1,108 +0,0 @@ -package main - -import ( - "log" - "math/rand" - "os" - "path/filepath" - "time" - - "gorm.io/driver/mysql" - "gorm.io/driver/postgres" - "gorm.io/driver/sqlite" - "gorm.io/driver/sqlserver" - "gorm.io/gorm" - "gorm.io/gorm/logger" -) - -var DB *gorm.DB - -func init() { - var err error - if DB, err = OpenTestConnection(); err != nil { - log.Printf("failed to connect database, got error %v\n", err) - os.Exit(1) - } else { - sqlDB, err := DB.DB() - if err == nil { - err = sqlDB.Ping() - } - - if err != nil { - log.Printf("failed to connect database, got error %v\n", err) - } - - RunMigrations() - if DB.Dialector.Name() == "sqlite" { - DB.Exec("PRAGMA foreign_keys = ON") - } - - DB.Logger = DB.Logger.LogMode(logger.Info) - } -} - -func OpenTestConnection() (db *gorm.DB, err error) { - dbDSN := os.Getenv("GORM_DSN") - switch os.Getenv("GORM_DIALECT") { - case "mysql": - log.Println("testing mysql...") - if dbDSN == "" { - dbDSN = "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local" - } - db, err = gorm.Open(mysql.Open(dbDSN), &gorm.Config{}) - case "postgres": - log.Println("testing postgres...") - if dbDSN == "" { - dbDSN = "user=gorm password=gorm host=localhost dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai" - } - db, err = gorm.Open(postgres.Open(dbDSN), &gorm.Config{}) - case "sqlserver": - // CREATE LOGIN gorm WITH PASSWORD = 'LoremIpsum86'; - // CREATE DATABASE gorm; - // USE gorm; - // CREATE USER gorm FROM LOGIN gorm; - // sp_changedbowner 'gorm'; - log.Println("testing sqlserver...") - if dbDSN == "" { - dbDSN = "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm" - } - db, err = gorm.Open(sqlserver.Open(dbDSN), &gorm.Config{}) - default: - log.Println("testing sqlite3...") - db, err = gorm.Open(sqlite.Open(filepath.Join(os.TempDir(), "gorm.db")), &gorm.Config{}) - } - - if debug := os.Getenv("DEBUG"); debug == "true" { - db.Logger = db.Logger.LogMode(logger.Info) - } else if debug == "false" { - db.Logger = db.Logger.LogMode(logger.Silent) - } - - return -} - -func RunMigrations() { - var err error - allModels := []interface{}{&User{}, &Account{}, &Pet{}, &Company{}, &Toy{}, &Language{}} - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(allModels), func(i, j int) { allModels[i], allModels[j] = allModels[j], allModels[i] }) - - DB.Migrator().DropTable("user_friends", "user_speaks") - - if err = DB.Migrator().DropTable(allModels...); err != nil { - log.Printf("Failed to drop table, got error %v\n", err) - os.Exit(1) - } - - if err = DB.AutoMigrate(allModels...); err != nil { - log.Printf("Failed to auto migrate, but got error %v\n", err) - os.Exit(1) - } - - for _, m := range allModels { - if !DB.Migrator().HasTable(m) { - log.Printf("Failed to create table for %#v\n", m) - os.Exit(1) - } - } -} diff --git a/gen.go b/gen.go index 3127d5d6..bcdf0430 100644 --- a/gen.go +++ b/gen.go @@ -3,6 +3,7 @@ package main import ( "gorm.io/gen" "gorm.io/gen/examples/dal" + "playground/model" ) func generate() { @@ -14,8 +15,11 @@ func generate() { }) g.UseDB(dal.DB) - g.ApplyBasic(Company{}, Language{}) // Associations - g.ApplyBasic(g.GenerateModel("user"), g.GenerateModelAs("account", "AccountInfo")) + g.ApplyBasic(model.User{}) + g.ApplyBasic(model.UserExt{}) + g.ApplyBasic(model.UserAccountRelation{}) + g.ApplyBasic(model.Account{}) + g.ApplyBasic(model.Company{}) g.Execute() } diff --git a/gen_test.go b/gen_test.go new file mode 100644 index 00000000..b6d93e96 --- /dev/null +++ b/gen_test.go @@ -0,0 +1,35 @@ +/** + * @Author: liuzhan (lz@ifreedom.top) + * @Description: gen_test.go + * @Version: 1.0.0 + * @Date: 2024/11/7 15:09 + */ + +package main + +import ( + "context" + "gorm.io/gen/examples/dal" + "playground/dal/query" + "testing" +) + +func TestGEN(t *testing.T) { + generate() +} + +func TestPl(t *testing.T) { + qUser := query.Use(dal.DB).User + qUserExt := query.Use(dal.DB).UserExt + qUser.WithContext(context.Background()).Preload( + qUser.UserAccountRelationInfo, + qUser.UserAccountRelationInfo.AccountInfo, + ).Find() + + qUserExt.WithContext(context.Background()).Preload( + qUserExt.UserInfo, + qUserExt.UserInfo.UserAccountRelationInfo, + qUserExt.UserInfo.UserAccountRelationInfo.AccountInfo, + qUserExt.UserInfo.UserAccountRelationInfo.AccountInfo.CompanyInfo, + ).Find() +} diff --git a/go.mod b/go.mod index 159394d4..6f430eeb 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module gorm.io/playground +module playground go 1.20 @@ -31,5 +31,3 @@ require ( gorm.io/hints v1.1.0 // indirect gorm.io/plugin/dbresolver v1.5.0 // indirect ) - -replace gorm.io/gorm => ./gorm diff --git a/main_test.go b/main_test.go deleted file mode 100644 index 60a388f7..00000000 --- a/main_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "testing" -) - -// GORM_REPO: https://github.com/go-gorm/gorm.git -// GORM_BRANCH: master -// TEST_DRIVERS: sqlite, mysql, postgres, sqlserver - -func TestGORM(t *testing.T) { - user := User{Name: "jinzhu"} - - DB.Create(&user) - - var result User - if err := DB.First(&result, user.ID).Error; err != nil { - t.Errorf("Failed, got error: %v", err) - } -} diff --git a/model/models.go b/model/models.go new file mode 100644 index 00000000..b340f5f5 --- /dev/null +++ b/model/models.go @@ -0,0 +1,43 @@ +package model + +import ( + "gorm.io/gorm" +) + +type User struct { + gorm.Model + UserMainID uint `gorm:"column:user_main_id;not null;" json:"user_main_id"` // 用户主表ID + Username string `gorm:"column:username;not null;" json:"username"` // 用户名 + + UserExtInfo *UserExt `gorm:"foreignKey:UserID;" json:"user_ext_info"` // 用户扩展信息,关联user_ext表 + UserAccountRelationInfo *UserAccountRelation `gorm:"foreignKey:UserID;" json:"user_account_relation_info"` // 用户账户关联信息,关联user_account_relation表 +} + +type UserExt struct { + gorm.Model + UserID uint `gorm:"column:user_id;not null;" json:"user_id"` // 用户ID + + UserInfo *User `gorm:"foreignKey:UserID;references:ID" json:"user_info"` // 用户信息,关联user表 +} + +type UserAccountRelation struct { + gorm.Model + + UserID uint `gorm:"column:user_id;not null;" json:"user_id"` // 用户ID + AccountID uint `gorm:"column:account_id;not null;" json:"account_id"` // 账户ID + + UserInfo *User `gorm:"foreignKey:UserID;references:ID" json:"user_info"` // 用户信息,关联user表 + AccountInfo *Account `gorm:"foreignKey:AccountID;references:ID" json:"account_info"` // 账户信息,关联account表 +} + +type Account struct { + gorm.Model + CompanyID uint `gorm:"column:company_id;not null;" json:"company_id"` // 公司ID + + CompanyInfo *Company `gorm:"foreignKey:CompanyID;references:ID" json:"company_info"` // 公司信息,关联company表 +} + +type Company struct { + gorm.Model + Name string `gorm:"column:name;not null;" json:"name"` // 公司名称 +} diff --git a/models.go b/models.go deleted file mode 100644 index 692a6842..00000000 --- a/models.go +++ /dev/null @@ -1,60 +0,0 @@ -package main - -import ( - "database/sql" - "time" - - "gorm.io/gorm" -) - -// User has one `Account` (has one), many `Pets` (has many) and `Toys` (has many - polymorphic) -// He works in a Company (belongs to), he has a Manager (belongs to - single-table), and also managed a Team (has many - single-table) -// He speaks many languages (many to many) and has many friends (many to many - single-table) -// His pet also has one Toy (has one - polymorphic) -type User struct { - gorm.Model - Name string - Age uint - Birthday *time.Time - Account Account - Pets []*Pet - Toys []Toy `gorm:"polymorphic:Owner"` - CompanyID *int - Company Company - ManagerID *uint - Manager *User - Team []User `gorm:"foreignkey:ManagerID"` - Languages []Language `gorm:"many2many:UserSpeak"` - Friends []*User `gorm:"many2many:user_friends"` - Active bool -} - -type Account struct { - gorm.Model - UserID sql.NullInt64 - Number string -} - -type Pet struct { - gorm.Model - UserID *uint - Name string - Toy Toy `gorm:"polymorphic:Owner;"` -} - -type Toy struct { - gorm.Model - Name string - OwnerID string - OwnerType string -} - -type Company struct { - ID int - Name string -} - -type Language struct { - Code string `gorm:"primarykey"` - Name string -}