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

	"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"
	"github.com/stephenafamo/bob/mods"
	"github.com/stephenafamo/bob/orm"
)

// AuthPermission is an object representing the database table.
type AuthPermission struct {
	ID            int32  `db:"id,pk,autoincr" `
	Name          string `db:"name" `
	ContentTypeID int32  `db:"content_type_id" `
	Codename      string `db:"codename" `

	R authPermissionR `db:"-" `
}

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

// AuthPermissions contains methods to work with the auth_permission table
var AuthPermissions = mysql.NewTablex[*AuthPermission, AuthPermissionSlice, *AuthPermissionSetter]("auth_permission", buildAuthPermissionColumns("auth_permission"), []string{"id"}, []string{"content_type_id", "codename"})

// AuthPermissionsQuery is a query on the auth_permission table
type AuthPermissionsQuery = *mysql.ViewQuery[*AuthPermission, AuthPermissionSlice]

// authPermissionR is where relationships are stored.
type authPermissionR struct {
	PermissionAuthGroupPermissions    AuthGroupPermissionSlice    // auth_group_permissio_permission_id_84c5c92e_fk_auth_perm
	ContentTypeDjangoContentType      *DjangoContentType          // auth_permission_content_type_id_2f476e4b_fk_django_co
	PermissionAuthUserUserPermissions AuthUserUserPermissionSlice // auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm
}

func buildAuthPermissionColumns(alias string) authPermissionColumns {
	return authPermissionColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "name", "content_type_id", "codename",
		).WithParent("auth_permission"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		Name:          mysql.Quote(alias, "name"),
		ContentTypeID: mysql.Quote(alias, "content_type_id"),
		Codename:      mysql.Quote(alias, "codename"),
	}
}

type authPermissionColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	Name          mysql.Expression
	ContentTypeID mysql.Expression
	Codename      mysql.Expression
}

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

func (authPermissionColumns) AliasedAs(alias string) authPermissionColumns {
	return buildAuthPermissionColumns(alias)
}

// AuthPermissionSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type AuthPermissionSetter struct {
	ID            omit.Val[int32]  `db:"id,pk,autoincr" `
	Name          omit.Val[string] `db:"name" `
	ContentTypeID omit.Val[int32]  `db:"content_type_id" `
	Codename      omit.Val[string] `db:"codename" `
}

func (s AuthPermissionSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if s.ContentTypeID.IsValue() {
		vals = append(vals, "content_type_id")
	}
	if s.Codename.IsValue() {
		vals = append(vals, "codename")
	}
	return vals
}

func (s AuthPermissionSetter) Overwrite(t *AuthPermission) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if s.ContentTypeID.IsValue() {
		t.ContentTypeID = s.ContentTypeID.MustGet()
	}
	if s.Codename.IsValue() {
		t.Codename = s.Codename.MustGet()
	}
}

func (s *AuthPermissionSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AuthPermissions.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.Name.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Name.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.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ContentTypeID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Codename.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Codename.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o AuthPermissionSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AuthPermissionSetter) error {
	_, err := AuthPermissions.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// PermissionAuthGroupPermissions starts a query for related objects on auth_group_permissions
func (o *AuthPermission) PermissionAuthGroupPermissions(mods ...bob.Mod[*dialect.SelectQuery]) AuthGroupPermissionsQuery {
	return AuthGroupPermissions.Query(append(mods,
		sm.Where(AuthGroupPermissions.Columns.PermissionID.EQ(mysql.Arg(o.ID))),
	)...)
}

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

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

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

func (os AuthPermissionSlice) 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)),
	)...)
}

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

func (os AuthPermissionSlice) PermissionAuthUserUserPermissions(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.PermissionID).OP("IN", PKArgExpr)),
	)...)
}

func insertAuthPermissionPermissionAuthGroupPermissions0(ctx context.Context, exec bob.Executor, authGroupPermissions1 []*AuthGroupPermissionSetter, authPermission0 *AuthPermission) (AuthGroupPermissionSlice, error) {
	for i := range authGroupPermissions1 {
		authGroupPermissions1[i].PermissionID = omit.From(authPermission0.ID)
	}

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

	return ret, nil
}

func attachAuthPermissionPermissionAuthGroupPermissions0(ctx context.Context, exec bob.Executor, count int, authGroupPermissions1 AuthGroupPermissionSlice, authPermission0 *AuthPermission) (AuthGroupPermissionSlice, error) {
	setter := &AuthGroupPermissionSetter{
		PermissionID: omit.From(authPermission0.ID),
	}

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

	return authGroupPermissions1, nil
}

