// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package models

import (
	"context"
	"fmt"
	"io"
	"time"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"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       int32            `db:"parcel_id" `
	ResidentOwned  null.Val[bool]   `db:"resident_owned" `
	Tags           pgtypes.HStore   `db:"tags" `
	Version        int32            `db:"version,pk" `

	R siteR `db:"-" `

	C siteC `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 {
	ComplianceReportRequests ComplianceReportRequestSlice // compliance_report_request.compliance_report_request_site_id_site_version_fkey
	Pools                    PoolSlice                    // pool.pool_site_id_site_version_fkey
	Residents                ResidentSlice                // resident.resident_site_id_site_version_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       omit.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,pk" `
}

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.IsValue() {
		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.IsValue() {
		t.ParcelID = s.ParcelID.MustGet()
	}
	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.IsValue() {
			vals[9] = psql.Arg(s.ParcelID.MustGet())
		} 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.IsValue() {
		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, VersionPK int32, cols ...string) (*Site, error) {
	if len(cols) == 0 {
		return Sites.Query(
			sm.Where(Sites.Columns.ID.EQ(psql.Arg(IDPK))),
			sm.Where(Sites.Columns.Version.EQ(psql.Arg(VersionPK))),
		).One(ctx, exec)
	}

	return Sites.Query(
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(IDPK))),
		sm.Where(Sites.Columns.Version.EQ(psql.Arg(VersionPK))),
		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, VersionPK int32) (bool, error) {
	return Sites.Query(
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(IDPK))),
		sm.Where(Sites.Columns.Version.EQ(psql.Arg(VersionPK))),
	).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.ArgGroup(
		o.ID,
		o.Version,
	)
}

func (o *Site) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("site", "id"), psql.Quote("site", "version")).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))),
		sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.Version))),
	).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.Group(psql.Quote("site", "id"), psql.Quote("site", "version")).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
			}
			if new.Version != old.Version {
				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
}

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

func (os SiteSlice) ComplianceReportRequests(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery {
	pkID := make(pgtypes.Array[int32], 0, len(os))

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

	return ComplianceReportRequests.Query(append(mods,
		sm.Where(psql.Group(ComplianceReportRequests.Columns.SiteID, ComplianceReportRequests.Columns.SiteVersion).OP("IN", PKArgExpr)),
	)...)
}

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

func (os SiteSlice) Pools(mods ...bob.Mod[*dialect.SelectQuery]) PoolsQuery {
	pkID := make(pgtypes.Array[int32], 0, len(os))

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

	return Pools.Query(append(mods,
		sm.Where(psql.Group(Pools.Columns.SiteID, Pools.Columns.SiteVersion).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))), sm.Where(Residents.Columns.SiteVersion.EQ(psql.Arg(o.Version))),
	)...)
}

