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

// Site is an object representing the database table.
type Site struct {
	AddressID      int32            `db:"address_id" `
	Created        time.Time        `db:"created" `
	CreatorID      int32            `db:"creator_id" `
	FileID         null.Val[int32]  `db:"file_id" `
	ID             int32            `db:"id,pk" `
	Notes          string           `db:"notes" `
	OrganizationID int32            `db:"organization_id" `
	OwnerName      string           `db:"owner_name" `
	OwnerPhoneE164 null.Val[string] `db:"owner_phone_e164" `
	ParcelID       null.Val[int32]  `db:"parcel_id" `
	ResidentOwned  null.Val[bool]   `db:"resident_owned" `
	Tags           pgtypes.HStore   `db:"tags" `
	Version        int32            `db:"version" `

	R siteR `db:"-" `
}

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

// Sites contains methods to work with the site table
var Sites = psql.NewTablex[*Site, SiteSlice, *SiteSetter]("", "site", buildSiteColumns("site"))

// SitesQuery is a query on the site table
type SitesQuery = *psql.ViewQuery[*Site, SiteSlice]

// siteR is where relationships are stored.
type siteR struct {
	Features    FeatureSlice    // feature.feature_site_id_fkey
	Leads       LeadSlice       // lead.lead_site_id_fkey
	Residents   ResidentSlice   // resident.resident_site_id_fkey
	Signals     SignalSlice     // signal.signal_site_id_fkey
	Address     *Address        // site.site_address_id_fkey
	CreatorUser *User           // site.site_creator_id_fkey
	File        *FileuploadFile // site.site_file_id_fkey
	Parcel      *Parcel         // site.site_parcel_id_fkey
}

func buildSiteColumns(alias string) siteColumns {
	return siteColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"address_id", "created", "creator_id", "file_id", "id", "notes", "organization_id", "owner_name", "owner_phone_e164", "parcel_id", "resident_owned", "tags", "version",
		).WithParent("site"),
		tableAlias:     alias,
		AddressID:      psql.Quote(alias, "address_id"),
		Created:        psql.Quote(alias, "created"),
		CreatorID:      psql.Quote(alias, "creator_id"),
		FileID:         psql.Quote(alias, "file_id"),
		ID:             psql.Quote(alias, "id"),
		Notes:          psql.Quote(alias, "notes"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		OwnerName:      psql.Quote(alias, "owner_name"),
		OwnerPhoneE164: psql.Quote(alias, "owner_phone_e164"),
		ParcelID:       psql.Quote(alias, "parcel_id"),
		ResidentOwned:  psql.Quote(alias, "resident_owned"),
		Tags:           psql.Quote(alias, "tags"),
		Version:        psql.Quote(alias, "version"),
	}
}

type siteColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	AddressID      psql.Expression
	Created        psql.Expression
	CreatorID      psql.Expression
	FileID         psql.Expression
	ID             psql.Expression
	Notes          psql.Expression
	OrganizationID psql.Expression
	OwnerName      psql.Expression
	OwnerPhoneE164 psql.Expression
	ParcelID       psql.Expression
	ResidentOwned  psql.Expression
	Tags           psql.Expression
	Version        psql.Expression
}

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

func (siteColumns) AliasedAs(alias string) siteColumns {
	return buildSiteColumns(alias)
}

// SiteSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type SiteSetter struct {
	AddressID      omit.Val[int32]          `db:"address_id" `
	Created        omit.Val[time.Time]      `db:"created" `
	CreatorID      omit.Val[int32]          `db:"creator_id" `
	FileID         omitnull.Val[int32]      `db:"file_id" `
	ID             omit.Val[int32]          `db:"id,pk" `
	Notes          omit.Val[string]         `db:"notes" `
	OrganizationID omit.Val[int32]          `db:"organization_id" `
	OwnerName      omit.Val[string]         `db:"owner_name" `
	OwnerPhoneE164 omitnull.Val[string]     `db:"owner_phone_e164" `
	ParcelID       omitnull.Val[int32]      `db:"parcel_id" `
	ResidentOwned  omitnull.Val[bool]       `db:"resident_owned" `
	Tags           omit.Val[pgtypes.HStore] `db:"tags" `
	Version        omit.Val[int32]          `db:"version" `
}

