// 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 newUser(db *gorm.DB, opts ...gen.DOOption) userQuery {
	_userQuery := userQuery{}

	_userQuery.userQueryDo.UseDB(db, opts...)
	_userQuery.userQueryDo.UseModel(&User{})

	tableName := _userQuery.userQueryDo.TableName()
	_userQuery.ALL = field.NewAsterisk(tableName)
	_userQuery.ID = field.NewInt64(tableName, "id")
	_userQuery.Username = field.NewString(tableName, "username")
	_userQuery.Password = field.NewString(tableName, "password")
	_userQuery.Roles = field.NewArray(tableName, "roles")
	_userQuery.Status = field.NewString(tableName, "status")
	_userQuery.Metas = field.NewJSONB(tableName, "metas")
	_userQuery.Balance = field.NewInt64(tableName, "balance")
	_userQuery.BalanceFrozen = field.NewInt64(tableName, "balance_frozen")
	_userQuery.VerifiedAt = field.NewTime(tableName, "verified_at")
	_userQuery.Nickname = field.NewString(tableName, "nickname")
	_userQuery.Avatar = field.NewString(tableName, "avatar")
	_userQuery.Gender = field.NewString(tableName, "gender")
	_userQuery.Bio = field.NewString(tableName, "bio")
	_userQuery.Birthday = field.NewField(tableName, "birthday")
	_userQuery.Location = field.NewJSONB(tableName, "location")
	_userQuery.Points = field.NewInt64(tableName, "points")
	_userQuery.Phone = field.NewString(tableName, "phone")
	_userQuery.IsRealNameVerified = field.NewBool(tableName, "is_real_name_verified")
	_userQuery.CreatedAt = field.NewTime(tableName, "created_at")
	_userQuery.UpdatedAt = field.NewTime(tableName, "updated_at")
	_userQuery.DeletedAt = field.NewField(tableName, "deleted_at")

	_userQuery.fillFieldMap()

	return _userQuery
}

type userQuery struct {
	userQueryDo userQueryDo

	ALL                field.Asterisk
	ID                 field.Int64
	Username           field.String
	Password           field.String
	Roles              field.Array
	Status             field.String
	Metas              field.JSONB
	Balance            field.Int64
	BalanceFrozen      field.Int64
	VerifiedAt         field.Time
	Nickname           field.String
	Avatar             field.String
	Gender             field.String
	Bio                field.String
	Birthday           field.Field
	Location           field.JSONB
	Points             field.Int64
	Phone              field.String
	IsRealNameVerified field.Bool
	CreatedAt          field.Time
	UpdatedAt          field.Time
	DeletedAt          field.Field

	fieldMap map[string]field.Expr
}

func (u userQuery) Table(newTableName string) *userQuery {
	u.userQueryDo.UseTable(newTableName)
	return u.updateTableName(newTableName)
}

func (u userQuery) As(alias string) *userQuery {
	u.userQueryDo.DO = *(u.userQueryDo.As(alias).(*gen.DO))
	return u.updateTableName(alias)
}

func (u *userQuery) updateTableName(table string) *userQuery {
	u.ALL = field.NewAsterisk(table)
	u.ID = field.NewInt64(table, "id")
	u.Username = field.NewString(table, "username")
	u.Password = field.NewString(table, "password")
	u.Roles = field.NewArray(table, "roles")
	u.Status = field.NewString(table, "status")
	u.Metas = field.NewJSONB(table, "metas")
	u.Balance = field.NewInt64(table, "balance")
	u.BalanceFrozen = field.NewInt64(table, "balance_frozen")
	u.VerifiedAt = field.NewTime(table, "verified_at")
	u.Nickname = field.NewString(table, "nickname")
	u.Avatar = field.NewString(table, "avatar")
	u.Gender = field.NewString(table, "gender")
	u.Bio = field.NewString(table, "bio")
	u.Birthday = field.NewField(table, "birthday")
	u.Location = field.NewJSONB(table, "location")
	u.Points = field.NewInt64(table, "points")
	u.Phone = field.NewString(table, "phone")
	u.IsRealNameVerified = field.NewBool(table, "is_real_name_verified")
	u.CreatedAt = field.NewTime(table, "created_at")
	u.UpdatedAt = field.NewTime(table, "updated_at")
	u.DeletedAt = field.NewField(table, "deleted_at")

	u.fillFieldMap()

	return u
}

