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

import (
	"context"
	"strings"

	"git.mstar.dev/mstar/linstrom/storage-new/models"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"

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

	"gorm.io/plugin/dbresolver"
)

func newAccessToken(db *gorm.DB, opts ...gen.DOOption) accessToken {
	_accessToken := accessToken{}

	_accessToken.accessTokenDo.UseDB(db, opts...)
	_accessToken.accessTokenDo.UseModel(&models.AccessToken{})

	tableName := _accessToken.accessTokenDo.TableName()
	_accessToken.ALL = field.NewAsterisk(tableName)
	_accessToken.UserId = field.NewString(tableName, "user_id")
	_accessToken.Token = field.NewString(tableName, "token")
	_accessToken.Name = field.NewString(tableName, "name")
	_accessToken.ExpiresAt = field.NewTime(tableName, "expires_at")
	_accessToken.User = accessTokenBelongsToUser{
		db: db.Session(&gorm.Session{}),

		RelationField: field.NewRelation("User", "models.User"),
		Server: struct {
			field.RelationField
			Icon struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.Server", "models.RemoteServer"),
			Icon: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Server.Icon", "models.MediaMetadata"),
			},
		},
		Icon: struct {
			field.RelationField
		}{
			RelationField: field.NewRelation("User.Icon", "models.MediaMetadata"),
		},
		Background: struct {
			field.RelationField
		}{
			RelationField: field.NewRelation("User.Background", "models.MediaMetadata"),
		},
		Banner: struct {
			field.RelationField
		}{
			RelationField: field.NewRelation("User.Banner", "models.MediaMetadata"),
		},
		RemoteInfo: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.RemoteInfo", "models.UserRemoteLinks"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.RemoteInfo.User", "models.User"),
			},
		},
		InfoFields: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.InfoFields", "models.UserInfoField"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.InfoFields.User", "models.User"),
			},
		},
		BeingTypes: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.BeingTypes", "models.UserToBeing"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.BeingTypes.User", "models.User"),
			},
		},
		Tags: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.Tags", "models.UserToTag"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Tags.User", "models.User"),
			},
		},
		Relations: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
			TargetUser struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.Relations", "models.UserToUserRelation"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Relations.User", "models.User"),
			},
			TargetUser: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Relations.TargetUser", "models.User"),
			},
		},
		Pronouns: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.Pronouns", "models.UserToPronoun"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Pronouns.User", "models.User"),
			},
		},
		Roles: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
			Role struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.Roles", "models.UserToRole"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Roles.User", "models.User"),
			},
			Role: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.Roles.Role", "models.Role"),
			},
		},
		AuthMethods: struct {
			field.RelationField
			User struct {
				field.RelationField
			}
		}{
			RelationField: field.NewRelation("User.AuthMethods", "models.UserAuthMethod"),
			User: struct {
				field.RelationField
			}{
				RelationField: field.NewRelation("User.AuthMethods.User", "models.User"),
			},
		},
	}

	_accessToken.fillFieldMap()

	return _accessToken
}

type accessToken struct {
	accessTokenDo

	ALL       field.Asterisk
	UserId    field.String
	Token     field.String
	Name      field.String
	ExpiresAt field.Time
	User      accessTokenBelongsToUser

	fieldMap map[string]field.Expr
}

func (a accessToken) Table(newTableName string) *accessToken {
	a.accessTokenDo.UseTable(newTableName)
	return a.updateTableName(newTableName)
}

func (a accessToken) As(alias string) *accessToken {
	a.accessTokenDo.DO = *(a.accessTokenDo.As(alias).(*gen.DO))
	return a.updateTableName(alias)
}

func (a *accessToken) updateTableName(table string) *accessToken {
	a.ALL = field.NewAsterisk(table)
	a.UserId = field.NewString(table, "user_id")
	a.Token = field.NewString(table, "token")
	a.Name = field.NewString(table, "name")
	a.ExpiresAt = field.NewTime(table, "expires_at")

	a.fillFieldMap()

	return a
}

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

func (a *accessToken) fillFieldMap() {
	a.fieldMap = make(map[string]field.Expr, 5)
	a.fieldMap["user_id"] = a.UserId
	a.fieldMap["token"] = a.Token
	a.fieldMap["name"] = a.Name
	a.fieldMap["expires_at"] = a.ExpiresAt

}

func (a accessToken) clone(db *gorm.DB) accessToken {
	a.accessTokenDo.ReplaceConnPool(db.Statement.ConnPool)
	return a
}

func (a accessToken) replaceDB(db *gorm.DB) accessToken {
	a.accessTokenDo.ReplaceDB(db)
	return a
}

type accessTokenBelongsToUser struct {
	db *gorm.DB

	field.RelationField

	Server struct {
		field.RelationField
		Icon struct {
			field.RelationField
		}
	}
	Icon struct {
		field.RelationField
	}
	Background struct {
		field.RelationField
	}
	Banner struct {
		field.RelationField
	}
	RemoteInfo struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
	InfoFields struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
	BeingTypes struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
	Tags struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
	Relations struct {
		field.RelationField
		User struct {
			field.RelationField
		}
		TargetUser struct {
			field.RelationField
		}
	}
	Pronouns struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
	Roles struct {
		field.RelationField
		User struct {
			field.RelationField
		}
		Role struct {
			field.RelationField
		}
	}
	AuthMethods struct {
		field.RelationField
		User struct {
			field.RelationField
		}
	}
}

