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

	_stream.streamDo.UseDB(db, opts...)
	_stream.streamDo.UseModel(&model.Stream{})

	tableName := _stream.streamDo.TableName()
	_stream.ALL = field.NewAsterisk(tableName)
	_stream.ID = field.NewUint64(tableName, "id")
	_stream.CreatedAt = field.NewTime(tableName, "created_at")
	_stream.UpdatedAt = field.NewTime(tableName, "updated_at")
	_stream.DeletedAt = field.NewField(tableName, "deleted_at")
	_stream.Path = field.NewString(tableName, "path")
	_stream.Advanced = field.NewBool(tableName, "advanced")
	_stream.NamespaceID = field.NewUint64(tableName, "namespace_id")
	_stream.SyncNodeIDs = field.NewField(tableName, "sync_node_ids")
	_stream.Namespace = streamBelongsToNamespace{
		db: db.Session(&gorm.Session{}),

		RelationField: field.NewRelation("Namespace", "model.Namespace"),
	}

	_stream.fillFieldMap()

	return _stream
}

type stream struct {
	streamDo

	ALL         field.Asterisk
	ID          field.Uint64
	CreatedAt   field.Time
	UpdatedAt   field.Time
	DeletedAt   field.Field
	Path        field.String
	Advanced    field.Bool
	NamespaceID field.Uint64
	SyncNodeIDs field.Field
	Namespace   streamBelongsToNamespace

	fieldMap map[string]field.Expr
}

func (s stream) Table(newTableName string) *stream {
	s.streamDo.UseTable(newTableName)
	return s.updateTableName(newTableName)
}

func (s stream) As(alias string) *stream {
	s.streamDo.DO = *(s.streamDo.As(alias).(*gen.DO))
	return s.updateTableName(alias)
}

func (s *stream) updateTableName(table string) *stream {
	s.ALL = field.NewAsterisk(table)
	s.ID = field.NewUint64(table, "id")
	s.CreatedAt = field.NewTime(table, "created_at")
	s.UpdatedAt = field.NewTime(table, "updated_at")
	s.DeletedAt = field.NewField(table, "deleted_at")
	s.Path = field.NewString(table, "path")
	s.Advanced = field.NewBool(table, "advanced")
	s.NamespaceID = field.NewUint64(table, "namespace_id")
	s.SyncNodeIDs = field.NewField(table, "sync_node_ids")

	s.fillFieldMap()

	return s
}

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

func (s *stream) fillFieldMap() {
	s.fieldMap = make(map[string]field.Expr, 9)
	s.fieldMap["id"] = s.ID
	s.fieldMap["created_at"] = s.CreatedAt
	s.fieldMap["updated_at"] = s.UpdatedAt
	s.fieldMap["deleted_at"] = s.DeletedAt
	s.fieldMap["path"] = s.Path
	s.fieldMap["advanced"] = s.Advanced
	s.fieldMap["namespace_id"] = s.NamespaceID
	s.fieldMap["sync_node_ids"] = s.SyncNodeIDs

}

func (s stream) clone(db *gorm.DB) stream {
	s.streamDo.ReplaceConnPool(db.Statement.ConnPool)
	s.Namespace.db = db.Session(&gorm.Session{Initialized: true})
	s.Namespace.db.Statement.ConnPool = db.Statement.ConnPool
	return s
}

func (s stream) replaceDB(db *gorm.DB) stream {
	s.streamDo.ReplaceDB(db)
	s.Namespace.db = db.Session(&gorm.Session{})
	return s
}

type streamBelongsToNamespace struct {
	db *gorm.DB

	field.RelationField
}

func (a streamBelongsToNamespace) Where(conds ...field.Expr) *streamBelongsToNamespace {
	if len(conds) == 0 {
		return &a
	}

	exprs := make([]clause.Expression, 0, len(conds))
	for _, cond := range conds {
		exprs = append(exprs, cond.BeCond().(clause.Expression))
	}
	a.db = a.db.Clauses(clause.Where{Exprs: exprs})
	return &a
}

func (a streamBelongsToNamespace) WithContext(ctx context.Context) *streamBelongsToNamespace {
	a.db = a.db.WithContext(ctx)
	return &a
}

func (a streamBelongsToNamespace) Session(session *gorm.Session) *streamBelongsToNamespace {
	a.db = a.db.Session(session)
	return &a
}

func (a streamBelongsToNamespace) Model(m *model.Stream) *streamBelongsToNamespaceTx {
	return &streamBelongsToNamespaceTx{a.db.Model(m).Association(a.Name())}
}

func (a streamBelongsToNamespace) Unscoped() *streamBelongsToNamespace {
	a.db = a.db.Unscoped()
	return &a
}

type streamBelongsToNamespaceTx struct{ tx *gorm.Association }

func (a streamBelongsToNamespaceTx) Find() (result *model.Namespace, err error) {
	return result, a.tx.Find(&result)
}

func (a streamBelongsToNamespaceTx) Append(values ...*model.Namespace) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Append(targetValues...)
}

