// 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"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// Signal is an object representing the database table.
type Signal struct {
	Addressed            null.Val[time.Time]             `db:"addressed" `
	Addressor            null.Val[int32]                 `db:"addressor" `
	Created              time.Time                       `db:"created" `
	Creator              int32                           `db:"creator" `
	ID                   int32                           `db:"id,pk" `
	OrganizationID       int32                           `db:"organization_id" `
	Species              null.Val[enums.Mosquitospecies] `db:"species" `
	Type                 enums.Signaltype                `db:"type_" `
	SiteID               null.Val[int32]                 `db:"site_id" `
	Location             string                          `db:"location" `
	FeaturePoolFeatureID null.Val[int32]                 `db:"feature_pool_feature_id" `
	ReportID             null.Val[int32]                 `db:"report_id" `

	R signalR `db:"-" `
}

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

// Signals contains methods to work with the signal table
var Signals = psql.NewTablex[*Signal, SignalSlice, *SignalSetter]("", "signal", buildSignalColumns("signal"))

// SignalsQuery is a query on the signal table
type SignalsQuery = *psql.ViewQuery[*Signal, SignalSlice]

// signalR is where relationships are stored.
type signalR struct {
	AddressorUser                 *User               // signal.signal_addressor_fkey
	CreatorUser                   *User               // signal.signal_creator_fkey
	FeaturePoolFeatureFeaturePool *FeaturePool        // signal.signal_feature_pool_feature_id_fkey
	Organization                  *Organization       // signal.signal_organization_id_fkey
	Report                        *PublicreportReport // signal.signal_report_id_fkey
	Site                          *Site               // signal.signal_site_id_fkey
}

func buildSignalColumns(alias string) signalColumns {
	return signalColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"addressed", "addressor", "created", "creator", "id", "organization_id", "species", "type_", "site_id", "location", "feature_pool_feature_id", "report_id",
		).WithParent("signal"),
		tableAlias:           alias,
		Addressed:            psql.Quote(alias, "addressed"),
		Addressor:            psql.Quote(alias, "addressor"),
		Created:              psql.Quote(alias, "created"),
		Creator:              psql.Quote(alias, "creator"),
		ID:                   psql.Quote(alias, "id"),
		OrganizationID:       psql.Quote(alias, "organization_id"),
		Species:              psql.Quote(alias, "species"),
		Type:                 psql.Quote(alias, "type_"),
		SiteID:               psql.Quote(alias, "site_id"),
		Location:             psql.Quote(alias, "location"),
		FeaturePoolFeatureID: psql.Quote(alias, "feature_pool_feature_id"),
		ReportID:             psql.Quote(alias, "report_id"),
	}
}

type signalColumns struct {
	expr.ColumnsExpr
	tableAlias           string
	Addressed            psql.Expression
	Addressor            psql.Expression
	Created              psql.Expression
	Creator              psql.Expression
	ID                   psql.Expression
	OrganizationID       psql.Expression
	Species              psql.Expression
	Type                 psql.Expression
	SiteID               psql.Expression
	Location             psql.Expression
	FeaturePoolFeatureID psql.Expression
	ReportID             psql.Expression
}

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

func (signalColumns) AliasedAs(alias string) signalColumns {
	return buildSignalColumns(alias)
}

// SignalSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type SignalSetter struct {
	Addressed            omitnull.Val[time.Time]             `db:"addressed" `
	Addressor            omitnull.Val[int32]                 `db:"addressor" `
	Created              omit.Val[time.Time]                 `db:"created" `
	Creator              omit.Val[int32]                     `db:"creator" `
	ID                   omit.Val[int32]                     `db:"id,pk" `
	OrganizationID       omit.Val[int32]                     `db:"organization_id" `
	Species              omitnull.Val[enums.Mosquitospecies] `db:"species" `
	Type                 omit.Val[enums.Signaltype]          `db:"type_" `
	SiteID               omitnull.Val[int32]                 `db:"site_id" `
	Location             omit.Val[string]                    `db:"location" `
	FeaturePoolFeatureID omitnull.Val[int32]                 `db:"feature_pool_feature_id" `
	ReportID             omitnull.Val[int32]                 `db:"report_id" `
}

