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

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

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

	"gorm.io/plugin/dbresolver"

	"canguidev/shelfy/internal/models"
)

func newMetadataItem(db *gorm.DB, opts ...gen.DOOption) metadataItem {
	_metadataItem := metadataItem{}

	_metadataItem.metadataItemDo.UseDB(db, opts...)
	_metadataItem.metadataItemDo.UseModel(&models.MetadataItem{})

	tableName := _metadataItem.metadataItemDo.TableName()
	_metadataItem.ALL = field.NewAsterisk(tableName)
	_metadataItem.ID = field.NewInt64(tableName, "id")
	_metadataItem.LibrarySectionID = field.NewInt64(tableName, "library_section_id")
	_metadataItem.ParentID = field.NewInt64(tableName, "parent_id")
	_metadataItem.MetadataType = field.NewInt64(tableName, "metadata_type")
	_metadataItem.GUID = field.NewString(tableName, "guid")
	_metadataItem.Title = field.NewString(tableName, "title")
	_metadataItem.TitleSort = field.NewString(tableName, "title_sort")
	_metadataItem.OriginalTitle = field.NewString(tableName, "original_title")
	_metadataItem.Studio = field.NewString(tableName, "studio")
	_metadataItem.Rating = field.NewFloat64(tableName, "rating")
	_metadataItem.ContentRating = field.NewString(tableName, "content_rating")
	_metadataItem.Tagline = field.NewString(tableName, "tagline")
	_metadataItem.Summary = field.NewString(tableName, "summary")
	_metadataItem.Index = field.NewInt64(tableName, "index")
	_metadataItem.Duration = field.NewInt64(tableName, "duration")
	_metadataItem.ReleaseDate = field.NewString(tableName, "release_date")
	_metadataItem.CreatedAt = field.NewString(tableName, "created_at")
	_metadataItem.UpdatedAt = field.NewString(tableName, "updated_at")
	_metadataItem.UserThumbURL = field.NewString(tableName, "user_thumb_url")

	_metadataItem.fillFieldMap()

	return _metadataItem
}

type metadataItem struct {
	metadataItemDo

	ALL              field.Asterisk
	ID               field.Int64
	LibrarySectionID field.Int64
	ParentID         field.Int64
	MetadataType     field.Int64
	GUID             field.String
	Title            field.String
	TitleSort        field.String
	OriginalTitle    field.String
	Studio           field.String
	Rating           field.Float64
	ContentRating    field.String
	Tagline          field.String
	Summary          field.String
	Index            field.Int64
	Duration         field.Int64
	ReleaseDate      field.String
	CreatedAt        field.String
	UpdatedAt        field.String
	UserThumbURL     field.String

	fieldMap map[string]field.Expr
}

func (m metadataItem) Table(newTableName string) *metadataItem {
	m.metadataItemDo.UseTable(newTableName)
	return m.updateTableName(newTableName)
}

func (m metadataItem) As(alias string) *metadataItem {
	m.metadataItemDo.DO = *(m.metadataItemDo.As(alias).(*gen.DO))
	return m.updateTableName(alias)
}

func (m *metadataItem) updateTableName(table string) *metadataItem {
	m.ALL = field.NewAsterisk(table)
	m.ID = field.NewInt64(table, "id")
	m.LibrarySectionID = field.NewInt64(table, "library_section_id")
	m.ParentID = field.NewInt64(table, "parent_id")
	m.MetadataType = field.NewInt64(table, "metadata_type")
	m.GUID = field.NewString(table, "guid")
	m.Title = field.NewString(table, "title")
	m.TitleSort = field.NewString(table, "title_sort")
	m.OriginalTitle = field.NewString(table, "original_title")
	m.Studio = field.NewString(table, "studio")
	m.Rating = field.NewFloat64(table, "rating")
	m.ContentRating = field.NewString(table, "content_rating")
	m.Tagline = field.NewString(table, "tagline")
	m.Summary = field.NewString(table, "summary")
	m.Index = field.NewInt64(table, "index")
	m.Duration = field.NewInt64(table, "duration")
	m.ReleaseDate = field.NewString(table, "release_date")
	m.CreatedAt = field.NewString(table, "created_at")
	m.UpdatedAt = field.NewString(table, "updated_at")
	m.UserThumbURL = field.NewString(table, "user_thumb_url")

	m.fillFieldMap()

	return m
}

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