func (authPermission0 *AuthPermission) InsertPermissionAuthGroupPermissions(ctx context.Context, exec bob.Executor, related ...*AuthGroupPermissionSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	authGroupPermissions1, err := insertAuthPermissionPermissionAuthGroupPermissions0(ctx, exec, related, authPermission0)
	if err != nil {
		return err
	}

	authPermission0.R.PermissionAuthGroupPermissions = append(authPermission0.R.PermissionAuthGroupPermissions, authGroupPermissions1...)

	for _, rel := range authGroupPermissions1 {
		rel.R.PermissionAuthPermission = authPermission0
	}
	return nil
}

func (authPermission0 *AuthPermission) AttachPermissionAuthGroupPermissions(ctx context.Context, exec bob.Executor, related ...*AuthGroupPermission) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authGroupPermissions1 := AuthGroupPermissionSlice(related)

	_, err = attachAuthPermissionPermissionAuthGroupPermissions0(ctx, exec, len(related), authGroupPermissions1, authPermission0)
	if err != nil {
		return err
	}

	authPermission0.R.PermissionAuthGroupPermissions = append(authPermission0.R.PermissionAuthGroupPermissions, authGroupPermissions1...)

	for _, rel := range related {
		rel.R.PermissionAuthPermission = authPermission0
	}

	return nil
}

func attachAuthPermissionContentTypeDjangoContentType0(ctx context.Context, exec bob.Executor, count int, authPermission0 *AuthPermission, djangoContentType1 *DjangoContentType) (*AuthPermission, error) {
	setter := &AuthPermissionSetter{
		ContentTypeID: omit.From(djangoContentType1.ID),
	}

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

	return authPermission0, nil
}

func (authPermission0 *AuthPermission) 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 = attachAuthPermissionContentTypeDjangoContentType0(ctx, exec, 1, authPermission0, djangoContentType1)
	if err != nil {
		return err
	}

	authPermission0.R.ContentTypeDjangoContentType = djangoContentType1

	djangoContentType1.R.ContentTypeAuthPermissions = append(djangoContentType1.R.ContentTypeAuthPermissions, authPermission0)

	return nil
}

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

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

	authPermission0.R.ContentTypeDjangoContentType = djangoContentType1

	djangoContentType1.R.ContentTypeAuthPermissions = append(djangoContentType1.R.ContentTypeAuthPermissions, authPermission0)

	return nil
}

func insertAuthPermissionPermissionAuthUserUserPermissions0(ctx context.Context, exec bob.Executor, authUserUserPermissions1 []*AuthUserUserPermissionSetter, authPermission0 *AuthPermission) (AuthUserUserPermissionSlice, error) {
	for i := range authUserUserPermissions1 {
		authUserUserPermissions1[i].PermissionID = omit.From(authPermission0.ID)
	}

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

	return ret, nil
}

func attachAuthPermissionPermissionAuthUserUserPermissions0(ctx context.Context, exec bob.Executor, count int, authUserUserPermissions1 AuthUserUserPermissionSlice, authPermission0 *AuthPermission) (AuthUserUserPermissionSlice, error) {
	setter := &AuthUserUserPermissionSetter{
		PermissionID: omit.From(authPermission0.ID),
	}

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

	return authUserUserPermissions1, nil
}

func (authPermission0 *AuthPermission) InsertPermissionAuthUserUserPermissions(ctx context.Context, exec bob.Executor, related ...*AuthUserUserPermissionSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	authPermission0.R.PermissionAuthUserUserPermissions = append(authPermission0.R.PermissionAuthUserUserPermissions, authUserUserPermissions1...)

	for _, rel := range authUserUserPermissions1 {
		rel.R.PermissionAuthPermission = authPermission0
	}
	return nil
}

func (authPermission0 *AuthPermission) AttachPermissionAuthUserUserPermissions(ctx context.Context, exec bob.Executor, related ...*AuthUserUserPermission) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authUserUserPermissions1 := AuthUserUserPermissionSlice(related)

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

	authPermission0.R.PermissionAuthUserUserPermissions = append(authPermission0.R.PermissionAuthUserUserPermissions, authUserUserPermissions1...)

	for _, rel := range related {
		rel.R.PermissionAuthPermission = authPermission0
	}

	return nil
}

type authPermissionWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	Name          mysql.WhereMod[Q, string]
	ContentTypeID mysql.WhereMod[Q, int32]
	Codename      mysql.WhereMod[Q, string]
}

func (authPermissionWhere[Q]) AliasedAs(alias string) authPermissionWhere[Q] {
	return buildAuthPermissionWhere[Q](buildAuthPermissionColumns(alias))
}

