// 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"
	"fmt"
	"io"
	"time"

	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	"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"
	"github.com/stephenafamo/bob/mods"
	"github.com/stephenafamo/bob/orm"
)

// DjangoAdminLog is an object representing the database table.
type DjangoAdminLog struct {
	ID            int32            `db:"id,pk,autoincr" `
	ActionTime    time.Time        `db:"action_time" `
	ObjectID      null.Val[string] `db:"object_id" `
	ObjectRepr    string           `db:"object_repr" `
	ActionFlag    uint16           `db:"action_flag" `
	ChangeMessage string           `db:"change_message" `
	ContentTypeID null.Val[int32]  `db:"content_type_id" `
	UserID        int32            `db:"user_id" `

	R djangoAdminLogR `db:"-" `
}

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

// DjangoAdminLogs contains methods to work with the django_admin_log table
var DjangoAdminLogs = mysql.NewTablex[*DjangoAdminLog, DjangoAdminLogSlice, *DjangoAdminLogSetter]("django_admin_log", buildDjangoAdminLogColumns("django_admin_log"), []string{"id"})

// DjangoAdminLogsQuery is a query on the django_admin_log table
type DjangoAdminLogsQuery = *mysql.ViewQuery[*DjangoAdminLog, DjangoAdminLogSlice]

// djangoAdminLogR is where relationships are stored.
type djangoAdminLogR struct {
	ContentTypeDjangoContentType *DjangoContentType // django_admin_log_content_type_id_c4bce8eb_fk_django_co
	UserAuthUser                 *AuthUser          // django_admin_log_user_id_c564eba6_fk_auth_user_id
}

func buildDjangoAdminLogColumns(alias string) djangoAdminLogColumns {
	return djangoAdminLogColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "action_time", "object_id", "object_repr", "action_flag", "change_message", "content_type_id", "user_id",
		).WithParent("django_admin_log"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		ActionTime:    mysql.Quote(alias, "action_time"),
		ObjectID:      mysql.Quote(alias, "object_id"),
		ObjectRepr:    mysql.Quote(alias, "object_repr"),
		ActionFlag:    mysql.Quote(alias, "action_flag"),
		ChangeMessage: mysql.Quote(alias, "change_message"),
		ContentTypeID: mysql.Quote(alias, "content_type_id"),
		UserID:        mysql.Quote(alias, "user_id"),
	}
}

type djangoAdminLogColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	ActionTime    mysql.Expression
	ObjectID      mysql.Expression
	ObjectRepr    mysql.Expression
	ActionFlag    mysql.Expression
	ChangeMessage mysql.Expression
	ContentTypeID mysql.Expression
	UserID        mysql.Expression
}

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

func (djangoAdminLogColumns) AliasedAs(alias string) djangoAdminLogColumns {
	return buildDjangoAdminLogColumns(alias)
}

// DjangoAdminLogSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type DjangoAdminLogSetter struct {
	ID            omit.Val[int32]      `db:"id,pk,autoincr" `
	ActionTime    omit.Val[time.Time]  `db:"action_time" `
	ObjectID      omitnull.Val[string] `db:"object_id" `
	ObjectRepr    omit.Val[string]     `db:"object_repr" `
	ActionFlag    omit.Val[uint16]     `db:"action_flag" `
	ChangeMessage omit.Val[string]     `db:"change_message" `
	ContentTypeID omitnull.Val[int32]  `db:"content_type_id" `
	UserID        omit.Val[int32]      `db:"user_id" `
}

func (s DjangoAdminLogSetter) SetColumns() []string {
	vals := make([]string, 0, 8)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.ActionTime.IsValue() {
		vals = append(vals, "action_time")
	}
	if !s.ObjectID.IsUnset() {
		vals = append(vals, "object_id")
	}
	if s.ObjectRepr.IsValue() {
		vals = append(vals, "object_repr")
	}
	if s.ActionFlag.IsValue() {
		vals = append(vals, "action_flag")
	}
	if s.ChangeMessage.IsValue() {
		vals = append(vals, "change_message")
	}
	if !s.ContentTypeID.IsUnset() {
		vals = append(vals, "content_type_id")
	}
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	return vals
}