func (s SignalSetter) SetColumns() []string {
	vals := make([]string, 0, 12)
	if !s.Addressed.IsUnset() {
		vals = append(vals, "addressed")
	}
	if !s.Addressor.IsUnset() {
		vals = append(vals, "addressor")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Creator.IsValue() {
		vals = append(vals, "creator")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if !s.Species.IsUnset() {
		vals = append(vals, "species")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	if !s.SiteID.IsUnset() {
		vals = append(vals, "site_id")
	}
	if s.Location.IsValue() {
		vals = append(vals, "location")
	}
	if !s.FeaturePoolFeatureID.IsUnset() {
		vals = append(vals, "feature_pool_feature_id")
	}
	if !s.ReportID.IsUnset() {
		vals = append(vals, "report_id")
	}
	return vals
}

func (s SignalSetter) Overwrite(t *Signal) {
	if !s.Addressed.IsUnset() {
		t.Addressed = s.Addressed.MustGetNull()
	}
	if !s.Addressor.IsUnset() {
		t.Addressor = s.Addressor.MustGetNull()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Creator.IsValue() {
		t.Creator = s.Creator.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if !s.Species.IsUnset() {
		t.Species = s.Species.MustGetNull()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
	if !s.SiteID.IsUnset() {
		t.SiteID = s.SiteID.MustGetNull()
	}
	if s.Location.IsValue() {
		t.Location = s.Location.MustGet()
	}
	if !s.FeaturePoolFeatureID.IsUnset() {
		t.FeaturePoolFeatureID = s.FeaturePoolFeatureID.MustGetNull()
	}
	if !s.ReportID.IsUnset() {
		t.ReportID = s.ReportID.MustGetNull()
	}
}

func (s *SignalSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return Signals.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, 12)
		if !s.Addressed.IsUnset() {
			vals[0] = psql.Arg(s.Addressed.MustGetNull())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

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

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

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

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

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

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

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

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

// Report starts a query for related objects on publicreport.report
func (o *Signal) Report(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportsQuery {
	return PublicreportReports.Query(append(mods,
		sm.Where(PublicreportReports.Columns.ID.EQ(psql.Arg(o.ReportID))),
	)...)
}

func (os SignalSlice) Report(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportsQuery {
	pkReportID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkReportID = append(pkReportID, o.ReportID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkReportID), "integer[]")),
	))

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

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

func (os SignalSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	pkSiteID := make(pgtypes.Array[null.Val[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)),
	)...)
}

func attachSignalAddressorUser0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, user1 *User) (*Signal, error) {
	setter := &SignalSetter{
		Addressor: omitnull.From(user1.ID),
	}

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

	return signal0, nil
}

func (signal0 *Signal) InsertAddressorUser(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 = attachSignalAddressorUser0(ctx, exec, 1, signal0, user1)
	if err != nil {
		return err
	}

	signal0.R.AddressorUser = user1

	user1.R.AddressorSignals = append(user1.R.AddressorSignals, signal0)

	return nil
}

func (signal0 *Signal) AttachAddressorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

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

	signal0.R.AddressorUser = user1

	user1.R.AddressorSignals = append(user1.R.AddressorSignals, signal0)

	return nil
}

func attachSignalCreatorUser0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, user1 *User) (*Signal, error) {
	setter := &SignalSetter{
		Creator: omit.From(user1.ID),
	}

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

	return signal0, nil
}

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

	signal0.R.CreatorUser = user1

	user1.R.CreatorSignals = append(user1.R.CreatorSignals, signal0)

	return nil
}

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

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

	signal0.R.CreatorUser = user1

	user1.R.CreatorSignals = append(user1.R.CreatorSignals, signal0)

	return nil
}

func attachSignalFeaturePoolFeatureFeaturePool0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, featurePool1 *FeaturePool) (*Signal, error) {
	setter := &SignalSetter{
		FeaturePoolFeatureID: omitnull.From(featurePool1.FeatureID),
	}

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

	return signal0, nil
}

func (signal0 *Signal) InsertFeaturePoolFeatureFeaturePool(ctx context.Context, exec bob.Executor, related *FeaturePoolSetter) error {
	var err error

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

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

	signal0.R.FeaturePoolFeatureFeaturePool = featurePool1

	featurePool1.R.FeaturePoolFeatureSignals = append(featurePool1.R.FeaturePoolFeatureSignals, signal0)

	return nil
}

func (signal0 *Signal) AttachFeaturePoolFeatureFeaturePool(ctx context.Context, exec bob.Executor, featurePool1 *FeaturePool) error {
	var err error

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

	signal0.R.FeaturePoolFeatureFeaturePool = featurePool1

	featurePool1.R.FeaturePoolFeatureSignals = append(featurePool1.R.FeaturePoolFeatureSignals, signal0)

	return nil
}

func attachSignalOrganization0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, organization1 *Organization) (*Signal, error) {
	setter := &SignalSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return signal0, nil
}

