// 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 dao

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/flowline-io/flowbot/internal/store/model"
)

func newDag(db *gorm.DB, opts ...gen.DOOption) dag {
	_dag := dag{}

	_dag.dagDo.UseDB(db, opts...)
	_dag.dagDo.UseModel(&model.Dag{})

	tableName := _dag.dagDo.TableName()
	_dag.ALL = field.NewAsterisk(tableName)
	_dag.ID = field.NewInt64(tableName, "id")
	_dag.WorkflowID = field.NewInt64(tableName, "workflow_id")
	_dag.ScriptID = field.NewInt64(tableName, "script_id")
	_dag.ScriptVersion = field.NewInt32(tableName, "script_version")
	_dag.Nodes = field.NewField(tableName, "nodes")
	_dag.Edges = field.NewField(tableName, "edges")
	_dag.CreatedAt = field.NewTime(tableName, "created_at")
	_dag.UpdatedAt = field.NewTime(tableName, "updated_at")

	_dag.fillFieldMap()

	return _dag
}

type dag struct {
	dagDo

	ALL           field.Asterisk
	ID            field.Int64
	WorkflowID    field.Int64
	ScriptID      field.Int64
	ScriptVersion field.Int32
	Nodes         field.Field
	Edges         field.Field
	CreatedAt     field.Time
	UpdatedAt     field.Time

	fieldMap map[string]field.Expr
}

func (d dag) Table(newTableName string) *dag {
	d.dagDo.UseTable(newTableName)
	return d.updateTableName(newTableName)
}

func (d dag) As(alias string) *dag {
	d.dagDo.DO = *(d.dagDo.As(alias).(*gen.DO))
	return d.updateTableName(alias)
}

func (d *dag) updateTableName(table string) *dag {
	d.ALL = field.NewAsterisk(table)
	d.ID = field.NewInt64(table, "id")
	d.WorkflowID = field.NewInt64(table, "workflow_id")
	d.ScriptID = field.NewInt64(table, "script_id")
	d.ScriptVersion = field.NewInt32(table, "script_version")
	d.Nodes = field.NewField(table, "nodes")
	d.Edges = field.NewField(table, "edges")
	d.CreatedAt = field.NewTime(table, "created_at")
	d.UpdatedAt = field.NewTime(table, "updated_at")

	d.fillFieldMap()

	return d
}

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

func (d *dag) fillFieldMap() {
	d.fieldMap = make(map[string]field.Expr, 8)
	d.fieldMap["id"] = d.ID
	d.fieldMap["workflow_id"] = d.WorkflowID
	d.fieldMap["script_id"] = d.ScriptID
	d.fieldMap["script_version"] = d.ScriptVersion
	d.fieldMap["nodes"] = d.Nodes
	d.fieldMap["edges"] = d.Edges
	d.fieldMap["created_at"] = d.CreatedAt
	d.fieldMap["updated_at"] = d.UpdatedAt
}

func (d dag) clone(db *gorm.DB) dag {
	d.dagDo.ReplaceConnPool(db.Statement.ConnPool)
	return d
}

func (d dag) replaceDB(db *gorm.DB) dag {
	d.dagDo.ReplaceDB(db)
	return d
}

type dagDo struct{ gen.DO }

// GetByID
//
// SELECT * FROM @@table WHERE id=@id
func (d dagDo) GetByID(id int) (result model.Dag, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, id)
	generateSQL.WriteString("SELECT * FROM dag WHERE id=? ")

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

	return
}

// TakeByUidAndTopic query data by uid and topic and return one
//
// where("uid=@uid AND topic=@topic")
func (d dagDo) TakeByUidAndTopic(uid string, topic string) (result model.Dag, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, uid)
	params = append(params, topic)
	generateSQL.WriteString("uid=? AND topic=? ")

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

	return
}

// FindByUidAndTopic query data by uid and topic and return array
//
// where("uid=@uid AND topic=@topic")
func (d dagDo) FindByUidAndTopic(uid string, topic string) (result []*model.Dag, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, uid)
	params = append(params, topic)
	generateSQL.WriteString("uid=? AND topic=? ")

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

	return
}

