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

	_couponQuery.couponQueryDo.UseDB(db, opts...)
	_couponQuery.couponQueryDo.UseModel(&Coupon{})

	tableName := _couponQuery.couponQueryDo.TableName()
	_couponQuery.ALL = field.NewAsterisk(tableName)
	_couponQuery.ID = field.NewInt64(tableName, "id")
	_couponQuery.TenantID = field.NewInt64(tableName, "tenant_id")
	_couponQuery.Title = field.NewString(tableName, "title")
	_couponQuery.Description = field.NewString(tableName, "description")
	_couponQuery.Type = field.NewField(tableName, "type")
	_couponQuery.Value = field.NewInt64(tableName, "value")
	_couponQuery.MinOrderAmount = field.NewInt64(tableName, "min_order_amount")
	_couponQuery.MaxDiscount = field.NewInt64(tableName, "max_discount")
	_couponQuery.TotalQuantity = field.NewInt32(tableName, "total_quantity")
	_couponQuery.UsedQuantity = field.NewInt32(tableName, "used_quantity")
	_couponQuery.StartAt = field.NewTime(tableName, "start_at")
	_couponQuery.EndAt = field.NewTime(tableName, "end_at")
	_couponQuery.CreatedAt = field.NewTime(tableName, "created_at")
	_couponQuery.UpdatedAt = field.NewTime(tableName, "updated_at")

	_couponQuery.fillFieldMap()

	return _couponQuery
}

type couponQuery struct {
	couponQueryDo couponQueryDo

	ALL            field.Asterisk
	ID             field.Int64
	TenantID       field.Int64
	Title          field.String
	Description    field.String
	Type           field.Field
	Value          field.Int64
	MinOrderAmount field.Int64
	MaxDiscount    field.Int64
	TotalQuantity  field.Int32
	UsedQuantity   field.Int32
	StartAt        field.Time
	EndAt          field.Time
	CreatedAt      field.Time
	UpdatedAt      field.Time

	fieldMap map[string]field.Expr
}

func (c couponQuery) Table(newTableName string) *couponQuery {
	c.couponQueryDo.UseTable(newTableName)
	return c.updateTableName(newTableName)
}

func (c couponQuery) As(alias string) *couponQuery {
	c.couponQueryDo.DO = *(c.couponQueryDo.As(alias).(*gen.DO))
	return c.updateTableName(alias)
}

func (c *couponQuery) updateTableName(table string) *couponQuery {
	c.ALL = field.NewAsterisk(table)
	c.ID = field.NewInt64(table, "id")
	c.TenantID = field.NewInt64(table, "tenant_id")
	c.Title = field.NewString(table, "title")
	c.Description = field.NewString(table, "description")
	c.Type = field.NewField(table, "type")
	c.Value = field.NewInt64(table, "value")
	c.MinOrderAmount = field.NewInt64(table, "min_order_amount")
	c.MaxDiscount = field.NewInt64(table, "max_discount")
	c.TotalQuantity = field.NewInt32(table, "total_quantity")
	c.UsedQuantity = field.NewInt32(table, "used_quantity")
	c.StartAt = field.NewTime(table, "start_at")
	c.EndAt = field.NewTime(table, "end_at")
	c.CreatedAt = field.NewTime(table, "created_at")
	c.UpdatedAt = field.NewTime(table, "updated_at")

	c.fillFieldMap()

	return c
}

func (c *couponQuery) QueryContext(ctx context.Context) (*couponQuery, *couponQueryDo) {
	return c, c.couponQueryDo.WithContext(ctx)
}

func (c *couponQuery) WithContext(ctx context.Context) *couponQueryDo {
	return c.couponQueryDo.WithContext(ctx)
}

func (c couponQuery) TableName() string { return c.couponQueryDo.TableName() }

func (c couponQuery) Alias() string { return c.couponQueryDo.Alias() }

func (c couponQuery) Columns(cols ...field.Expr) gen.Columns { return c.couponQueryDo.Columns(cols...) }

func (c *couponQuery) 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 *couponQuery) fillFieldMap() {
	c.fieldMap = make(map[string]field.Expr, 14)
	c.fieldMap["id"] = c.ID
	c.fieldMap["tenant_id"] = c.TenantID
	c.fieldMap["title"] = c.Title
	c.fieldMap["description"] = c.Description
	c.fieldMap["type"] = c.Type
	c.fieldMap["value"] = c.Value
	c.fieldMap["min_order_amount"] = c.MinOrderAmount
	c.fieldMap["max_discount"] = c.MaxDiscount
	c.fieldMap["total_quantity"] = c.TotalQuantity
	c.fieldMap["used_quantity"] = c.UsedQuantity
	c.fieldMap["start_at"] = c.StartAt
	c.fieldMap["end_at"] = c.EndAt
	c.fieldMap["created_at"] = c.CreatedAt
	c.fieldMap["updated_at"] = c.UpdatedAt
}

