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

// LocationsPackageRelatedPackage is an object representing the database table.
type LocationsPackageRelatedPackage struct {
	ID            int32 `db:"id,pk,autoincr" `
	FromPackageID int32 `db:"from_package_id" `
	ToPackageID   int32 `db:"to_package_id" `

	R locationsPackageRelatedPackageR `db:"-" `
}

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

// LocationsPackageRelatedPackages contains methods to work with the locations_package_related_packages table
var LocationsPackageRelatedPackages = mysql.NewTablex[*LocationsPackageRelatedPackage, LocationsPackageRelatedPackageSlice, *LocationsPackageRelatedPackageSetter]("locations_package_related_packages", buildLocationsPackageRelatedPackageColumns("locations_package_related_packages"), []string{"id"}, []string{"from_package_id", "to_package_id"})

// LocationsPackageRelatedPackagesQuery is a query on the locations_package_related_packages table
type LocationsPackageRelatedPackagesQuery = *mysql.ViewQuery[*LocationsPackageRelatedPackage, LocationsPackageRelatedPackageSlice]

// locationsPackageRelatedPackageR is where relationships are stored.
type locationsPackageRelatedPackageR struct {
	FromPackageLocationsPackage *LocationsPackage // locations_package_re_from_package_id_eab8b60c_fk_locations
	ToPackageLocationsPackage   *LocationsPackage // locations_package_re_to_package_id_7a32b99c_fk_locations
}

func buildLocationsPackageRelatedPackageColumns(alias string) locationsPackageRelatedPackageColumns {
	return locationsPackageRelatedPackageColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "from_package_id", "to_package_id",
		).WithParent("locations_package_related_packages"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		FromPackageID: mysql.Quote(alias, "from_package_id"),
		ToPackageID:   mysql.Quote(alias, "to_package_id"),
	}
}

type locationsPackageRelatedPackageColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	FromPackageID mysql.Expression
	ToPackageID   mysql.Expression
}

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

func (locationsPackageRelatedPackageColumns) AliasedAs(alias string) locationsPackageRelatedPackageColumns {
	return buildLocationsPackageRelatedPackageColumns(alias)
}

// LocationsPackageRelatedPackageSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsPackageRelatedPackageSetter struct {
	ID            omit.Val[int32] `db:"id,pk,autoincr" `
	FromPackageID omit.Val[int32] `db:"from_package_id" `
	ToPackageID   omit.Val[int32] `db:"to_package_id" `
}

func (s LocationsPackageRelatedPackageSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.FromPackageID.IsValue() {
		vals = append(vals, "from_package_id")
	}
	if s.ToPackageID.IsValue() {
		vals = append(vals, "to_package_id")
	}
	return vals
}

func (s LocationsPackageRelatedPackageSetter) Overwrite(t *LocationsPackageRelatedPackage) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.FromPackageID.IsValue() {
		t.FromPackageID = s.FromPackageID.MustGet()
	}
	if s.ToPackageID.IsValue() {
		t.ToPackageID = s.ToPackageID.MustGet()
	}
}

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsPackageRelatedPackageSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsPackageRelatedPackageSetter) error {
	_, err := LocationsPackageRelatedPackages.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// FromPackageLocationsPackage starts a query for related objects on locations_package
func (o *LocationsPackageRelatedPackage) FromPackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	return LocationsPackages.Query(append(mods,
		sm.Where(LocationsPackages.Columns.ID.EQ(mysql.Arg(o.FromPackageID))),
	)...)
}

func (os LocationsPackageRelatedPackageSlice) FromPackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.FromPackageID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// ToPackageLocationsPackage starts a query for related objects on locations_package
func (o *LocationsPackageRelatedPackage) ToPackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	return LocationsPackages.Query(append(mods,
		sm.Where(LocationsPackages.Columns.ID.EQ(mysql.Arg(o.ToPackageID))),
	)...)
}

func (os LocationsPackageRelatedPackageSlice) ToPackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ToPackageID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachLocationsPackageRelatedPackageFromPackageLocationsPackage0(ctx context.Context, exec bob.Executor, count int, locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage, locationsPackage1 *LocationsPackage) (*LocationsPackageRelatedPackage, error) {
	setter := &LocationsPackageRelatedPackageSetter{
		FromPackageID: omit.From(locationsPackage1.ID),
	}

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

	return locationsPackageRelatedPackage0, nil
}

