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

// LocationsSwift is an object representing the database table.
type LocationsSwift struct {
	ID          int32            `db:"id,pk,autoincr" `
	AuthURL     string           `db:"auth_url" `
	AuthVersion string           `db:"auth_version" `
	Username    string           `db:"username" `
	Password    string           `db:"password" `
	Container   string           `db:"container" `
	Tenant      null.Val[string] `db:"tenant" `
	Region      null.Val[string] `db:"region" `
	SpaceID     string           `db:"space_id" `

	R locationsSwiftR `db:"-" `
}

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

// LocationsSwifts contains methods to work with the locations_swift table
var LocationsSwifts = mysql.NewTablex[*LocationsSwift, LocationsSwiftSlice, *LocationsSwiftSetter]("locations_swift", buildLocationsSwiftColumns("locations_swift"), []string{"id"}, []string{"space_id"})

// LocationsSwiftsQuery is a query on the locations_swift table
type LocationsSwiftsQuery = *mysql.ViewQuery[*LocationsSwift, LocationsSwiftSlice]

// locationsSwiftR is where relationships are stored.
type locationsSwiftR struct {
	SpaceLocationsSpace *LocationsSpace // locations_swift_space_id_9cfded49_fk_locations_space_uuid
}

func buildLocationsSwiftColumns(alias string) locationsSwiftColumns {
	return locationsSwiftColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "auth_url", "auth_version", "username", "password", "container", "tenant", "region", "space_id",
		).WithParent("locations_swift"),
		tableAlias:  alias,
		ID:          mysql.Quote(alias, "id"),
		AuthURL:     mysql.Quote(alias, "auth_url"),
		AuthVersion: mysql.Quote(alias, "auth_version"),
		Username:    mysql.Quote(alias, "username"),
		Password:    mysql.Quote(alias, "password"),
		Container:   mysql.Quote(alias, "container"),
		Tenant:      mysql.Quote(alias, "tenant"),
		Region:      mysql.Quote(alias, "region"),
		SpaceID:     mysql.Quote(alias, "space_id"),
	}
}

type locationsSwiftColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	ID          mysql.Expression
	AuthURL     mysql.Expression
	AuthVersion mysql.Expression
	Username    mysql.Expression
	Password    mysql.Expression
	Container   mysql.Expression
	Tenant      mysql.Expression
	Region      mysql.Expression
	SpaceID     mysql.Expression
}

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

func (locationsSwiftColumns) AliasedAs(alias string) locationsSwiftColumns {
	return buildLocationsSwiftColumns(alias)
}

// LocationsSwiftSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsSwiftSetter struct {
	ID          omit.Val[int32]      `db:"id,pk,autoincr" `
	AuthURL     omit.Val[string]     `db:"auth_url" `
	AuthVersion omit.Val[string]     `db:"auth_version" `
	Username    omit.Val[string]     `db:"username" `
	Password    omit.Val[string]     `db:"password" `
	Container   omit.Val[string]     `db:"container" `
	Tenant      omitnull.Val[string] `db:"tenant" `
	Region      omitnull.Val[string] `db:"region" `
	SpaceID     omit.Val[string]     `db:"space_id" `
}

func (s LocationsSwiftSetter) SetColumns() []string {
	vals := make([]string, 0, 9)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.AuthURL.IsValue() {
		vals = append(vals, "auth_url")
	}
	if s.AuthVersion.IsValue() {
		vals = append(vals, "auth_version")
	}
	if s.Username.IsValue() {
		vals = append(vals, "username")
	}
	if s.Password.IsValue() {
		vals = append(vals, "password")
	}
	if s.Container.IsValue() {
		vals = append(vals, "container")
	}
	if !s.Tenant.IsUnset() {
		vals = append(vals, "tenant")
	}
	if !s.Region.IsUnset() {
		vals = append(vals, "region")
	}
	if s.SpaceID.IsValue() {
		vals = append(vals, "space_id")
	}
	return vals
}

func (s LocationsSwiftSetter) Overwrite(t *LocationsSwift) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.AuthURL.IsValue() {
		t.AuthURL = s.AuthURL.MustGet()
	}
	if s.AuthVersion.IsValue() {
		t.AuthVersion = s.AuthVersion.MustGet()
	}
	if s.Username.IsValue() {
		t.Username = s.Username.MustGet()
	}
	if s.Password.IsValue() {
		t.Password = s.Password.MustGet()
	}
	if s.Container.IsValue() {
		t.Container = s.Container.MustGet()
	}
	if !s.Tenant.IsUnset() {
		t.Tenant = s.Tenant.MustGetNull()
	}
	if !s.Region.IsUnset() {
		t.Region = s.Region.MustGetNull()
	}
	if s.SpaceID.IsValue() {
		t.SpaceID = s.SpaceID.MustGet()
	}
}

func (s *LocationsSwiftSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsSwifts.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.AuthURL.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AuthURL.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.AuthVersion.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AuthVersion.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.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.Container.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Container.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Tenant.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Tenant.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Region.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Region.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SpaceID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SpaceID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsSwiftSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsSwiftSetter) error {
	_, err := LocationsSwifts.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// SpaceLocationsSpace starts a query for related objects on locations_space
func (o *LocationsSwift) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	return LocationsSpaces.Query(append(mods,
		sm.Where(LocationsSpaces.Columns.UUID.EQ(mysql.Arg(o.SpaceID))),
	)...)
}