func (u *userQuery) QueryContext(ctx context.Context) (*userQuery, *userQueryDo) {
	return u, u.userQueryDo.WithContext(ctx)
}

func (u *userQuery) WithContext(ctx context.Context) *userQueryDo {
	return u.userQueryDo.WithContext(ctx)
}

func (u userQuery) TableName() string { return u.userQueryDo.TableName() }

func (u userQuery) Alias() string { return u.userQueryDo.Alias() }

func (u userQuery) Columns(cols ...field.Expr) gen.Columns { return u.userQueryDo.Columns(cols...) }

func (u *userQuery) 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 *userQuery) fillFieldMap() {
	u.fieldMap = make(map[string]field.Expr, 21)
	u.fieldMap["id"] = u.ID
	u.fieldMap["username"] = u.Username
	u.fieldMap["password"] = u.Password
	u.fieldMap["roles"] = u.Roles
	u.fieldMap["status"] = u.Status
	u.fieldMap["metas"] = u.Metas
	u.fieldMap["balance"] = u.Balance
	u.fieldMap["balance_frozen"] = u.BalanceFrozen
	u.fieldMap["verified_at"] = u.VerifiedAt
	u.fieldMap["nickname"] = u.Nickname
	u.fieldMap["avatar"] = u.Avatar
	u.fieldMap["gender"] = u.Gender
	u.fieldMap["bio"] = u.Bio
	u.fieldMap["birthday"] = u.Birthday
	u.fieldMap["location"] = u.Location
	u.fieldMap["points"] = u.Points
	u.fieldMap["phone"] = u.Phone
	u.fieldMap["is_real_name_verified"] = u.IsRealNameVerified
	u.fieldMap["created_at"] = u.CreatedAt
	u.fieldMap["updated_at"] = u.UpdatedAt
	u.fieldMap["deleted_at"] = u.DeletedAt
}

func (u userQuery) clone(db *gorm.DB) userQuery {
	u.userQueryDo.ReplaceConnPool(db.Statement.ConnPool)
	return u
}

func (u userQuery) replaceDB(db *gorm.DB) userQuery {
	u.userQueryDo.ReplaceDB(db)
	return u
}

type userQueryDo struct{ gen.DO }

func (u userQueryDo) Debug() *userQueryDo {
	return u.withDO(u.DO.Debug())
}

func (u userQueryDo) WithContext(ctx context.Context) *userQueryDo {
	return u.withDO(u.DO.WithContext(ctx))
}

func (u userQueryDo) ReadDB() *userQueryDo {
	return u.Clauses(dbresolver.Read)
}

func (u userQueryDo) WriteDB() *userQueryDo {
	return u.Clauses(dbresolver.Write)
}

func (u userQueryDo) Session(config *gorm.Session) *userQueryDo {
	return u.withDO(u.DO.Session(config))
}

func (u userQueryDo) Clauses(conds ...clause.Expression) *userQueryDo {
	return u.withDO(u.DO.Clauses(conds...))
}

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

func (u userQueryDo) Not(conds ...gen.Condition) *userQueryDo {
	return u.withDO(u.DO.Not(conds...))
}

func (u userQueryDo) Or(conds ...gen.Condition) *userQueryDo {
	return u.withDO(u.DO.Or(conds...))
}

func (u userQueryDo) Select(conds ...field.Expr) *userQueryDo {
	return u.withDO(u.DO.Select(conds...))
}

func (u userQueryDo) Where(conds ...gen.Condition) *userQueryDo {
	return u.withDO(u.DO.Where(conds...))
}

func (u userQueryDo) Order(conds ...field.Expr) *userQueryDo {
	return u.withDO(u.DO.Order(conds...))
}

