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

	"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/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// FeaturePool is an object representing the database table.
type FeaturePool struct {
	FeatureID   int32                   `db:"feature_id,pk" `
	Condition   enums.Poolconditiontype `db:"condition" `
	DepthMeters null.Val[float64]       `db:"depth_meters" `
	Geometry    null.Val[string]        `db:"geometry" `

	R featurePoolR `db:"-" `
}

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

// FeaturePools contains methods to work with the feature_pool table
var FeaturePools = psql.NewTablex[*FeaturePool, FeaturePoolSlice, *FeaturePoolSetter]("", "feature_pool", buildFeaturePoolColumns("feature_pool"))

// FeaturePoolsQuery is a query on the feature_pool table
type FeaturePoolsQuery = *psql.ViewQuery[*FeaturePool, FeaturePoolSlice]

// featurePoolR is where relationships are stored.
type featurePoolR struct {
	Feature                   *Feature            // feature_pool.feature_pool_feature_id_fkey
	ReviewTaskPools           ReviewTaskPoolSlice // review_task_pool.review_task_pool_feature_pool_fkey
	FeaturePoolFeatureSignals SignalSlice         // signal.signal_feature_pool_feature_id_fkey
}

func buildFeaturePoolColumns(alias string) featurePoolColumns {
	return featurePoolColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"feature_id", "condition", "depth_meters", "geometry",
		).WithParent("feature_pool"),
		tableAlias:  alias,
		FeatureID:   psql.Quote(alias, "feature_id"),
		Condition:   psql.Quote(alias, "condition"),
		DepthMeters: psql.Quote(alias, "depth_meters"),
		Geometry:    psql.Quote(alias, "geometry"),
	}
}

type featurePoolColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	FeatureID   psql.Expression
	Condition   psql.Expression
	DepthMeters psql.Expression
	Geometry    psql.Expression
}

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

func (featurePoolColumns) AliasedAs(alias string) featurePoolColumns {
	return buildFeaturePoolColumns(alias)
}

// FeaturePoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type FeaturePoolSetter struct {
	FeatureID   omit.Val[int32]                   `db:"feature_id,pk" `
	Condition   omit.Val[enums.Poolconditiontype] `db:"condition" `
	DepthMeters omitnull.Val[float64]             `db:"depth_meters" `
	Geometry    omitnull.Val[string]              `db:"geometry" `
}

func (s FeaturePoolSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.FeatureID.IsValue() {
		vals = append(vals, "feature_id")
	}
	if s.Condition.IsValue() {
		vals = append(vals, "condition")
	}
	if !s.DepthMeters.IsUnset() {
		vals = append(vals, "depth_meters")
	}
	if !s.Geometry.IsUnset() {
		vals = append(vals, "geometry")
	}
	return vals
}

func (s FeaturePoolSetter) Overwrite(t *FeaturePool) {
	if s.FeatureID.IsValue() {
		t.FeatureID = s.FeatureID.MustGet()
	}
	if s.Condition.IsValue() {
		t.Condition = s.Condition.MustGet()
	}
	if !s.DepthMeters.IsUnset() {
		t.DepthMeters = s.DepthMeters.MustGetNull()
	}
	if !s.Geometry.IsUnset() {
		t.Geometry = s.Geometry.MustGetNull()
	}
}

