// 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/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// Feature is an object representing the database table.
type Feature struct {
	Created        time.Time        `db:"created" `
	CreatorID      int32            `db:"creator_id" `
	ID             int32            `db:"id,pk" `
	OrganizationID int32            `db:"organization_id" `
	SiteID         int32            `db:"site_id" `
	Location       null.Val[string] `db:"location" `

	R featureR `db:"-" `
}

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

// Features contains methods to work with the feature table
var Features = psql.NewTablex[*Feature, FeatureSlice, *FeatureSetter]("", "feature", buildFeatureColumns("feature"))

// FeaturesQuery is a query on the feature table
type FeaturesQuery = *psql.ViewQuery[*Feature, FeatureSlice]

// featureR is where relationships are stored.
type featureR struct {
	CreatorUser  *User         // feature.feature_creator_id_fkey
	Organization *Organization // feature.feature_organization_id_fkey
	Site         *Site         // feature.feature_site_id_fkey
	FeaturePool  *FeaturePool  // feature_pool.feature_pool_feature_id_fkey
}

func buildFeatureColumns(alias string) featureColumns {
	return featureColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator_id", "id", "organization_id", "site_id", "location",
		).WithParent("feature"),
		tableAlias:     alias,
		Created:        psql.Quote(alias, "created"),
		CreatorID:      psql.Quote(alias, "creator_id"),
		ID:             psql.Quote(alias, "id"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		SiteID:         psql.Quote(alias, "site_id"),
		Location:       psql.Quote(alias, "location"),
	}
}

type featureColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Created        psql.Expression
	CreatorID      psql.Expression
	ID             psql.Expression
	OrganizationID psql.Expression
	SiteID         psql.Expression
	Location       psql.Expression
}

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

func (featureColumns) AliasedAs(alias string) featureColumns {
	return buildFeatureColumns(alias)
}

// FeatureSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type FeatureSetter struct {
	Created        omit.Val[time.Time]  `db:"created" `
	CreatorID      omit.Val[int32]      `db:"creator_id" `
	ID             omit.Val[int32]      `db:"id,pk" `
	OrganizationID omit.Val[int32]      `db:"organization_id" `
	SiteID         omit.Val[int32]      `db:"site_id" `
	Location       omitnull.Val[string] `db:"location" `
}

func (s FeatureSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	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.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.SiteID.IsValue() {
		vals = append(vals, "site_id")
	}
	if !s.Location.IsUnset() {
		vals = append(vals, "location")
	}
	return vals
}

func (s FeatureSetter) Overwrite(t *Feature) {
	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.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.SiteID.IsValue() {
		t.SiteID = s.SiteID.MustGet()
	}
	if !s.Location.IsUnset() {
		t.Location = s.Location.MustGetNull()
	}
}

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

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

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

		if s.OrganizationID.IsValue() {
			vals[3] = psql.Arg(s.OrganizationID.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.Location.IsUnset() {
			vals[5] = psql.Arg(s.Location.MustGetNull())
		} else {
			vals[5] = psql.Raw("DEFAULT")
		}

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

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

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

	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.OrganizationID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "organization_id")...),
			psql.Arg(s.OrganizationID),
		}})
	}

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := Features.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 *Feature) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.CreatorID))),
	)...)
}

func (os FeatureSlice) 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)),
	)...)
}

// Organization starts a query for related objects on organization
func (o *Feature) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

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

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

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

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

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

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

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

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

func attachFeatureCreatorUser0(ctx context.Context, exec bob.Executor, count int, feature0 *Feature, user1 *User) (*Feature, error) {
	setter := &FeatureSetter{
		CreatorID: omit.From(user1.ID),
	}

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

	return feature0, nil
}

func (feature0 *Feature) 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 = attachFeatureCreatorUser0(ctx, exec, 1, feature0, user1)
	if err != nil {
		return err
	}

	feature0.R.CreatorUser = user1

	user1.R.CreatorFeatures = append(user1.R.CreatorFeatures, feature0)

	return nil
}

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

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

	feature0.R.CreatorUser = user1

	user1.R.CreatorFeatures = append(user1.R.CreatorFeatures, feature0)

	return nil
}

func attachFeatureOrganization0(ctx context.Context, exec bob.Executor, count int, feature0 *Feature, organization1 *Organization) (*Feature, error) {
	setter := &FeatureSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return feature0, nil
}

func (feature0 *Feature) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error {
	var err error

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

	_, err = attachFeatureOrganization0(ctx, exec, 1, feature0, organization1)
	if err != nil {
		return err
	}

	feature0.R.Organization = organization1

	organization1.R.Features = append(organization1.R.Features, feature0)

	return nil
}

func (feature0 *Feature) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error {
	var err error

	_, err = attachFeatureOrganization0(ctx, exec, 1, feature0, organization1)
	if err != nil {
		return err
	}

	feature0.R.Organization = organization1

	organization1.R.Features = append(organization1.R.Features, feature0)

	return nil
}

func attachFeatureSite0(ctx context.Context, exec bob.Executor, count int, feature0 *Feature, site1 *Site) (*Feature, error) {
	setter := &FeatureSetter{
		SiteID: omit.From(site1.ID),
	}

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

	return feature0, nil
}