func (s SiteSetter) SetColumns() []string {
	vals := make([]string, 0, 13)
	if s.AddressID.IsValue() {
		vals = append(vals, "address_id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.CreatorID.IsValue() {
		vals = append(vals, "creator_id")
	}
	if !s.FileID.IsUnset() {
		vals = append(vals, "file_id")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Notes.IsValue() {
		vals = append(vals, "notes")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.OwnerName.IsValue() {
		vals = append(vals, "owner_name")
	}
	if !s.OwnerPhoneE164.IsUnset() {
		vals = append(vals, "owner_phone_e164")
	}
	if !s.ParcelID.IsUnset() {
		vals = append(vals, "parcel_id")
	}
	if !s.ResidentOwned.IsUnset() {
		vals = append(vals, "resident_owned")
	}
	if s.Tags.IsValue() {
		vals = append(vals, "tags")
	}
	if s.Version.IsValue() {
		vals = append(vals, "version")
	}
	return vals
}

func (s SiteSetter) Overwrite(t *Site) {
	if s.AddressID.IsValue() {
		t.AddressID = s.AddressID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.CreatorID.IsValue() {
		t.CreatorID = s.CreatorID.MustGet()
	}
	if !s.FileID.IsUnset() {
		t.FileID = s.FileID.MustGetNull()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Notes.IsValue() {
		t.Notes = s.Notes.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.OwnerName.IsValue() {
		t.OwnerName = s.OwnerName.MustGet()
	}
	if !s.OwnerPhoneE164.IsUnset() {
		t.OwnerPhoneE164 = s.OwnerPhoneE164.MustGetNull()
	}
	if !s.ParcelID.IsUnset() {
		t.ParcelID = s.ParcelID.MustGetNull()
	}
	if !s.ResidentOwned.IsUnset() {
		t.ResidentOwned = s.ResidentOwned.MustGetNull()
	}
	if s.Tags.IsValue() {
		t.Tags = s.Tags.MustGet()
	}
	if s.Version.IsValue() {
		t.Version = s.Version.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os SiteSlice) Features(mods ...bob.Mod[*dialect.SelectQuery]) FeaturesQuery {
	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 Features.Query(append(mods,
		sm.Where(psql.Group(Features.Columns.SiteID).OP("IN", PKArgExpr)),
	)...)
}

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

func (os SiteSlice) Leads(mods ...bob.Mod[*dialect.SelectQuery]) LeadsQuery {
	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 Leads.Query(append(mods,
		sm.Where(psql.Group(Leads.Columns.SiteID).OP("IN", PKArgExpr)),
	)...)
}

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

func (os SiteSlice) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery {
	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 Residents.Query(append(mods,
		sm.Where(psql.Group(Residents.Columns.SiteID).OP("IN", PKArgExpr)),
	)...)
}

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

func (os SiteSlice) Signals(mods ...bob.Mod[*dialect.SelectQuery]) SignalsQuery {
	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 Signals.Query(append(mods,
		sm.Where(psql.Group(Signals.Columns.SiteID).OP("IN", PKArgExpr)),
	)...)
}

// Address starts a query for related objects on address
func (o *Site) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery {
	return Addresses.Query(append(mods,
		sm.Where(Addresses.Columns.ID.EQ(psql.Arg(o.AddressID))),
	)...)
}

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

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

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

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

// File starts a query for related objects on fileupload.file
func (o *Site) File(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadFilesQuery {
	return FileuploadFiles.Query(append(mods,
		sm.Where(FileuploadFiles.Columns.ID.EQ(psql.Arg(o.FileID))),
	)...)
}

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

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

// Parcel starts a query for related objects on parcel
func (o *Site) Parcel(mods ...bob.Mod[*dialect.SelectQuery]) ParcelsQuery {
	return Parcels.Query(append(mods,
		sm.Where(Parcels.Columns.ID.EQ(psql.Arg(o.ParcelID))),
	)...)
}

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

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

func insertSiteFeatures0(ctx context.Context, exec bob.Executor, features1 []*FeatureSetter, site0 *Site) (FeatureSlice, error) {
	for i := range features1 {
		features1[i].SiteID = omit.From(site0.ID)
	}

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

	return ret, nil
}

func attachSiteFeatures0(ctx context.Context, exec bob.Executor, count int, features1 FeatureSlice, site0 *Site) (FeatureSlice, error) {
	setter := &FeatureSetter{
		SiteID: omit.From(site0.ID),
	}

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

	return features1, nil
}

func (site0 *Site) InsertFeatures(ctx context.Context, exec bob.Executor, related ...*FeatureSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	features1, err := insertSiteFeatures0(ctx, exec, related, site0)
	if err != nil {
		return err
	}

	site0.R.Features = append(site0.R.Features, features1...)

	for _, rel := range features1 {
		rel.R.Site = site0
	}
	return nil
}

func (site0 *Site) AttachFeatures(ctx context.Context, exec bob.Executor, related ...*Feature) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	features1 := FeatureSlice(related)

	_, err = attachSiteFeatures0(ctx, exec, len(related), features1, site0)
	if err != nil {
		return err
	}

	site0.R.Features = append(site0.R.Features, features1...)

	for _, rel := range related {
		rel.R.Site = site0
	}

	return nil
}

func insertSiteLeads0(ctx context.Context, exec bob.Executor, leads1 []*LeadSetter, site0 *Site) (LeadSlice, error) {
	for i := range leads1 {
		leads1[i].SiteID = omitnull.From(site0.ID)
	}

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

	return ret, nil
}

func attachSiteLeads0(ctx context.Context, exec bob.Executor, count int, leads1 LeadSlice, site0 *Site) (LeadSlice, error) {
	setter := &LeadSetter{
		SiteID: omitnull.From(site0.ID),
	}

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

	return leads1, nil
}

func (site0 *Site) InsertLeads(ctx context.Context, exec bob.Executor, related ...*LeadSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	leads1, err := insertSiteLeads0(ctx, exec, related, site0)
	if err != nil {
		return err
	}

	site0.R.Leads = append(site0.R.Leads, leads1...)

	for _, rel := range leads1 {
		rel.R.Site = site0
	}
	return nil
}

func (site0 *Site) AttachLeads(ctx context.Context, exec bob.Executor, related ...*Lead) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	leads1 := LeadSlice(related)

	_, err = attachSiteLeads0(ctx, exec, len(related), leads1, site0)
	if err != nil {
		return err
	}

	site0.R.Leads = append(site0.R.Leads, leads1...)

	for _, rel := range related {
		rel.R.Site = site0
	}

	return nil
}

func insertSiteResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, site0 *Site) (ResidentSlice, error) {
	for i := range residents1 {
		residents1[i].SiteID = omit.From(site0.ID)
	}

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

	return ret, nil
}

func attachSiteResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, site0 *Site) (ResidentSlice, error) {
	setter := &ResidentSetter{
		SiteID: omit.From(site0.ID),
	}

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

	return residents1, nil
}

func (site0 *Site) InsertResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	residents1, err := insertSiteResidents0(ctx, exec, related, site0)
	if err != nil {
		return err
	}

	site0.R.Residents = append(site0.R.Residents, residents1...)

	for _, rel := range residents1 {
		rel.R.Site = site0
	}
	return nil
}

func (site0 *Site) AttachResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	residents1 := ResidentSlice(related)

	_, err = attachSiteResidents0(ctx, exec, len(related), residents1, site0)
	if err != nil {
		return err
	}

	site0.R.Residents = append(site0.R.Residents, residents1...)

	for _, rel := range related {
		rel.R.Site = site0
	}

	return nil
}

func insertSiteSignals0(ctx context.Context, exec bob.Executor, signals1 []*SignalSetter, site0 *Site) (SignalSlice, error) {
	for i := range signals1 {
		signals1[i].SiteID = omitnull.From(site0.ID)
	}

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

	return ret, nil
}

func attachSiteSignals0(ctx context.Context, exec bob.Executor, count int, signals1 SignalSlice, site0 *Site) (SignalSlice, error) {
	setter := &SignalSetter{
		SiteID: omitnull.From(site0.ID),
	}

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

	return signals1, nil
}

func (site0 *Site) InsertSignals(ctx context.Context, exec bob.Executor, related ...*SignalSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	site0.R.Signals = append(site0.R.Signals, signals1...)

	for _, rel := range signals1 {
		rel.R.Site = site0
	}
	return nil
}

func (site0 *Site) AttachSignals(ctx context.Context, exec bob.Executor, related ...*Signal) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	signals1 := SignalSlice(related)

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

	site0.R.Signals = append(site0.R.Signals, signals1...)

	for _, rel := range related {
		rel.R.Site = site0
	}

	return nil
}

func attachSiteAddress0(ctx context.Context, exec bob.Executor, count int, site0 *Site, address1 *Address) (*Site, error) {
	setter := &SiteSetter{
		AddressID: omit.From(address1.ID),
	}

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

	return site0, nil
}

func (site0 *Site) InsertAddress(ctx context.Context, exec bob.Executor, related *AddressSetter) error {
	var err error

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

	_, err = attachSiteAddress0(ctx, exec, 1, site0, address1)
	if err != nil {
		return err
	}

	site0.R.Address = address1

	address1.R.Site = site0

	return nil
}

func (site0 *Site) AttachAddress(ctx context.Context, exec bob.Executor, address1 *Address) error {
	var err error

	_, err = attachSiteAddress0(ctx, exec, 1, site0, address1)
	if err != nil {
		return err
	}

	site0.R.Address = address1

	address1.R.Site = site0

	return nil
}

func attachSiteCreatorUser0(ctx context.Context, exec bob.Executor, count int, site0 *Site, user1 *User) (*Site, error) {
	setter := &SiteSetter{
		CreatorID: omit.From(user1.ID),
	}

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

	return site0, nil
}

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

	site0.R.CreatorUser = user1

	user1.R.CreatorSites = append(user1.R.CreatorSites, site0)

	return nil
}

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

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

	site0.R.CreatorUser = user1

	user1.R.CreatorSites = append(user1.R.CreatorSites, site0)

	return nil
}