func (m *metadataItem) fillFieldMap() {
	m.fieldMap = make(map[string]field.Expr, 19)
	m.fieldMap["id"] = m.ID
	m.fieldMap["library_section_id"] = m.LibrarySectionID
	m.fieldMap["parent_id"] = m.ParentID
	m.fieldMap["metadata_type"] = m.MetadataType
	m.fieldMap["guid"] = m.GUID
	m.fieldMap["title"] = m.Title
	m.fieldMap["title_sort"] = m.TitleSort
	m.fieldMap["original_title"] = m.OriginalTitle
	m.fieldMap["studio"] = m.Studio
	m.fieldMap["rating"] = m.Rating
	m.fieldMap["content_rating"] = m.ContentRating
	m.fieldMap["tagline"] = m.Tagline
	m.fieldMap["summary"] = m.Summary
	m.fieldMap["index"] = m.Index
	m.fieldMap["duration"] = m.Duration
	m.fieldMap["release_date"] = m.ReleaseDate
	m.fieldMap["created_at"] = m.CreatedAt
	m.fieldMap["updated_at"] = m.UpdatedAt
	m.fieldMap["user_thumb_url"] = m.UserThumbURL
}

func (m metadataItem) clone(db *gorm.DB) metadataItem {
	m.metadataItemDo.ReplaceConnPool(db.Statement.ConnPool)
	return m
}

func (m metadataItem) replaceDB(db *gorm.DB) metadataItem {
	m.metadataItemDo.ReplaceDB(db)
	return m
}

type metadataItemDo struct{ gen.DO }

type IMetadataItemDo interface {
	gen.SubQuery
	Debug() IMetadataItemDo
	WithContext(ctx context.Context) IMetadataItemDo
	WithResult(fc func(tx gen.Dao)) gen.ResultInfo
	ReplaceDB(db *gorm.DB)
	ReadDB() IMetadataItemDo
	WriteDB() IMetadataItemDo
	As(alias string) gen.Dao
	Session(config *gorm.Session) IMetadataItemDo
	Columns(cols ...field.Expr) gen.Columns
	Clauses(conds ...clause.Expression) IMetadataItemDo
	Not(conds ...gen.Condition) IMetadataItemDo
	Or(conds ...gen.Condition) IMetadataItemDo
	Select(conds ...field.Expr) IMetadataItemDo
	Where(conds ...gen.Condition) IMetadataItemDo
	Order(conds ...field.Expr) IMetadataItemDo
	Distinct(cols ...field.Expr) IMetadataItemDo
	Omit(cols ...field.Expr) IMetadataItemDo
	Join(table schema.Tabler, on ...field.Expr) IMetadataItemDo
	LeftJoin(table schema.Tabler, on ...field.Expr) IMetadataItemDo
	RightJoin(table schema.Tabler, on ...field.Expr) IMetadataItemDo
	Group(cols ...field.Expr) IMetadataItemDo
	Having(conds ...gen.Condition) IMetadataItemDo
	Limit(limit int) IMetadataItemDo
	Offset(offset int) IMetadataItemDo
	Count() (count int64, err error)
	Scopes(funcs ...func(gen.Dao) gen.Dao) IMetadataItemDo
	Unscoped() IMetadataItemDo
	Create(values ...*models.MetadataItem) error
	CreateInBatches(values []*models.MetadataItem, batchSize int) error
	Save(values ...*models.MetadataItem) error
	First() (*models.MetadataItem, error)
	Take() (*models.MetadataItem, error)
	Last() (*models.MetadataItem, error)
	Find() ([]*models.MetadataItem, error)
	FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.MetadataItem, err error)
	FindInBatches(result *[]*models.MetadataItem, batchSize int, fc func(tx gen.Dao, batch int) error) error
	Pluck(column field.Expr, dest interface{}) error
	Delete(...*models.MetadataItem) (info gen.ResultInfo, err error)
	Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
	UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
	Updates(value interface{}) (info gen.ResultInfo, err error)
	UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
	UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
	UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
	UpdateFrom(q gen.SubQuery) gen.Dao
	Attrs(attrs ...field.AssignExpr) IMetadataItemDo
	Assign(attrs ...field.AssignExpr) IMetadataItemDo
	Joins(fields ...field.RelationField) IMetadataItemDo
	Preload(fields ...field.RelationField) IMetadataItemDo
	FirstOrInit() (*models.MetadataItem, error)
	FirstOrCreate() (*models.MetadataItem, error)
	FindByPage(offset int, limit int) (result []*models.MetadataItem, count int64, err error)
	ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
	Rows() (*sql.Rows, error)
	Row() *sql.Row
	Scan(result interface{}) (err error)
	Returning(value interface{}, columns ...string) IMetadataItemDo
	UnderlyingDB() *gorm.DB
	schema.Tabler

	FilterWithNameAndRole(name string, role string) (result []models.MetadataItem, err error)
}

// SELECT * FROM @@table WHERE name = @name{{if role !=""}} AND role = @role{{end}}
func (m metadataItemDo) FilterWithNameAndRole(name string, role string) (result []models.MetadataItem, err error) {
	var params []interface{}

	var generateSQL strings.Builder
	params = append(params, name)
	generateSQL.WriteString("SELECT * FROM metadata_items WHERE name = ? ")
	if role != "" {
		params = append(params, role)
		generateSQL.WriteString("AND role = ? ")
	}

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

	return
}