func (os LocationsSwiftSlice) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.SpaceID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachLocationsSwiftSpaceLocationsSpace0(ctx context.Context, exec bob.Executor, count int, locationsSwift0 *LocationsSwift, locationsSpace1 *LocationsSpace) (*LocationsSwift, error) {
	setter := &LocationsSwiftSetter{
		SpaceID: omit.From(locationsSpace1.UUID),
	}

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

	return locationsSwift0, nil
}

func (locationsSwift0 *LocationsSwift) InsertSpaceLocationsSpace(ctx context.Context, exec bob.Executor, related *LocationsSpaceSetter) error {
	var err error

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

	_, err = attachLocationsSwiftSpaceLocationsSpace0(ctx, exec, 1, locationsSwift0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsSwift0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsSwift = locationsSwift0

	return nil
}

func (locationsSwift0 *LocationsSwift) AttachSpaceLocationsSpace(ctx context.Context, exec bob.Executor, locationsSpace1 *LocationsSpace) error {
	var err error

	_, err = attachLocationsSwiftSpaceLocationsSpace0(ctx, exec, 1, locationsSwift0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsSwift0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsSwift = locationsSwift0

	return nil
}

type locationsSwiftWhere[Q mysql.Filterable] struct {
	ID          mysql.WhereMod[Q, int32]
	AuthURL     mysql.WhereMod[Q, string]
	AuthVersion mysql.WhereMod[Q, string]
	Username    mysql.WhereMod[Q, string]
	Password    mysql.WhereMod[Q, string]
	Container   mysql.WhereMod[Q, string]
	Tenant      mysql.WhereNullMod[Q, string]
	Region      mysql.WhereNullMod[Q, string]
	SpaceID     mysql.WhereMod[Q, string]
}

func (locationsSwiftWhere[Q]) AliasedAs(alias string) locationsSwiftWhere[Q] {
	return buildLocationsSwiftWhere[Q](buildLocationsSwiftColumns(alias))
}

func buildLocationsSwiftWhere[Q mysql.Filterable](cols locationsSwiftColumns) locationsSwiftWhere[Q] {
	return locationsSwiftWhere[Q]{
		ID:          mysql.Where[Q, int32](cols.ID),
		AuthURL:     mysql.Where[Q, string](cols.AuthURL),
		AuthVersion: mysql.Where[Q, string](cols.AuthVersion),
		Username:    mysql.Where[Q, string](cols.Username),
		Password:    mysql.Where[Q, string](cols.Password),
		Container:   mysql.Where[Q, string](cols.Container),
		Tenant:      mysql.WhereNull[Q, string](cols.Tenant),
		Region:      mysql.WhereNull[Q, string](cols.Region),
		SpaceID:     mysql.Where[Q, string](cols.SpaceID),
	}
}

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

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

		o.R.SpaceLocationsSpace = rel

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

type locationsSwiftPreloader struct {
	SpaceLocationsSpace func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsSwiftPreloader() locationsSwiftPreloader {
	return locationsSwiftPreloader{
		SpaceLocationsSpace: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsSpace, LocationsSpaceSlice](mysql.PreloadRel{
				Name: "SpaceLocationsSpace",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsSwifts,
						To:          LocationsSpaces,
						FromColumns: []string{"space_id"},
						ToColumns:   []string{"uuid"},
					},
				},
			}, LocationsSpaces.Columns.Names(), opts...)
		},
	}
}

type locationsSwiftThenLoader[Q orm.Loadable] struct {
	SpaceLocationsSpace func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildLocationsSwiftThenLoader[Q orm.Loadable]() locationsSwiftThenLoader[Q] {
	type SpaceLocationsSpaceLoadInterface interface {
		LoadSpaceLocationsSpace(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsSwiftThenLoader[Q]{
		SpaceLocationsSpace: thenLoadBuilder[Q](
			"SpaceLocationsSpace",
			func(ctx context.Context, exec bob.Executor, retrieved SpaceLocationsSpaceLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSpaceLocationsSpace(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.SpaceLocationsSwift = o

	o.R.SpaceLocationsSpace = related
	return nil
}

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

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

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

		for _, rel := range locationsSpaces {

			if !(o.SpaceID == rel.UUID) {
				continue
			}

			rel.R.SpaceLocationsSwift = o

			o.R.SpaceLocationsSpace = rel
			break
		}
	}

	return nil
}

type locationsSwiftJoins[Q dialect.Joinable] struct {
	typ                 string
	SpaceLocationsSpace modAs[Q, locationsSpaceColumns]
}

func (j locationsSwiftJoins[Q]) aliasedAs(alias string) locationsSwiftJoins[Q] {
	return buildLocationsSwiftJoins[Q](buildLocationsSwiftColumns(alias), j.typ)
}

func buildLocationsSwiftJoins[Q dialect.Joinable](cols locationsSwiftColumns, typ string) locationsSwiftJoins[Q] {
	return locationsSwiftJoins[Q]{
		typ: typ,
		SpaceLocationsSpace: modAs[Q, locationsSpaceColumns]{
			c: LocationsSpaces.Columns,
			f: func(to locationsSpaceColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, LocationsSpaces.Name().As(to.Alias())).On(
						to.UUID.EQ(cols.SpaceID),
					))
				}

				return mods
			},
		},
	}
}