func attachSiteFile0(ctx context.Context, exec bob.Executor, count int, site0 *Site, fileuploadFile1 *FileuploadFile) (*Site, error) {
	setter := &SiteSetter{
		FileID: omitnull.From(fileuploadFile1.ID),
	}

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

	return site0, nil
}

func (site0 *Site) InsertFile(ctx context.Context, exec bob.Executor, related *FileuploadFileSetter) error {
	var err error

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

	_, err = attachSiteFile0(ctx, exec, 1, site0, fileuploadFile1)
	if err != nil {
		return err
	}

	site0.R.File = fileuploadFile1

	fileuploadFile1.R.Sites = append(fileuploadFile1.R.Sites, site0)

	return nil
}

func (site0 *Site) AttachFile(ctx context.Context, exec bob.Executor, fileuploadFile1 *FileuploadFile) error {
	var err error

	_, err = attachSiteFile0(ctx, exec, 1, site0, fileuploadFile1)
	if err != nil {
		return err
	}

	site0.R.File = fileuploadFile1

	fileuploadFile1.R.Sites = append(fileuploadFile1.R.Sites, site0)

	return nil
}

func attachSiteParcel0(ctx context.Context, exec bob.Executor, count int, site0 *Site, parcel1 *Parcel) (*Site, error) {
	setter := &SiteSetter{
		ParcelID: omitnull.From(parcel1.ID),
	}

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

	return site0, nil
}