func (a streamBelongsToNamespaceTx) Replace(values ...*model.Namespace) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Replace(targetValues...)
}

func (a streamBelongsToNamespaceTx) Delete(values ...*model.Namespace) (err error) {
	targetValues := make([]interface{}, len(values))
	for i, v := range values {
		targetValues[i] = v
	}
	return a.tx.Delete(targetValues...)
}

func (a streamBelongsToNamespaceTx) Clear() error {
	return a.tx.Clear()
}

func (a streamBelongsToNamespaceTx) Count() int64 {
	return a.tx.Count()
}

func (a streamBelongsToNamespaceTx) Unscoped() *streamBelongsToNamespaceTx {
	a.tx = a.tx.Unscoped()
	return &a
}

type streamDo struct{ gen.DO }

// FirstByID Where("id=@id")
func (s streamDo) FirstByID(id uint64) (result *model.Stream, err error) {
	var params []interface{}

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

	var executeSQL *gorm.DB
	executeSQL = s.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 (s streamDo) DeleteByID(id uint64) (err error) {
	var params []interface{}

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

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

	return
}

func (s streamDo) Debug() *streamDo {
	return s.withDO(s.DO.Debug())
}

func (s streamDo) WithContext(ctx context.Context) *streamDo {
	return s.withDO(s.DO.WithContext(ctx))
}

func (s streamDo) ReadDB() *streamDo {
	return s.Clauses(dbresolver.Read)
}

func (s streamDo) WriteDB() *streamDo {
	return s.Clauses(dbresolver.Write)
}

func (s streamDo) Session(config *gorm.Session) *streamDo {
	return s.withDO(s.DO.Session(config))
}

func (s streamDo) Clauses(conds ...clause.Expression) *streamDo {
	return s.withDO(s.DO.Clauses(conds...))
}

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

func (s streamDo) Not(conds ...gen.Condition) *streamDo {
	return s.withDO(s.DO.Not(conds...))
}

func (s streamDo) Or(conds ...gen.Condition) *streamDo {
	return s.withDO(s.DO.Or(conds...))
}

func (s streamDo) Select(conds ...field.Expr) *streamDo {
	return s.withDO(s.DO.Select(conds...))
}

func (s streamDo) Where(conds ...gen.Condition) *streamDo {
	return s.withDO(s.DO.Where(conds...))
}

func (s streamDo) Order(conds ...field.Expr) *streamDo {
	return s.withDO(s.DO.Order(conds...))
}

func (s streamDo) Distinct(cols ...field.Expr) *streamDo {
	return s.withDO(s.DO.Distinct(cols...))
}

func (s streamDo) Omit(cols ...field.Expr) *streamDo {
	return s.withDO(s.DO.Omit(cols...))
}

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

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

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

func (s streamDo) Group(cols ...field.Expr) *streamDo {
	return s.withDO(s.DO.Group(cols...))
}

func (s streamDo) Having(conds ...gen.Condition) *streamDo {
	return s.withDO(s.DO.Having(conds...))
}

func (s streamDo) Limit(limit int) *streamDo {
	return s.withDO(s.DO.Limit(limit))
}

func (s streamDo) Offset(offset int) *streamDo {
	return s.withDO(s.DO.Offset(offset))
}

func (s streamDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *streamDo {
	return s.withDO(s.DO.Scopes(funcs...))
}

func (s streamDo) Unscoped() *streamDo {
	return s.withDO(s.DO.Unscoped())
}

func (s streamDo) Create(values ...*model.Stream) error {
	if len(values) == 0 {
		return nil
	}
	return s.DO.Create(values)
}

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

func (s streamDo) First() (*model.Stream, error) {
	if result, err := s.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*model.Stream), nil
	}
}

func (s streamDo) Take() (*model.Stream, error) {
	if result, err := s.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*model.Stream), nil
	}
}

func (s streamDo) Last() (*model.Stream, error) {
	if result, err := s.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*model.Stream), nil
	}
}

func (s streamDo) Find() ([]*model.Stream, error) {
	result, err := s.DO.Find()
	return result.([]*model.Stream), err
}

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

func (s streamDo) Attrs(attrs ...field.AssignExpr) *streamDo {
	return s.withDO(s.DO.Attrs(attrs...))
}

func (s streamDo) Assign(attrs ...field.AssignExpr) *streamDo {
	return s.withDO(s.DO.Assign(attrs...))
}

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

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

func (s streamDo) FirstOrInit() (*model.Stream, error) {
	if result, err := s.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*model.Stream), nil
	}
}

func (s streamDo) FirstOrCreate() (*model.Stream, error) {
	if result, err := s.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*model.Stream), nil
	}
}

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

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

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

func (s streamDo) Scan(result interface{}) (err error) {
	return s.DO.Scan(result)
}

func (s streamDo) Delete(models ...*model.Stream) (result gen.ResultInfo, err error) {
	return s.DO.Delete(models)
}

func (s *streamDo) withDO(do gen.Dao) *streamDo {
	s.DO = *do.(*gen.DO)
	return s
}