func (signal0 *Signal) 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 = attachSignalOrganization0(ctx, exec, 1, signal0, organization1)
	if err != nil {
		return err
	}

	signal0.R.Organization = organization1

	organization1.R.Signals = append(organization1.R.Signals, signal0)

	return nil
}

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

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

	signal0.R.Organization = organization1

	organization1.R.Signals = append(organization1.R.Signals, signal0)

	return nil
}

func attachSignalReport0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, publicreportReport1 *PublicreportReport) (*Signal, error) {
	setter := &SignalSetter{
		ReportID: omitnull.From(publicreportReport1.ID),
	}

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

	return signal0, nil
}

func (signal0 *Signal) InsertReport(ctx context.Context, exec bob.Executor, related *PublicreportReportSetter) error {
	var err error

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

	_, err = attachSignalReport0(ctx, exec, 1, signal0, publicreportReport1)
	if err != nil {
		return err
	}

	signal0.R.Report = publicreportReport1

	publicreportReport1.R.Signals = append(publicreportReport1.R.Signals, signal0)

	return nil
}

func (signal0 *Signal) AttachReport(ctx context.Context, exec bob.Executor, publicreportReport1 *PublicreportReport) error {
	var err error

	_, err = attachSignalReport0(ctx, exec, 1, signal0, publicreportReport1)
	if err != nil {
		return err
	}

	signal0.R.Report = publicreportReport1

	publicreportReport1.R.Signals = append(publicreportReport1.R.Signals, signal0)

	return nil
}

func attachSignalSite0(ctx context.Context, exec bob.Executor, count int, signal0 *Signal, site1 *Site) (*Signal, error) {
	setter := &SignalSetter{
		SiteID: omitnull.From(site1.ID),
	}

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

	return signal0, nil
}

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

	signal0.R.Site = site1

	site1.R.Signals = append(site1.R.Signals, signal0)

	return nil
}

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

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

	signal0.R.Site = site1

	site1.R.Signals = append(site1.R.Signals, signal0)

	return nil
}

type signalWhere[Q psql.Filterable] struct {
	Addressed            psql.WhereNullMod[Q, time.Time]
	Addressor            psql.WhereNullMod[Q, int32]
	Created              psql.WhereMod[Q, time.Time]
	Creator              psql.WhereMod[Q, int32]
	ID                   psql.WhereMod[Q, int32]
	OrganizationID       psql.WhereMod[Q, int32]
	Species              psql.WhereNullMod[Q, enums.Mosquitospecies]
	Type                 psql.WhereMod[Q, enums.Signaltype]
	SiteID               psql.WhereNullMod[Q, int32]
	Location             psql.WhereMod[Q, string]
	FeaturePoolFeatureID psql.WhereNullMod[Q, int32]
	ReportID             psql.WhereNullMod[Q, int32]
}

func (signalWhere[Q]) AliasedAs(alias string) signalWhere[Q] {
	return buildSignalWhere[Q](buildSignalColumns(alias))
}

func buildSignalWhere[Q psql.Filterable](cols signalColumns) signalWhere[Q] {
	return signalWhere[Q]{
		Addressed:            psql.WhereNull[Q, time.Time](cols.Addressed),
		Addressor:            psql.WhereNull[Q, int32](cols.Addressor),
		Created:              psql.Where[Q, time.Time](cols.Created),
		Creator:              psql.Where[Q, int32](cols.Creator),
		ID:                   psql.Where[Q, int32](cols.ID),
		OrganizationID:       psql.Where[Q, int32](cols.OrganizationID),
		Species:              psql.WhereNull[Q, enums.Mosquitospecies](cols.Species),
		Type:                 psql.Where[Q, enums.Signaltype](cols.Type),
		SiteID:               psql.WhereNull[Q, int32](cols.SiteID),
		Location:             psql.Where[Q, string](cols.Location),
		FeaturePoolFeatureID: psql.WhereNull[Q, int32](cols.FeaturePoolFeatureID),
		ReportID:             psql.WhereNull[Q, int32](cols.ReportID),
	}
}

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

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

		o.R.AddressorUser = rel

		if rel != nil {
			rel.R.AddressorSignals = SignalSlice{o}
		}
		return nil
	case "CreatorUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("signal cannot load %T as %q", retrieved, name)
		}

		o.R.CreatorUser = rel

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

		o.R.FeaturePoolFeatureFeaturePool = rel

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

		o.R.Organization = rel

		if rel != nil {
			rel.R.Signals = SignalSlice{o}
		}
		return nil
	case "Report":
		rel, ok := retrieved.(*PublicreportReport)
		if !ok {
			return fmt.Errorf("signal cannot load %T as %q", retrieved, name)
		}

		o.R.Report = rel

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

		o.R.Site = rel

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

