// Code generated by BobGen mysql v0.42.0. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package models

import (
	"context"
	"io"

	"github.com/aarondl/opt/omit"
	"github.com/stephenafamo/bob"
	"github.com/stephenafamo/bob/dialect/mysql"
	"github.com/stephenafamo/bob/dialect/mysql/dialect"
	"github.com/stephenafamo/bob/dialect/mysql/dm"
	"github.com/stephenafamo/bob/dialect/mysql/sm"
	"github.com/stephenafamo/bob/dialect/mysql/um"
	"github.com/stephenafamo/bob/expr"
)

// TastypieApiaccess is an object representing the database table.
type TastypieApiaccess struct {
	ID            int32  `db:"id,pk,autoincr" `
	Identifier    string `db:"identifier" `
	URL           string `db:"url" `
	RequestMethod string `db:"request_method" `
	Accessed      uint32 `db:"accessed" `
}

// TastypieApiaccessSlice is an alias for a slice of pointers to TastypieApiaccess.
// This should almost always be used instead of []*TastypieApiaccess.
type TastypieApiaccessSlice []*TastypieApiaccess

// TastypieApiaccesses contains methods to work with the tastypie_apiaccess table
var TastypieApiaccesses = mysql.NewTablex[*TastypieApiaccess, TastypieApiaccessSlice, *TastypieApiaccessSetter]("tastypie_apiaccess", buildTastypieApiaccessColumns("tastypie_apiaccess"), []string{"id"})

// TastypieApiaccessesQuery is a query on the tastypie_apiaccess table
type TastypieApiaccessesQuery = *mysql.ViewQuery[*TastypieApiaccess, TastypieApiaccessSlice]

func buildTastypieApiaccessColumns(alias string) tastypieApiaccessColumns {
	return tastypieApiaccessColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "identifier", "url", "request_method", "accessed",
		).WithParent("tastypie_apiaccess"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		Identifier:    mysql.Quote(alias, "identifier"),
		URL:           mysql.Quote(alias, "url"),
		RequestMethod: mysql.Quote(alias, "request_method"),
		Accessed:      mysql.Quote(alias, "accessed"),
	}
}

type tastypieApiaccessColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	Identifier    mysql.Expression
	URL           mysql.Expression
	RequestMethod mysql.Expression
	Accessed      mysql.Expression
}

func (c tastypieApiaccessColumns) Alias() string {
	return c.tableAlias
}

func (tastypieApiaccessColumns) AliasedAs(alias string) tastypieApiaccessColumns {
	return buildTastypieApiaccessColumns(alias)
}

// TastypieApiaccessSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type TastypieApiaccessSetter struct {
	ID            omit.Val[int32]  `db:"id,pk,autoincr" `
	Identifier    omit.Val[string] `db:"identifier" `
	URL           omit.Val[string] `db:"url" `
	RequestMethod omit.Val[string] `db:"request_method" `
	Accessed      omit.Val[uint32] `db:"accessed" `
}

func (s TastypieApiaccessSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Identifier.IsValue() {
		vals = append(vals, "identifier")
	}
	if s.URL.IsValue() {
		vals = append(vals, "url")
	}
	if s.RequestMethod.IsValue() {
		vals = append(vals, "request_method")
	}
	if s.Accessed.IsValue() {
		vals = append(vals, "accessed")
	}
	return vals
}

func (s TastypieApiaccessSetter) Overwrite(t *TastypieApiaccess) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Identifier.IsValue() {
		t.Identifier = s.Identifier.MustGet()
	}
	if s.URL.IsValue() {
		t.URL = s.URL.MustGet()
	}
	if s.RequestMethod.IsValue() {
		t.RequestMethod = s.RequestMethod.MustGet()
	}
	if s.Accessed.IsValue() {
		t.Accessed = s.Accessed.MustGet()
	}
}

func (s *TastypieApiaccessSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return TastypieApiaccesses.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(
		bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Identifier.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Identifier.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.URL.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.URL.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.RequestMethod.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.RequestMethod.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Accessed.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Accessed.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

func (s TastypieApiaccessSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions("tastypie_apiaccess")...)
}

func (s TastypieApiaccessSetter) Expressions(prefix ...string) []bob.Expression {
	exprs := make([]bob.Expression, 0, 5)

	if s.ID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "id")...),
			mysql.Arg(s.ID),
		}})
	}

	if s.Identifier.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "identifier")...),
			mysql.Arg(s.Identifier),
		}})
	}

	if s.URL.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "url")...),
			mysql.Arg(s.URL),
		}})
	}

	if s.RequestMethod.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "request_method")...),
			mysql.Arg(s.RequestMethod),
		}})
	}

	if s.Accessed.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "accessed")...),
			mysql.Arg(s.Accessed),
		}})
	}

	return exprs
}

// FindTastypieApiaccess retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindTastypieApiaccess(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*TastypieApiaccess, error) {
	if len(cols) == 0 {
		return TastypieApiaccesses.Query(
			sm.Where(TastypieApiaccesses.Columns.ID.EQ(mysql.Arg(IDPK))),
		).One(ctx, exec)
	}

	return TastypieApiaccesses.Query(
		sm.Where(TastypieApiaccesses.Columns.ID.EQ(mysql.Arg(IDPK))),
		sm.Columns(TastypieApiaccesses.Columns.Only(cols...)),
	).One(ctx, exec)
}

// TastypieApiaccessExists checks the presence of a single record by primary key
func TastypieApiaccessExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) {
	return TastypieApiaccesses.Query(
		sm.Where(TastypieApiaccesses.Columns.ID.EQ(mysql.Arg(IDPK))),
	).Exists(ctx, exec)
}