func (s DjangoAdminLogSetter) Overwrite(t *DjangoAdminLog) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.ActionTime.IsValue() {
		t.ActionTime = s.ActionTime.MustGet()
	}
	if !s.ObjectID.IsUnset() {
		t.ObjectID = s.ObjectID.MustGetNull()
	}
	if s.ObjectRepr.IsValue() {
		t.ObjectRepr = s.ObjectRepr.MustGet()
	}
	if s.ActionFlag.IsValue() {
		t.ActionFlag = s.ActionFlag.MustGet()
	}
	if s.ChangeMessage.IsValue() {
		t.ChangeMessage = s.ChangeMessage.MustGet()
	}
	if !s.ContentTypeID.IsUnset() {
		t.ContentTypeID = s.ContentTypeID.MustGetNull()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
}

func (s *DjangoAdminLogSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return DjangoAdminLogs.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.ActionTime.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ActionTime.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.ObjectID.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ObjectID.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ObjectRepr.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ObjectRepr.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ActionFlag.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ActionFlag.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ChangeMessage.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ChangeMessage.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.ContentTypeID.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ContentTypeID.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.UserID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UserID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

	if !s.ObjectID.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "object_id")...),
			mysql.Arg(s.ObjectID),
		}})
	}

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

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

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

	if !s.ContentTypeID.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "content_type_id")...),
			mysql.Arg(s.ContentTypeID),
		}})
	}

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *DjangoAdminLog) pkEQ() dialect.Expression {
	return mysql.Quote("django_admin_log", "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 DjangoAdminLog
func (o *DjangoAdminLog) Update(ctx context.Context, exec bob.Executor, s *DjangoAdminLogSetter) error {
	_, err := DjangoAdminLogs.Update(s.UpdateMod(), um.Where(o.pkEQ())).Exec(ctx, exec)
	if err != nil {
		return err
	}

	s.Overwrite(o)

	return nil
}

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

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

	return nil
}

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

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

	return err
}

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

	return mysql.Quote("django_admin_log", "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 DjangoAdminLogSlice) copyMatchingRows(from ...*DjangoAdminLog) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o DjangoAdminLogSlice) 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 DjangoAdminLogs.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 *DjangoAdminLog:
				o.copyMatchingRows(retrieved)
			case []*DjangoAdminLog:
				o.copyMatchingRows(retrieved...)
			case DjangoAdminLogSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a DjangoAdminLog or a slice of DjangoAdminLog
				// then run the AfterUpdateHooks on the slice
				_, err = DjangoAdminLogs.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o DjangoAdminLogSlice) 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 DjangoAdminLogs.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 *DjangoAdminLog:
				o.copyMatchingRows(retrieved)
			case []*DjangoAdminLog:
				o.copyMatchingRows(retrieved...)
			case DjangoAdminLogSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a DjangoAdminLog or a slice of DjangoAdminLog
				// then run the AfterDeleteHooks on the slice
				_, err = DjangoAdminLogs.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