func (os SiteSlice) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery {
	pkID := make(pgtypes.Array[int32], 0, len(os))

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

	return Residents.Query(append(mods,
		sm.Where(psql.Group(Residents.Columns.SiteID, Residents.Columns.SiteVersion).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[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 insertSiteComplianceReportRequests0(ctx context.Context, exec bob.Executor, complianceReportRequests1 []*ComplianceReportRequestSetter, site0 *Site) (ComplianceReportRequestSlice, error) {
	for i := range complianceReportRequests1 {
		complianceReportRequests1[i].SiteID = omit.From(site0.ID)
		complianceReportRequests1[i].SiteVersion = omit.From(site0.Version)
	}

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

	return ret, nil
}

func attachSiteComplianceReportRequests0(ctx context.Context, exec bob.Executor, count int, complianceReportRequests1 ComplianceReportRequestSlice, site0 *Site) (ComplianceReportRequestSlice, error) {
	setter := &ComplianceReportRequestSetter{
		SiteID:      omit.From(site0.ID),
		SiteVersion: omit.From(site0.Version),
	}

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

	return complianceReportRequests1, nil
}

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

	var err error

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

	site0.R.ComplianceReportRequests = append(site0.R.ComplianceReportRequests, complianceReportRequests1...)

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

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

	var err error
	complianceReportRequests1 := ComplianceReportRequestSlice(related)

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

	site0.R.ComplianceReportRequests = append(site0.R.ComplianceReportRequests, complianceReportRequests1...)

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

	return nil
}

func insertSitePools0(ctx context.Context, exec bob.Executor, pools1 []*PoolSetter, site0 *Site) (PoolSlice, error) {
	for i := range pools1 {
		pools1[i].SiteID = omit.From(site0.ID)
		pools1[i].SiteVersion = omit.From(site0.Version)
	}

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

	return ret, nil
}

func attachSitePools0(ctx context.Context, exec bob.Executor, count int, pools1 PoolSlice, site0 *Site) (PoolSlice, error) {
	setter := &PoolSetter{
		SiteID:      omit.From(site0.ID),
		SiteVersion: omit.From(site0.Version),
	}

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

	return pools1, nil
}

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

	var err error

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

	site0.R.Pools = append(site0.R.Pools, pools1...)

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

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

	var err error
	pools1 := PoolSlice(related)

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

	site0.R.Pools = append(site0.R.Pools, pools1...)

	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)
		residents1[i].SiteVersion = omit.From(site0.Version)
	}

	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),
		SiteVersion: omit.From(site0.Version),
	}

	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 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: omit.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.WhereMod[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.Where[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 "ComplianceReportRequests":
		rels, ok := retrieved.(ComplianceReportRequestSlice)
		if !ok {
			return fmt.Errorf("site cannot load %T as %q", retrieved, name)
		}

		o.R.ComplianceReportRequests = rels

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

		o.R.Pools = 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 "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 {
	ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Pools                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Residents                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 ComplianceReportRequestsLoadInterface interface {
		LoadComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PoolsLoadInterface interface {
		LoadPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResidentsLoadInterface interface {
		LoadResidents(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]{
		ComplianceReportRequests: thenLoadBuilder[Q](
			"ComplianceReportRequests",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadComplianceReportRequests(ctx, exec, mods...)
			},
		),
		Pools: thenLoadBuilder[Q](
			"Pools",
			func(ctx context.Context, exec bob.Executor, retrieved PoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPools(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...)
			},
		),
		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...)
			},
		),
	}
}

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

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

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

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

	o.R.ComplianceReportRequests = related
	return nil
}

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

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

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

		o.R.ComplianceReportRequests = nil
	}

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

		for _, rel := range complianceReportRequests {

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

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

			rel.R.Site = o

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

	return nil
}

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

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

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

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

	o.R.Pools = related
	return nil
}

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

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

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

		o.R.Pools = nil
	}

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

		for _, rel := range pools {

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

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

			rel.R.Site = o

			o.R.Pools = append(o.R.Pools, 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
			}

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

			rel.R.Site = o

			o.R.Residents = append(o.R.Residents, 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 == rel.ID) {
				continue
			}

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

			o.R.Parcel = rel
			break
		}
	}

	return nil
}

// siteC is where relationship counts are stored.
type siteC struct {
	ComplianceReportRequests *int64
	Pools                    *int64
	Residents                *int64
}

// PreloadCount sets a count in the C struct by name
func (o *Site) PreloadCount(name string, count int64) error {
	if o == nil {
		return nil
	}

	switch name {
	case "ComplianceReportRequests":
		o.C.ComplianceReportRequests = &count
	case "Pools":
		o.C.Pools = &count
	case "Residents":
		o.C.Residents = &count
	}
	return nil
}

type siteCountPreloader struct {
	ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	Pools                    func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	Residents                func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
}