func (a accessTokenBelongsToUser) Where(conds ...field.Expr) *accessTokenBelongsToUser {
	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 accessTokenBelongsToUser) WithContext(ctx context.Context) *accessTokenBelongsToUser {
	a.db = a.db.WithContext(ctx)
	return &a
}

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

func (a accessTokenBelongsToUser) Model(m *models.AccessToken) *accessTokenBelongsToUserTx {
	return &accessTokenBelongsToUserTx{a.db.Model(m).Association(a.Name())}
}

type accessTokenBelongsToUserTx struct{ tx *gorm.Association }

func (a accessTokenBelongsToUserTx) Find() (result *models.User, err error) {
	return result, a.tx.Find(&result)
}

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

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

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

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

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

type accessTokenDo struct{ gen.DO }

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

	GetTokenIfValid(token string) (result *models.AccessToken, err error)
}

// Get the data for a token
//
// SELECT * FROM @@table WHERE token = @token
func (a accessTokenDo) GetTokenIfValid(token string) (result *models.AccessToken, err error) {
	var params []interface{}

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

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

	return
}

func (a accessTokenDo) Debug() IAccessTokenDo {
	return a.withDO(a.DO.Debug())
}

func (a accessTokenDo) WithContext(ctx context.Context) IAccessTokenDo {
	return a.withDO(a.DO.WithContext(ctx))
}

func (a accessTokenDo) ReadDB() IAccessTokenDo {
	return a.Clauses(dbresolver.Read)
}

func (a accessTokenDo) WriteDB() IAccessTokenDo {
	return a.Clauses(dbresolver.Write)
}

func (a accessTokenDo) Session(config *gorm.Session) IAccessTokenDo {
	return a.withDO(a.DO.Session(config))
}

func (a accessTokenDo) Clauses(conds ...clause.Expression) IAccessTokenDo {
	return a.withDO(a.DO.Clauses(conds...))
}

func (a accessTokenDo) Returning(value interface{}, columns ...string) IAccessTokenDo {
	return a.withDO(a.DO.Returning(value, columns...))
}

func (a accessTokenDo) Not(conds ...gen.Condition) IAccessTokenDo {
	return a.withDO(a.DO.Not(conds...))
}

func (a accessTokenDo) Or(conds ...gen.Condition) IAccessTokenDo {
	return a.withDO(a.DO.Or(conds...))
}

func (a accessTokenDo) Select(conds ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Select(conds...))
}

func (a accessTokenDo) Where(conds ...gen.Condition) IAccessTokenDo {
	return a.withDO(a.DO.Where(conds...))
}

func (a accessTokenDo) Order(conds ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Order(conds...))
}

func (a accessTokenDo) Distinct(cols ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Distinct(cols...))
}

func (a accessTokenDo) Omit(cols ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Omit(cols...))
}

func (a accessTokenDo) Join(table schema.Tabler, on ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Join(table, on...))
}

func (a accessTokenDo) LeftJoin(table schema.Tabler, on ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.LeftJoin(table, on...))
}

func (a accessTokenDo) RightJoin(table schema.Tabler, on ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.RightJoin(table, on...))
}

func (a accessTokenDo) Group(cols ...field.Expr) IAccessTokenDo {
	return a.withDO(a.DO.Group(cols...))
}

func (a accessTokenDo) Having(conds ...gen.Condition) IAccessTokenDo {
	return a.withDO(a.DO.Having(conds...))
}

func (a accessTokenDo) Limit(limit int) IAccessTokenDo {
	return a.withDO(a.DO.Limit(limit))
}

func (a accessTokenDo) Offset(offset int) IAccessTokenDo {
	return a.withDO(a.DO.Offset(offset))
}

func (a accessTokenDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IAccessTokenDo {
	return a.withDO(a.DO.Scopes(funcs...))
}

func (a accessTokenDo) Unscoped() IAccessTokenDo {
	return a.withDO(a.DO.Unscoped())
}

func (a accessTokenDo) Create(values ...*models.AccessToken) error {
	if len(values) == 0 {
		return nil
	}
	return a.DO.Create(values)
}

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

func (a accessTokenDo) First() (*models.AccessToken, error) {
	if result, err := a.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*models.AccessToken), nil
	}
}

func (a accessTokenDo) Take() (*models.AccessToken, error) {
	if result, err := a.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*models.AccessToken), nil
	}
}

func (a accessTokenDo) Last() (*models.AccessToken, error) {
	if result, err := a.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*models.AccessToken), nil
	}
}

func (a accessTokenDo) Find() ([]*models.AccessToken, error) {
	result, err := a.DO.Find()
	return result.([]*models.AccessToken), err
}

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

func (a accessTokenDo) Attrs(attrs ...field.AssignExpr) IAccessTokenDo {
	return a.withDO(a.DO.Attrs(attrs...))
}

func (a accessTokenDo) Assign(attrs ...field.AssignExpr) IAccessTokenDo {
	return a.withDO(a.DO.Assign(attrs...))
}

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

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

func (a accessTokenDo) FirstOrInit() (*models.AccessToken, error) {
	if result, err := a.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*models.AccessToken), nil
	}
}

func (a accessTokenDo) FirstOrCreate() (*models.AccessToken, error) {
	if result, err := a.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*models.AccessToken), nil
	}
}

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

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

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

func (a accessTokenDo) Scan(result interface{}) (err error) {
	return a.DO.Scan(result)
}

func (a accessTokenDo) Delete(models ...*models.AccessToken) (result gen.ResultInfo, err error) {
	return a.DO.Delete(models)
}

func (a *accessTokenDo) withDO(do gen.Dao) *accessTokenDo {
	a.DO = *do.(*gen.DO)
	return a
}
