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

// LocationsLockssomatic is an object representing the database table.
type LocationsLockssomatic struct {
	ID                int32            `db:"id,pk,autoincr" `
	AuSize            null.Val[int64]  `db:"au_size" `
	SDIri             string           `db:"sd_iri" `
	CollectionIri     null.Val[string] `db:"collection_iri" `
	ContentProviderID string           `db:"content_provider_id" `
	ExternalDomain    string           `db:"external_domain" `
	ChecksumType      null.Val[string] `db:"checksum_type" `
	KeepLocal         bool             `db:"keep_local" `
	SpaceID           string           `db:"space_id" `

	R locationsLockssomaticR `db:"-" `
}

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

// LocationsLockssomatics contains methods to work with the locations_lockssomatic table
var LocationsLockssomatics = mysql.NewTablex[*LocationsLockssomatic, LocationsLockssomaticSlice, *LocationsLockssomaticSetter]("locations_lockssomatic", buildLocationsLockssomaticColumns("locations_lockssomatic"), []string{"id"}, []string{"space_id"})

// LocationsLockssomaticsQuery is a query on the locations_lockssomatic table
type LocationsLockssomaticsQuery = *mysql.ViewQuery[*LocationsLockssomatic, LocationsLockssomaticSlice]

// locationsLockssomaticR is where relationships are stored.
type locationsLockssomaticR struct {
	SpaceLocationsSpace *LocationsSpace // locations_lockssomatic_space_id_cc6a3cd6_fk_locations_space_uuid
}

func buildLocationsLockssomaticColumns(alias string) locationsLockssomaticColumns {
	return locationsLockssomaticColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "au_size", "sd_iri", "collection_iri", "content_provider_id", "external_domain", "checksum_type", "keep_local", "space_id",
		).WithParent("locations_lockssomatic"),
		tableAlias:        alias,
		ID:                mysql.Quote(alias, "id"),
		AuSize:            mysql.Quote(alias, "au_size"),
		SDIri:             mysql.Quote(alias, "sd_iri"),
		CollectionIri:     mysql.Quote(alias, "collection_iri"),
		ContentProviderID: mysql.Quote(alias, "content_provider_id"),
		ExternalDomain:    mysql.Quote(alias, "external_domain"),
		ChecksumType:      mysql.Quote(alias, "checksum_type"),
		KeepLocal:         mysql.Quote(alias, "keep_local"),
		SpaceID:           mysql.Quote(alias, "space_id"),
	}
}

type locationsLockssomaticColumns struct {
	expr.ColumnsExpr
	tableAlias        string
	ID                mysql.Expression
	AuSize            mysql.Expression
	SDIri             mysql.Expression
	CollectionIri     mysql.Expression
	ContentProviderID mysql.Expression
	ExternalDomain    mysql.Expression
	ChecksumType      mysql.Expression
	KeepLocal         mysql.Expression
	SpaceID           mysql.Expression
}

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

func (locationsLockssomaticColumns) AliasedAs(alias string) locationsLockssomaticColumns {
	return buildLocationsLockssomaticColumns(alias)
}

// LocationsLockssomaticSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsLockssomaticSetter struct {
	ID                omit.Val[int32]      `db:"id,pk,autoincr" `
	AuSize            omitnull.Val[int64]  `db:"au_size" `
	SDIri             omit.Val[string]     `db:"sd_iri" `
	CollectionIri     omitnull.Val[string] `db:"collection_iri" `
	ContentProviderID omit.Val[string]     `db:"content_provider_id" `
	ExternalDomain    omit.Val[string]     `db:"external_domain" `
	ChecksumType      omitnull.Val[string] `db:"checksum_type" `
	KeepLocal         omit.Val[bool]       `db:"keep_local" `
	SpaceID           omit.Val[string]     `db:"space_id" `
}

func (s LocationsLockssomaticSetter) SetColumns() []string {
	vals := make([]string, 0, 9)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if !s.AuSize.IsUnset() {
		vals = append(vals, "au_size")
	}
	if s.SDIri.IsValue() {
		vals = append(vals, "sd_iri")
	}
	if !s.CollectionIri.IsUnset() {
		vals = append(vals, "collection_iri")
	}
	if s.ContentProviderID.IsValue() {
		vals = append(vals, "content_provider_id")
	}
	if s.ExternalDomain.IsValue() {
		vals = append(vals, "external_domain")
	}
	if !s.ChecksumType.IsUnset() {
		vals = append(vals, "checksum_type")
	}
	if s.KeepLocal.IsValue() {
		vals = append(vals, "keep_local")
	}
	if s.SpaceID.IsValue() {
		vals = append(vals, "space_id")
	}
	return vals
}

