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

package models

import (
	"context"
	"fmt"
	"io"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	"github.com/stephenafamo/scan"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// CommsPhone is an object representing the database table.
type CommsPhone struct {
	E164         string                     `db:"e164,pk" `
	IsSubscribed bool                       `db:"is_subscribed" `
	Status       enums.CommsPhonestatustype `db:"status" `
	CanSMS       bool                       `db:"can_sms" `

	R commsPhoneR `db:"-" `
}

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

// CommsPhones contains methods to work with the phone table
var CommsPhones = psql.NewTablex[*CommsPhone, CommsPhoneSlice, *CommsPhoneSetter]("comms", "phone", buildCommsPhoneColumns("comms.phone"))

// CommsPhonesQuery is a query on the phone table
type CommsPhonesQuery = *psql.ViewQuery[*CommsPhone, CommsPhoneSlice]

// commsPhoneR is where relationships are stored.
type commsPhoneR struct {
	DestinationTextJobs              CommsTextJobSlice                       // comms.text_job.text_job_destination_fkey
	DestinationTextLogs              CommsTextLogSlice                       // comms.text_log.text_log_destination_fkey
	SourceTextLogs                   CommsTextLogSlice                       // comms.text_log.text_log_source_fkey
	Organizations                    OrganizationSlice                       // district_subscription_phone.district_subscription_phone_organization_id_fkeydistrict_subscription_phone.district_subscription_phone_phone_e164_fkey
	PropertyOwnerPhoneE164Pools      FileuploadPoolSlice                     // fileupload.pool.pool_property_owner_phone_e164_fkey
	ResidentPhoneE164Pools           FileuploadPoolSlice                     // fileupload.pool.pool_resident_phone_e164_fkey
	PhoneE164NotifyPhones            PublicreportNotifyPhoneSlice            // publicreport.notify_phone.notify_phone_phone_e164_fkey
	PhoneE164NotifyPhoneNuisanceOlds PublicreportNotifyPhoneNuisanceOldSlice // publicreport.notify_phone_nuisance_old.notify_phone_nuisance_phone_e164_fkey
	PhoneE164NotifyPhoneWaterOlds    PublicreportNotifyPhoneWaterOldSlice    // publicreport.notify_phone_water_old.notify_phone_pool_phone_e164_fkey
	PhoneE164SubscribePhones         PublicreportSubscribePhoneSlice         // publicreport.subscribe_phone.subscribe_phone_phone_e164_fkey
	PhoneMobileResidents             ResidentSlice                           // resident.resident_phone_mobile_fkey
}

func buildCommsPhoneColumns(alias string) commsPhoneColumns {
	return commsPhoneColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"e164", "is_subscribed", "status", "can_sms",
		).WithParent("comms.phone"),
		tableAlias:   alias,
		E164:         psql.Quote(alias, "e164"),
		IsSubscribed: psql.Quote(alias, "is_subscribed"),
		Status:       psql.Quote(alias, "status"),
		CanSMS:       psql.Quote(alias, "can_sms"),
	}
}

type commsPhoneColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	E164         psql.Expression
	IsSubscribed psql.Expression
	Status       psql.Expression
	CanSMS       psql.Expression
}

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

func (commsPhoneColumns) AliasedAs(alias string) commsPhoneColumns {
	return buildCommsPhoneColumns(alias)
}

// CommsPhoneSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsPhoneSetter struct {
	E164         omit.Val[string]                     `db:"e164,pk" `
	IsSubscribed omit.Val[bool]                       `db:"is_subscribed" `
	Status       omit.Val[enums.CommsPhonestatustype] `db:"status" `
	CanSMS       omit.Val[bool]                       `db:"can_sms" `
}

func (s CommsPhoneSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.E164.IsValue() {
		vals = append(vals, "e164")
	}
	if s.IsSubscribed.IsValue() {
		vals = append(vals, "is_subscribed")
	}
	if s.Status.IsValue() {
		vals = append(vals, "status")
	}
	if s.CanSMS.IsValue() {
		vals = append(vals, "can_sms")
	}
	return vals
}

func (s CommsPhoneSetter) Overwrite(t *CommsPhone) {
	if s.E164.IsValue() {
		t.E164 = s.E164.MustGet()
	}
	if s.IsSubscribed.IsValue() {
		t.IsSubscribed = s.IsSubscribed.MustGet()
	}
	if s.Status.IsValue() {
		t.Status = s.Status.MustGet()
	}
	if s.CanSMS.IsValue() {
		t.CanSMS = s.CanSMS.MustGet()
	}
}

func (s *CommsPhoneSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return CommsPhones.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 4)
		if s.E164.IsValue() {
			vals[0] = psql.Arg(s.E164.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return CommsPhones.Query(
		sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(E164PK))),
		sm.Columns(CommsPhones.Columns.Only(cols...)),
	).One(ctx, exec)
}