func (locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage) InsertFromPackageLocationsPackage(ctx context.Context, exec bob.Executor, related *LocationsPackageSetter) error {
	var err error

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

	_, err = attachLocationsPackageRelatedPackageFromPackageLocationsPackage0(ctx, exec, 1, locationsPackageRelatedPackage0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsPackageRelatedPackage0.R.FromPackageLocationsPackage = locationsPackage1

	locationsPackage1.R.FromPackageLocationsPackageRelatedPackages = append(locationsPackage1.R.FromPackageLocationsPackageRelatedPackages, locationsPackageRelatedPackage0)

	return nil
}

func (locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage) AttachFromPackageLocationsPackage(ctx context.Context, exec bob.Executor, locationsPackage1 *LocationsPackage) error {
	var err error

	_, err = attachLocationsPackageRelatedPackageFromPackageLocationsPackage0(ctx, exec, 1, locationsPackageRelatedPackage0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsPackageRelatedPackage0.R.FromPackageLocationsPackage = locationsPackage1

	locationsPackage1.R.FromPackageLocationsPackageRelatedPackages = append(locationsPackage1.R.FromPackageLocationsPackageRelatedPackages, locationsPackageRelatedPackage0)

	return nil
}

func attachLocationsPackageRelatedPackageToPackageLocationsPackage0(ctx context.Context, exec bob.Executor, count int, locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage, locationsPackage1 *LocationsPackage) (*LocationsPackageRelatedPackage, error) {
	setter := &LocationsPackageRelatedPackageSetter{
		ToPackageID: omit.From(locationsPackage1.ID),
	}

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

	return locationsPackageRelatedPackage0, nil
}

func (locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage) InsertToPackageLocationsPackage(ctx context.Context, exec bob.Executor, related *LocationsPackageSetter) error {
	var err error

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

	_, err = attachLocationsPackageRelatedPackageToPackageLocationsPackage0(ctx, exec, 1, locationsPackageRelatedPackage0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsPackageRelatedPackage0.R.ToPackageLocationsPackage = locationsPackage1

	locationsPackage1.R.ToPackageLocationsPackageRelatedPackages = append(locationsPackage1.R.ToPackageLocationsPackageRelatedPackages, locationsPackageRelatedPackage0)

	return nil
}

func (locationsPackageRelatedPackage0 *LocationsPackageRelatedPackage) AttachToPackageLocationsPackage(ctx context.Context, exec bob.Executor, locationsPackage1 *LocationsPackage) error {
	var err error

	_, err = attachLocationsPackageRelatedPackageToPackageLocationsPackage0(ctx, exec, 1, locationsPackageRelatedPackage0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsPackageRelatedPackage0.R.ToPackageLocationsPackage = locationsPackage1

	locationsPackage1.R.ToPackageLocationsPackageRelatedPackages = append(locationsPackage1.R.ToPackageLocationsPackageRelatedPackages, locationsPackageRelatedPackage0)

	return nil
}

type locationsPackageRelatedPackageWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	FromPackageID mysql.WhereMod[Q, int32]
	ToPackageID   mysql.WhereMod[Q, int32]
}

func (locationsPackageRelatedPackageWhere[Q]) AliasedAs(alias string) locationsPackageRelatedPackageWhere[Q] {
	return buildLocationsPackageRelatedPackageWhere[Q](buildLocationsPackageRelatedPackageColumns(alias))
}

func buildLocationsPackageRelatedPackageWhere[Q mysql.Filterable](cols locationsPackageRelatedPackageColumns) locationsPackageRelatedPackageWhere[Q] {
	return locationsPackageRelatedPackageWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		FromPackageID: mysql.Where[Q, int32](cols.FromPackageID),
		ToPackageID:   mysql.Where[Q, int32](cols.ToPackageID),
	}
}

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

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

		o.R.FromPackageLocationsPackage = rel

		if rel != nil {
			rel.R.FromPackageLocationsPackageRelatedPackages = LocationsPackageRelatedPackageSlice{o}
		}
		return nil
	case "ToPackageLocationsPackage":
		rel, ok := retrieved.(*LocationsPackage)
		if !ok {
			return fmt.Errorf("locationsPackageRelatedPackage cannot load %T as %q", retrieved, name)
		}

		o.R.ToPackageLocationsPackage = rel

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

type locationsPackageRelatedPackagePreloader struct {
	FromPackageLocationsPackage func(...mysql.PreloadOption) mysql.Preloader
	ToPackageLocationsPackage   func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsPackageRelatedPackagePreloader() locationsPackageRelatedPackagePreloader {
	return locationsPackageRelatedPackagePreloader{
		FromPackageLocationsPackage: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsPackage, LocationsPackageSlice](mysql.PreloadRel{
				Name: "FromPackageLocationsPackage",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsPackageRelatedPackages,
						To:          LocationsPackages,
						FromColumns: []string{"from_package_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, LocationsPackages.Columns.Names(), opts...)
		},
		ToPackageLocationsPackage: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsPackage, LocationsPackageSlice](mysql.PreloadRel{
				Name: "ToPackageLocationsPackage",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsPackageRelatedPackages,
						To:          LocationsPackages,
						FromColumns: []string{"to_package_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, LocationsPackages.Columns.Names(), opts...)
		},
	}
}

type locationsPackageRelatedPackageThenLoader[Q orm.Loadable] struct {
	FromPackageLocationsPackage func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ToPackageLocationsPackage   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildLocationsPackageRelatedPackageThenLoader[Q orm.Loadable]() locationsPackageRelatedPackageThenLoader[Q] {
	type FromPackageLocationsPackageLoadInterface interface {
		LoadFromPackageLocationsPackage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ToPackageLocationsPackageLoadInterface interface {
		LoadToPackageLocationsPackage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsPackageRelatedPackageThenLoader[Q]{
		FromPackageLocationsPackage: thenLoadBuilder[Q](
			"FromPackageLocationsPackage",
			func(ctx context.Context, exec bob.Executor, retrieved FromPackageLocationsPackageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFromPackageLocationsPackage(ctx, exec, mods...)
			},
		),
		ToPackageLocationsPackage: thenLoadBuilder[Q](
			"ToPackageLocationsPackage",
			func(ctx context.Context, exec bob.Executor, retrieved ToPackageLocationsPackageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadToPackageLocationsPackage(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.FromPackageLocationsPackageRelatedPackages = LocationsPackageRelatedPackageSlice{o}

	o.R.FromPackageLocationsPackage = related
	return nil
}

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

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

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

		for _, rel := range locationsPackages {

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

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

			o.R.FromPackageLocationsPackage = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ToPackageLocationsPackageRelatedPackages = LocationsPackageRelatedPackageSlice{o}

	o.R.ToPackageLocationsPackage = related
	return nil
}

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

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

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

		for _, rel := range locationsPackages {

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

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

			o.R.ToPackageLocationsPackage = rel
			break
		}
	}

	return nil
}

type locationsPackageRelatedPackageJoins[Q dialect.Joinable] struct {
	typ                         string
	FromPackageLocationsPackage modAs[Q, locationsPackageColumns]
	ToPackageLocationsPackage   modAs[Q, locationsPackageColumns]
}

func (j locationsPackageRelatedPackageJoins[Q]) aliasedAs(alias string) locationsPackageRelatedPackageJoins[Q] {
	return buildLocationsPackageRelatedPackageJoins[Q](buildLocationsPackageRelatedPackageColumns(alias), j.typ)
}

func buildLocationsPackageRelatedPackageJoins[Q dialect.Joinable](cols locationsPackageRelatedPackageColumns, typ string) locationsPackageRelatedPackageJoins[Q] {
	return locationsPackageRelatedPackageJoins[Q]{
		typ: typ,
		FromPackageLocationsPackage: modAs[Q, locationsPackageColumns]{
			c: LocationsPackages.Columns,
			f: func(to locationsPackageColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

				return mods
			},
		},
	}
}
