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

// LocationsArchipelago is an object representing the database table.
type LocationsArchipelago struct {
	ID                  int32  `db:"id,pk,autoincr" `
	ArchipelagoURL      string `db:"archipelago_url" `
	ArchipelagoUser     string `db:"archipelago_user" `
	ArchipelagoPassword string `db:"archipelago_password" `
	SpaceID             string `db:"space_id" `

	R locationsArchipelagoR `db:"-" `
}

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

// LocationsArchipelagos contains methods to work with the locations_archipelago table
var LocationsArchipelagos = mysql.NewTablex[*LocationsArchipelago, LocationsArchipelagoSlice, *LocationsArchipelagoSetter]("locations_archipelago", buildLocationsArchipelagoColumns("locations_archipelago"), []string{"id"}, []string{"space_id"})

// LocationsArchipelagosQuery is a query on the locations_archipelago table
type LocationsArchipelagosQuery = *mysql.ViewQuery[*LocationsArchipelago, LocationsArchipelagoSlice]

// locationsArchipelagoR is where relationships are stored.
type locationsArchipelagoR struct {
	SpaceLocationsSpace *LocationsSpace // locations_archipelago_space_id_be47fd5c_fk_locations_space_uuid
}

func buildLocationsArchipelagoColumns(alias string) locationsArchipelagoColumns {
	return locationsArchipelagoColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "archipelago_url", "archipelago_user", "archipelago_password", "space_id",
		).WithParent("locations_archipelago"),
		tableAlias:          alias,
		ID:                  mysql.Quote(alias, "id"),
		ArchipelagoURL:      mysql.Quote(alias, "archipelago_url"),
		ArchipelagoUser:     mysql.Quote(alias, "archipelago_user"),
		ArchipelagoPassword: mysql.Quote(alias, "archipelago_password"),
		SpaceID:             mysql.Quote(alias, "space_id"),
	}
}

type locationsArchipelagoColumns struct {
	expr.ColumnsExpr
	tableAlias          string
	ID                  mysql.Expression
	ArchipelagoURL      mysql.Expression
	ArchipelagoUser     mysql.Expression
	ArchipelagoPassword mysql.Expression
	SpaceID             mysql.Expression
}

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

func (locationsArchipelagoColumns) AliasedAs(alias string) locationsArchipelagoColumns {
	return buildLocationsArchipelagoColumns(alias)
}

// LocationsArchipelagoSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsArchipelagoSetter struct {
	ID                  omit.Val[int32]  `db:"id,pk,autoincr" `
	ArchipelagoURL      omit.Val[string] `db:"archipelago_url" `
	ArchipelagoUser     omit.Val[string] `db:"archipelago_user" `
	ArchipelagoPassword omit.Val[string] `db:"archipelago_password" `
	SpaceID             omit.Val[string] `db:"space_id" `
}

func (s LocationsArchipelagoSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.ArchipelagoURL.IsValue() {
		vals = append(vals, "archipelago_url")
	}
	if s.ArchipelagoUser.IsValue() {
		vals = append(vals, "archipelago_user")
	}
	if s.ArchipelagoPassword.IsValue() {
		vals = append(vals, "archipelago_password")
	}
	if s.SpaceID.IsValue() {
		vals = append(vals, "space_id")
	}
	return vals
}

func (s LocationsArchipelagoSetter) Overwrite(t *LocationsArchipelago) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.ArchipelagoURL.IsValue() {
		t.ArchipelagoURL = s.ArchipelagoURL.MustGet()
	}
	if s.ArchipelagoUser.IsValue() {
		t.ArchipelagoUser = s.ArchipelagoUser.MustGet()
	}
	if s.ArchipelagoPassword.IsValue() {
		t.ArchipelagoPassword = s.ArchipelagoPassword.MustGet()
	}
	if s.SpaceID.IsValue() {
		t.SpaceID = s.SpaceID.MustGet()
	}
}