func (site0 *Site) InsertParcel(ctx context.Context, exec bob.Executor, related *ParcelSetter) error {
	var err error

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

	_, err = attachSiteParcel0(ctx, exec, 1, site0, parcel1)
	if err != nil {
		return err
	}

	site0.R.Parcel = parcel1

	parcel1.R.Sites = append(parcel1.R.Sites, site0)

	return nil
}

func (site0 *Site) AttachParcel(ctx context.Context, exec bob.Executor, parcel1 *Parcel) error {
	var err error

	_, err = attachSiteParcel0(ctx, exec, 1, site0, parcel1)
	if err != nil {
		return err
	}

	site0.R.Parcel = parcel1

	parcel1.R.Sites = append(parcel1.R.Sites, site0)

	return nil
}

type siteWhere[Q psql.Filterable] struct {
	AddressID      psql.WhereMod[Q, int32]
	Created        psql.WhereMod[Q, time.Time]
	CreatorID      psql.WhereMod[Q, int32]
	FileID         psql.WhereNullMod[Q, int32]
	ID             psql.WhereMod[Q, int32]
	Notes          psql.WhereMod[Q, string]
	OrganizationID psql.WhereMod[Q, int32]
	OwnerName      psql.WhereMod[Q, string]
	OwnerPhoneE164 psql.WhereNullMod[Q, string]
	ParcelID       psql.WhereNullMod[Q, int32]
	ResidentOwned  psql.WhereNullMod[Q, bool]
	Tags           psql.WhereMod[Q, pgtypes.HStore]
	Version        psql.WhereMod[Q, int32]
}