func (s *FeaturePoolSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return FeaturePools.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, 4)
		if s.FeatureID.IsValue() {
			vals[0] = psql.Arg(s.FeatureID.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

		if !s.DepthMeters.IsUnset() {
			vals[2] = psql.Arg(s.DepthMeters.MustGetNull())
		} else {
			vals[2] = psql.Raw("DEFAULT")
		}

		if !s.Geometry.IsUnset() {
			vals[3] = psql.Arg(s.Geometry.MustGetNull())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

	return exprs
}

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

	return FeaturePools.Query(
		sm.Where(FeaturePools.Columns.FeatureID.EQ(psql.Arg(FeatureIDPK))),
		sm.Columns(FeaturePools.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

func (o *FeaturePool) pkEQ() dialect.Expression {
	return psql.Quote("feature_pool", "feature_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 FeaturePool
func (o *FeaturePool) Update(ctx context.Context, exec bob.Executor, s *FeaturePoolSetter) error {
	v, err := FeaturePools.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 FeaturePool record with an executor
func (o *FeaturePool) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := FeaturePools.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("feature_pool", "feature_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 FeaturePoolSlice) copyMatchingRows(from ...*FeaturePool) {
	for i, old := range o {
		for _, new := range from {
			if new.FeatureID != old.FeatureID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// Feature starts a query for related objects on feature
func (o *FeaturePool) Feature(mods ...bob.Mod[*dialect.SelectQuery]) FeaturesQuery {
	return Features.Query(append(mods,
		sm.Where(Features.Columns.ID.EQ(psql.Arg(o.FeatureID))),
	)...)
}

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

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

// ReviewTaskPools starts a query for related objects on review_task_pool
func (o *FeaturePool) ReviewTaskPools(mods ...bob.Mod[*dialect.SelectQuery]) ReviewTaskPoolsQuery {
	return ReviewTaskPools.Query(append(mods,
		sm.Where(ReviewTaskPools.Columns.FeaturePoolID.EQ(psql.Arg(o.FeatureID))),
	)...)
}

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

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

// FeaturePoolFeatureSignals starts a query for related objects on signal
func (o *FeaturePool) FeaturePoolFeatureSignals(mods ...bob.Mod[*dialect.SelectQuery]) SignalsQuery {
	return Signals.Query(append(mods,
		sm.Where(Signals.Columns.FeaturePoolFeatureID.EQ(psql.Arg(o.FeatureID))),
	)...)
}

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

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

func attachFeaturePoolFeature0(ctx context.Context, exec bob.Executor, count int, featurePool0 *FeaturePool, feature1 *Feature) (*FeaturePool, error) {
	setter := &FeaturePoolSetter{
		FeatureID: omit.From(feature1.ID),
	}

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

	return featurePool0, nil
}

func (featurePool0 *FeaturePool) InsertFeature(ctx context.Context, exec bob.Executor, related *FeatureSetter) error {
	var err error

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

	_, err = attachFeaturePoolFeature0(ctx, exec, 1, featurePool0, feature1)
	if err != nil {
		return err
	}

	featurePool0.R.Feature = feature1

	feature1.R.FeaturePool = featurePool0

	return nil
}

func (featurePool0 *FeaturePool) AttachFeature(ctx context.Context, exec bob.Executor, feature1 *Feature) error {
	var err error

	_, err = attachFeaturePoolFeature0(ctx, exec, 1, featurePool0, feature1)
	if err != nil {
		return err
	}

	featurePool0.R.Feature = feature1

	feature1.R.FeaturePool = featurePool0

	return nil
}

func insertFeaturePoolReviewTaskPools0(ctx context.Context, exec bob.Executor, reviewTaskPools1 []*ReviewTaskPoolSetter, featurePool0 *FeaturePool) (ReviewTaskPoolSlice, error) {
	for i := range reviewTaskPools1 {
		reviewTaskPools1[i].FeaturePoolID = omit.From(featurePool0.FeatureID)
	}

	ret, err := ReviewTaskPools.Insert(bob.ToMods(reviewTaskPools1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertFeaturePoolReviewTaskPools0: %w", err)
	}

	return ret, nil
}

func attachFeaturePoolReviewTaskPools0(ctx context.Context, exec bob.Executor, count int, reviewTaskPools1 ReviewTaskPoolSlice, featurePool0 *FeaturePool) (ReviewTaskPoolSlice, error) {
	setter := &ReviewTaskPoolSetter{
		FeaturePoolID: omit.From(featurePool0.FeatureID),
	}

	err := reviewTaskPools1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachFeaturePoolReviewTaskPools0: %w", err)
	}

	return reviewTaskPools1, nil
}

func (featurePool0 *FeaturePool) InsertReviewTaskPools(ctx context.Context, exec bob.Executor, related ...*ReviewTaskPoolSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	reviewTaskPools1, err := insertFeaturePoolReviewTaskPools0(ctx, exec, related, featurePool0)
	if err != nil {
		return err
	}

	featurePool0.R.ReviewTaskPools = append(featurePool0.R.ReviewTaskPools, reviewTaskPools1...)

	for _, rel := range reviewTaskPools1 {
		rel.R.FeaturePool = featurePool0
	}
	return nil
}

func (featurePool0 *FeaturePool) AttachReviewTaskPools(ctx context.Context, exec bob.Executor, related ...*ReviewTaskPool) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	reviewTaskPools1 := ReviewTaskPoolSlice(related)

	_, err = attachFeaturePoolReviewTaskPools0(ctx, exec, len(related), reviewTaskPools1, featurePool0)
	if err != nil {
		return err
	}

	featurePool0.R.ReviewTaskPools = append(featurePool0.R.ReviewTaskPools, reviewTaskPools1...)

	for _, rel := range related {
		rel.R.FeaturePool = featurePool0
	}

	return nil
}

func insertFeaturePoolFeaturePoolFeatureSignals0(ctx context.Context, exec bob.Executor, signals1 []*SignalSetter, featurePool0 *FeaturePool) (SignalSlice, error) {
	for i := range signals1 {
		signals1[i].FeaturePoolFeatureID = omitnull.From(featurePool0.FeatureID)
	}

	ret, err := Signals.Insert(bob.ToMods(signals1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertFeaturePoolFeaturePoolFeatureSignals0: %w", err)
	}

	return ret, nil
}

func attachFeaturePoolFeaturePoolFeatureSignals0(ctx context.Context, exec bob.Executor, count int, signals1 SignalSlice, featurePool0 *FeaturePool) (SignalSlice, error) {
	setter := &SignalSetter{
		FeaturePoolFeatureID: omitnull.From(featurePool0.FeatureID),
	}

	err := signals1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachFeaturePoolFeaturePoolFeatureSignals0: %w", err)
	}

	return signals1, nil
}

func (featurePool0 *FeaturePool) InsertFeaturePoolFeatureSignals(ctx context.Context, exec bob.Executor, related ...*SignalSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	signals1, err := insertFeaturePoolFeaturePoolFeatureSignals0(ctx, exec, related, featurePool0)
	if err != nil {
		return err
	}

	featurePool0.R.FeaturePoolFeatureSignals = append(featurePool0.R.FeaturePoolFeatureSignals, signals1...)

	for _, rel := range signals1 {
		rel.R.FeaturePoolFeatureFeaturePool = featurePool0
	}
	return nil
}

func (featurePool0 *FeaturePool) AttachFeaturePoolFeatureSignals(ctx context.Context, exec bob.Executor, related ...*Signal) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	signals1 := SignalSlice(related)

	_, err = attachFeaturePoolFeaturePoolFeatureSignals0(ctx, exec, len(related), signals1, featurePool0)
	if err != nil {
		return err
	}

	featurePool0.R.FeaturePoolFeatureSignals = append(featurePool0.R.FeaturePoolFeatureSignals, signals1...)

	for _, rel := range related {
		rel.R.FeaturePoolFeatureFeaturePool = featurePool0
	}

	return nil
}

type featurePoolWhere[Q psql.Filterable] struct {
	FeatureID   psql.WhereMod[Q, int32]
	Condition   psql.WhereMod[Q, enums.Poolconditiontype]
	DepthMeters psql.WhereNullMod[Q, float64]
	Geometry    psql.WhereNullMod[Q, string]
}

func (featurePoolWhere[Q]) AliasedAs(alias string) featurePoolWhere[Q] {
	return buildFeaturePoolWhere[Q](buildFeaturePoolColumns(alias))
}

func buildFeaturePoolWhere[Q psql.Filterable](cols featurePoolColumns) featurePoolWhere[Q] {
	return featurePoolWhere[Q]{
		FeatureID:   psql.Where[Q, int32](cols.FeatureID),
		Condition:   psql.Where[Q, enums.Poolconditiontype](cols.Condition),
		DepthMeters: psql.WhereNull[Q, float64](cols.DepthMeters),
		Geometry:    psql.WhereNull[Q, string](cols.Geometry),
	}
}

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

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

		o.R.Feature = rel

		if rel != nil {
			rel.R.FeaturePool = o
		}
		return nil
	case "ReviewTaskPools":
		rels, ok := retrieved.(ReviewTaskPoolSlice)
		if !ok {
			return fmt.Errorf("featurePool cannot load %T as %q", retrieved, name)
		}

		o.R.ReviewTaskPools = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.FeaturePool = o
			}
		}
		return nil
	case "FeaturePoolFeatureSignals":
		rels, ok := retrieved.(SignalSlice)
		if !ok {
			return fmt.Errorf("featurePool cannot load %T as %q", retrieved, name)
		}

		o.R.FeaturePoolFeatureSignals = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.FeaturePoolFeatureFeaturePool = o
			}
		}
		return nil
	default:
		return fmt.Errorf("featurePool has no relationship %q", name)
	}
}

type featurePoolPreloader struct {
	Feature func(...psql.PreloadOption) psql.Preloader
}

func buildFeaturePoolPreloader() featurePoolPreloader {
	return featurePoolPreloader{
		Feature: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Feature, FeatureSlice](psql.PreloadRel{
				Name: "Feature",
				Sides: []psql.PreloadSide{
					{
						From:        FeaturePools,
						To:          Features,
						FromColumns: []string{"feature_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Features.Columns.Names(), opts...)
		},
	}
}

type featurePoolThenLoader[Q orm.Loadable] struct {
	Feature                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReviewTaskPools           func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	FeaturePoolFeatureSignals func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildFeaturePoolThenLoader[Q orm.Loadable]() featurePoolThenLoader[Q] {
	type FeatureLoadInterface interface {
		LoadFeature(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReviewTaskPoolsLoadInterface interface {
		LoadReviewTaskPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FeaturePoolFeatureSignalsLoadInterface interface {
		LoadFeaturePoolFeatureSignals(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return featurePoolThenLoader[Q]{
		Feature: thenLoadBuilder[Q](
			"Feature",
			func(ctx context.Context, exec bob.Executor, retrieved FeatureLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeature(ctx, exec, mods...)
			},
		),
		ReviewTaskPools: thenLoadBuilder[Q](
			"ReviewTaskPools",
			func(ctx context.Context, exec bob.Executor, retrieved ReviewTaskPoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReviewTaskPools(ctx, exec, mods...)
			},
		),
		FeaturePoolFeatureSignals: thenLoadBuilder[Q](
			"FeaturePoolFeatureSignals",
			func(ctx context.Context, exec bob.Executor, retrieved FeaturePoolFeatureSignalsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeaturePoolFeatureSignals(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.FeaturePool = o

	o.R.Feature = related
	return nil
}

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

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

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

		for _, rel := range features {

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

			rel.R.FeaturePool = o

			o.R.Feature = rel
			break
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.FeaturePool = o
	}

	o.R.ReviewTaskPools = related
	return nil
}

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

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

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

		o.R.ReviewTaskPools = nil
	}

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

		for _, rel := range reviewTaskPools {

			if !(o.FeatureID == rel.FeaturePoolID) {
				continue
			}

			rel.R.FeaturePool = o

			o.R.ReviewTaskPools = append(o.R.ReviewTaskPools, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.FeaturePoolFeatureFeaturePool = o
	}

	o.R.FeaturePoolFeatureSignals = related
	return nil
}

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

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

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

		o.R.FeaturePoolFeatureSignals = nil
	}

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

		for _, rel := range signals {

			if !rel.FeaturePoolFeatureID.IsValue() {
				continue
			}
			if !(rel.FeaturePoolFeatureID.IsValue() && o.FeatureID == rel.FeaturePoolFeatureID.MustGet()) {
				continue
			}

			rel.R.FeaturePoolFeatureFeaturePool = o

			o.R.FeaturePoolFeatureSignals = append(o.R.FeaturePoolFeatureSignals, rel)
		}
	}

	return nil
}