func (s *LocationsArchipelagoSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsArchipelagos.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.ArchipelagoURL.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ArchipelagoURL.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ArchipelagoUser.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ArchipelagoUser.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ArchipelagoPassword.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ArchipelagoPassword.MustGet()).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 LocationsArchipelagoSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions("locations_archipelago")...)
}

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

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

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

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

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

	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
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsArchipelagoSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsArchipelagoSetter) error {
	_, err := LocationsArchipelagos.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

	o2, err := LocationsArchipelagos.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 *LocationsArchipelago) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	return LocationsSpaces.Query(append(mods,
		sm.Where(LocationsSpaces.Columns.UUID.EQ(mysql.Arg(o.SpaceID))),
	)...)
}

func (os LocationsArchipelagoSlice) 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 attachLocationsArchipelagoSpaceLocationsSpace0(ctx context.Context, exec bob.Executor, count int, locationsArchipelago0 *LocationsArchipelago, locationsSpace1 *LocationsSpace) (*LocationsArchipelago, error) {
	setter := &LocationsArchipelagoSetter{
		SpaceID: omit.From(locationsSpace1.UUID),
	}

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

	return locationsArchipelago0, nil
}

func (locationsArchipelago0 *LocationsArchipelago) 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 = attachLocationsArchipelagoSpaceLocationsSpace0(ctx, exec, 1, locationsArchipelago0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsArchipelago0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsArchipelago = locationsArchipelago0

	return nil
}

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

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

	locationsArchipelago0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsArchipelago = locationsArchipelago0

	return nil
}

type locationsArchipelagoWhere[Q mysql.Filterable] struct {
	ID                  mysql.WhereMod[Q, int32]
	ArchipelagoURL      mysql.WhereMod[Q, string]
	ArchipelagoUser     mysql.WhereMod[Q, string]
	ArchipelagoPassword mysql.WhereMod[Q, string]
	SpaceID             mysql.WhereMod[Q, string]
}

func (locationsArchipelagoWhere[Q]) AliasedAs(alias string) locationsArchipelagoWhere[Q] {
	return buildLocationsArchipelagoWhere[Q](buildLocationsArchipelagoColumns(alias))
}

func buildLocationsArchipelagoWhere[Q mysql.Filterable](cols locationsArchipelagoColumns) locationsArchipelagoWhere[Q] {
	return locationsArchipelagoWhere[Q]{
		ID:                  mysql.Where[Q, int32](cols.ID),
		ArchipelagoURL:      mysql.Where[Q, string](cols.ArchipelagoURL),
		ArchipelagoUser:     mysql.Where[Q, string](cols.ArchipelagoUser),
		ArchipelagoPassword: mysql.Where[Q, string](cols.ArchipelagoPassword),
		SpaceID:             mysql.Where[Q, string](cols.SpaceID),
	}
}

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

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

		o.R.SpaceLocationsSpace = rel

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

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

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

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

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

	return locationsArchipelagoThenLoader[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 locationsArchipelago's SpaceLocationsSpace into the .R struct
func (o *LocationsArchipelago) 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.SpaceLocationsArchipelago = o

	o.R.SpaceLocationsSpace = related
	return nil
}

// LoadSpaceLocationsSpace loads the locationsArchipelago's SpaceLocationsSpace into the .R struct
func (os LocationsArchipelagoSlice) 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.SpaceLocationsArchipelago = o

			o.R.SpaceLocationsSpace = rel
			break
		}
	}

	return nil
}

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

func (j locationsArchipelagoJoins[Q]) aliasedAs(alias string) locationsArchipelagoJoins[Q] {
	return buildLocationsArchipelagoJoins[Q](buildLocationsArchipelagoColumns(alias), j.typ)
}

func buildLocationsArchipelagoJoins[Q dialect.Joinable](cols locationsArchipelagoColumns, typ string) locationsArchipelagoJoins[Q] {
	return locationsArchipelagoJoins[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
			},
		},
	}
}