func (siteWhere[Q]) AliasedAs(alias string) siteWhere[Q] {
	return buildSiteWhere[Q](buildSiteColumns(alias))
}

func buildSiteWhere[Q psql.Filterable](cols siteColumns) siteWhere[Q] {
	return siteWhere[Q]{
		AddressID:      psql.Where[Q, int32](cols.AddressID),
		Created:        psql.Where[Q, time.Time](cols.Created),
		CreatorID:      psql.Where[Q, int32](cols.CreatorID),
		FileID:         psql.WhereNull[Q, int32](cols.FileID),
		ID:             psql.Where[Q, int32](cols.ID),
		Notes:          psql.Where[Q, string](cols.Notes),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		OwnerName:      psql.Where[Q, string](cols.OwnerName),
		OwnerPhoneE164: psql.WhereNull[Q, string](cols.OwnerPhoneE164),
		ParcelID:       psql.WhereNull[Q, int32](cols.ParcelID),
		ResidentOwned:  psql.WhereNull[Q, bool](cols.ResidentOwned),
		Tags:           psql.Where[Q, pgtypes.HStore](cols.Tags),
		Version:        psql.Where[Q, int32](cols.Version),
	}
}

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

	switch name {
	case "Features":
		rels, ok := retrieved.(FeatureSlice)
		if !ok {
			return fmt.Errorf("site cannot load %T as %q", retrieved, name)
		}

		o.R.Features = rels

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

		o.R.Leads = rels

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

		o.R.Residents = rels

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

		o.R.Signals = rels

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

		o.R.Address = rel

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorSites = SiteSlice{o}
		}
		return nil
	case "File":
		rel, ok := retrieved.(*FileuploadFile)
		if !ok {
			return fmt.Errorf("site cannot load %T as %q", retrieved, name)
		}

		o.R.File = rel

		if rel != nil {
			rel.R.Sites = SiteSlice{o}
		}
		return nil
	case "Parcel":
		rel, ok := retrieved.(*Parcel)
		if !ok {
			return fmt.Errorf("site cannot load %T as %q", retrieved, name)
		}

		o.R.Parcel = rel

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

type sitePreloader struct {
	Address     func(...psql.PreloadOption) psql.Preloader
	CreatorUser func(...psql.PreloadOption) psql.Preloader
	File        func(...psql.PreloadOption) psql.Preloader
	Parcel      func(...psql.PreloadOption) psql.Preloader
}

