// Code generated by BobGen psql v0.42.5. 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"
	"time"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
	"github.com/aarondl/opt/omit"
)

// Pool is an object representing the database table.
type Pool struct {
	Condition   enums.Poolconditiontype `db:"condition" `
	Created     time.Time               `db:"created" `
	CreatorID   int32                   `db:"creator_id" `
	ID          int32                   `db:"id,pk" `
	SiteID      int32                   `db:"site_id" `
	SiteVersion int32                   `db:"site_version" `

	R poolR `db:"-" `
}

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

// Pools contains methods to work with the pool table
var Pools = psql.NewTablex[*Pool, PoolSlice, *PoolSetter]("", "pool", buildPoolColumns("pool"))

// PoolsQuery is a query on the pool table
type PoolsQuery = *psql.ViewQuery[*Pool, PoolSlice]

// poolR is where relationships are stored.
type poolR struct {
	CreatorUser *User // pool.pool_creator_id_fkey
	Site        *Site // pool.pool_site_id_site_version_fkey
}

func buildPoolColumns(alias string) poolColumns {
	return poolColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"condition", "created", "creator_id", "id", "site_id", "site_version",
		).WithParent("pool"),
		tableAlias:  alias,
		Condition:   psql.Quote(alias, "condition"),
		Created:     psql.Quote(alias, "created"),
		CreatorID:   psql.Quote(alias, "creator_id"),
		ID:          psql.Quote(alias, "id"),
		SiteID:      psql.Quote(alias, "site_id"),
		SiteVersion: psql.Quote(alias, "site_version"),
	}
}

type poolColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	Condition   psql.Expression
	Created     psql.Expression
	CreatorID   psql.Expression
	ID          psql.Expression
	SiteID      psql.Expression
	SiteVersion psql.Expression
}

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

func (poolColumns) AliasedAs(alias string) poolColumns {
	return buildPoolColumns(alias)
}

// PoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PoolSetter struct {
	Condition   omit.Val[enums.Poolconditiontype] `db:"condition" `
	Created     omit.Val[time.Time]               `db:"created" `
	CreatorID   omit.Val[int32]                   `db:"creator_id" `
	ID          omit.Val[int32]                   `db:"id,pk" `
	SiteID      omit.Val[int32]                   `db:"site_id" `
	SiteVersion omit.Val[int32]                   `db:"site_version" `
}

func (s PoolSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	if s.Condition.IsValue() {
		vals = append(vals, "condition")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.CreatorID.IsValue() {
		vals = append(vals, "creator_id")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.SiteID.IsValue() {
		vals = append(vals, "site_id")
	}
	if s.SiteVersion.IsValue() {
		vals = append(vals, "site_version")
	}
	return vals
}

func (s PoolSetter) Overwrite(t *Pool) {
	if s.Condition.IsValue() {
		t.Condition = s.Condition.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.CreatorID.IsValue() {
		t.CreatorID = s.CreatorID.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.SiteID.IsValue() {
		t.SiteID = s.SiteID.MustGet()
	}
	if s.SiteVersion.IsValue() {
		t.SiteVersion = s.SiteVersion.MustGet()
	}
}

func (s *PoolSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return Pools.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 6)
		if s.Condition.IsValue() {
			vals[0] = psql.Arg(s.Condition.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

		if s.Created.IsValue() {
			vals[1] = psql.Arg(s.Created.MustGet())
		} else {
			vals[1] = psql.Raw("DEFAULT")
		}

		if s.CreatorID.IsValue() {
			vals[2] = psql.Arg(s.CreatorID.MustGet())
		} else {
			vals[2] = psql.Raw("DEFAULT")
		}

		if s.ID.IsValue() {
			vals[3] = psql.Arg(s.ID.MustGet())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

		if s.SiteID.IsValue() {
			vals[4] = psql.Arg(s.SiteID.MustGet())
		} else {
			vals[4] = psql.Raw("DEFAULT")
		}

		if s.SiteVersion.IsValue() {
			vals[5] = psql.Arg(s.SiteVersion.MustGet())
		} else {
			vals[5] = psql.Raw("DEFAULT")
		}

		return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
	}))
}

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *Pool) pkEQ() dialect.Expression {
	return psql.Quote("pool", "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 Pool
func (o *Pool) Update(ctx context.Context, exec bob.Executor, s *PoolSetter) error {
	v, err := Pools.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	o.R = v.R
	*o = *v

	return nil
}

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

// Reload refreshes the Pool using the executor
func (o *Pool) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := Pools.Query(
		sm.Where(Pools.Columns.ID.EQ(psql.Arg(o.ID))),
	).One(ctx, exec)
	if err != nil {
		return err
	}
	o2.R = o.R
	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o PoolSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PoolSetter) error {
	if len(o) == 0 {
		return nil
	}

	_, err := Pools.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// CreatorUser starts a query for related objects on user_
func (o *Pool) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.CreatorID))),
	)...)
}

func (os PoolSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkCreatorID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkCreatorID = append(pkCreatorID, o.CreatorID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkCreatorID), "integer[]")),
	))

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

// Site starts a query for related objects on site
func (o *Pool) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	return Sites.Query(append(mods,
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))), sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.SiteVersion))),
	)...)
}