func (d dagDo) Debug() *dagDo {
	return d.withDO(d.DO.Debug())
}

func (d dagDo) WithContext(ctx context.Context) *dagDo {
	return d.withDO(d.DO.WithContext(ctx))
}

func (d dagDo) ReadDB() *dagDo {
	return d.Clauses(dbresolver.Read)
}

func (d dagDo) WriteDB() *dagDo {
	return d.Clauses(dbresolver.Write)
}

func (d dagDo) Session(config *gorm.Session) *dagDo {
	return d.withDO(d.DO.Session(config))
}

func (d dagDo) Clauses(conds ...clause.Expression) *dagDo {
	return d.withDO(d.DO.Clauses(conds...))
}

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

func (d dagDo) Not(conds ...gen.Condition) *dagDo {
	return d.withDO(d.DO.Not(conds...))
}

func (d dagDo) Or(conds ...gen.Condition) *dagDo {
	return d.withDO(d.DO.Or(conds...))
}

func (d dagDo) Select(conds ...field.Expr) *dagDo {
	return d.withDO(d.DO.Select(conds...))
}

func (d dagDo) Where(conds ...gen.Condition) *dagDo {
	return d.withDO(d.DO.Where(conds...))
}

func (d dagDo) Order(conds ...field.Expr) *dagDo {
	return d.withDO(d.DO.Order(conds...))
}

func (d dagDo) Distinct(cols ...field.Expr) *dagDo {
	return d.withDO(d.DO.Distinct(cols...))
}

func (d dagDo) Omit(cols ...field.Expr) *dagDo {
	return d.withDO(d.DO.Omit(cols...))
}

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

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

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

func (d dagDo) Group(cols ...field.Expr) *dagDo {
	return d.withDO(d.DO.Group(cols...))
}

func (d dagDo) Having(conds ...gen.Condition) *dagDo {
	return d.withDO(d.DO.Having(conds...))
}

func (d dagDo) Limit(limit int) *dagDo {
	return d.withDO(d.DO.Limit(limit))
}

func (d dagDo) Offset(offset int) *dagDo {
	return d.withDO(d.DO.Offset(offset))
}

func (d dagDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *dagDo {
	return d.withDO(d.DO.Scopes(funcs...))
}

func (d dagDo) Unscoped() *dagDo {
	return d.withDO(d.DO.Unscoped())
}

func (d dagDo) Create(values ...*model.Dag) error {
	if len(values) == 0 {
		return nil
	}
	return d.DO.Create(values)
}

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

func (d dagDo) First() (*model.Dag, error) {
	if result, err := d.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*model.Dag), nil
	}
}

func (d dagDo) Take() (*model.Dag, error) {
	if result, err := d.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*model.Dag), nil
	}
}

func (d dagDo) Last() (*model.Dag, error) {
	if result, err := d.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*model.Dag), nil
	}
}

func (d dagDo) Find() ([]*model.Dag, error) {
	result, err := d.DO.Find()
	return result.([]*model.Dag), err
}

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

func (d dagDo) Attrs(attrs ...field.AssignExpr) *dagDo {
	return d.withDO(d.DO.Attrs(attrs...))
}

func (d dagDo) Assign(attrs ...field.AssignExpr) *dagDo {
	return d.withDO(d.DO.Assign(attrs...))
}

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

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

func (d dagDo) FirstOrInit() (*model.Dag, error) {
	if result, err := d.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*model.Dag), nil
	}
}

func (d dagDo) FirstOrCreate() (*model.Dag, error) {
	if result, err := d.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*model.Dag), nil
	}
}

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

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

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

func (d dagDo) Scan(result interface{}) (err error) {
	return d.DO.Scan(result)
}

func (d dagDo) Delete(models ...*model.Dag) (result gen.ResultInfo, err error) {
	return d.DO.Delete(models)
}

func (d *dagDo) withDO(do gen.Dao) *dagDo {
	d.DO = *do.(*gen.DO)
	return d
}