func (c couponQuery) clone(db *gorm.DB) couponQuery {
	c.couponQueryDo.ReplaceConnPool(db.Statement.ConnPool)
	return c
}

func (c couponQuery) replaceDB(db *gorm.DB) couponQuery {
	c.couponQueryDo.ReplaceDB(db)
	return c
}

type couponQueryDo struct{ gen.DO }

func (c couponQueryDo) Debug() *couponQueryDo {
	return c.withDO(c.DO.Debug())
}

func (c couponQueryDo) WithContext(ctx context.Context) *couponQueryDo {
	return c.withDO(c.DO.WithContext(ctx))
}

func (c couponQueryDo) ReadDB() *couponQueryDo {
	return c.Clauses(dbresolver.Read)
}

func (c couponQueryDo) WriteDB() *couponQueryDo {
	return c.Clauses(dbresolver.Write)
}

func (c couponQueryDo) Session(config *gorm.Session) *couponQueryDo {
	return c.withDO(c.DO.Session(config))
}

func (c couponQueryDo) Clauses(conds ...clause.Expression) *couponQueryDo {
	return c.withDO(c.DO.Clauses(conds...))
}

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

func (c couponQueryDo) Not(conds ...gen.Condition) *couponQueryDo {
	return c.withDO(c.DO.Not(conds...))
}

func (c couponQueryDo) Or(conds ...gen.Condition) *couponQueryDo {
	return c.withDO(c.DO.Or(conds...))
}

func (c couponQueryDo) Select(conds ...field.Expr) *couponQueryDo {
	return c.withDO(c.DO.Select(conds...))
}

func (c couponQueryDo) Where(conds ...gen.Condition) *couponQueryDo {
	return c.withDO(c.DO.Where(conds...))
}

func (c couponQueryDo) Order(conds ...field.Expr) *couponQueryDo {
	return c.withDO(c.DO.Order(conds...))
}

func (c couponQueryDo) Distinct(cols ...field.Expr) *couponQueryDo {
	return c.withDO(c.DO.Distinct(cols...))
}

func (c couponQueryDo) Omit(cols ...field.Expr) *couponQueryDo {
	return c.withDO(c.DO.Omit(cols...))
}

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

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

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

func (c couponQueryDo) Group(cols ...field.Expr) *couponQueryDo {
	return c.withDO(c.DO.Group(cols...))
}

func (c couponQueryDo) Having(conds ...gen.Condition) *couponQueryDo {
	return c.withDO(c.DO.Having(conds...))
}

func (c couponQueryDo) Limit(limit int) *couponQueryDo {
	return c.withDO(c.DO.Limit(limit))
}

func (c couponQueryDo) Offset(offset int) *couponQueryDo {
	return c.withDO(c.DO.Offset(offset))
}

func (c couponQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *couponQueryDo {
	return c.withDO(c.DO.Scopes(funcs...))
}

func (c couponQueryDo) Unscoped() *couponQueryDo {
	return c.withDO(c.DO.Unscoped())
}

func (c couponQueryDo) Create(values ...*Coupon) error {
	if len(values) == 0 {
		return nil
	}
	return c.DO.Create(values)
}

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

func (c couponQueryDo) First() (*Coupon, error) {
	if result, err := c.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*Coupon), nil
	}
}

func (c couponQueryDo) Take() (*Coupon, error) {
	if result, err := c.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*Coupon), nil
	}
}

func (c couponQueryDo) Last() (*Coupon, error) {
	if result, err := c.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*Coupon), nil
	}
}

func (c couponQueryDo) Find() ([]*Coupon, error) {
	result, err := c.DO.Find()
	return result.([]*Coupon), err
}

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

func (c couponQueryDo) Attrs(attrs ...field.AssignExpr) *couponQueryDo {
	return c.withDO(c.DO.Attrs(attrs...))
}

func (c couponQueryDo) Assign(attrs ...field.AssignExpr) *couponQueryDo {
	return c.withDO(c.DO.Assign(attrs...))
}

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

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

func (c couponQueryDo) FirstOrInit() (*Coupon, error) {
	if result, err := c.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*Coupon), nil
	}
}

func (c couponQueryDo) FirstOrCreate() (*Coupon, error) {
	if result, err := c.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*Coupon), nil
	}
}

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

func (c couponQueryDo) Delete(models ...*Coupon) (result gen.ResultInfo, err error) {
	return c.DO.Delete(models)
}

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

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

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

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

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

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

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

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

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

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

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

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

func (c *couponQueryDo) withDO(do gen.Dao) *couponQueryDo {
	c.DO = *do.(*gen.DO)
	return c
}