func (os PoolSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	pkSiteID := make(pgtypes.Array[int32], 0, len(os))

	pkSiteVersion := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkSiteID = append(pkSiteID, o.SiteID)
		pkSiteVersion = append(pkSiteVersion, o.SiteVersion)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkSiteID), "integer[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkSiteVersion), "integer[]")),
	))

	return Sites.Query(append(mods,
		sm.Where(psql.Group(Sites.Columns.ID, Sites.Columns.Version).OP("IN", PKArgExpr)),
	)...)
}

func attachPoolCreatorUser0(ctx context.Context, exec bob.Executor, count int, pool0 *Pool, user1 *User) (*Pool, error) {
	setter := &PoolSetter{
		CreatorID: omit.From(user1.ID),
	}

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

	return pool0, nil
}

func (pool0 *Pool) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachPoolCreatorUser0(ctx, exec, 1, pool0, user1)
	if err != nil {
		return err
	}

	pool0.R.CreatorUser = user1

	user1.R.CreatorPools = append(user1.R.CreatorPools, pool0)

	return nil
}

func (pool0 *Pool) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachPoolCreatorUser0(ctx, exec, 1, pool0, user1)
	if err != nil {
		return err
	}

	pool0.R.CreatorUser = user1

	user1.R.CreatorPools = append(user1.R.CreatorPools, pool0)

	return nil
}

func attachPoolSite0(ctx context.Context, exec bob.Executor, count int, pool0 *Pool, site1 *Site) (*Pool, error) {
	setter := &PoolSetter{
		SiteID:      omit.From(site1.ID),
		SiteVersion: omit.From(site1.Version),
	}

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

	return pool0, nil
}

func (pool0 *Pool) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error {
	var err error

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

	_, err = attachPoolSite0(ctx, exec, 1, pool0, site1)
	if err != nil {
		return err
	}

	pool0.R.Site = site1

	site1.R.Pools = append(site1.R.Pools, pool0)

	return nil
}

func (pool0 *Pool) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error {
	var err error

	_, err = attachPoolSite0(ctx, exec, 1, pool0, site1)
	if err != nil {
		return err
	}

	pool0.R.Site = site1

	site1.R.Pools = append(site1.R.Pools, pool0)

	return nil
}

type poolWhere[Q psql.Filterable] struct {
	Condition   psql.WhereMod[Q, enums.Poolconditiontype]
	Created     psql.WhereMod[Q, time.Time]
	CreatorID   psql.WhereMod[Q, int32]
	ID          psql.WhereMod[Q, int32]
	SiteID      psql.WhereMod[Q, int32]
	SiteVersion psql.WhereMod[Q, int32]
}

func (poolWhere[Q]) AliasedAs(alias string) poolWhere[Q] {
	return buildPoolWhere[Q](buildPoolColumns(alias))
}

func buildPoolWhere[Q psql.Filterable](cols poolColumns) poolWhere[Q] {
	return poolWhere[Q]{
		Condition:   psql.Where[Q, enums.Poolconditiontype](cols.Condition),
		Created:     psql.Where[Q, time.Time](cols.Created),
		CreatorID:   psql.Where[Q, int32](cols.CreatorID),
		ID:          psql.Where[Q, int32](cols.ID),
		SiteID:      psql.Where[Q, int32](cols.SiteID),
		SiteVersion: psql.Where[Q, int32](cols.SiteVersion),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorPools = PoolSlice{o}
		}
		return nil
	case "Site":
		rel, ok := retrieved.(*Site)
		if !ok {
			return fmt.Errorf("pool cannot load %T as %q", retrieved, name)
		}

		o.R.Site = rel

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

type poolPreloader struct {
	CreatorUser func(...psql.PreloadOption) psql.Preloader
	Site        func(...psql.PreloadOption) psql.Preloader
}

func buildPoolPreloader() poolPreloader {
	return poolPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Pools,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Pools,
						To:          Sites,
						FromColumns: []string{"site_id", "site_version"},
						ToColumns:   []string{"id", "version"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type poolThenLoader[Q orm.Loadable] struct {
	CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPoolThenLoader[Q orm.Loadable]() poolThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return poolThenLoader[Q]{
		CreatorUser: thenLoadBuilder[Q](
			"CreatorUser",
			func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCreatorUser(ctx, exec, mods...)
			},
		),
		Site: thenLoadBuilder[Q](
			"Site",
			func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSite(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.CreatorPools = PoolSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Pools = PoolSlice{o}

	o.R.Site = related
	return nil
}

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

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

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

		for _, rel := range sites {

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

			if !(o.SiteVersion == rel.Version) {
				continue
			}

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

			o.R.Site = rel
			break
		}
	}

	return nil
}

type poolJoins[Q dialect.Joinable] struct {
	typ         string
	CreatorUser modAs[Q, userColumns]
	Site        modAs[Q, siteColumns]
}

func (j poolJoins[Q]) aliasedAs(alias string) poolJoins[Q] {
	return buildPoolJoins[Q](buildPoolColumns(alias), j.typ)
}

func buildPoolJoins[Q dialect.Joinable](cols poolColumns, typ string) poolJoins[Q] {
	return poolJoins[Q]{
		typ: typ,
		CreatorUser: modAs[Q, userColumns]{
			c: Users.Columns,
			f: func(to userColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

				{
					mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On(
						to.ID.EQ(cols.SiteID), to.Version.EQ(cols.SiteVersion),
					))
				}

				return mods
			},
		},
	}
}