// CommsPhoneExists checks the presence of a single record by primary key
func CommsPhoneExists(ctx context.Context, exec bob.Executor, E164PK string) (bool, error) {
	return CommsPhones.Query(
		sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(E164PK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("comms.phone", "e164").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 CommsPhoneSlice) copyMatchingRows(from ...*CommsPhone) {
	for i, old := range o {
		for _, new := range from {
			if new.E164 != old.E164 {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// DestinationTextJobs starts a query for related objects on comms.text_job
func (o *CommsPhone) DestinationTextJobs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextJobsQuery {
	return CommsTextJobs.Query(append(mods,
		sm.Where(CommsTextJobs.Columns.Destination.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) DestinationTextJobs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextJobsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// DestinationTextLogs starts a query for related objects on comms.text_log
func (o *CommsPhone) DestinationTextLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	return CommsTextLogs.Query(append(mods,
		sm.Where(CommsTextLogs.Columns.Destination.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) DestinationTextLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// SourceTextLogs starts a query for related objects on comms.text_log
func (o *CommsPhone) SourceTextLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	return CommsTextLogs.Query(append(mods,
		sm.Where(CommsTextLogs.Columns.Source.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) SourceTextLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

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

func (os CommsPhoneSlice) Organizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

	return Organizations.Query(append(mods,
		sm.InnerJoin(DistrictSubscriptionPhones.NameAs()).On(
			Organizations.Columns.ID.EQ(DistrictSubscriptionPhones.Columns.OrganizationID),
		),
		sm.Where(psql.Group(DistrictSubscriptionPhones.Columns.PhoneE164).OP("IN", PKArgExpr)),
	)...)
}

// PropertyOwnerPhoneE164Pools starts a query for related objects on fileupload.pool
func (o *CommsPhone) PropertyOwnerPhoneE164Pools(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadPoolsQuery {
	return FileuploadPools.Query(append(mods,
		sm.Where(FileuploadPools.Columns.PropertyOwnerPhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) PropertyOwnerPhoneE164Pools(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadPoolsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// ResidentPhoneE164Pools starts a query for related objects on fileupload.pool
func (o *CommsPhone) ResidentPhoneE164Pools(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadPoolsQuery {
	return FileuploadPools.Query(append(mods,
		sm.Where(FileuploadPools.Columns.ResidentPhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) ResidentPhoneE164Pools(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadPoolsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// PhoneE164NotifyPhones starts a query for related objects on publicreport.notify_phone
func (o *CommsPhone) PhoneE164NotifyPhones(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhonesQuery {
	return PublicreportNotifyPhones.Query(append(mods,
		sm.Where(PublicreportNotifyPhones.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) PhoneE164NotifyPhones(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhonesQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// PhoneE164NotifyPhoneNuisanceOlds starts a query for related objects on publicreport.notify_phone_nuisance_old
func (o *CommsPhone) PhoneE164NotifyPhoneNuisanceOlds(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneNuisanceOldsQuery {
	return PublicreportNotifyPhoneNuisanceOlds.Query(append(mods,
		sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) PhoneE164NotifyPhoneNuisanceOlds(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneNuisanceOldsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// PhoneE164NotifyPhoneWaterOlds starts a query for related objects on publicreport.notify_phone_water_old
func (o *CommsPhone) PhoneE164NotifyPhoneWaterOlds(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneWaterOldsQuery {
	return PublicreportNotifyPhoneWaterOlds.Query(append(mods,
		sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) PhoneE164NotifyPhoneWaterOlds(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneWaterOldsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

// PhoneE164SubscribePhones starts a query for related objects on publicreport.subscribe_phone
func (o *CommsPhone) PhoneE164SubscribePhones(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportSubscribePhonesQuery {
	return PublicreportSubscribePhones.Query(append(mods,
		sm.Where(PublicreportSubscribePhones.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
	)...)
}

func (os CommsPhoneSlice) PhoneE164SubscribePhones(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportSubscribePhonesQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

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

func (os CommsPhoneSlice) PhoneMobileResidents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery {
	pkE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkE164 = append(pkE164, o.E164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
	))

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

func insertCommsPhoneDestinationTextJobs0(ctx context.Context, exec bob.Executor, commsTextJobs1 []*CommsTextJobSetter, commsPhone0 *CommsPhone) (CommsTextJobSlice, error) {
	for i := range commsTextJobs1 {
		commsTextJobs1[i].Destination = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhoneDestinationTextJobs0(ctx context.Context, exec bob.Executor, count int, commsTextJobs1 CommsTextJobSlice, commsPhone0 *CommsPhone) (CommsTextJobSlice, error) {
	setter := &CommsTextJobSetter{
		Destination: omit.From(commsPhone0.E164),
	}

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

	return commsTextJobs1, nil
}

func (commsPhone0 *CommsPhone) InsertDestinationTextJobs(ctx context.Context, exec bob.Executor, related ...*CommsTextJobSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	commsTextJobs1, err := insertCommsPhoneDestinationTextJobs0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.DestinationTextJobs = append(commsPhone0.R.DestinationTextJobs, commsTextJobs1...)

	for _, rel := range commsTextJobs1 {
		rel.R.DestinationPhone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachDestinationTextJobs(ctx context.Context, exec bob.Executor, related ...*CommsTextJob) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	commsTextJobs1 := CommsTextJobSlice(related)

	_, err = attachCommsPhoneDestinationTextJobs0(ctx, exec, len(related), commsTextJobs1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.DestinationTextJobs = append(commsPhone0.R.DestinationTextJobs, commsTextJobs1...)

	for _, rel := range related {
		rel.R.DestinationPhone = commsPhone0
	}

	return nil
}

func insertCommsPhoneDestinationTextLogs0(ctx context.Context, exec bob.Executor, commsTextLogs1 []*CommsTextLogSetter, commsPhone0 *CommsPhone) (CommsTextLogSlice, error) {
	for i := range commsTextLogs1 {
		commsTextLogs1[i].Destination = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhoneDestinationTextLogs0(ctx context.Context, exec bob.Executor, count int, commsTextLogs1 CommsTextLogSlice, commsPhone0 *CommsPhone) (CommsTextLogSlice, error) {
	setter := &CommsTextLogSetter{
		Destination: omit.From(commsPhone0.E164),
	}

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

	return commsTextLogs1, nil
}

func (commsPhone0 *CommsPhone) InsertDestinationTextLogs(ctx context.Context, exec bob.Executor, related ...*CommsTextLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	commsTextLogs1, err := insertCommsPhoneDestinationTextLogs0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.DestinationTextLogs = append(commsPhone0.R.DestinationTextLogs, commsTextLogs1...)

	for _, rel := range commsTextLogs1 {
		rel.R.DestinationPhone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachDestinationTextLogs(ctx context.Context, exec bob.Executor, related ...*CommsTextLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	commsTextLogs1 := CommsTextLogSlice(related)

	_, err = attachCommsPhoneDestinationTextLogs0(ctx, exec, len(related), commsTextLogs1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.DestinationTextLogs = append(commsPhone0.R.DestinationTextLogs, commsTextLogs1...)

	for _, rel := range related {
		rel.R.DestinationPhone = commsPhone0
	}

	return nil
}

func insertCommsPhoneSourceTextLogs0(ctx context.Context, exec bob.Executor, commsTextLogs1 []*CommsTextLogSetter, commsPhone0 *CommsPhone) (CommsTextLogSlice, error) {
	for i := range commsTextLogs1 {
		commsTextLogs1[i].Source = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhoneSourceTextLogs0(ctx context.Context, exec bob.Executor, count int, commsTextLogs1 CommsTextLogSlice, commsPhone0 *CommsPhone) (CommsTextLogSlice, error) {
	setter := &CommsTextLogSetter{
		Source: omit.From(commsPhone0.E164),
	}

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

	return commsTextLogs1, nil
}

func (commsPhone0 *CommsPhone) InsertSourceTextLogs(ctx context.Context, exec bob.Executor, related ...*CommsTextLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	commsTextLogs1, err := insertCommsPhoneSourceTextLogs0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.SourceTextLogs = append(commsPhone0.R.SourceTextLogs, commsTextLogs1...)

	for _, rel := range commsTextLogs1 {
		rel.R.SourcePhone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachSourceTextLogs(ctx context.Context, exec bob.Executor, related ...*CommsTextLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	commsTextLogs1 := CommsTextLogSlice(related)

	_, err = attachCommsPhoneSourceTextLogs0(ctx, exec, len(related), commsTextLogs1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.SourceTextLogs = append(commsPhone0.R.SourceTextLogs, commsTextLogs1...)

	for _, rel := range related {
		rel.R.SourcePhone = commsPhone0
	}

	return nil
}

func attachCommsPhoneOrganizations0(ctx context.Context, exec bob.Executor, count int, commsPhone0 *CommsPhone, organizations2 OrganizationSlice) (DistrictSubscriptionPhoneSlice, error) {
	setters := make([]*DistrictSubscriptionPhoneSetter, count)
	for i := range count {
		setters[i] = &DistrictSubscriptionPhoneSetter{
			PhoneE164:      omit.From(commsPhone0.E164),
			OrganizationID: omit.From(organizations2[i].ID),
		}
	}

	districtSubscriptionPhones1, err := DistrictSubscriptionPhones.Insert(bob.ToMods(setters...)).All(ctx, exec)
	if err != nil {
		return nil, fmt.Errorf("attachCommsPhoneOrganizations0: %w", err)
	}

	return districtSubscriptionPhones1, nil
}

func (commsPhone0 *CommsPhone) InsertOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	inserted, err := Organizations.Insert(bob.ToMods(related...)).All(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}
	organizations2 := OrganizationSlice(inserted)

	_, err = attachCommsPhoneOrganizations0(ctx, exec, len(related), commsPhone0, organizations2)
	if err != nil {
		return err
	}

	commsPhone0.R.Organizations = append(commsPhone0.R.Organizations, organizations2...)

	for _, rel := range organizations2 {
		rel.R.Phones = append(rel.R.Phones, commsPhone0)
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	organizations2 := OrganizationSlice(related)

	_, err = attachCommsPhoneOrganizations0(ctx, exec, len(related), commsPhone0, organizations2)
	if err != nil {
		return err
	}

	commsPhone0.R.Organizations = append(commsPhone0.R.Organizations, organizations2...)

	for _, rel := range related {
		rel.R.Phones = append(rel.R.Phones, commsPhone0)
	}

	return nil
}

func insertCommsPhonePropertyOwnerPhoneE164Pools0(ctx context.Context, exec bob.Executor, fileuploadPools1 []*FileuploadPoolSetter, commsPhone0 *CommsPhone) (FileuploadPoolSlice, error) {
	for i := range fileuploadPools1 {
		fileuploadPools1[i].PropertyOwnerPhoneE164 = omitnull.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePropertyOwnerPhoneE164Pools0(ctx context.Context, exec bob.Executor, count int, fileuploadPools1 FileuploadPoolSlice, commsPhone0 *CommsPhone) (FileuploadPoolSlice, error) {
	setter := &FileuploadPoolSetter{
		PropertyOwnerPhoneE164: omitnull.From(commsPhone0.E164),
	}

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

	return fileuploadPools1, nil
}

func (commsPhone0 *CommsPhone) InsertPropertyOwnerPhoneE164Pools(ctx context.Context, exec bob.Executor, related ...*FileuploadPoolSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	fileuploadPools1, err := insertCommsPhonePropertyOwnerPhoneE164Pools0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PropertyOwnerPhoneE164Pools = append(commsPhone0.R.PropertyOwnerPhoneE164Pools, fileuploadPools1...)

	for _, rel := range fileuploadPools1 {
		rel.R.PropertyOwnerPhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPropertyOwnerPhoneE164Pools(ctx context.Context, exec bob.Executor, related ...*FileuploadPool) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	fileuploadPools1 := FileuploadPoolSlice(related)

	_, err = attachCommsPhonePropertyOwnerPhoneE164Pools0(ctx, exec, len(related), fileuploadPools1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PropertyOwnerPhoneE164Pools = append(commsPhone0.R.PropertyOwnerPhoneE164Pools, fileuploadPools1...)

	for _, rel := range related {
		rel.R.PropertyOwnerPhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhoneResidentPhoneE164Pools0(ctx context.Context, exec bob.Executor, fileuploadPools1 []*FileuploadPoolSetter, commsPhone0 *CommsPhone) (FileuploadPoolSlice, error) {
	for i := range fileuploadPools1 {
		fileuploadPools1[i].ResidentPhoneE164 = omitnull.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhoneResidentPhoneE164Pools0(ctx context.Context, exec bob.Executor, count int, fileuploadPools1 FileuploadPoolSlice, commsPhone0 *CommsPhone) (FileuploadPoolSlice, error) {
	setter := &FileuploadPoolSetter{
		ResidentPhoneE164: omitnull.From(commsPhone0.E164),
	}

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

	return fileuploadPools1, nil
}

func (commsPhone0 *CommsPhone) InsertResidentPhoneE164Pools(ctx context.Context, exec bob.Executor, related ...*FileuploadPoolSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	fileuploadPools1, err := insertCommsPhoneResidentPhoneE164Pools0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.ResidentPhoneE164Pools = append(commsPhone0.R.ResidentPhoneE164Pools, fileuploadPools1...)

	for _, rel := range fileuploadPools1 {
		rel.R.ResidentPhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachResidentPhoneE164Pools(ctx context.Context, exec bob.Executor, related ...*FileuploadPool) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	fileuploadPools1 := FileuploadPoolSlice(related)

	_, err = attachCommsPhoneResidentPhoneE164Pools0(ctx, exec, len(related), fileuploadPools1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.ResidentPhoneE164Pools = append(commsPhone0.R.ResidentPhoneE164Pools, fileuploadPools1...)

	for _, rel := range related {
		rel.R.ResidentPhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhonePhoneE164NotifyPhones0(ctx context.Context, exec bob.Executor, publicreportNotifyPhones1 []*PublicreportNotifyPhoneSetter, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneSlice, error) {
	for i := range publicreportNotifyPhones1 {
		publicreportNotifyPhones1[i].PhoneE164 = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePhoneE164NotifyPhones0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhones1 PublicreportNotifyPhoneSlice, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneSlice, error) {
	setter := &PublicreportNotifyPhoneSetter{
		PhoneE164: omit.From(commsPhone0.E164),
	}

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

	return publicreportNotifyPhones1, nil
}

func (commsPhone0 *CommsPhone) InsertPhoneE164NotifyPhones(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportNotifyPhones1, err := insertCommsPhonePhoneE164NotifyPhones0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhones = append(commsPhone0.R.PhoneE164NotifyPhones, publicreportNotifyPhones1...)

	for _, rel := range publicreportNotifyPhones1 {
		rel.R.PhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhones(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhone) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportNotifyPhones1 := PublicreportNotifyPhoneSlice(related)

	_, err = attachCommsPhonePhoneE164NotifyPhones0(ctx, exec, len(related), publicreportNotifyPhones1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhones = append(commsPhone0.R.PhoneE164NotifyPhones, publicreportNotifyPhones1...)

	for _, rel := range related {
		rel.R.PhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhonePhoneE164NotifyPhoneNuisanceOlds0(ctx context.Context, exec bob.Executor, publicreportNotifyPhoneNuisanceOlds1 []*PublicreportNotifyPhoneNuisanceOldSetter, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneNuisanceOldSlice, error) {
	for i := range publicreportNotifyPhoneNuisanceOlds1 {
		publicreportNotifyPhoneNuisanceOlds1[i].PhoneE164 = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePhoneE164NotifyPhoneNuisanceOlds0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneNuisanceOlds1 PublicreportNotifyPhoneNuisanceOldSlice, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneNuisanceOldSlice, error) {
	setter := &PublicreportNotifyPhoneNuisanceOldSetter{
		PhoneE164: omit.From(commsPhone0.E164),
	}

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

	return publicreportNotifyPhoneNuisanceOlds1, nil
}

func (commsPhone0 *CommsPhone) InsertPhoneE164NotifyPhoneNuisanceOlds(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneNuisanceOldSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportNotifyPhoneNuisanceOlds1, err := insertCommsPhonePhoneE164NotifyPhoneNuisanceOlds0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhoneNuisanceOlds = append(commsPhone0.R.PhoneE164NotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOlds1...)

	for _, rel := range publicreportNotifyPhoneNuisanceOlds1 {
		rel.R.PhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhoneNuisanceOlds(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneNuisanceOld) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportNotifyPhoneNuisanceOlds1 := PublicreportNotifyPhoneNuisanceOldSlice(related)

	_, err = attachCommsPhonePhoneE164NotifyPhoneNuisanceOlds0(ctx, exec, len(related), publicreportNotifyPhoneNuisanceOlds1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhoneNuisanceOlds = append(commsPhone0.R.PhoneE164NotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOlds1...)

	for _, rel := range related {
		rel.R.PhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhonePhoneE164NotifyPhoneWaterOlds0(ctx context.Context, exec bob.Executor, publicreportNotifyPhoneWaterOlds1 []*PublicreportNotifyPhoneWaterOldSetter, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneWaterOldSlice, error) {
	for i := range publicreportNotifyPhoneWaterOlds1 {
		publicreportNotifyPhoneWaterOlds1[i].PhoneE164 = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePhoneE164NotifyPhoneWaterOlds0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWaterOlds1 PublicreportNotifyPhoneWaterOldSlice, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneWaterOldSlice, error) {
	setter := &PublicreportNotifyPhoneWaterOldSetter{
		PhoneE164: omit.From(commsPhone0.E164),
	}

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

	return publicreportNotifyPhoneWaterOlds1, nil
}

func (commsPhone0 *CommsPhone) InsertPhoneE164NotifyPhoneWaterOlds(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneWaterOldSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportNotifyPhoneWaterOlds1, err := insertCommsPhonePhoneE164NotifyPhoneWaterOlds0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhoneWaterOlds = append(commsPhone0.R.PhoneE164NotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOlds1...)

	for _, rel := range publicreportNotifyPhoneWaterOlds1 {
		rel.R.PhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhoneWaterOlds(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneWaterOld) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportNotifyPhoneWaterOlds1 := PublicreportNotifyPhoneWaterOldSlice(related)

	_, err = attachCommsPhonePhoneE164NotifyPhoneWaterOlds0(ctx, exec, len(related), publicreportNotifyPhoneWaterOlds1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164NotifyPhoneWaterOlds = append(commsPhone0.R.PhoneE164NotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOlds1...)

	for _, rel := range related {
		rel.R.PhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhonePhoneE164SubscribePhones0(ctx context.Context, exec bob.Executor, publicreportSubscribePhones1 []*PublicreportSubscribePhoneSetter, commsPhone0 *CommsPhone) (PublicreportSubscribePhoneSlice, error) {
	for i := range publicreportSubscribePhones1 {
		publicreportSubscribePhones1[i].PhoneE164 = omit.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePhoneE164SubscribePhones0(ctx context.Context, exec bob.Executor, count int, publicreportSubscribePhones1 PublicreportSubscribePhoneSlice, commsPhone0 *CommsPhone) (PublicreportSubscribePhoneSlice, error) {
	setter := &PublicreportSubscribePhoneSetter{
		PhoneE164: omit.From(commsPhone0.E164),
	}

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

	return publicreportSubscribePhones1, nil
}

func (commsPhone0 *CommsPhone) InsertPhoneE164SubscribePhones(ctx context.Context, exec bob.Executor, related ...*PublicreportSubscribePhoneSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportSubscribePhones1, err := insertCommsPhonePhoneE164SubscribePhones0(ctx, exec, related, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164SubscribePhones = append(commsPhone0.R.PhoneE164SubscribePhones, publicreportSubscribePhones1...)

	for _, rel := range publicreportSubscribePhones1 {
		rel.R.PhoneE164Phone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPhoneE164SubscribePhones(ctx context.Context, exec bob.Executor, related ...*PublicreportSubscribePhone) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportSubscribePhones1 := PublicreportSubscribePhoneSlice(related)

	_, err = attachCommsPhonePhoneE164SubscribePhones0(ctx, exec, len(related), publicreportSubscribePhones1, commsPhone0)
	if err != nil {
		return err
	}

	commsPhone0.R.PhoneE164SubscribePhones = append(commsPhone0.R.PhoneE164SubscribePhones, publicreportSubscribePhones1...)

	for _, rel := range related {
		rel.R.PhoneE164Phone = commsPhone0
	}

	return nil
}

func insertCommsPhonePhoneMobileResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, commsPhone0 *CommsPhone) (ResidentSlice, error) {
	for i := range residents1 {
		residents1[i].PhoneMobile = omitnull.From(commsPhone0.E164)
	}

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

	return ret, nil
}

func attachCommsPhonePhoneMobileResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, commsPhone0 *CommsPhone) (ResidentSlice, error) {
	setter := &ResidentSetter{
		PhoneMobile: omitnull.From(commsPhone0.E164),
	}

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

	return residents1, nil
}

func (commsPhone0 *CommsPhone) InsertPhoneMobileResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	commsPhone0.R.PhoneMobileResidents = append(commsPhone0.R.PhoneMobileResidents, residents1...)

	for _, rel := range residents1 {
		rel.R.PhoneMobilePhone = commsPhone0
	}
	return nil
}

func (commsPhone0 *CommsPhone) AttachPhoneMobileResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	residents1 := ResidentSlice(related)

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

	commsPhone0.R.PhoneMobileResidents = append(commsPhone0.R.PhoneMobileResidents, residents1...)

	for _, rel := range related {
		rel.R.PhoneMobilePhone = commsPhone0
	}

	return nil
}

type commsPhoneWhere[Q psql.Filterable] struct {
	E164         psql.WhereMod[Q, string]
	IsSubscribed psql.WhereMod[Q, bool]
	Status       psql.WhereMod[Q, enums.CommsPhonestatustype]
	CanSMS       psql.WhereMod[Q, bool]
}

func (commsPhoneWhere[Q]) AliasedAs(alias string) commsPhoneWhere[Q] {
	return buildCommsPhoneWhere[Q](buildCommsPhoneColumns(alias))
}

func buildCommsPhoneWhere[Q psql.Filterable](cols commsPhoneColumns) commsPhoneWhere[Q] {
	return commsPhoneWhere[Q]{
		E164:         psql.Where[Q, string](cols.E164),
		IsSubscribed: psql.Where[Q, bool](cols.IsSubscribed),
		Status:       psql.Where[Q, enums.CommsPhonestatustype](cols.Status),
		CanSMS:       psql.Where[Q, bool](cols.CanSMS),
	}
}

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

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

		o.R.DestinationTextJobs = rels

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

		o.R.DestinationTextLogs = rels

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

		o.R.SourceTextLogs = rels

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

		o.R.Organizations = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.Phones = CommsPhoneSlice{o}
			}
		}
		return nil
	case "PropertyOwnerPhoneE164Pools":
		rels, ok := retrieved.(FileuploadPoolSlice)
		if !ok {
			return fmt.Errorf("commsPhone cannot load %T as %q", retrieved, name)
		}

		o.R.PropertyOwnerPhoneE164Pools = rels

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

		o.R.ResidentPhoneE164Pools = rels

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

		o.R.PhoneE164NotifyPhones = rels

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

		o.R.PhoneE164NotifyPhoneNuisanceOlds = rels

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

		o.R.PhoneE164NotifyPhoneWaterOlds = rels

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

		o.R.PhoneE164SubscribePhones = rels

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

		o.R.PhoneMobileResidents = rels

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

type commsPhonePreloader struct{}

func buildCommsPhonePreloader() commsPhonePreloader {
	return commsPhonePreloader{}
}

type commsPhoneThenLoader[Q orm.Loadable] struct {
	DestinationTextJobs              func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	DestinationTextLogs              func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceTextLogs                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organizations                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PropertyOwnerPhoneE164Pools      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ResidentPhoneE164Pools           func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164NotifyPhones            func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164NotifyPhoneNuisanceOlds func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164NotifyPhoneWaterOlds    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164SubscribePhones         func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneMobileResidents             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] {
	type DestinationTextJobsLoadInterface interface {
		LoadDestinationTextJobs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type DestinationTextLogsLoadInterface interface {
		LoadDestinationTextLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceTextLogsLoadInterface interface {
		LoadSourceTextLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationsLoadInterface interface {
		LoadOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PropertyOwnerPhoneE164PoolsLoadInterface interface {
		LoadPropertyOwnerPhoneE164Pools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResidentPhoneE164PoolsLoadInterface interface {
		LoadResidentPhoneE164Pools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164NotifyPhonesLoadInterface interface {
		LoadPhoneE164NotifyPhones(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164NotifyPhoneNuisanceOldsLoadInterface interface {
		LoadPhoneE164NotifyPhoneNuisanceOlds(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164NotifyPhoneWaterOldsLoadInterface interface {
		LoadPhoneE164NotifyPhoneWaterOlds(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164SubscribePhonesLoadInterface interface {
		LoadPhoneE164SubscribePhones(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneMobileResidentsLoadInterface interface {
		LoadPhoneMobileResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsPhoneThenLoader[Q]{
		DestinationTextJobs: thenLoadBuilder[Q](
			"DestinationTextJobs",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationTextJobsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDestinationTextJobs(ctx, exec, mods...)
			},
		),
		DestinationTextLogs: thenLoadBuilder[Q](
			"DestinationTextLogs",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationTextLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDestinationTextLogs(ctx, exec, mods...)
			},
		),
		SourceTextLogs: thenLoadBuilder[Q](
			"SourceTextLogs",
			func(ctx context.Context, exec bob.Executor, retrieved SourceTextLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceTextLogs(ctx, exec, mods...)
			},
		),
		Organizations: thenLoadBuilder[Q](
			"Organizations",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganizations(ctx, exec, mods...)
			},
		),
		PropertyOwnerPhoneE164Pools: thenLoadBuilder[Q](
			"PropertyOwnerPhoneE164Pools",
			func(ctx context.Context, exec bob.Executor, retrieved PropertyOwnerPhoneE164PoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPropertyOwnerPhoneE164Pools(ctx, exec, mods...)
			},
		),
		ResidentPhoneE164Pools: thenLoadBuilder[Q](
			"ResidentPhoneE164Pools",
			func(ctx context.Context, exec bob.Executor, retrieved ResidentPhoneE164PoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResidentPhoneE164Pools(ctx, exec, mods...)
			},
		),
		PhoneE164NotifyPhones: thenLoadBuilder[Q](
			"PhoneE164NotifyPhones",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164NotifyPhonesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164NotifyPhones(ctx, exec, mods...)
			},
		),
		PhoneE164NotifyPhoneNuisanceOlds: thenLoadBuilder[Q](
			"PhoneE164NotifyPhoneNuisanceOlds",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164NotifyPhoneNuisanceOldsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164NotifyPhoneNuisanceOlds(ctx, exec, mods...)
			},
		),
		PhoneE164NotifyPhoneWaterOlds: thenLoadBuilder[Q](
			"PhoneE164NotifyPhoneWaterOlds",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164NotifyPhoneWaterOldsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164NotifyPhoneWaterOlds(ctx, exec, mods...)
			},
		),
		PhoneE164SubscribePhones: thenLoadBuilder[Q](
			"PhoneE164SubscribePhones",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164SubscribePhonesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164SubscribePhones(ctx, exec, mods...)
			},
		),
		PhoneMobileResidents: thenLoadBuilder[Q](
			"PhoneMobileResidents",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneMobileResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneMobileResidents(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.DestinationTextJobs = related
	return nil
}

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

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

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

		o.R.DestinationTextJobs = nil
	}

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

		for _, rel := range commsTextJobs {

			if !(o.E164 == rel.Destination) {
				continue
			}

			rel.R.DestinationPhone = o

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

	return nil
}

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

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

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

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

	o.R.DestinationTextLogs = related
	return nil
}

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

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

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

		o.R.DestinationTextLogs = nil
	}

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

		for _, rel := range commsTextLogs {

			if !(o.E164 == rel.Destination) {
				continue
			}

			rel.R.DestinationPhone = o

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

	return nil
}

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

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

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

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

	o.R.SourceTextLogs = related
	return nil
}

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

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

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

		o.R.SourceTextLogs = nil
	}

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

		for _, rel := range commsTextLogs {

			if !(o.E164 == rel.Source) {
				continue
			}

			rel.R.SourcePhone = o

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

	return nil
}

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

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

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

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

	o.R.Organizations = related
	return nil
}

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

	// since we are changing the columns, we need to check if the original columns were set or add the defaults
	sq := dialect.SelectQuery{}
	for _, mod := range mods {
		mod.Apply(&sq)
	}

	if len(sq.SelectList.Columns) == 0 {
		mods = append(mods, sm.Columns(Organizations.Columns))
	}

	q := os.Organizations(append(
		mods,
		sm.Columns(DistrictSubscriptionPhones.Columns.PhoneE164.As("related_comms.phone.E164")),
	)...)

	E164Slice := []string{}

	mapper := scan.Mod(scan.StructMapper[*Organization](), func(ctx context.Context, cols []string) (scan.BeforeFunc, func(any, any) error) {
		return func(row *scan.Row) (any, error) {
				E164Slice = append(E164Slice, *new(string))
				row.ScheduleScanByName("related_comms.phone.E164", &E164Slice[len(E164Slice)-1])

				return nil, nil
			},
			func(any, any) error {
				return nil
			}
	})

	organizations, err := bob.Allx[bob.SliceTransformer[*Organization, OrganizationSlice]](ctx, exec, q, mapper)
	if err != nil {
		return err
	}

	for _, o := range os {
		o.R.Organizations = nil
	}

	for _, o := range os {
		for i, rel := range organizations {
			if !(o.E164 == E164Slice[i]) {
				continue
			}

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

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

	return nil
}

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

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

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

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

	o.R.PropertyOwnerPhoneE164Pools = related
	return nil
}

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

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

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

		o.R.PropertyOwnerPhoneE164Pools = nil
	}

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

		for _, rel := range fileuploadPools {

			if !rel.PropertyOwnerPhoneE164.IsValue() {
				continue
			}
			if !(rel.PropertyOwnerPhoneE164.IsValue() && o.E164 == rel.PropertyOwnerPhoneE164.MustGet()) {
				continue
			}

			rel.R.PropertyOwnerPhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.ResidentPhoneE164Pools = related
	return nil
}

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

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

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

		o.R.ResidentPhoneE164Pools = nil
	}

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

		for _, rel := range fileuploadPools {

			if !rel.ResidentPhoneE164.IsValue() {
				continue
			}
			if !(rel.ResidentPhoneE164.IsValue() && o.E164 == rel.ResidentPhoneE164.MustGet()) {
				continue
			}

			rel.R.ResidentPhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.PhoneE164NotifyPhones = related
	return nil
}

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

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

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

		o.R.PhoneE164NotifyPhones = nil
	}

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

		for _, rel := range publicreportNotifyPhones {

			if !(o.E164 == rel.PhoneE164) {
				continue
			}

			rel.R.PhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.PhoneE164NotifyPhoneNuisanceOlds = related
	return nil
}

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

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

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

		o.R.PhoneE164NotifyPhoneNuisanceOlds = nil
	}

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

		for _, rel := range publicreportNotifyPhoneNuisanceOlds {

			if !(o.E164 == rel.PhoneE164) {
				continue
			}

			rel.R.PhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.PhoneE164NotifyPhoneWaterOlds = related
	return nil
}

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

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

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

		o.R.PhoneE164NotifyPhoneWaterOlds = nil
	}

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

		for _, rel := range publicreportNotifyPhoneWaterOlds {

			if !(o.E164 == rel.PhoneE164) {
				continue
			}

			rel.R.PhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.PhoneE164SubscribePhones = related
	return nil
}

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

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

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

		o.R.PhoneE164SubscribePhones = nil
	}

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

		for _, rel := range publicreportSubscribePhones {

			if !(o.E164 == rel.PhoneE164) {
				continue
			}

			rel.R.PhoneE164Phone = o

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

	return nil
}

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

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

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

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

	o.R.PhoneMobileResidents = related
	return nil
}

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

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

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

		o.R.PhoneMobileResidents = nil
	}

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

		for _, rel := range residents {

			if !rel.PhoneMobile.IsValue() {
				continue
			}
			if !(rel.PhoneMobile.IsValue() && o.E164 == rel.PhoneMobile.MustGet()) {
				continue
			}

			rel.R.PhoneMobilePhone = o

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

	return nil
}
