// 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"
)

// AuthUser is an object representing the database table.
type AuthUser struct {
	ID          int32               `db:"id,pk,autoincr" `
	Password    string              `db:"password" `
	LastLogin   null.Val[time.Time] `db:"last_login" `
	IsSuperuser bool                `db:"is_superuser" `
	Username    string              `db:"username" `
	FirstName   string              `db:"first_name" `
	LastName    string              `db:"last_name" `
	Email       string              `db:"email" `
	IsStaff     bool                `db:"is_staff" `
	IsActive    bool                `db:"is_active" `
	DateJoined  time.Time           `db:"date_joined" `

	R authUserR `db:"-" `
}

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

// AuthUsers contains methods to work with the auth_user table
var AuthUsers = mysql.NewTablex[*AuthUser, AuthUserSlice, *AuthUserSetter]("auth_user", buildAuthUserColumns("auth_user"), []string{"id"}, []string{"username"})

// AuthUsersQuery is a query on the auth_user table
type AuthUsersQuery = *mysql.ViewQuery[*AuthUser, AuthUserSlice]

// authUserR is where relationships are stored.
type authUserR struct {
	UserAuthUserGroups          AuthUserGroupSlice          // auth_user_groups_user_id_6a12ed8b_fk_auth_user_id
	UserAuthUserUserPermissions AuthUserUserPermissionSlice // auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id
	UserDjangoAdminLogs         DjangoAdminLogSlice         // django_admin_log_user_id_c564eba6_fk_auth_user_id
	AdminIDLocationsEvents      LocationsEventSlice         // locations_event_admin_id_id_4a50d36a_fk_auth_user_id
	UserTastypieApikey          *TastypieApikey             // tastypie_apikey_user_id_8c8fa920_fk_auth_user_id
}

func buildAuthUserColumns(alias string) authUserColumns {
	return authUserColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined",
		).WithParent("auth_user"),
		tableAlias:  alias,
		ID:          mysql.Quote(alias, "id"),
		Password:    mysql.Quote(alias, "password"),
		LastLogin:   mysql.Quote(alias, "last_login"),
		IsSuperuser: mysql.Quote(alias, "is_superuser"),
		Username:    mysql.Quote(alias, "username"),
		FirstName:   mysql.Quote(alias, "first_name"),
		LastName:    mysql.Quote(alias, "last_name"),
		Email:       mysql.Quote(alias, "email"),
		IsStaff:     mysql.Quote(alias, "is_staff"),
		IsActive:    mysql.Quote(alias, "is_active"),
		DateJoined:  mysql.Quote(alias, "date_joined"),
	}
}

type authUserColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	ID          mysql.Expression
	Password    mysql.Expression
	LastLogin   mysql.Expression
	IsSuperuser mysql.Expression
	Username    mysql.Expression
	FirstName   mysql.Expression
	LastName    mysql.Expression
	Email       mysql.Expression
	IsStaff     mysql.Expression
	IsActive    mysql.Expression
	DateJoined  mysql.Expression
}

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

func (authUserColumns) AliasedAs(alias string) authUserColumns {
	return buildAuthUserColumns(alias)
}

// AuthUserSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type AuthUserSetter struct {
	ID          omit.Val[int32]         `db:"id,pk,autoincr" `
	Password    omit.Val[string]        `db:"password" `
	LastLogin   omitnull.Val[time.Time] `db:"last_login" `
	IsSuperuser omit.Val[bool]          `db:"is_superuser" `
	Username    omit.Val[string]        `db:"username" `
	FirstName   omit.Val[string]        `db:"first_name" `
	LastName    omit.Val[string]        `db:"last_name" `
	Email       omit.Val[string]        `db:"email" `
	IsStaff     omit.Val[bool]          `db:"is_staff" `
	IsActive    omit.Val[bool]          `db:"is_active" `
	DateJoined  omit.Val[time.Time]     `db:"date_joined" `
}

