// Code generated by go.ipao.vip/gen. DO NOT EDIT.
// Code generated by go.ipao.vip/gen. DO NOT EDIT.
// Code generated by go.ipao.vip/gen. DO NOT EDIT.

package models

import (
	"context"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"

	"go.ipao.vip/gen"
	"go.ipao.vip/gen/field"

	"gorm.io/plugin/dbresolver"
)

func newTenant(db *gorm.DB, opts ...gen.DOOption) tenantQuery {
	_tenantQuery := tenantQuery{}

	_tenantQuery.tenantQueryDo.UseDB(db, opts...)
	_tenantQuery.tenantQueryDo.UseModel(&Tenant{})

	tableName := _tenantQuery.tenantQueryDo.TableName()
	_tenantQuery.ALL = field.NewAsterisk(tableName)
	_tenantQuery.ID = field.NewInt64(tableName, "id")
	_tenantQuery.UserID = field.NewInt64(tableName, "user_id")
	_tenantQuery.Code = field.NewString(tableName, "code")
	_tenantQuery.UUID = field.NewField(tableName, "uuid")
	_tenantQuery.Name = field.NewString(tableName, "name")
	_tenantQuery.Status = field.NewString(tableName, "status")
	_tenantQuery.Config = field.NewJSONB(tableName, "config")
	_tenantQuery.ExpiredAt = field.NewTime(tableName, "expired_at")
	_tenantQuery.CreatedAt = field.NewTime(tableName, "created_at")
	_tenantQuery.UpdatedAt = field.NewTime(tableName, "updated_at")

	_tenantQuery.fillFieldMap()

	return _tenantQuery
}

type tenantQuery struct {
	tenantQueryDo tenantQueryDo

	ALL       field.Asterisk
	ID        field.Int64
	UserID    field.Int64
	Code      field.String
	UUID      field.Field
	Name      field.String
	Status    field.String
	Config    field.JSONB
	ExpiredAt field.Time
	CreatedAt field.Time
	UpdatedAt field.Time

	fieldMap map[string]field.Expr
}

func (t tenantQuery) Table(newTableName string) *tenantQuery {
	t.tenantQueryDo.UseTable(newTableName)
	return t.updateTableName(newTableName)
}

func (t tenantQuery) As(alias string) *tenantQuery {
	t.tenantQueryDo.DO = *(t.tenantQueryDo.As(alias).(*gen.DO))
	return t.updateTableName(alias)
}

func (t *tenantQuery) updateTableName(table string) *tenantQuery {
	t.ALL = field.NewAsterisk(table)
	t.ID = field.NewInt64(table, "id")
	t.UserID = field.NewInt64(table, "user_id")
	t.Code = field.NewString(table, "code")
	t.UUID = field.NewField(table, "uuid")
	t.Name = field.NewString(table, "name")
	t.Status = field.NewString(table, "status")
	t.Config = field.NewJSONB(table, "config")
	t.ExpiredAt = field.NewTime(table, "expired_at")
	t.CreatedAt = field.NewTime(table, "created_at")
	t.UpdatedAt = field.NewTime(table, "updated_at")

	t.fillFieldMap()

	return t
}

func (t *tenantQuery) QueryContext(ctx context.Context) (*tenantQuery, *tenantQueryDo) {
	return t, t.tenantQueryDo.WithContext(ctx)
}

func (t *tenantQuery) WithContext(ctx context.Context) *tenantQueryDo {
	return t.tenantQueryDo.WithContext(ctx)
}

func (t tenantQuery) TableName() string { return t.tenantQueryDo.TableName() }

func (t tenantQuery) Alias() string { return t.tenantQueryDo.Alias() }

func (t tenantQuery) Columns(cols ...field.Expr) gen.Columns { return t.tenantQueryDo.Columns(cols...) }

func (t *tenantQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
	_f, ok := t.fieldMap[fieldName]
	if !ok || _f == nil {
		return nil, false
	}
	_oe, ok := _f.(field.OrderExpr)
	return _oe, ok
}

func (t *tenantQuery) fillFieldMap() {
	t.fieldMap = make(map[string]field.Expr, 10)
	t.fieldMap["id"] = t.ID
	t.fieldMap["user_id"] = t.UserID
	t.fieldMap["code"] = t.Code
	t.fieldMap["uuid"] = t.UUID
	t.fieldMap["name"] = t.Name
	t.fieldMap["status"] = t.Status
	t.fieldMap["config"] = t.Config
	t.fieldMap["expired_at"] = t.ExpiredAt
	t.fieldMap["created_at"] = t.CreatedAt
	t.fieldMap["updated_at"] = t.UpdatedAt
}

