// 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"
	"strings"

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

	"gorm.io/gen"
	"gorm.io/gen/field"

	"gorm.io/plugin/dbresolver"

	"github.com/0xJacky/Nginx-UI/model"
)

func newEnvironment(db *gorm.DB, opts ...gen.DOOption) environment {
	_environment := environment{}

	_environment.environmentDo.UseDB(db, opts...)
	_environment.environmentDo.UseModel(&model.Environment{})

	tableName := _environment.environmentDo.TableName()
	_environment.ALL = field.NewAsterisk(tableName)
	_environment.ID = field.NewInt(tableName, "id")
	_environment.CreatedAt = field.NewTime(tableName, "created_at")
	_environment.UpdatedAt = field.NewTime(tableName, "updated_at")
	_environment.DeletedAt = field.NewField(tableName, "deleted_at")
	_environment.Name = field.NewString(tableName, "name")
	_environment.URL = field.NewString(tableName, "url")
	_environment.Token = field.NewString(tableName, "token")
	_environment.Enabled = field.NewBool(tableName, "enabled")
	_environment.OperationSync = field.NewBool(tableName, "operation_sync")
	_environment.SyncApiRegex = field.NewString(tableName, "sync_api_regex")

	_environment.fillFieldMap()

	return _environment
}

type environment struct {
	environmentDo

	ALL           field.Asterisk
	ID            field.Int
	CreatedAt     field.Time
	UpdatedAt     field.Time
	DeletedAt     field.Field
	Name          field.String
	URL           field.String
	Token         field.String
	Enabled       field.Bool
	OperationSync field.Bool
	SyncApiRegex  field.String

	fieldMap map[string]field.Expr
}

func (e environment) Table(newTableName string) *environment {
	e.environmentDo.UseTable(newTableName)
	return e.updateTableName(newTableName)
}

func (e environment) As(alias string) *environment {
	e.environmentDo.DO = *(e.environmentDo.As(alias).(*gen.DO))
	return e.updateTableName(alias)
}

func (e *environment) updateTableName(table string) *environment {
	e.ALL = field.NewAsterisk(table)
	e.ID = field.NewInt(table, "id")
	e.CreatedAt = field.NewTime(table, "created_at")
	e.UpdatedAt = field.NewTime(table, "updated_at")
	e.DeletedAt = field.NewField(table, "deleted_at")
	e.Name = field.NewString(table, "name")
	e.URL = field.NewString(table, "url")
	e.Token = field.NewString(table, "token")
	e.Enabled = field.NewBool(table, "enabled")
	e.OperationSync = field.NewBool(table, "operation_sync")
	e.SyncApiRegex = field.NewString(table, "sync_api_regex")

	e.fillFieldMap()

	return e
}

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

func (e *environment) fillFieldMap() {
	e.fieldMap = make(map[string]field.Expr, 10)
	e.fieldMap["id"] = e.ID
	e.fieldMap["created_at"] = e.CreatedAt
	e.fieldMap["updated_at"] = e.UpdatedAt
	e.fieldMap["deleted_at"] = e.DeletedAt
	e.fieldMap["name"] = e.Name
	e.fieldMap["url"] = e.URL
	e.fieldMap["token"] = e.Token
	e.fieldMap["enabled"] = e.Enabled
	e.fieldMap["operation_sync"] = e.OperationSync
	e.fieldMap["sync_api_regex"] = e.SyncApiRegex
}

func (e environment) clone(db *gorm.DB) environment {
	e.environmentDo.ReplaceConnPool(db.Statement.ConnPool)
	return e
}

func (e environment) replaceDB(db *gorm.DB) environment {
	e.environmentDo.ReplaceDB(db)
	return e
}

type environmentDo struct{ gen.DO }

// FirstByID Where("id=@id")
func (e environmentDo) FirstByID(id int) (result *model.Environment, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("id=? ")

	var executeSQL *gorm.DB
	executeSQL = e.UnderlyingDB().Where(generateSQL.String(), params...).Take(&result) // ignore_security_alert
	err = executeSQL.Error

	return
}

// DeleteByID update @@table set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=@id
func (e environmentDo) DeleteByID(id int) (err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("update environments set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=? ")

	var executeSQL *gorm.DB
	executeSQL = e.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert
	err = executeSQL.Error

	return
}