func (feature0 *Feature) 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 = attachFeatureSite0(ctx, exec, 1, feature0, site1)
	if err != nil {
		return err
	}

	feature0.R.Site = site1

	site1.R.Features = append(site1.R.Features, feature0)

	return nil
}

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

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

	feature0.R.Site = site1

	site1.R.Features = append(site1.R.Features, feature0)

	return nil
}

func insertFeatureFeaturePool0(ctx context.Context, exec bob.Executor, featurePool1 *FeaturePoolSetter, feature0 *Feature) (*FeaturePool, error) {
	featurePool1.FeatureID = omit.From(feature0.ID)

	ret, err := FeaturePools.Insert(featurePool1).One(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertFeatureFeaturePool0: %w", err)
	}

	return ret, nil
}

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

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

	return featurePool1, nil
}

func (feature0 *Feature) InsertFeaturePool(ctx context.Context, exec bob.Executor, related *FeaturePoolSetter) error {
	var err error

	featurePool1, err := insertFeatureFeaturePool0(ctx, exec, related, feature0)
	if err != nil {
		return err
	}

	feature0.R.FeaturePool = featurePool1

	featurePool1.R.Feature = feature0

	return nil
}

func (feature0 *Feature) AttachFeaturePool(ctx context.Context, exec bob.Executor, featurePool1 *FeaturePool) error {
	var err error

	_, err = attachFeatureFeaturePool0(ctx, exec, 1, featurePool1, feature0)
	if err != nil {
		return err
	}

	feature0.R.FeaturePool = featurePool1

	featurePool1.R.Feature = feature0

	return nil
}

type featureWhere[Q psql.Filterable] struct {
	Created        psql.WhereMod[Q, time.Time]
	CreatorID      psql.WhereMod[Q, int32]
	ID             psql.WhereMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
	SiteID         psql.WhereMod[Q, int32]
	Location       psql.WhereNullMod[Q, string]
}

func (featureWhere[Q]) AliasedAs(alias string) featureWhere[Q] {
	return buildFeatureWhere[Q](buildFeatureColumns(alias))
}

func buildFeatureWhere[Q psql.Filterable](cols featureColumns) featureWhere[Q] {
	return featureWhere[Q]{
		Created:        psql.Where[Q, time.Time](cols.Created),
		CreatorID:      psql.Where[Q, int32](cols.CreatorID),
		ID:             psql.Where[Q, int32](cols.ID),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		SiteID:         psql.Where[Q, int32](cols.SiteID),
		Location:       psql.WhereNull[Q, string](cols.Location),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorFeatures = FeatureSlice{o}
		}
		return nil
	case "Organization":
		rel, ok := retrieved.(*Organization)
		if !ok {
			return fmt.Errorf("feature cannot load %T as %q", retrieved, name)
		}

		o.R.Organization = rel

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

		o.R.Site = rel

		if rel != nil {
			rel.R.Features = FeatureSlice{o}
		}
		return nil
	case "FeaturePool":
		rel, ok := retrieved.(*FeaturePool)
		if !ok {
			return fmt.Errorf("feature cannot load %T as %q", retrieved, name)
		}

		o.R.FeaturePool = rel

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

type featurePreloader struct {
	CreatorUser  func(...psql.PreloadOption) psql.Preloader
	Organization func(...psql.PreloadOption) psql.Preloader
	Site         func(...psql.PreloadOption) psql.Preloader
	FeaturePool  func(...psql.PreloadOption) psql.Preloader
}

func buildFeaturePreloader() featurePreloader {
	return featurePreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Features,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        Features,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Features,
						To:          Sites,
						FromColumns: []string{"site_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
		FeaturePool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FeaturePool, FeaturePoolSlice](psql.PreloadRel{
				Name: "FeaturePool",
				Sides: []psql.PreloadSide{
					{
						From:        Features,
						To:          FeaturePools,
						FromColumns: []string{"id"},
						ToColumns:   []string{"feature_id"},
					},
				},
			}, FeaturePools.Columns.Names(), opts...)
		},
	}
}

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

func buildFeatureThenLoader[Q orm.Loadable]() featureThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FeaturePoolLoadInterface interface {
		LoadFeaturePool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return featureThenLoader[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...)
			},
		),
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(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...)
			},
		),
		FeaturePool: thenLoadBuilder[Q](
			"FeaturePool",
			func(ctx context.Context, exec bob.Executor, retrieved FeaturePoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeaturePool(ctx, exec, mods...)
			},
		),
	}
}

// LoadCreatorUser loads the feature's CreatorUser into the .R struct
func (o *Feature) 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.CreatorFeatures = FeatureSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the feature's CreatorUser into the .R struct
func (os FeatureSlice) 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.CreatorFeatures = append(rel.R.CreatorFeatures, o)

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Features = FeatureSlice{o}

	o.R.Organization = related
	return nil
}

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

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

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

		for _, rel := range organizations {

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

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

// LoadSite loads the feature's Site into the .R struct
func (o *Feature) 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.Features = FeatureSlice{o}

	o.R.Site = related
	return nil
}

// LoadSite loads the feature's Site into the .R struct
func (os FeatureSlice) 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
			}

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

			o.R.Site = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Feature = o

	o.R.FeaturePool = related
	return nil
}

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

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

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

		for _, rel := range featurePools {

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

			rel.R.Feature = o

			o.R.FeaturePool = rel
			break
		}
	}

	return nil
}