func (t tenantQuery) clone(db *gorm.DB) tenantQuery {
	t.tenantQueryDo.ReplaceConnPool(db.Statement.ConnPool)
	return t
}

func (t tenantQuery) replaceDB(db *gorm.DB) tenantQuery {
	t.tenantQueryDo.ReplaceDB(db)
	return t
}

type tenantQueryDo struct{ gen.DO }

func (t tenantQueryDo) Debug() *tenantQueryDo {
	return t.withDO(t.DO.Debug())
}

func (t tenantQueryDo) WithContext(ctx context.Context) *tenantQueryDo {
	return t.withDO(t.DO.WithContext(ctx))
}

func (t tenantQueryDo) ReadDB() *tenantQueryDo {
	return t.Clauses(dbresolver.Read)
}

func (t tenantQueryDo) WriteDB() *tenantQueryDo {
	return t.Clauses(dbresolver.Write)
}

func (t tenantQueryDo) Session(config *gorm.Session) *tenantQueryDo {
	return t.withDO(t.DO.Session(config))
}

func (t tenantQueryDo) Clauses(conds ...clause.Expression) *tenantQueryDo {
	return t.withDO(t.DO.Clauses(conds...))
}

func (t tenantQueryDo) Returning(value interface{}, columns ...string) *tenantQueryDo {
	return t.withDO(t.DO.Returning(value, columns...))
}

func (t tenantQueryDo) Not(conds ...gen.Condition) *tenantQueryDo {
	return t.withDO(t.DO.Not(conds...))
}

func (t tenantQueryDo) Or(conds ...gen.Condition) *tenantQueryDo {
	return t.withDO(t.DO.Or(conds...))
}

func (t tenantQueryDo) Select(conds ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Select(conds...))
}

func (t tenantQueryDo) Where(conds ...gen.Condition) *tenantQueryDo {
	return t.withDO(t.DO.Where(conds...))
}

func (t tenantQueryDo) Order(conds ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Order(conds...))
}

func (t tenantQueryDo) Distinct(cols ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Distinct(cols...))
}

func (t tenantQueryDo) Omit(cols ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Omit(cols...))
}

func (t tenantQueryDo) Join(table schema.Tabler, on ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Join(table, on...))
}

func (t tenantQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.LeftJoin(table, on...))
}

func (t tenantQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.RightJoin(table, on...))
}

func (t tenantQueryDo) Group(cols ...field.Expr) *tenantQueryDo {
	return t.withDO(t.DO.Group(cols...))
}

func (t tenantQueryDo) Having(conds ...gen.Condition) *tenantQueryDo {
	return t.withDO(t.DO.Having(conds...))
}

func (t tenantQueryDo) Limit(limit int) *tenantQueryDo {
	return t.withDO(t.DO.Limit(limit))
}

func (t tenantQueryDo) Offset(offset int) *tenantQueryDo {
	return t.withDO(t.DO.Offset(offset))
}

func (t tenantQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *tenantQueryDo {
	return t.withDO(t.DO.Scopes(funcs...))
}

func (t tenantQueryDo) Unscoped() *tenantQueryDo {
	return t.withDO(t.DO.Unscoped())
}

func (t tenantQueryDo) Create(values ...*Tenant) error {
	if len(values) == 0 {
		return nil
	}
	return t.DO.Create(values)
}

func (t tenantQueryDo) CreateInBatches(values []*Tenant, batchSize int) error {
	return t.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 (t tenantQueryDo) Save(values ...*Tenant) error {
	if len(values) == 0 {
		return nil
	}
	return t.DO.Save(values)
}

func (t tenantQueryDo) First() (*Tenant, error) {
	if result, err := t.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*Tenant), nil
	}
}

func (t tenantQueryDo) Take() (*Tenant, error) {
	if result, err := t.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*Tenant), nil
	}
}

func (t tenantQueryDo) Last() (*Tenant, error) {
	if result, err := t.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*Tenant), nil
	}
}

func (t tenantQueryDo) Find() ([]*Tenant, error) {
	result, err := t.DO.Find()
	return result.([]*Tenant), err
}