func (s AuthUserSetter) SetColumns() []string {
	vals := make([]string, 0, 11)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Password.IsValue() {
		vals = append(vals, "password")
	}
	if !s.LastLogin.IsUnset() {
		vals = append(vals, "last_login")
	}
	if s.IsSuperuser.IsValue() {
		vals = append(vals, "is_superuser")
	}
	if s.Username.IsValue() {
		vals = append(vals, "username")
	}
	if s.FirstName.IsValue() {
		vals = append(vals, "first_name")
	}
	if s.LastName.IsValue() {
		vals = append(vals, "last_name")
	}
	if s.Email.IsValue() {
		vals = append(vals, "email")
	}
	if s.IsStaff.IsValue() {
		vals = append(vals, "is_staff")
	}
	if s.IsActive.IsValue() {
		vals = append(vals, "is_active")
	}
	if s.DateJoined.IsValue() {
		vals = append(vals, "date_joined")
	}
	return vals
}

func (s AuthUserSetter) Overwrite(t *AuthUser) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Password.IsValue() {
		t.Password = s.Password.MustGet()
	}
	if !s.LastLogin.IsUnset() {
		t.LastLogin = s.LastLogin.MustGetNull()
	}
	if s.IsSuperuser.IsValue() {
		t.IsSuperuser = s.IsSuperuser.MustGet()
	}
	if s.Username.IsValue() {
		t.Username = s.Username.MustGet()
	}
	if s.FirstName.IsValue() {
		t.FirstName = s.FirstName.MustGet()
	}
	if s.LastName.IsValue() {
		t.LastName = s.LastName.MustGet()
	}
	if s.Email.IsValue() {
		t.Email = s.Email.MustGet()
	}
	if s.IsStaff.IsValue() {
		t.IsStaff = s.IsStaff.MustGet()
	}
	if s.IsActive.IsValue() {
		t.IsActive = s.IsActive.MustGet()
	}
	if s.DateJoined.IsValue() {
		t.DateJoined = s.DateJoined.MustGet()
	}
}