func (e environmentDo) Debug() *environmentDo {
	return e.withDO(e.DO.Debug())
}

func (e environmentDo) WithContext(ctx context.Context) *environmentDo {
	return e.withDO(e.DO.WithContext(ctx))
}

func (e environmentDo) ReadDB() *environmentDo {
	return e.Clauses(dbresolver.Read)
}

func (e environmentDo) WriteDB() *environmentDo {
	return e.Clauses(dbresolver.Write)
}

func (e environmentDo) Session(config *gorm.Session) *environmentDo {
	return e.withDO(e.DO.Session(config))
}

func (e environmentDo) Clauses(conds ...clause.Expression) *environmentDo {
	return e.withDO(e.DO.Clauses(conds...))
}

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

func (e environmentDo) Not(conds ...gen.Condition) *environmentDo {
	return e.withDO(e.DO.Not(conds...))
}

func (e environmentDo) Or(conds ...gen.Condition) *environmentDo {
	return e.withDO(e.DO.Or(conds...))
}

func (e environmentDo) Select(conds ...field.Expr) *environmentDo {
	return e.withDO(e.DO.Select(conds...))
}

func (e environmentDo) Where(conds ...gen.Condition) *environmentDo {
	return e.withDO(e.DO.Where(conds...))
}

func (e environmentDo) Order(conds ...field.Expr) *environmentDo {
	return e.withDO(e.DO.Order(conds...))
}

func (e environmentDo) Distinct(cols ...field.Expr) *environmentDo {
	return e.withDO(e.DO.Distinct(cols...))
}

func (e environmentDo) Omit(cols ...field.Expr) *environmentDo {
	return e.withDO(e.DO.Omit(cols...))
}

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

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

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

func (e environmentDo) Group(cols ...field.Expr) *environmentDo {
	return e.withDO(e.DO.Group(cols...))
}

func (e environmentDo) Having(conds ...gen.Condition) *environmentDo {
	return e.withDO(e.DO.Having(conds...))
}

func (e environmentDo) Limit(limit int) *environmentDo {
	return e.withDO(e.DO.Limit(limit))
}

func (e environmentDo) Offset(offset int) *environmentDo {
	return e.withDO(e.DO.Offset(offset))
}

func (e environmentDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *environmentDo {
	return e.withDO(e.DO.Scopes(funcs...))
}

func (e environmentDo) Unscoped() *environmentDo {
	return e.withDO(e.DO.Unscoped())
}

func (e environmentDo) Create(values ...*model.Environment) error {
	if len(values) == 0 {
		return nil
	}
	return e.DO.Create(values)
}

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

func (e environmentDo) First() (*model.Environment, error) {
	if result, err := e.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*model.Environment), nil
	}
}

func (e environmentDo) Take() (*model.Environment, error) {
	if result, err := e.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*model.Environment), nil
	}
}

func (e environmentDo) Last() (*model.Environment, error) {
	if result, err := e.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*model.Environment), nil
	}
}

func (e environmentDo) Find() ([]*model.Environment, error) {
	result, err := e.DO.Find()
	return result.([]*model.Environment), err
}

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

func (e environmentDo) Attrs(attrs ...field.AssignExpr) *environmentDo {
	return e.withDO(e.DO.Attrs(attrs...))
}

func (e environmentDo) Assign(attrs ...field.AssignExpr) *environmentDo {
	return e.withDO(e.DO.Assign(attrs...))
}

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

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

func (e environmentDo) FirstOrInit() (*model.Environment, error) {
	if result, err := e.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*model.Environment), nil
	}
}

func (e environmentDo) FirstOrCreate() (*model.Environment, error) {
	if result, err := e.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*model.Environment), nil
	}
}

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

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

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

func (e environmentDo) Scan(result interface{}) (err error) {
	return e.DO.Scan(result)
}

func (e environmentDo) Delete(models ...*model.Environment) (result gen.ResultInfo, err error) {
	return e.DO.Delete(models)
}

func (e *environmentDo) withDO(do gen.Dao) *environmentDo {
	e.DO = *do.(*gen.DO)
	return e
}