func (t tenantQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Tenant, err error) {
	buf := make([]*Tenant, 0, batchSize)
	err = t.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 (t tenantQueryDo) FindInBatches(result *[]*Tenant, batchSize int, fc func(tx gen.Dao, batch int) error) error {
	return t.DO.FindInBatches(result, batchSize, fc)
}

func (t tenantQueryDo) Attrs(attrs ...field.AssignExpr) *tenantQueryDo {
	return t.withDO(t.DO.Attrs(attrs...))
}

func (t tenantQueryDo) Assign(attrs ...field.AssignExpr) *tenantQueryDo {
	return t.withDO(t.DO.Assign(attrs...))
}

func (t tenantQueryDo) Joins(fields ...field.RelationField) *tenantQueryDo {
	for _, _f := range fields {
		t = *t.withDO(t.DO.Joins(_f))
	}
	return &t
}

func (t tenantQueryDo) Preload(fields ...field.RelationField) *tenantQueryDo {
	for _, _f := range fields {
		t = *t.withDO(t.DO.Preload(_f))
	}
	return &t
}

func (t tenantQueryDo) FirstOrInit() (*Tenant, error) {
	if result, err := t.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*Tenant), nil
	}
}

func (t tenantQueryDo) FirstOrCreate() (*Tenant, error) {
	if result, err := t.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*Tenant), nil
	}
}

func (t tenantQueryDo) FindByPage(offset int, limit int) (result []*Tenant, count int64, err error) {
	result, err = t.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 = t.Offset(-1).Limit(-1).Count()
	return
}

func (t tenantQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
	count, err = t.Count()
	if err != nil {
		return
	}

	err = t.Offset(offset).Limit(limit).Scan(result)
	return
}

func (t tenantQueryDo) Scan(result interface{}) (err error) {
	return t.DO.Scan(result)
}

func (t tenantQueryDo) Delete(models ...*Tenant) (result gen.ResultInfo, err error) {
	return t.DO.Delete(models)
}

// ForceDelete performs a permanent delete (ignores soft-delete) for current scope.
func (t tenantQueryDo) ForceDelete() (gen.ResultInfo, error) {
	return t.Unscoped().Delete()
}

// Inc increases the given column by step for current scope.
func (t tenantQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) {
	// column = column + step
	e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step)
	return t.DO.UpdateColumn(column, e)
}

// Dec decreases the given column by step for current scope.
func (t tenantQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) {
	// column = column - step
	e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step)
	return t.DO.UpdateColumn(column, e)
}

// Sum returns SUM(column) for current scope.
func (t tenantQueryDo) Sum(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr())
	if err := t.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Avg returns AVG(column) for current scope.
func (t tenantQueryDo) Avg(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr())
	if err := t.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Min returns MIN(column) for current scope.
func (t tenantQueryDo) Min(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr())
	if err := t.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Max returns MAX(column) for current scope.
func (t tenantQueryDo) Max(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr())
	if err := t.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// PluckMap returns a map[key]value for selected key/value expressions within current scope.
func (t tenantQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) {
	do := t.Select(key, val)
	rows, err := do.DO.Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	mm := make(map[interface{}]interface{})
	for rows.Next() {
		var k interface{}
		var v interface{}
		if err := rows.Scan(&k, &v); err != nil {
			return nil, err
		}
		mm[k] = v
	}
	return mm, rows.Err()
}

// Exists returns true if any record matches the given conditions.
func (t tenantQueryDo) Exists(conds ...gen.Condition) (bool, error) {
	cnt, err := t.Where(conds...).Count()
	if err != nil {
		return false, err
	}
	return cnt > 0, nil
}

// PluckIDs returns all primary key values under current scope.
func (t tenantQueryDo) PluckIDs() ([]int64, error) {
	ids := make([]int64, 0, 16)
	pk := field.NewInt64(t.TableName(), "id")
	if err := t.DO.Pluck(pk, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// GetByID finds a single record by primary key.
func (t tenantQueryDo) GetByID(id int64) (*Tenant, error) {
	pk := field.NewInt64(t.TableName(), "id")
	return t.Where(pk.Eq(id)).First()
}

// GetByIDs finds records by primary key list.
func (t tenantQueryDo) GetByIDs(ids ...int64) ([]*Tenant, error) {
	if len(ids) == 0 {
		return []*Tenant{}, nil
	}
	pk := field.NewInt64(t.TableName(), "id")
	return t.Where(pk.In(ids...)).Find()
}

// DeleteByID deletes records by primary key.
func (t tenantQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) {
	pk := field.NewInt64(t.TableName(), "id")
	return t.Where(pk.Eq(id)).Delete()
}

// DeleteByIDs deletes records by a list of primary keys.
func (t tenantQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) {
	if len(ids) == 0 {
		return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil
	}
	pk := field.NewInt64(t.TableName(), "id")
	return t.Where(pk.In(ids...)).Delete()
}

func (t *tenantQueryDo) withDO(do gen.Dao) *tenantQueryDo {
	t.DO = *do.(*gen.DO)
	return t
}