func (s *AuthUserSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AuthUsers.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.Password.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Password.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.LastLogin.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.LastLogin.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.IsSuperuser.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.IsSuperuser.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Username.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Username.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.FirstName.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.FirstName.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.LastName.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.LastName.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Email.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Email.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.IsStaff.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.IsStaff.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.IsActive.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.IsActive.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.DateJoined.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.DateJoined.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

// Reload refreshes the AuthUser using the executor
func (o *AuthUser) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := AuthUsers.Query(
		sm.Where(AuthUsers.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 AuthUserSlice is retrieved from the database
func (o AuthUserSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

	return mysql.Quote("auth_user", "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 AuthUserSlice) copyMatchingRows(from ...*AuthUser) {
	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 AuthUserSlice) 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 AuthUsers.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 *AuthUser:
				o.copyMatchingRows(retrieved)
			case []*AuthUser:
				o.copyMatchingRows(retrieved...)
			case AuthUserSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a AuthUser or a slice of AuthUser
				// then run the AfterUpdateHooks on the slice
				_, err = AuthUsers.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

			return err
		}))

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

func (o AuthUserSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AuthUserSetter) error {
	_, err := AuthUsers.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// UserAuthUserGroups starts a query for related objects on auth_user_groups
func (o *AuthUser) UserAuthUserGroups(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserGroupsQuery {
	return AuthUserGroups.Query(append(mods,
		sm.Where(AuthUserGroups.Columns.UserID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthUserSlice) UserAuthUserGroups(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserGroupsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// UserAuthUserUserPermissions starts a query for related objects on auth_user_user_permissions
func (o *AuthUser) UserAuthUserUserPermissions(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserUserPermissionsQuery {
	return AuthUserUserPermissions.Query(append(mods,
		sm.Where(AuthUserUserPermissions.Columns.UserID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthUserSlice) UserAuthUserUserPermissions(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserUserPermissionsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// UserDjangoAdminLogs starts a query for related objects on django_admin_log
func (o *AuthUser) UserDjangoAdminLogs(mods ...bob.Mod[*dialect.SelectQuery]) DjangoAdminLogsQuery {
	return DjangoAdminLogs.Query(append(mods,
		sm.Where(DjangoAdminLogs.Columns.UserID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthUserSlice) UserDjangoAdminLogs(mods ...bob.Mod[*dialect.SelectQuery]) DjangoAdminLogsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// AdminIDLocationsEvents starts a query for related objects on locations_event
func (o *AuthUser) AdminIDLocationsEvents(mods ...bob.Mod[*dialect.SelectQuery]) LocationsEventsQuery {
	return LocationsEvents.Query(append(mods,
		sm.Where(LocationsEvents.Columns.AdminIDID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthUserSlice) AdminIDLocationsEvents(mods ...bob.Mod[*dialect.SelectQuery]) LocationsEventsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// UserTastypieApikey starts a query for related objects on tastypie_apikey
func (o *AuthUser) UserTastypieApikey(mods ...bob.Mod[*dialect.SelectQuery]) TastypieApikeysQuery {
	return TastypieApikeys.Query(append(mods,
		sm.Where(TastypieApikeys.Columns.UserID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthUserSlice) UserTastypieApikey(mods ...bob.Mod[*dialect.SelectQuery]) TastypieApikeysQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func insertAuthUserUserAuthUserGroups0(ctx context.Context, exec bob.Executor, authUserGroups1 []*AuthUserGroupSetter, authUser0 *AuthUser) (AuthUserGroupSlice, error) {
	for i := range authUserGroups1 {
		authUserGroups1[i].UserID = omit.From(authUser0.ID)
	}

	ret, err := AuthUserGroups.Insert(bob.ToMods(authUserGroups1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthUserUserAuthUserGroups0: %w", err)
	}

	return ret, nil
}

func attachAuthUserUserAuthUserGroups0(ctx context.Context, exec bob.Executor, count int, authUserGroups1 AuthUserGroupSlice, authUser0 *AuthUser) (AuthUserGroupSlice, error) {
	setter := &AuthUserGroupSetter{
		UserID: omit.From(authUser0.ID),
	}

	err := authUserGroups1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthUserUserAuthUserGroups0: %w", err)
	}

	return authUserGroups1, nil
}

func (authUser0 *AuthUser) InsertUserAuthUserGroups(ctx context.Context, exec bob.Executor, related ...*AuthUserGroupSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	authUserGroups1, err := insertAuthUserUserAuthUserGroups0(ctx, exec, related, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserAuthUserGroups = append(authUser0.R.UserAuthUserGroups, authUserGroups1...)

	for _, rel := range authUserGroups1 {
		rel.R.UserAuthUser = authUser0
	}
	return nil
}

func (authUser0 *AuthUser) AttachUserAuthUserGroups(ctx context.Context, exec bob.Executor, related ...*AuthUserGroup) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authUserGroups1 := AuthUserGroupSlice(related)

	_, err = attachAuthUserUserAuthUserGroups0(ctx, exec, len(related), authUserGroups1, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserAuthUserGroups = append(authUser0.R.UserAuthUserGroups, authUserGroups1...)

	for _, rel := range related {
		rel.R.UserAuthUser = authUser0
	}

	return nil
}

func insertAuthUserUserAuthUserUserPermissions0(ctx context.Context, exec bob.Executor, authUserUserPermissions1 []*AuthUserUserPermissionSetter, authUser0 *AuthUser) (AuthUserUserPermissionSlice, error) {
	for i := range authUserUserPermissions1 {
		authUserUserPermissions1[i].UserID = omit.From(authUser0.ID)
	}

	ret, err := AuthUserUserPermissions.Insert(bob.ToMods(authUserUserPermissions1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthUserUserAuthUserUserPermissions0: %w", err)
	}

	return ret, nil
}

func attachAuthUserUserAuthUserUserPermissions0(ctx context.Context, exec bob.Executor, count int, authUserUserPermissions1 AuthUserUserPermissionSlice, authUser0 *AuthUser) (AuthUserUserPermissionSlice, error) {
	setter := &AuthUserUserPermissionSetter{
		UserID: omit.From(authUser0.ID),
	}

	err := authUserUserPermissions1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthUserUserAuthUserUserPermissions0: %w", err)
	}

	return authUserUserPermissions1, nil
}

func (authUser0 *AuthUser) InsertUserAuthUserUserPermissions(ctx context.Context, exec bob.Executor, related ...*AuthUserUserPermissionSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	authUserUserPermissions1, err := insertAuthUserUserAuthUserUserPermissions0(ctx, exec, related, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserAuthUserUserPermissions = append(authUser0.R.UserAuthUserUserPermissions, authUserUserPermissions1...)

	for _, rel := range authUserUserPermissions1 {
		rel.R.UserAuthUser = authUser0
	}
	return nil
}

func (authUser0 *AuthUser) AttachUserAuthUserUserPermissions(ctx context.Context, exec bob.Executor, related ...*AuthUserUserPermission) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authUserUserPermissions1 := AuthUserUserPermissionSlice(related)

	_, err = attachAuthUserUserAuthUserUserPermissions0(ctx, exec, len(related), authUserUserPermissions1, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserAuthUserUserPermissions = append(authUser0.R.UserAuthUserUserPermissions, authUserUserPermissions1...)

	for _, rel := range related {
		rel.R.UserAuthUser = authUser0
	}

	return nil
}

func insertAuthUserUserDjangoAdminLogs0(ctx context.Context, exec bob.Executor, djangoAdminLogs1 []*DjangoAdminLogSetter, authUser0 *AuthUser) (DjangoAdminLogSlice, error) {
	for i := range djangoAdminLogs1 {
		djangoAdminLogs1[i].UserID = omit.From(authUser0.ID)
	}

	ret, err := DjangoAdminLogs.Insert(bob.ToMods(djangoAdminLogs1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthUserUserDjangoAdminLogs0: %w", err)
	}

	return ret, nil
}

func attachAuthUserUserDjangoAdminLogs0(ctx context.Context, exec bob.Executor, count int, djangoAdminLogs1 DjangoAdminLogSlice, authUser0 *AuthUser) (DjangoAdminLogSlice, error) {
	setter := &DjangoAdminLogSetter{
		UserID: omit.From(authUser0.ID),
	}

	err := djangoAdminLogs1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthUserUserDjangoAdminLogs0: %w", err)
	}

	return djangoAdminLogs1, nil
}

func (authUser0 *AuthUser) InsertUserDjangoAdminLogs(ctx context.Context, exec bob.Executor, related ...*DjangoAdminLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	djangoAdminLogs1, err := insertAuthUserUserDjangoAdminLogs0(ctx, exec, related, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserDjangoAdminLogs = append(authUser0.R.UserDjangoAdminLogs, djangoAdminLogs1...)

	for _, rel := range djangoAdminLogs1 {
		rel.R.UserAuthUser = authUser0
	}
	return nil
}

func (authUser0 *AuthUser) AttachUserDjangoAdminLogs(ctx context.Context, exec bob.Executor, related ...*DjangoAdminLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	djangoAdminLogs1 := DjangoAdminLogSlice(related)

	_, err = attachAuthUserUserDjangoAdminLogs0(ctx, exec, len(related), djangoAdminLogs1, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserDjangoAdminLogs = append(authUser0.R.UserDjangoAdminLogs, djangoAdminLogs1...)

	for _, rel := range related {
		rel.R.UserAuthUser = authUser0
	}

	return nil
}

func insertAuthUserAdminIDLocationsEvents0(ctx context.Context, exec bob.Executor, locationsEvents1 []*LocationsEventSetter, authUser0 *AuthUser) (LocationsEventSlice, error) {
	for i := range locationsEvents1 {
		locationsEvents1[i].AdminIDID = omitnull.From(authUser0.ID)
	}

	ret, err := LocationsEvents.Insert(bob.ToMods(locationsEvents1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthUserAdminIDLocationsEvents0: %w", err)
	}

	return ret, nil
}

func attachAuthUserAdminIDLocationsEvents0(ctx context.Context, exec bob.Executor, count int, locationsEvents1 LocationsEventSlice, authUser0 *AuthUser) (LocationsEventSlice, error) {
	setter := &LocationsEventSetter{
		AdminIDID: omitnull.From(authUser0.ID),
	}

	err := locationsEvents1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthUserAdminIDLocationsEvents0: %w", err)
	}

	return locationsEvents1, nil
}

func (authUser0 *AuthUser) InsertAdminIDLocationsEvents(ctx context.Context, exec bob.Executor, related ...*LocationsEventSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	locationsEvents1, err := insertAuthUserAdminIDLocationsEvents0(ctx, exec, related, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.AdminIDLocationsEvents = append(authUser0.R.AdminIDLocationsEvents, locationsEvents1...)

	for _, rel := range locationsEvents1 {
		rel.R.AdminIDAuthUser = authUser0
	}
	return nil
}

func (authUser0 *AuthUser) AttachAdminIDLocationsEvents(ctx context.Context, exec bob.Executor, related ...*LocationsEvent) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	locationsEvents1 := LocationsEventSlice(related)

	_, err = attachAuthUserAdminIDLocationsEvents0(ctx, exec, len(related), locationsEvents1, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.AdminIDLocationsEvents = append(authUser0.R.AdminIDLocationsEvents, locationsEvents1...)

	for _, rel := range related {
		rel.R.AdminIDAuthUser = authUser0
	}

	return nil
}

func insertAuthUserUserTastypieApikey0(ctx context.Context, exec bob.Executor, tastypieApikey1 *TastypieApikeySetter, authUser0 *AuthUser) (*TastypieApikey, error) {
	tastypieApikey1.UserID = omit.From(authUser0.ID)

	ret, err := TastypieApikeys.Insert(tastypieApikey1).One(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthUserUserTastypieApikey0: %w", err)
	}

	return ret, nil
}

func attachAuthUserUserTastypieApikey0(ctx context.Context, exec bob.Executor, count int, tastypieApikey1 *TastypieApikey, authUser0 *AuthUser) (*TastypieApikey, error) {
	setter := &TastypieApikeySetter{
		UserID: omit.From(authUser0.ID),
	}

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

	return tastypieApikey1, nil
}

func (authUser0 *AuthUser) InsertUserTastypieApikey(ctx context.Context, exec bob.Executor, related *TastypieApikeySetter) error {
	var err error

	tastypieApikey1, err := insertAuthUserUserTastypieApikey0(ctx, exec, related, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserTastypieApikey = tastypieApikey1

	tastypieApikey1.R.UserAuthUser = authUser0

	return nil
}

func (authUser0 *AuthUser) AttachUserTastypieApikey(ctx context.Context, exec bob.Executor, tastypieApikey1 *TastypieApikey) error {
	var err error

	_, err = attachAuthUserUserTastypieApikey0(ctx, exec, 1, tastypieApikey1, authUser0)
	if err != nil {
		return err
	}

	authUser0.R.UserTastypieApikey = tastypieApikey1

	tastypieApikey1.R.UserAuthUser = authUser0

	return nil
}

type authUserWhere[Q mysql.Filterable] struct {
	ID          mysql.WhereMod[Q, int32]
	Password    mysql.WhereMod[Q, string]
	LastLogin   mysql.WhereNullMod[Q, time.Time]
	IsSuperuser mysql.WhereMod[Q, bool]
	Username    mysql.WhereMod[Q, string]
	FirstName   mysql.WhereMod[Q, string]
	LastName    mysql.WhereMod[Q, string]
	Email       mysql.WhereMod[Q, string]
	IsStaff     mysql.WhereMod[Q, bool]
	IsActive    mysql.WhereMod[Q, bool]
	DateJoined  mysql.WhereMod[Q, time.Time]
}

func (authUserWhere[Q]) AliasedAs(alias string) authUserWhere[Q] {
	return buildAuthUserWhere[Q](buildAuthUserColumns(alias))
}

func buildAuthUserWhere[Q mysql.Filterable](cols authUserColumns) authUserWhere[Q] {
	return authUserWhere[Q]{
		ID:          mysql.Where[Q, int32](cols.ID),
		Password:    mysql.Where[Q, string](cols.Password),
		LastLogin:   mysql.WhereNull[Q, time.Time](cols.LastLogin),
		IsSuperuser: mysql.Where[Q, bool](cols.IsSuperuser),
		Username:    mysql.Where[Q, string](cols.Username),
		FirstName:   mysql.Where[Q, string](cols.FirstName),
		LastName:    mysql.Where[Q, string](cols.LastName),
		Email:       mysql.Where[Q, string](cols.Email),
		IsStaff:     mysql.Where[Q, bool](cols.IsStaff),
		IsActive:    mysql.Where[Q, bool](cols.IsActive),
		DateJoined:  mysql.Where[Q, time.Time](cols.DateJoined),
	}
}

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

	switch name {
	case "UserAuthUserGroups":
		rels, ok := retrieved.(AuthUserGroupSlice)
		if !ok {
			return fmt.Errorf("authUser cannot load %T as %q", retrieved, name)
		}

		o.R.UserAuthUserGroups = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.UserAuthUser = o
			}
		}
		return nil
	case "UserAuthUserUserPermissions":
		rels, ok := retrieved.(AuthUserUserPermissionSlice)
		if !ok {
			return fmt.Errorf("authUser cannot load %T as %q", retrieved, name)
		}

		o.R.UserAuthUserUserPermissions = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.UserAuthUser = o
			}
		}
		return nil
	case "UserDjangoAdminLogs":
		rels, ok := retrieved.(DjangoAdminLogSlice)
		if !ok {
			return fmt.Errorf("authUser cannot load %T as %q", retrieved, name)
		}

		o.R.UserDjangoAdminLogs = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.UserAuthUser = o
			}
		}
		return nil
	case "AdminIDLocationsEvents":
		rels, ok := retrieved.(LocationsEventSlice)
		if !ok {
			return fmt.Errorf("authUser cannot load %T as %q", retrieved, name)
		}

		o.R.AdminIDLocationsEvents = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.AdminIDAuthUser = o
			}
		}
		return nil
	case "UserTastypieApikey":
		rel, ok := retrieved.(*TastypieApikey)
		if !ok {
			return fmt.Errorf("authUser cannot load %T as %q", retrieved, name)
		}

		o.R.UserTastypieApikey = rel

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

type authUserPreloader struct {
	UserTastypieApikey func(...mysql.PreloadOption) mysql.Preloader
}

func buildAuthUserPreloader() authUserPreloader {
	return authUserPreloader{
		UserTastypieApikey: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*TastypieApikey, TastypieApikeySlice](mysql.PreloadRel{
				Name: "UserTastypieApikey",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthUsers,
						To:          TastypieApikeys,
						FromColumns: []string{"id"},
						ToColumns:   []string{"user_id"},
					},
				},
			}, TastypieApikeys.Columns.Names(), opts...)
		},
	}
}

type authUserThenLoader[Q orm.Loadable] struct {
	UserAuthUserGroups          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserAuthUserUserPermissions func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserDjangoAdminLogs         func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	AdminIDLocationsEvents      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserTastypieApikey          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildAuthUserThenLoader[Q orm.Loadable]() authUserThenLoader[Q] {
	type UserAuthUserGroupsLoadInterface interface {
		LoadUserAuthUserGroups(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserAuthUserUserPermissionsLoadInterface interface {
		LoadUserAuthUserUserPermissions(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserDjangoAdminLogsLoadInterface interface {
		LoadUserDjangoAdminLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type AdminIDLocationsEventsLoadInterface interface {
		LoadAdminIDLocationsEvents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserTastypieApikeyLoadInterface interface {
		LoadUserTastypieApikey(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return authUserThenLoader[Q]{
		UserAuthUserGroups: thenLoadBuilder[Q](
			"UserAuthUserGroups",
			func(ctx context.Context, exec bob.Executor, retrieved UserAuthUserGroupsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserAuthUserGroups(ctx, exec, mods...)
			},
		),
		UserAuthUserUserPermissions: thenLoadBuilder[Q](
			"UserAuthUserUserPermissions",
			func(ctx context.Context, exec bob.Executor, retrieved UserAuthUserUserPermissionsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserAuthUserUserPermissions(ctx, exec, mods...)
			},
		),
		UserDjangoAdminLogs: thenLoadBuilder[Q](
			"UserDjangoAdminLogs",
			func(ctx context.Context, exec bob.Executor, retrieved UserDjangoAdminLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserDjangoAdminLogs(ctx, exec, mods...)
			},
		),
		AdminIDLocationsEvents: thenLoadBuilder[Q](
			"AdminIDLocationsEvents",
			func(ctx context.Context, exec bob.Executor, retrieved AdminIDLocationsEventsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAdminIDLocationsEvents(ctx, exec, mods...)
			},
		),
		UserTastypieApikey: thenLoadBuilder[Q](
			"UserTastypieApikey",
			func(ctx context.Context, exec bob.Executor, retrieved UserTastypieApikeyLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserTastypieApikey(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	for _, rel := range related {
		rel.R.UserAuthUser = o
	}

	o.R.UserAuthUserGroups = related
	return nil
}

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

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

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

		o.R.UserAuthUserGroups = nil
	}

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

		for _, rel := range authUserGroups {

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

			rel.R.UserAuthUser = o

			o.R.UserAuthUserGroups = append(o.R.UserAuthUserGroups, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.UserAuthUser = o
	}

	o.R.UserAuthUserUserPermissions = related
	return nil
}

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

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

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

		o.R.UserAuthUserUserPermissions = nil
	}

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

		for _, rel := range authUserUserPermissions {

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

			rel.R.UserAuthUser = o

			o.R.UserAuthUserUserPermissions = append(o.R.UserAuthUserUserPermissions, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.UserAuthUser = o
	}

	o.R.UserDjangoAdminLogs = related
	return nil
}

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

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

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

		o.R.UserDjangoAdminLogs = nil
	}

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

		for _, rel := range djangoAdminLogs {

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

			rel.R.UserAuthUser = o

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

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.AdminIDAuthUser = o
	}

	o.R.AdminIDLocationsEvents = related
	return nil
}

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

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

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

		o.R.AdminIDLocationsEvents = nil
	}

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

		for _, rel := range locationsEvents {

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

			rel.R.AdminIDAuthUser = o

			o.R.AdminIDLocationsEvents = append(o.R.AdminIDLocationsEvents, rel)
		}
	}

	return nil
}

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

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

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

	related.R.UserAuthUser = o

	o.R.UserTastypieApikey = related
	return nil
}

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

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

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

		for _, rel := range tastypieApikeys {

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

			rel.R.UserAuthUser = o

			o.R.UserTastypieApikey = rel
			break
		}
	}

	return nil
}

type authUserJoins[Q dialect.Joinable] struct {
	typ                         string
	UserAuthUserGroups          modAs[Q, authUserGroupColumns]
	UserAuthUserUserPermissions modAs[Q, authUserUserPermissionColumns]
	UserDjangoAdminLogs         modAs[Q, djangoAdminLogColumns]
	AdminIDLocationsEvents      modAs[Q, locationsEventColumns]
	UserTastypieApikey          modAs[Q, tastypieApikeyColumns]
}

func (j authUserJoins[Q]) aliasedAs(alias string) authUserJoins[Q] {
	return buildAuthUserJoins[Q](buildAuthUserColumns(alias), j.typ)
}

func buildAuthUserJoins[Q dialect.Joinable](cols authUserColumns, typ string) authUserJoins[Q] {
	return authUserJoins[Q]{
		typ: typ,
		UserAuthUserGroups: modAs[Q, authUserGroupColumns]{
			c: AuthUserGroups.Columns,
			f: func(to authUserGroupColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

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

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

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

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

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

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

				return mods
			},
		},
	}
}