func buildSitePreloader() sitePreloader {
	return sitePreloader{
		Address: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Address, AddressSlice](psql.PreloadRel{
				Name: "Address",
				Sides: []psql.PreloadSide{
					{
						From:        Sites,
						To:          Addresses,
						FromColumns: []string{"address_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Addresses.Columns.Names(), opts...)
		},
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Sites,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		File: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FileuploadFile, FileuploadFileSlice](psql.PreloadRel{
				Name: "File",
				Sides: []psql.PreloadSide{
					{
						From:        Sites,
						To:          FileuploadFiles,
						FromColumns: []string{"file_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, FileuploadFiles.Columns.Names(), opts...)
		},
		Parcel: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Parcel, ParcelSlice](psql.PreloadRel{
				Name: "Parcel",
				Sides: []psql.PreloadSide{
					{
						From:        Sites,
						To:          Parcels,
						FromColumns: []string{"parcel_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Parcels.Columns.Names(), opts...)
		},
	}
}

type siteThenLoader[Q orm.Loadable] struct {
	Features    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Leads       func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Residents   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Signals     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Address     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	File        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Parcel      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildSiteThenLoader[Q orm.Loadable]() siteThenLoader[Q] {
	type FeaturesLoadInterface interface {
		LoadFeatures(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type LeadsLoadInterface interface {
		LoadLeads(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResidentsLoadInterface interface {
		LoadResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SignalsLoadInterface interface {
		LoadSignals(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type AddressLoadInterface interface {
		LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FileLoadInterface interface {
		LoadFile(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ParcelLoadInterface interface {
		LoadParcel(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return siteThenLoader[Q]{
		Features: thenLoadBuilder[Q](
			"Features",
			func(ctx context.Context, exec bob.Executor, retrieved FeaturesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeatures(ctx, exec, mods...)
			},
		),
		Leads: thenLoadBuilder[Q](
			"Leads",
			func(ctx context.Context, exec bob.Executor, retrieved LeadsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadLeads(ctx, exec, mods...)
			},
		),
		Residents: thenLoadBuilder[Q](
			"Residents",
			func(ctx context.Context, exec bob.Executor, retrieved ResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResidents(ctx, exec, mods...)
			},
		),
		Signals: thenLoadBuilder[Q](
			"Signals",
			func(ctx context.Context, exec bob.Executor, retrieved SignalsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSignals(ctx, exec, mods...)
			},
		),
		Address: thenLoadBuilder[Q](
			"Address",
			func(ctx context.Context, exec bob.Executor, retrieved AddressLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAddress(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...)
			},
		),
		File: thenLoadBuilder[Q](
			"File",
			func(ctx context.Context, exec bob.Executor, retrieved FileLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFile(ctx, exec, mods...)
			},
		),
		Parcel: thenLoadBuilder[Q](
			"Parcel",
			func(ctx context.Context, exec bob.Executor, retrieved ParcelLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadParcel(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.Features = related
	return nil
}

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

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

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

		o.R.Features = nil
	}

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

		for _, rel := range features {

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

			rel.R.Site = o

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

	return nil
}

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

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

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

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

	o.R.Leads = related
	return nil
}

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

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

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

		o.R.Leads = nil
	}

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

		for _, rel := range leads {

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

			rel.R.Site = o

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

	return nil
}

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

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

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

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

	o.R.Residents = related
	return nil
}

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

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

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

		o.R.Residents = nil
	}

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

		for _, rel := range residents {

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

			rel.R.Site = o

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

	return nil
}

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

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

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

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

	o.R.Signals = related
	return nil
}

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

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

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

		o.R.Signals = nil
	}

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

		for _, rel := range signals {

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

			rel.R.Site = o

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

	return nil
}

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

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

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

	related.R.Site = o

	o.R.Address = related
	return nil
}

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

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

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

		for _, rel := range addresses {

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

			rel.R.Site = o

			o.R.Address = rel
			break
		}
	}

	return nil
}

// LoadCreatorUser loads the site's CreatorUser into the .R struct
func (o *Site) 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.CreatorSites = SiteSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Sites = SiteSlice{o}

	o.R.File = related
	return nil
}

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

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

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

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

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

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

			o.R.File = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Sites = SiteSlice{o}

	o.R.Parcel = related
	return nil
}

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

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

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

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

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

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

			o.R.Parcel = rel
			break
		}
	}

	return nil
}