func buildAuthPermissionWhere[Q mysql.Filterable](cols authPermissionColumns) authPermissionWhere[Q] {
	return authPermissionWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		Name:          mysql.Where[Q, string](cols.Name),
		ContentTypeID: mysql.Where[Q, int32](cols.ContentTypeID),
		Codename:      mysql.Where[Q, string](cols.Codename),
	}
}

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

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

		o.R.PermissionAuthGroupPermissions = rels

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

		o.R.ContentTypeDjangoContentType = rel

		if rel != nil {
			rel.R.ContentTypeAuthPermissions = AuthPermissionSlice{o}
		}
		return nil
	case "PermissionAuthUserUserPermissions":
		rels, ok := retrieved.(AuthUserUserPermissionSlice)
		if !ok {
			return fmt.Errorf("authPermission cannot load %T as %q", retrieved, name)
		}

		o.R.PermissionAuthUserUserPermissions = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.PermissionAuthPermission = o
			}
		}
		return nil
	default:
		return fmt.Errorf("authPermission has no relationship %q", name)
	}
}

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

func buildAuthPermissionPreloader() authPermissionPreloader {
	return authPermissionPreloader{
		ContentTypeDjangoContentType: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*DjangoContentType, DjangoContentTypeSlice](mysql.PreloadRel{
				Name: "ContentTypeDjangoContentType",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthPermissions,
						To:          DjangoContentTypes,
						FromColumns: []string{"content_type_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, DjangoContentTypes.Columns.Names(), opts...)
		},
	}
}

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

func buildAuthPermissionThenLoader[Q orm.Loadable]() authPermissionThenLoader[Q] {
	type PermissionAuthGroupPermissionsLoadInterface interface {
		LoadPermissionAuthGroupPermissions(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ContentTypeDjangoContentTypeLoadInterface interface {
		LoadContentTypeDjangoContentType(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PermissionAuthUserUserPermissionsLoadInterface interface {
		LoadPermissionAuthUserUserPermissions(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return authPermissionThenLoader[Q]{
		PermissionAuthGroupPermissions: thenLoadBuilder[Q](
			"PermissionAuthGroupPermissions",
			func(ctx context.Context, exec bob.Executor, retrieved PermissionAuthGroupPermissionsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPermissionAuthGroupPermissions(ctx, exec, mods...)
			},
		),
		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...)
			},
		),
		PermissionAuthUserUserPermissions: thenLoadBuilder[Q](
			"PermissionAuthUserUserPermissions",
			func(ctx context.Context, exec bob.Executor, retrieved PermissionAuthUserUserPermissionsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPermissionAuthUserUserPermissions(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.PermissionAuthGroupPermissions = related
	return nil
}

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

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

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

		o.R.PermissionAuthGroupPermissions = nil
	}

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

		for _, rel := range authGroupPermissions {

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

			rel.R.PermissionAuthPermission = o

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

	return nil
}

// LoadContentTypeDjangoContentType loads the authPermission's ContentTypeDjangoContentType into the .R struct
func (o *AuthPermission) 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.ContentTypeAuthPermissions = AuthPermissionSlice{o}

	o.R.ContentTypeDjangoContentType = related
	return nil
}

// LoadContentTypeDjangoContentType loads the authPermission's ContentTypeDjangoContentType into the .R struct
func (os AuthPermissionSlice) 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 == rel.ID) {
				continue
			}

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

			o.R.ContentTypeDjangoContentType = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.PermissionAuthUserUserPermissions = related
	return nil
}

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

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

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

		o.R.PermissionAuthUserUserPermissions = nil
	}

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

		for _, rel := range authUserUserPermissions {

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

			rel.R.PermissionAuthPermission = o

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

	return nil
}

type authPermissionJoins[Q dialect.Joinable] struct {
	typ                               string
	PermissionAuthGroupPermissions    modAs[Q, authGroupPermissionColumns]
	ContentTypeDjangoContentType      modAs[Q, djangoContentTypeColumns]
	PermissionAuthUserUserPermissions modAs[Q, authUserUserPermissionColumns]
}

func (j authPermissionJoins[Q]) aliasedAs(alias string) authPermissionJoins[Q] {
	return buildAuthPermissionJoins[Q](buildAuthPermissionColumns(alias), j.typ)
}

func buildAuthPermissionJoins[Q dialect.Joinable](cols authPermissionColumns, typ string) authPermissionJoins[Q] {
	return authPermissionJoins[Q]{
		typ: typ,
		PermissionAuthGroupPermissions: modAs[Q, authGroupPermissionColumns]{
			c: AuthGroupPermissions.Columns,
			f: func(to authGroupPermissionColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
		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
			},
		},
		PermissionAuthUserUserPermissions: 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.PermissionID.EQ(cols.ID),
					))
				}

				return mods
			},
		},
	}
}