func (m metadataItemDo) Debug() IMetadataItemDo {
	return m.withDO(m.DO.Debug())
}

func (m metadataItemDo) WithContext(ctx context.Context) IMetadataItemDo {
	return m.withDO(m.DO.WithContext(ctx))
}

func (m metadataItemDo) ReadDB() IMetadataItemDo {
	return m.Clauses(dbresolver.Read)
}

func (m metadataItemDo) WriteDB() IMetadataItemDo {
	return m.Clauses(dbresolver.Write)
}

func (m metadataItemDo) Session(config *gorm.Session) IMetadataItemDo {
	return m.withDO(m.DO.Session(config))
}

func (m metadataItemDo) Clauses(conds ...clause.Expression) IMetadataItemDo {
	return m.withDO(m.DO.Clauses(conds...))
}

func (m metadataItemDo) Returning(value interface{}, columns ...string) IMetadataItemDo {
	return m.withDO(m.DO.Returning(value, columns...))
}

func (m metadataItemDo) Not(conds ...gen.Condition) IMetadataItemDo {
	return m.withDO(m.DO.Not(conds...))
}

func (m metadataItemDo) Or(conds ...gen.Condition) IMetadataItemDo {
	return m.withDO(m.DO.Or(conds...))
}

func (m metadataItemDo) Select(conds ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Select(conds...))
}

func (m metadataItemDo) Where(conds ...gen.Condition) IMetadataItemDo {
	return m.withDO(m.DO.Where(conds...))
}

func (m metadataItemDo) Order(conds ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Order(conds...))
}

func (m metadataItemDo) Distinct(cols ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Distinct(cols...))
}

func (m metadataItemDo) Omit(cols ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Omit(cols...))
}

func (m metadataItemDo) Join(table schema.Tabler, on ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Join(table, on...))
}

func (m metadataItemDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.LeftJoin(table, on...))
}

func (m metadataItemDo) RightJoin(table schema.Tabler, on ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.RightJoin(table, on...))
}

func (m metadataItemDo) Group(cols ...field.Expr) IMetadataItemDo {
	return m.withDO(m.DO.Group(cols...))
}

func (m metadataItemDo) Having(conds ...gen.Condition) IMetadataItemDo {
	return m.withDO(m.DO.Having(conds...))
}

func (m metadataItemDo) Limit(limit int) IMetadataItemDo {
	return m.withDO(m.DO.Limit(limit))
}

func (m metadataItemDo) Offset(offset int) IMetadataItemDo {
	return m.withDO(m.DO.Offset(offset))
}

func (m metadataItemDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMetadataItemDo {
	return m.withDO(m.DO.Scopes(funcs...))
}

func (m metadataItemDo) Unscoped() IMetadataItemDo {
	return m.withDO(m.DO.Unscoped())
}

func (m metadataItemDo) Create(values ...*models.MetadataItem) error {
	if len(values) == 0 {
		return nil
	}
	return m.DO.Create(values)
}

func (m metadataItemDo) CreateInBatches(values []*models.MetadataItem, batchSize int) error {
	return m.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 (m metadataItemDo) Save(values ...*models.MetadataItem) error {
	if len(values) == 0 {
		return nil
	}
	return m.DO.Save(values)
}

func (m metadataItemDo) First() (*models.MetadataItem, error) {
	if result, err := m.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*models.MetadataItem), nil
	}
}

func (m metadataItemDo) Take() (*models.MetadataItem, error) {
	if result, err := m.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*models.MetadataItem), nil
	}
}

func (m metadataItemDo) Last() (*models.MetadataItem, error) {
	if result, err := m.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*models.MetadataItem), nil
	}
}

func (m metadataItemDo) Find() ([]*models.MetadataItem, error) {
	result, err := m.DO.Find()
	return result.([]*models.MetadataItem), err
}

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

func (m metadataItemDo) Attrs(attrs ...field.AssignExpr) IMetadataItemDo {
	return m.withDO(m.DO.Attrs(attrs...))
}

func (m metadataItemDo) Assign(attrs ...field.AssignExpr) IMetadataItemDo {
	return m.withDO(m.DO.Assign(attrs...))
}

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

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

func (m metadataItemDo) FirstOrInit() (*models.MetadataItem, error) {
	if result, err := m.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*models.MetadataItem), nil
	}
}

func (m metadataItemDo) FirstOrCreate() (*models.MetadataItem, error) {
	if result, err := m.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*models.MetadataItem), nil
	}
}

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

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

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

func (m metadataItemDo) Scan(result interface{}) (err error) {
	return m.DO.Scan(result)
}

func (m metadataItemDo) Delete(models ...*models.MetadataItem) (result gen.ResultInfo, err error) {
	return m.DO.Delete(models)
}

func (m *metadataItemDo) withDO(do gen.Dao) *metadataItemDo {
	m.DO = *do.(*gen.DO)
	return m
}