func (s LocationsLockssomaticSetter) Overwrite(t *LocationsLockssomatic) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if !s.AuSize.IsUnset() {
		t.AuSize = s.AuSize.MustGetNull()
	}
	if s.SDIri.IsValue() {
		t.SDIri = s.SDIri.MustGet()
	}
	if !s.CollectionIri.IsUnset() {
		t.CollectionIri = s.CollectionIri.MustGetNull()
	}
	if s.ContentProviderID.IsValue() {
		t.ContentProviderID = s.ContentProviderID.MustGet()
	}
	if s.ExternalDomain.IsValue() {
		t.ExternalDomain = s.ExternalDomain.MustGet()
	}
	if !s.ChecksumType.IsUnset() {
		t.ChecksumType = s.ChecksumType.MustGetNull()
	}
	if s.KeepLocal.IsValue() {
		t.KeepLocal = s.KeepLocal.MustGet()
	}
	if s.SpaceID.IsValue() {
		t.SpaceID = s.SpaceID.MustGet()
	}
}

func (s *LocationsLockssomaticSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsLockssomatics.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.AuSize.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AuSize.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SDIri.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SDIri.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.CollectionIri.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.CollectionIri.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ContentProviderID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ContentProviderID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ExternalDomain.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ExternalDomain.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.ChecksumType.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ChecksumType.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.KeepLocal.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.KeepLocal.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 LocationsLockssomaticSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions("locations_lockssomatic")...)
}

func (s LocationsLockssomaticSetter) 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.AuSize.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "au_size")...),
			mysql.Arg(s.AuSize),
		}})
	}

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

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

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

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

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

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

	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
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsLockssomaticSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsLockssomaticSetter) error {
	_, err := LocationsLockssomatics.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

func (os LocationsLockssomaticSlice) 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 attachLocationsLockssomaticSpaceLocationsSpace0(ctx context.Context, exec bob.Executor, count int, locationsLockssomatic0 *LocationsLockssomatic, locationsSpace1 *LocationsSpace) (*LocationsLockssomatic, error) {
	setter := &LocationsLockssomaticSetter{
		SpaceID: omit.From(locationsSpace1.UUID),
	}

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

	return locationsLockssomatic0, nil
}

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

	locationsLockssomatic0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsLockssomatic = locationsLockssomatic0

	return nil
}

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

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

	locationsLockssomatic0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsLockssomatic = locationsLockssomatic0

	return nil
}

type locationsLockssomaticWhere[Q mysql.Filterable] struct {
	ID                mysql.WhereMod[Q, int32]
	AuSize            mysql.WhereNullMod[Q, int64]
	SDIri             mysql.WhereMod[Q, string]
	CollectionIri     mysql.WhereNullMod[Q, string]
	ContentProviderID mysql.WhereMod[Q, string]
	ExternalDomain    mysql.WhereMod[Q, string]
	ChecksumType      mysql.WhereNullMod[Q, string]
	KeepLocal         mysql.WhereMod[Q, bool]
	SpaceID           mysql.WhereMod[Q, string]
}

func (locationsLockssomaticWhere[Q]) AliasedAs(alias string) locationsLockssomaticWhere[Q] {
	return buildLocationsLockssomaticWhere[Q](buildLocationsLockssomaticColumns(alias))
}

func buildLocationsLockssomaticWhere[Q mysql.Filterable](cols locationsLockssomaticColumns) locationsLockssomaticWhere[Q] {
	return locationsLockssomaticWhere[Q]{
		ID:                mysql.Where[Q, int32](cols.ID),
		AuSize:            mysql.WhereNull[Q, int64](cols.AuSize),
		SDIri:             mysql.Where[Q, string](cols.SDIri),
		CollectionIri:     mysql.WhereNull[Q, string](cols.CollectionIri),
		ContentProviderID: mysql.Where[Q, string](cols.ContentProviderID),
		ExternalDomain:    mysql.Where[Q, string](cols.ExternalDomain),
		ChecksumType:      mysql.WhereNull[Q, string](cols.ChecksumType),
		KeepLocal:         mysql.Where[Q, bool](cols.KeepLocal),
		SpaceID:           mysql.Where[Q, string](cols.SpaceID),
	}
}

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

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

		o.R.SpaceLocationsSpace = rel

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

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

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

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

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

	return locationsLockssomaticThenLoader[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 locationsLockssomatic's SpaceLocationsSpace into the .R struct
func (o *LocationsLockssomatic) 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.SpaceLocationsLockssomatic = o

	o.R.SpaceLocationsSpace = related
	return nil
}

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

			o.R.SpaceLocationsSpace = rel
			break
		}
	}

	return nil
}

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

func (j locationsLockssomaticJoins[Q]) aliasedAs(alias string) locationsLockssomaticJoins[Q] {
	return buildLocationsLockssomaticJoins[Q](buildLocationsLockssomaticColumns(alias), j.typ)
}

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