func (o DjangoAdminLogSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals DjangoAdminLogSetter) error {
	_, err := DjangoAdminLogs.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// ContentTypeDjangoContentType starts a query for related objects on django_content_type
func (o *DjangoAdminLog) ContentTypeDjangoContentType(mods ...bob.Mod[*dialect.SelectQuery]) DjangoContentTypesQuery {
	return DjangoContentTypes.Query(append(mods,
		sm.Where(DjangoContentTypes.Columns.ID.EQ(mysql.Arg(o.ContentTypeID))),
	)...)
}

func (os DjangoAdminLogSlice) ContentTypeDjangoContentType(mods ...bob.Mod[*dialect.SelectQuery]) DjangoContentTypesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ContentTypeID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

	return DjangoContentTypes.Query(append(mods,
		sm.Where(mysql.Group(DjangoContentTypes.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

// UserAuthUser starts a query for related objects on auth_user
func (o *DjangoAdminLog) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	return AuthUsers.Query(append(mods,
		sm.Where(AuthUsers.Columns.ID.EQ(mysql.Arg(o.UserID))),
	)...)
}

func (os DjangoAdminLogSlice) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.UserID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

	return AuthUsers.Query(append(mods,
		sm.Where(mysql.Group(AuthUsers.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

func attachDjangoAdminLogContentTypeDjangoContentType0(ctx context.Context, exec bob.Executor, count int, djangoAdminLog0 *DjangoAdminLog, djangoContentType1 *DjangoContentType) (*DjangoAdminLog, error) {
	setter := &DjangoAdminLogSetter{
		ContentTypeID: omitnull.From(djangoContentType1.ID),
	}

	err := djangoAdminLog0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachDjangoAdminLogContentTypeDjangoContentType0: %w", err)
	}

	return djangoAdminLog0, nil
}

func (djangoAdminLog0 *DjangoAdminLog) InsertContentTypeDjangoContentType(ctx context.Context, exec bob.Executor, related *DjangoContentTypeSetter) error {
	var err error

	djangoContentType1, err := DjangoContentTypes.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachDjangoAdminLogContentTypeDjangoContentType0(ctx, exec, 1, djangoAdminLog0, djangoContentType1)
	if err != nil {
		return err
	}

	djangoAdminLog0.R.ContentTypeDjangoContentType = djangoContentType1

	djangoContentType1.R.ContentTypeDjangoAdminLogs = append(djangoContentType1.R.ContentTypeDjangoAdminLogs, djangoAdminLog0)

	return nil
}

func (djangoAdminLog0 *DjangoAdminLog) AttachContentTypeDjangoContentType(ctx context.Context, exec bob.Executor, djangoContentType1 *DjangoContentType) error {
	var err error

	_, err = attachDjangoAdminLogContentTypeDjangoContentType0(ctx, exec, 1, djangoAdminLog0, djangoContentType1)
	if err != nil {
		return err
	}

	djangoAdminLog0.R.ContentTypeDjangoContentType = djangoContentType1

	djangoContentType1.R.ContentTypeDjangoAdminLogs = append(djangoContentType1.R.ContentTypeDjangoAdminLogs, djangoAdminLog0)

	return nil
}

func attachDjangoAdminLogUserAuthUser0(ctx context.Context, exec bob.Executor, count int, djangoAdminLog0 *DjangoAdminLog, authUser1 *AuthUser) (*DjangoAdminLog, error) {
	setter := &DjangoAdminLogSetter{
		UserID: omit.From(authUser1.ID),
	}

	err := djangoAdminLog0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachDjangoAdminLogUserAuthUser0: %w", err)
	}

	return djangoAdminLog0, nil
}

func (djangoAdminLog0 *DjangoAdminLog) InsertUserAuthUser(ctx context.Context, exec bob.Executor, related *AuthUserSetter) error {
	var err error

	authUser1, err := AuthUsers.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachDjangoAdminLogUserAuthUser0(ctx, exec, 1, djangoAdminLog0, authUser1)
	if err != nil {
		return err
	}

	djangoAdminLog0.R.UserAuthUser = authUser1

	authUser1.R.UserDjangoAdminLogs = append(authUser1.R.UserDjangoAdminLogs, djangoAdminLog0)

	return nil
}

func (djangoAdminLog0 *DjangoAdminLog) AttachUserAuthUser(ctx context.Context, exec bob.Executor, authUser1 *AuthUser) error {
	var err error

	_, err = attachDjangoAdminLogUserAuthUser0(ctx, exec, 1, djangoAdminLog0, authUser1)
	if err != nil {
		return err
	}

	djangoAdminLog0.R.UserAuthUser = authUser1

	authUser1.R.UserDjangoAdminLogs = append(authUser1.R.UserDjangoAdminLogs, djangoAdminLog0)

	return nil
}

type djangoAdminLogWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	ActionTime    mysql.WhereMod[Q, time.Time]
	ObjectID      mysql.WhereNullMod[Q, string]
	ObjectRepr    mysql.WhereMod[Q, string]
	ActionFlag    mysql.WhereMod[Q, uint16]
	ChangeMessage mysql.WhereMod[Q, string]
	ContentTypeID mysql.WhereNullMod[Q, int32]
	UserID        mysql.WhereMod[Q, int32]
}

func (djangoAdminLogWhere[Q]) AliasedAs(alias string) djangoAdminLogWhere[Q] {
	return buildDjangoAdminLogWhere[Q](buildDjangoAdminLogColumns(alias))
}

func buildDjangoAdminLogWhere[Q mysql.Filterable](cols djangoAdminLogColumns) djangoAdminLogWhere[Q] {
	return djangoAdminLogWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		ActionTime:    mysql.Where[Q, time.Time](cols.ActionTime),
		ObjectID:      mysql.WhereNull[Q, string](cols.ObjectID),
		ObjectRepr:    mysql.Where[Q, string](cols.ObjectRepr),
		ActionFlag:    mysql.Where[Q, uint16](cols.ActionFlag),
		ChangeMessage: mysql.Where[Q, string](cols.ChangeMessage),
		ContentTypeID: mysql.WhereNull[Q, int32](cols.ContentTypeID),
		UserID:        mysql.Where[Q, int32](cols.UserID),
	}
}

func (o *DjangoAdminLog) Preload(name string, retrieved any) error {
	if o == nil {
		return nil
	}

	switch name {
	case "ContentTypeDjangoContentType":
		rel, ok := retrieved.(*DjangoContentType)
		if !ok {
			return fmt.Errorf("djangoAdminLog cannot load %T as %q", retrieved, name)
		}

		o.R.ContentTypeDjangoContentType = rel

		if rel != nil {
			rel.R.ContentTypeDjangoAdminLogs = DjangoAdminLogSlice{o}
		}
		return nil
	case "UserAuthUser":
		rel, ok := retrieved.(*AuthUser)
		if !ok {
			return fmt.Errorf("djangoAdminLog cannot load %T as %q", retrieved, name)
		}

		o.R.UserAuthUser = rel

		if rel != nil {
			rel.R.UserDjangoAdminLogs = DjangoAdminLogSlice{o}
		}
		return nil
	default:
		return fmt.Errorf("djangoAdminLog has no relationship %q", name)
	}
}

type djangoAdminLogPreloader struct {
	ContentTypeDjangoContentType func(...mysql.PreloadOption) mysql.Preloader
	UserAuthUser                 func(...mysql.PreloadOption) mysql.Preloader
}

func buildDjangoAdminLogPreloader() djangoAdminLogPreloader {
	return djangoAdminLogPreloader{
		ContentTypeDjangoContentType: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*DjangoContentType, DjangoContentTypeSlice](mysql.PreloadRel{
				Name: "ContentTypeDjangoContentType",
				Sides: []mysql.PreloadSide{
					{
						From:        DjangoAdminLogs,
						To:          DjangoContentTypes,
						FromColumns: []string{"content_type_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, DjangoContentTypes.Columns.Names(), opts...)
		},
		UserAuthUser: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthUser, AuthUserSlice](mysql.PreloadRel{
				Name: "UserAuthUser",
				Sides: []mysql.PreloadSide{
					{
						From:        DjangoAdminLogs,
						To:          AuthUsers,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthUsers.Columns.Names(), opts...)
		},
	}
}

type djangoAdminLogThenLoader[Q orm.Loadable] struct {
	ContentTypeDjangoContentType func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserAuthUser                 func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildDjangoAdminLogThenLoader[Q orm.Loadable]() djangoAdminLogThenLoader[Q] {
	type ContentTypeDjangoContentTypeLoadInterface interface {
		LoadContentTypeDjangoContentType(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserAuthUserLoadInterface interface {
		LoadUserAuthUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return djangoAdminLogThenLoader[Q]{
		ContentTypeDjangoContentType: thenLoadBuilder[Q](
			"ContentTypeDjangoContentType",
			func(ctx context.Context, exec bob.Executor, retrieved ContentTypeDjangoContentTypeLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadContentTypeDjangoContentType(ctx, exec, mods...)
			},
		),
		UserAuthUser: thenLoadBuilder[Q](
			"UserAuthUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserAuthUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserAuthUser(ctx, exec, mods...)
			},
		),
	}
}

// LoadContentTypeDjangoContentType loads the djangoAdminLog's ContentTypeDjangoContentType into the .R struct
func (o *DjangoAdminLog) LoadContentTypeDjangoContentType(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.ContentTypeDjangoContentType = nil

	related, err := o.ContentTypeDjangoContentType(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ContentTypeDjangoAdminLogs = DjangoAdminLogSlice{o}

	o.R.ContentTypeDjangoContentType = related
	return nil
}

// LoadContentTypeDjangoContentType loads the djangoAdminLog's ContentTypeDjangoContentType into the .R struct
func (os DjangoAdminLogSlice) LoadContentTypeDjangoContentType(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	djangoContentTypes, err := os.ContentTypeDjangoContentType(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range djangoContentTypes {
			if !o.ContentTypeID.IsValue() {
				continue
			}

			if !(o.ContentTypeID.IsValue() && o.ContentTypeID.MustGet() == rel.ID) {
				continue
			}

			rel.R.ContentTypeDjangoAdminLogs = append(rel.R.ContentTypeDjangoAdminLogs, o)

			o.R.ContentTypeDjangoContentType = rel
			break
		}
	}

	return nil
}

// LoadUserAuthUser loads the djangoAdminLog's UserAuthUser into the .R struct
func (o *DjangoAdminLog) LoadUserAuthUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.UserAuthUser = nil

	related, err := o.UserAuthUser(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.UserDjangoAdminLogs = DjangoAdminLogSlice{o}

	o.R.UserAuthUser = related
	return nil
}

// LoadUserAuthUser loads the djangoAdminLog's UserAuthUser into the .R struct
func (os DjangoAdminLogSlice) LoadUserAuthUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	authUsers, err := os.UserAuthUser(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range authUsers {

			if !(o.UserID == rel.ID) {
				continue
			}

			rel.R.UserDjangoAdminLogs = append(rel.R.UserDjangoAdminLogs, o)

			o.R.UserAuthUser = rel
			break
		}
	}

	return nil
}

type djangoAdminLogJoins[Q dialect.Joinable] struct {
	typ                          string
	ContentTypeDjangoContentType modAs[Q, djangoContentTypeColumns]
	UserAuthUser                 modAs[Q, authUserColumns]
}

func (j djangoAdminLogJoins[Q]) aliasedAs(alias string) djangoAdminLogJoins[Q] {
	return buildDjangoAdminLogJoins[Q](buildDjangoAdminLogColumns(alias), j.typ)
}

func buildDjangoAdminLogJoins[Q dialect.Joinable](cols djangoAdminLogColumns, typ string) djangoAdminLogJoins[Q] {
	return djangoAdminLogJoins[Q]{
		typ: typ,
		ContentTypeDjangoContentType: modAs[Q, djangoContentTypeColumns]{
			c: DjangoContentTypes.Columns,
			f: func(to djangoContentTypeColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, DjangoContentTypes.Name().As(to.Alias())).On(
						to.ID.EQ(cols.ContentTypeID),
					))
				}

				return mods
			},
		},
		UserAuthUser: modAs[Q, authUserColumns]{
			c: AuthUsers.Columns,
			f: func(to authUserColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, AuthUsers.Name().As(to.Alias())).On(
						to.ID.EQ(cols.UserID),
					))
				}

				return mods
			},
		},
	}
}