func (u userQueryDo) Distinct(cols ...field.Expr) *userQueryDo {
	return u.withDO(u.DO.Distinct(cols...))
}

func (u userQueryDo) Omit(cols ...field.Expr) *userQueryDo {
	return u.withDO(u.DO.Omit(cols...))
}

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

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

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

func (u userQueryDo) Group(cols ...field.Expr) *userQueryDo {
	return u.withDO(u.DO.Group(cols...))
}

func (u userQueryDo) Having(conds ...gen.Condition) *userQueryDo {
	return u.withDO(u.DO.Having(conds...))
}

func (u userQueryDo) Limit(limit int) *userQueryDo {
	return u.withDO(u.DO.Limit(limit))
}

func (u userQueryDo) Offset(offset int) *userQueryDo {
	return u.withDO(u.DO.Offset(offset))
}

func (u userQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *userQueryDo {
	return u.withDO(u.DO.Scopes(funcs...))
}

func (u userQueryDo) Unscoped() *userQueryDo {
	return u.withDO(u.DO.Unscoped())
}

func (u userQueryDo) Create(values ...*User) error {
	if len(values) == 0 {
		return nil
	}
	return u.DO.Create(values)
}

func (u userQueryDo) CreateInBatches(values []*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 userQueryDo) Save(values ...*User) error {
	if len(values) == 0 {
		return nil
	}
	return u.DO.Save(values)
}

func (u userQueryDo) First() (*User, error) {
	if result, err := u.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*User), nil
	}
}

func (u userQueryDo) Take() (*User, error) {
	if result, err := u.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*User), nil
	}
}

func (u userQueryDo) Last() (*User, error) {
	if result, err := u.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*User), nil
	}
}

func (u userQueryDo) Find() ([]*User, error) {
	result, err := u.DO.Find()
	return result.([]*User), err
}

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

func (u userQueryDo) Attrs(attrs ...field.AssignExpr) *userQueryDo {
	return u.withDO(u.DO.Attrs(attrs...))
}

func (u userQueryDo) Assign(attrs ...field.AssignExpr) *userQueryDo {
	return u.withDO(u.DO.Assign(attrs...))
}

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

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

func (u userQueryDo) FirstOrInit() (*User, error) {
	if result, err := u.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*User), nil
	}
}

func (u userQueryDo) FirstOrCreate() (*User, error) {
	if result, err := u.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*User), nil
	}
}

func (u userQueryDo) FindByPage(offset int, limit int) (result []*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 userQueryDo) 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 userQueryDo) Scan(result interface{}) (err error) {
	return u.DO.Scan(result)
}

func (u userQueryDo) Delete(models ...*User) (result gen.ResultInfo, err error) {
	return u.DO.Delete(models)
}

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

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

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

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

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

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

// Max returns MAX(column) for current scope.
func (u userQueryDo) Max(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr())
	if err := u.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 (u userQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) {
	do := u.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 (u userQueryDo) Exists(conds ...gen.Condition) (bool, error) {
	cnt, err := u.Where(conds...).Count()
	if err != nil {
		return false, err
	}
	return cnt > 0, nil
}

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

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

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

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

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

// RestoreWhere sets deleted_at to NULL for rows matching current scope + conds.
func (u userQueryDo) RestoreWhere(conds ...gen.Condition) (gen.ResultInfo, error) {
	col := field.NewField(u.TableName(), "deleted_at")
	return u.Unscoped().Where(conds...).UpdateColumn(col, nil)
}

// RestoreByID sets deleted_at to NULL for the given primary key.
func (u userQueryDo) RestoreByID(id int64) (gen.ResultInfo, error) {
	pk := field.NewInt64(u.TableName(), "id")
	col := field.NewField(u.TableName(), "deleted_at")
	return u.Unscoped().Where(pk.Eq(id)).UpdateColumn(col, nil)
}

func (u *userQueryDo) withDO(do gen.Dao) *userQueryDo {
	u.DO = *do.(*gen.DO)
	return u
}