func buildSiteCountPreloader() siteCountPreloader {
	return siteCountPreloader{
		ComplianceReportRequests: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*Site]("ComplianceReportRequests", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = Sites.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(ComplianceReportRequests.Name()),
					sm.Where(psql.Quote(ComplianceReportRequests.Alias(), "site_id").EQ(psql.Quote(parent, "id"))),
					sm.Where(psql.Quote(ComplianceReportRequests.Alias(), "site_version").EQ(psql.Quote(parent, "version"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		Pools: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*Site]("Pools", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = Sites.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(Pools.Name()),
					sm.Where(psql.Quote(Pools.Alias(), "site_id").EQ(psql.Quote(parent, "id"))),
					sm.Where(psql.Quote(Pools.Alias(), "site_version").EQ(psql.Quote(parent, "version"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		Residents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*Site]("Residents", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = Sites.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(Residents.Name()),
					sm.Where(psql.Quote(Residents.Alias(), "site_id").EQ(psql.Quote(parent, "id"))),
					sm.Where(psql.Quote(Residents.Alias(), "site_version").EQ(psql.Quote(parent, "version"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
	}
}

type siteCountThenLoader[Q orm.Loadable] struct {
	ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Pools                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Residents                func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildSiteCountThenLoader[Q orm.Loadable]() siteCountThenLoader[Q] {
	type ComplianceReportRequestsCountInterface interface {
		LoadCountComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PoolsCountInterface interface {
		LoadCountPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResidentsCountInterface interface {
		LoadCountResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return siteCountThenLoader[Q]{
		ComplianceReportRequests: countThenLoadBuilder[Q](
			"ComplianceReportRequests",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountComplianceReportRequests(ctx, exec, mods...)
			},
		),
		Pools: countThenLoadBuilder[Q](
			"Pools",
			func(ctx context.Context, exec bob.Executor, retrieved PoolsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountPools(ctx, exec, mods...)
			},
		),
		Residents: countThenLoadBuilder[Q](
			"Residents",
			func(ctx context.Context, exec bob.Executor, retrieved ResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountResidents(ctx, exec, mods...)
			},
		),
	}
}

// LoadCountComplianceReportRequests loads the count of ComplianceReportRequests into the C struct
func (o *Site) LoadCountComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.ComplianceReportRequests(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.ComplianceReportRequests = &count
	return nil
}

// LoadCountComplianceReportRequests loads the count of ComplianceReportRequests for a slice
func (os SiteSlice) LoadCountComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountComplianceReportRequests(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

// LoadCountPools loads the count of Pools into the C struct
func (o *Site) LoadCountPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.Pools(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.Pools = &count
	return nil
}

// LoadCountPools loads the count of Pools for a slice
func (os SiteSlice) LoadCountPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountPools(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

// LoadCountResidents loads the count of Residents into the C struct
func (o *Site) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

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

	o.C.Residents = &count
	return nil
}

// LoadCountResidents loads the count of Residents for a slice
func (os SiteSlice) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountResidents(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

type siteJoins[Q dialect.Joinable] struct {
	typ                      string
	ComplianceReportRequests modAs[Q, complianceReportRequestColumns]
	Pools                    modAs[Q, poolColumns]
	Residents                modAs[Q, residentColumns]
	Address                  modAs[Q, addressColumns]
	CreatorUser              modAs[Q, userColumns]
	File                     modAs[Q, fileuploadFileColumns]
	Parcel                   modAs[Q, parcelColumns]
}

func (j siteJoins[Q]) aliasedAs(alias string) siteJoins[Q] {
	return buildSiteJoins[Q](buildSiteColumns(alias), j.typ)
}

func buildSiteJoins[Q dialect.Joinable](cols siteColumns, typ string) siteJoins[Q] {
	return siteJoins[Q]{
		typ: typ,
		ComplianceReportRequests: modAs[Q, complianceReportRequestColumns]{
			c: ComplianceReportRequests.Columns,
			f: func(to complianceReportRequestColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

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

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

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

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

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

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

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

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

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

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

				return mods
			},
		},
	}
}