type signalPreloader struct {
	AddressorUser                 func(...psql.PreloadOption) psql.Preloader
	CreatorUser                   func(...psql.PreloadOption) psql.Preloader
	FeaturePoolFeatureFeaturePool func(...psql.PreloadOption) psql.Preloader
	Organization                  func(...psql.PreloadOption) psql.Preloader
	Report                        func(...psql.PreloadOption) psql.Preloader
	Site                          func(...psql.PreloadOption) psql.Preloader
}

func buildSignalPreloader() signalPreloader {
	return signalPreloader{
		AddressorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "AddressorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          Users,
						FromColumns: []string{"addressor"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          Users,
						FromColumns: []string{"creator"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		FeaturePoolFeatureFeaturePool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FeaturePool, FeaturePoolSlice](psql.PreloadRel{
				Name: "FeaturePoolFeatureFeaturePool",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          FeaturePools,
						FromColumns: []string{"feature_pool_feature_id"},
						ToColumns:   []string{"feature_id"},
					},
				},
			}, FeaturePools.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		Report: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "Report",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          PublicreportReports,
						FromColumns: []string{"report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Signals,
						To:          Sites,
						FromColumns: []string{"site_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type signalThenLoader[Q orm.Loadable] struct {
	AddressorUser                 func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	CreatorUser                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	FeaturePoolFeatureFeaturePool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organization                  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Report                        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site                          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildSignalThenLoader[Q orm.Loadable]() signalThenLoader[Q] {
	type AddressorUserLoadInterface interface {
		LoadAddressorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FeaturePoolFeatureFeaturePoolLoadInterface interface {
		LoadFeaturePoolFeatureFeaturePool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLoadInterface interface {
		LoadReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return signalThenLoader[Q]{
		AddressorUser: thenLoadBuilder[Q](
			"AddressorUser",
			func(ctx context.Context, exec bob.Executor, retrieved AddressorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAddressorUser(ctx, exec, mods...)
			},
		),
		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...)
			},
		),
		FeaturePoolFeatureFeaturePool: thenLoadBuilder[Q](
			"FeaturePoolFeatureFeaturePool",
			func(ctx context.Context, exec bob.Executor, retrieved FeaturePoolFeatureFeaturePoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeaturePoolFeatureFeaturePool(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...)
			},
		),
		Report: thenLoadBuilder[Q](
			"Report",
			func(ctx context.Context, exec bob.Executor, retrieved ReportLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReport(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...)
			},
		),
	}
}

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

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

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

	related.R.AddressorSignals = SignalSlice{o}

	o.R.AddressorUser = related
	return nil
}

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

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

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

		for _, rel := range users {
			if !o.Addressor.IsValue() {
				continue
			}

			if !(o.Addressor.IsValue() && o.Addressor.MustGet() == rel.ID) {
				continue
			}

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

			o.R.AddressorUser = rel
			break
		}
	}

	return nil
}

// LoadCreatorUser loads the signal's CreatorUser into the .R struct
func (o *Signal) 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.CreatorSignals = SignalSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the signal's CreatorUser into the .R struct
func (os SignalSlice) 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.Creator == rel.ID) {
				continue
			}

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.FeaturePoolFeatureSignals = SignalSlice{o}

	o.R.FeaturePoolFeatureFeaturePool = related
	return nil
}

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

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

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

		for _, rel := range featurePools {
			if !o.FeaturePoolFeatureID.IsValue() {
				continue
			}

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

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

			o.R.FeaturePoolFeatureFeaturePool = rel
			break
		}
	}

	return nil
}

// LoadOrganization loads the signal's Organization into the .R struct
func (o *Signal) 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.Signals = SignalSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the signal's Organization into the .R struct
func (os SignalSlice) 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.Signals = append(rel.R.Signals, o)

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Signals = SignalSlice{o}

	o.R.Report = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {
			if !o.ReportID.IsValue() {
				continue
			}

			if !(o.ReportID.IsValue() && o.ReportID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.Report = rel
			break
		}
	}

	return nil
}

// LoadSite loads the signal's Site into the .R struct
func (o *Signal) 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.Signals = SignalSlice{o}

	o.R.Site = related
	return nil
}

// LoadSite loads the signal's Site into the .R struct
func (os SignalSlice) 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.IsValue() {
				continue
			}

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

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

			o.R.Site = rel
			break
		}
	}

	return nil
}