// AfterQueryHook is called after TastypieApiaccess is retrieved from the database
func (o *TastypieApiaccess) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = TastypieApiaccesses.AfterSelectHooks.RunHooks(ctx, exec, TastypieApiaccessSlice{o})
	case bob.QueryTypeInsert:
		ctx, err = TastypieApiaccesses.AfterInsertHooks.RunHooks(ctx, exec, TastypieApiaccessSlice{o})
	case bob.QueryTypeUpdate:
		ctx, err = TastypieApiaccesses.AfterUpdateHooks.RunHooks(ctx, exec, TastypieApiaccessSlice{o})
	case bob.QueryTypeDelete:
		ctx, err = TastypieApiaccesses.AfterDeleteHooks.RunHooks(ctx, exec, TastypieApiaccessSlice{o})
	}

	return err
}

// primaryKeyVals returns the primary key values of the TastypieApiaccess
func (o *TastypieApiaccess) primaryKeyVals() bob.Expression {
	return mysql.Arg(o.ID)
}

func (o *TastypieApiaccess) pkEQ() dialect.Expression {
	return mysql.Quote("tastypie_apiaccess", "id").EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
	}))
}

// Update uses an executor to update the TastypieApiaccess
func (o *TastypieApiaccess) Update(ctx context.Context, exec bob.Executor, s *TastypieApiaccessSetter) error {
	_, err := TastypieApiaccesses.Update(s.UpdateMod(), um.Where(o.pkEQ())).Exec(ctx, exec)
	if err != nil {
		return err
	}

	s.Overwrite(o)

	return nil
}

// Delete deletes a single TastypieApiaccess record with an executor
func (o *TastypieApiaccess) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := TastypieApiaccesses.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

// Reload refreshes the TastypieApiaccess using the executor
func (o *TastypieApiaccess) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := TastypieApiaccesses.Query(
		sm.Where(TastypieApiaccesses.Columns.ID.EQ(mysql.Arg(o.ID))),
	).One(ctx, exec)
	if err != nil {
		return err
	}

	*o = *o2

	return nil
}

// AfterQueryHook is called after TastypieApiaccessSlice is retrieved from the database
func (o TastypieApiaccessSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = TastypieApiaccesses.AfterSelectHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeInsert:
		ctx, err = TastypieApiaccesses.AfterInsertHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeUpdate:
		ctx, err = TastypieApiaccesses.AfterUpdateHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeDelete:
		ctx, err = TastypieApiaccesses.AfterDeleteHooks.RunHooks(ctx, exec, o)
	}

	return err
}

func (o TastypieApiaccessSlice) pkIN() dialect.Expression {
	if len(o) == 0 {
		return mysql.Raw("NULL")
	}

	return mysql.Quote("tastypie_apiaccess", "id").In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		pkPairs := make([]bob.Expression, len(o))
		for i, row := range o {
			pkPairs[i] = row.primaryKeyVals()
		}
		return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
	}))
}

// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o TastypieApiaccessSlice) copyMatchingRows(from ...*TastypieApiaccess) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}

			o[i] = new
			break
		}
	}
}

// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o TastypieApiaccessSlice) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return bob.ModFunc[*dialect.UpdateQuery](func(q *dialect.UpdateQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return TastypieApiaccesses.BeforeUpdateHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *TastypieApiaccess:
				o.copyMatchingRows(retrieved)
			case []*TastypieApiaccess:
				o.copyMatchingRows(retrieved...)
			case TastypieApiaccessSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a TastypieApiaccess or a slice of TastypieApiaccess
				// then run the AfterUpdateHooks on the slice
				_, err = TastypieApiaccesses.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o TastypieApiaccessSlice) DeleteMod() bob.Mod[*dialect.DeleteQuery] {
	return bob.ModFunc[*dialect.DeleteQuery](func(q *dialect.DeleteQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return TastypieApiaccesses.BeforeDeleteHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *TastypieApiaccess:
				o.copyMatchingRows(retrieved)
			case []*TastypieApiaccess:
				o.copyMatchingRows(retrieved...)
			case TastypieApiaccessSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a TastypieApiaccess or a slice of TastypieApiaccess
				// then run the AfterDeleteHooks on the slice
				_, err = TastypieApiaccesses.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

func (o TastypieApiaccessSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals TastypieApiaccessSetter) error {
	_, err := TastypieApiaccesses.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

	for i := range o {
		vals.Overwrite(o[i])
	}

	return err
}

func (o TastypieApiaccessSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	_, err := TastypieApiaccesses.Delete(o.DeleteMod()).Exec(ctx, exec)
	return err
}

func (o TastypieApiaccessSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	o2, err := TastypieApiaccesses.Query(sm.Where(o.pkIN())).All(ctx, exec)
	if err != nil {
		return err
	}

	o.copyMatchingRows(o2...)

	return nil
}

type tastypieApiaccessWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	Identifier    mysql.WhereMod[Q, string]
	URL           mysql.WhereMod[Q, string]
	RequestMethod mysql.WhereMod[Q, string]
	Accessed      mysql.WhereMod[Q, uint32]
}

func (tastypieApiaccessWhere[Q]) AliasedAs(alias string) tastypieApiaccessWhere[Q] {
	return buildTastypieApiaccessWhere[Q](buildTastypieApiaccessColumns(alias))
}

func buildTastypieApiaccessWhere[Q mysql.Filterable](cols tastypieApiaccessColumns) tastypieApiaccessWhere[Q] {
	return tastypieApiaccessWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		Identifier:    mysql.Where[Q, string](cols.Identifier),
		URL:           mysql.Where[Q, string](cols.URL),
		RequestMethod: mysql.Where[Q, string](cols.RequestMethod),
		Accessed:      mysql.Where[Q, uint32](cols.Accessed),
	}
}
