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

	"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/omit"
	"github.com/stephenafamo/scan"
)

// CommsEmailContact is an object representing the database table.
type CommsEmailContact struct {
	Address      string `db:"address,pk" `
	Confirmed    bool   `db:"confirmed" `
	IsSubscribed bool   `db:"is_subscribed" `
	PublicID     string `db:"public_id" `

	R commsEmailContactR `db:"-" `

	C commsEmailContactC `db:"-" `
}

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

// CommsEmailContacts contains methods to work with the email_contact table
var CommsEmailContacts = psql.NewTablex[*CommsEmailContact, CommsEmailContactSlice, *CommsEmailContactSetter]("comms", "email_contact", buildCommsEmailContactColumns("comms.email_contact"))

// CommsEmailContactsQuery is a query on the email_contact table
type CommsEmailContactsQuery = *psql.ViewQuery[*CommsEmailContact, CommsEmailContactSlice]

// commsEmailContactR is where relationships are stored.
type commsEmailContactR struct {
	DestinationEmailLogs             CommsEmailLogSlice                   // comms.email_log.email_log_destination_fkey
	Organizations                    OrganizationSlice                    // district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey
	EmailAddressNotifyEmailNuisances PublicreportNotifyEmailNuisanceSlice // publicreport.notify_email_nuisance.notify_email_nuisance_email_address_fkey
	EmailAddressNotifyEmailPools     PublicreportNotifyEmailPoolSlice     // publicreport.notify_email_pool.notify_email_pool_email_address_fkey
	EmailAddressSubscribeEmails      PublicreportSubscribeEmailSlice      // publicreport.subscribe_email.subscribe_email_email_address_fkey
}

func buildCommsEmailContactColumns(alias string) commsEmailContactColumns {
	return commsEmailContactColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"address", "confirmed", "is_subscribed", "public_id",
		).WithParent("comms.email_contact"),
		tableAlias:   alias,
		Address:      psql.Quote(alias, "address"),
		Confirmed:    psql.Quote(alias, "confirmed"),
		IsSubscribed: psql.Quote(alias, "is_subscribed"),
		PublicID:     psql.Quote(alias, "public_id"),
	}
}

type commsEmailContactColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Address      psql.Expression
	Confirmed    psql.Expression
	IsSubscribed psql.Expression
	PublicID     psql.Expression
}

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

func (commsEmailContactColumns) AliasedAs(alias string) commsEmailContactColumns {
	return buildCommsEmailContactColumns(alias)
}

// CommsEmailContactSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsEmailContactSetter struct {
	Address      omit.Val[string] `db:"address,pk" `
	Confirmed    omit.Val[bool]   `db:"confirmed" `
	IsSubscribed omit.Val[bool]   `db:"is_subscribed" `
	PublicID     omit.Val[string] `db:"public_id" `
}

func (s CommsEmailContactSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.Address.IsValue() {
		vals = append(vals, "address")
	}
	if s.Confirmed.IsValue() {
		vals = append(vals, "confirmed")
	}
	if s.IsSubscribed.IsValue() {
		vals = append(vals, "is_subscribed")
	}
	if s.PublicID.IsValue() {
		vals = append(vals, "public_id")
	}
	return vals
}

func (s CommsEmailContactSetter) Overwrite(t *CommsEmailContact) {
	if s.Address.IsValue() {
		t.Address = s.Address.MustGet()
	}
	if s.Confirmed.IsValue() {
		t.Confirmed = s.Confirmed.MustGet()
	}
	if s.IsSubscribed.IsValue() {
		t.IsSubscribed = s.IsSubscribed.MustGet()
	}
	if s.PublicID.IsValue() {
		t.PublicID = s.PublicID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return CommsEmailContacts.Query(
		sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(AddressPK))),
		sm.Columns(CommsEmailContacts.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("comms.email_contact", "address").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 CommsEmailContactSlice) copyMatchingRows(from ...*CommsEmailContact) {
	for i, old := range o {
		for _, new := range from {
			if new.Address != old.Address {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// DestinationEmailLogs starts a query for related objects on comms.email_log
func (o *CommsEmailContact) DestinationEmailLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailLogsQuery {
	return CommsEmailLogs.Query(append(mods,
		sm.Where(CommsEmailLogs.Columns.Destination.EQ(psql.Arg(o.Address))),
	)...)
}

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

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

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

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

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

// EmailAddressNotifyEmailNuisances starts a query for related objects on publicreport.notify_email_nuisance
func (o *CommsEmailContact) EmailAddressNotifyEmailNuisances(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailNuisancesQuery {
	return PublicreportNotifyEmailNuisances.Query(append(mods,
		sm.Where(PublicreportNotifyEmailNuisances.Columns.EmailAddress.EQ(psql.Arg(o.Address))),
	)...)
}

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

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

// EmailAddressNotifyEmailPools starts a query for related objects on publicreport.notify_email_pool
func (o *CommsEmailContact) EmailAddressNotifyEmailPools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailPoolsQuery {
	return PublicreportNotifyEmailPools.Query(append(mods,
		sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(o.Address))),
	)...)
}

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

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

// EmailAddressSubscribeEmails starts a query for related objects on publicreport.subscribe_email
func (o *CommsEmailContact) EmailAddressSubscribeEmails(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportSubscribeEmailsQuery {
	return PublicreportSubscribeEmails.Query(append(mods,
		sm.Where(PublicreportSubscribeEmails.Columns.EmailAddress.EQ(psql.Arg(o.Address))),
	)...)
}

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

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

func insertCommsEmailContactDestinationEmailLogs0(ctx context.Context, exec bob.Executor, commsEmailLogs1 []*CommsEmailLogSetter, commsEmailContact0 *CommsEmailContact) (CommsEmailLogSlice, error) {
	for i := range commsEmailLogs1 {
		commsEmailLogs1[i].Destination = omit.From(commsEmailContact0.Address)
	}

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

	return ret, nil
}

func attachCommsEmailContactDestinationEmailLogs0(ctx context.Context, exec bob.Executor, count int, commsEmailLogs1 CommsEmailLogSlice, commsEmailContact0 *CommsEmailContact) (CommsEmailLogSlice, error) {
	setter := &CommsEmailLogSetter{
		Destination: omit.From(commsEmailContact0.Address),
	}

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

	return commsEmailLogs1, nil
}

func (commsEmailContact0 *CommsEmailContact) InsertDestinationEmailLogs(ctx context.Context, exec bob.Executor, related ...*CommsEmailLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	commsEmailLogs1, err := insertCommsEmailContactDestinationEmailLogs0(ctx, exec, related, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.DestinationEmailLogs = append(commsEmailContact0.R.DestinationEmailLogs, commsEmailLogs1...)

	for _, rel := range commsEmailLogs1 {
		rel.R.DestinationEmailContact = commsEmailContact0
	}
	return nil
}

func (commsEmailContact0 *CommsEmailContact) AttachDestinationEmailLogs(ctx context.Context, exec bob.Executor, related ...*CommsEmailLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	commsEmailLogs1 := CommsEmailLogSlice(related)

	_, err = attachCommsEmailContactDestinationEmailLogs0(ctx, exec, len(related), commsEmailLogs1, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.DestinationEmailLogs = append(commsEmailContact0.R.DestinationEmailLogs, commsEmailLogs1...)

	for _, rel := range related {
		rel.R.DestinationEmailContact = commsEmailContact0
	}

	return nil
}

func attachCommsEmailContactOrganizations0(ctx context.Context, exec bob.Executor, count int, commsEmailContact0 *CommsEmailContact, organizations2 OrganizationSlice) (DistrictSubscriptionEmailSlice, error) {
	setters := make([]*DistrictSubscriptionEmailSetter, count)
	for i := range count {
		setters[i] = &DistrictSubscriptionEmailSetter{
			EmailContactAddress: omit.From(commsEmailContact0.Address),
			OrganizationID:      omit.From(organizations2[i].ID),
		}
	}

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

	return districtSubscriptionEmails1, nil
}

func (commsEmailContact0 *CommsEmailContact) 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 = attachCommsEmailContactOrganizations0(ctx, exec, len(related), commsEmailContact0, organizations2)
	if err != nil {
		return err
	}

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

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

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

	var err error
	organizations2 := OrganizationSlice(related)

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

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

	for _, rel := range related {
		rel.R.EmailContacts = append(rel.R.EmailContacts, commsEmailContact0)
	}

	return nil
}

func insertCommsEmailContactEmailAddressNotifyEmailNuisances0(ctx context.Context, exec bob.Executor, publicreportNotifyEmailNuisances1 []*PublicreportNotifyEmailNuisanceSetter, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailNuisanceSlice, error) {
	for i := range publicreportNotifyEmailNuisances1 {
		publicreportNotifyEmailNuisances1[i].EmailAddress = omit.From(commsEmailContact0.Address)
	}

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

	return ret, nil
}

func attachCommsEmailContactEmailAddressNotifyEmailNuisances0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailNuisances1 PublicreportNotifyEmailNuisanceSlice, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailNuisanceSlice, error) {
	setter := &PublicreportNotifyEmailNuisanceSetter{
		EmailAddress: omit.From(commsEmailContact0.Address),
	}

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

	return publicreportNotifyEmailNuisances1, nil
}

func (commsEmailContact0 *CommsEmailContact) InsertEmailAddressNotifyEmailNuisances(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailNuisanceSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportNotifyEmailNuisances1, err := insertCommsEmailContactEmailAddressNotifyEmailNuisances0(ctx, exec, related, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressNotifyEmailNuisances = append(commsEmailContact0.R.EmailAddressNotifyEmailNuisances, publicreportNotifyEmailNuisances1...)

	for _, rel := range publicreportNotifyEmailNuisances1 {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}
	return nil
}

func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressNotifyEmailNuisances(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailNuisance) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportNotifyEmailNuisances1 := PublicreportNotifyEmailNuisanceSlice(related)

	_, err = attachCommsEmailContactEmailAddressNotifyEmailNuisances0(ctx, exec, len(related), publicreportNotifyEmailNuisances1, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressNotifyEmailNuisances = append(commsEmailContact0.R.EmailAddressNotifyEmailNuisances, publicreportNotifyEmailNuisances1...)

	for _, rel := range related {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}

	return nil
}

func insertCommsEmailContactEmailAddressNotifyEmailPools0(ctx context.Context, exec bob.Executor, publicreportNotifyEmailPools1 []*PublicreportNotifyEmailPoolSetter, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailPoolSlice, error) {
	for i := range publicreportNotifyEmailPools1 {
		publicreportNotifyEmailPools1[i].EmailAddress = omit.From(commsEmailContact0.Address)
	}

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

	return ret, nil
}

func attachCommsEmailContactEmailAddressNotifyEmailPools0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPools1 PublicreportNotifyEmailPoolSlice, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailPoolSlice, error) {
	setter := &PublicreportNotifyEmailPoolSetter{
		EmailAddress: omit.From(commsEmailContact0.Address),
	}

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

	return publicreportNotifyEmailPools1, nil
}

func (commsEmailContact0 *CommsEmailContact) InsertEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailPoolSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportNotifyEmailPools1, err := insertCommsEmailContactEmailAddressNotifyEmailPools0(ctx, exec, related, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressNotifyEmailPools = append(commsEmailContact0.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPools1...)

	for _, rel := range publicreportNotifyEmailPools1 {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}
	return nil
}

func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailPool) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportNotifyEmailPools1 := PublicreportNotifyEmailPoolSlice(related)

	_, err = attachCommsEmailContactEmailAddressNotifyEmailPools0(ctx, exec, len(related), publicreportNotifyEmailPools1, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressNotifyEmailPools = append(commsEmailContact0.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPools1...)

	for _, rel := range related {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}

	return nil
}

func insertCommsEmailContactEmailAddressSubscribeEmails0(ctx context.Context, exec bob.Executor, publicreportSubscribeEmails1 []*PublicreportSubscribeEmailSetter, commsEmailContact0 *CommsEmailContact) (PublicreportSubscribeEmailSlice, error) {
	for i := range publicreportSubscribeEmails1 {
		publicreportSubscribeEmails1[i].EmailAddress = omit.From(commsEmailContact0.Address)
	}

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

	return ret, nil
}

func attachCommsEmailContactEmailAddressSubscribeEmails0(ctx context.Context, exec bob.Executor, count int, publicreportSubscribeEmails1 PublicreportSubscribeEmailSlice, commsEmailContact0 *CommsEmailContact) (PublicreportSubscribeEmailSlice, error) {
	setter := &PublicreportSubscribeEmailSetter{
		EmailAddress: omit.From(commsEmailContact0.Address),
	}

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

	return publicreportSubscribeEmails1, nil
}

func (commsEmailContact0 *CommsEmailContact) InsertEmailAddressSubscribeEmails(ctx context.Context, exec bob.Executor, related ...*PublicreportSubscribeEmailSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportSubscribeEmails1, err := insertCommsEmailContactEmailAddressSubscribeEmails0(ctx, exec, related, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressSubscribeEmails = append(commsEmailContact0.R.EmailAddressSubscribeEmails, publicreportSubscribeEmails1...)

	for _, rel := range publicreportSubscribeEmails1 {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}
	return nil
}

func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressSubscribeEmails(ctx context.Context, exec bob.Executor, related ...*PublicreportSubscribeEmail) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportSubscribeEmails1 := PublicreportSubscribeEmailSlice(related)

	_, err = attachCommsEmailContactEmailAddressSubscribeEmails0(ctx, exec, len(related), publicreportSubscribeEmails1, commsEmailContact0)
	if err != nil {
		return err
	}

	commsEmailContact0.R.EmailAddressSubscribeEmails = append(commsEmailContact0.R.EmailAddressSubscribeEmails, publicreportSubscribeEmails1...)

	for _, rel := range related {
		rel.R.EmailAddressEmailContact = commsEmailContact0
	}

	return nil
}

type commsEmailContactWhere[Q psql.Filterable] struct {
	Address      psql.WhereMod[Q, string]
	Confirmed    psql.WhereMod[Q, bool]
	IsSubscribed psql.WhereMod[Q, bool]
	PublicID     psql.WhereMod[Q, string]
}

func (commsEmailContactWhere[Q]) AliasedAs(alias string) commsEmailContactWhere[Q] {
	return buildCommsEmailContactWhere[Q](buildCommsEmailContactColumns(alias))
}

func buildCommsEmailContactWhere[Q psql.Filterable](cols commsEmailContactColumns) commsEmailContactWhere[Q] {
	return commsEmailContactWhere[Q]{
		Address:      psql.Where[Q, string](cols.Address),
		Confirmed:    psql.Where[Q, bool](cols.Confirmed),
		IsSubscribed: psql.Where[Q, bool](cols.IsSubscribed),
		PublicID:     psql.Where[Q, string](cols.PublicID),
	}
}

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

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

		o.R.DestinationEmailLogs = rels

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

		o.R.Organizations = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.EmailContacts = CommsEmailContactSlice{o}
			}
		}
		return nil
	case "EmailAddressNotifyEmailNuisances":
		rels, ok := retrieved.(PublicreportNotifyEmailNuisanceSlice)
		if !ok {
			return fmt.Errorf("commsEmailContact cannot load %T as %q", retrieved, name)
		}

		o.R.EmailAddressNotifyEmailNuisances = rels

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

		o.R.EmailAddressNotifyEmailPools = rels

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

		o.R.EmailAddressSubscribeEmails = rels

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

type commsEmailContactPreloader struct{}

func buildCommsEmailContactPreloader() commsEmailContactPreloader {
	return commsEmailContactPreloader{}
}

type commsEmailContactThenLoader[Q orm.Loadable] struct {
	DestinationEmailLogs             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organizations                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressNotifyEmailNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressNotifyEmailPools     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressSubscribeEmails      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsEmailContactThenLoader[Q orm.Loadable]() commsEmailContactThenLoader[Q] {
	type DestinationEmailLogsLoadInterface interface {
		LoadDestinationEmailLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationsLoadInterface interface {
		LoadOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressNotifyEmailNuisancesLoadInterface interface {
		LoadEmailAddressNotifyEmailNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressNotifyEmailPoolsLoadInterface interface {
		LoadEmailAddressNotifyEmailPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressSubscribeEmailsLoadInterface interface {
		LoadEmailAddressSubscribeEmails(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsEmailContactThenLoader[Q]{
		DestinationEmailLogs: thenLoadBuilder[Q](
			"DestinationEmailLogs",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationEmailLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDestinationEmailLogs(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...)
			},
		),
		EmailAddressNotifyEmailNuisances: thenLoadBuilder[Q](
			"EmailAddressNotifyEmailNuisances",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailNuisancesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailAddressNotifyEmailNuisances(ctx, exec, mods...)
			},
		),
		EmailAddressNotifyEmailPools: thenLoadBuilder[Q](
			"EmailAddressNotifyEmailPools",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailPoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailAddressNotifyEmailPools(ctx, exec, mods...)
			},
		),
		EmailAddressSubscribeEmails: thenLoadBuilder[Q](
			"EmailAddressSubscribeEmails",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressSubscribeEmailsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailAddressSubscribeEmails(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.DestinationEmailLogs = related
	return nil
}

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

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

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

		o.R.DestinationEmailLogs = nil
	}

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

		for _, rel := range commsEmailLogs {

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

			rel.R.DestinationEmailContact = o

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

	return nil
}

// LoadOrganizations loads the commsEmailContact's Organizations into the .R struct
func (o *CommsEmailContact) 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.EmailContacts = CommsEmailContactSlice{o}
	}

	o.R.Organizations = related
	return nil
}

// LoadOrganizations loads the commsEmailContact's Organizations into the .R struct
func (os CommsEmailContactSlice) 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(DistrictSubscriptionEmails.Columns.EmailContactAddress.As("related_comms.email_contact.Address")),
	)...)

	AddressSlice := []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) {
				AddressSlice = append(AddressSlice, *new(string))
				row.ScheduleScanByName("related_comms.email_contact.Address", &AddressSlice[len(AddressSlice)-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.Address == AddressSlice[i]) {
				continue
			}

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

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

	return nil
}

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

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

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

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

	o.R.EmailAddressNotifyEmailNuisances = related
	return nil
}

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

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

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

		o.R.EmailAddressNotifyEmailNuisances = nil
	}

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

		for _, rel := range publicreportNotifyEmailNuisances {

			if !(o.Address == rel.EmailAddress) {
				continue
			}

			rel.R.EmailAddressEmailContact = o

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

	return nil
}

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

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

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

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

	o.R.EmailAddressNotifyEmailPools = related
	return nil
}

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

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

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

		o.R.EmailAddressNotifyEmailPools = nil
	}

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

		for _, rel := range publicreportNotifyEmailPools {

			if !(o.Address == rel.EmailAddress) {
				continue
			}

			rel.R.EmailAddressEmailContact = o

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

	return nil
}

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

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

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

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

	o.R.EmailAddressSubscribeEmails = related
	return nil
}

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

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

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

		o.R.EmailAddressSubscribeEmails = nil
	}

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

		for _, rel := range publicreportSubscribeEmails {

			if !(o.Address == rel.EmailAddress) {
				continue
			}

			rel.R.EmailAddressEmailContact = o

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

	return nil
}

// commsEmailContactC is where relationship counts are stored.
type commsEmailContactC struct {
	DestinationEmailLogs             *int64
	Organizations                    *int64
	EmailAddressNotifyEmailNuisances *int64
	EmailAddressNotifyEmailPools     *int64
	EmailAddressSubscribeEmails      *int64
}

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

	switch name {
	case "DestinationEmailLogs":
		o.C.DestinationEmailLogs = &count
	case "Organizations":
		o.C.Organizations = &count
	case "EmailAddressNotifyEmailNuisances":
		o.C.EmailAddressNotifyEmailNuisances = &count
	case "EmailAddressNotifyEmailPools":
		o.C.EmailAddressNotifyEmailPools = &count
	case "EmailAddressSubscribeEmails":
		o.C.EmailAddressSubscribeEmails = &count
	}
	return nil
}

type commsEmailContactCountPreloader struct {
	DestinationEmailLogs             func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	Organizations                    func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	EmailAddressNotifyEmailNuisances func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	EmailAddressNotifyEmailPools     func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	EmailAddressSubscribeEmails      func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
}

func buildCommsEmailContactCountPreloader() commsEmailContactCountPreloader {
	return commsEmailContactCountPreloader{
		DestinationEmailLogs: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*CommsEmailContact]("DestinationEmailLogs", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = CommsEmailContacts.Alias()
				}

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

					sm.From(CommsEmailLogs.Name()),
					sm.Where(psql.Quote(CommsEmailLogs.Alias(), "destination").EQ(psql.Quote(parent, "address"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		Organizations: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*CommsEmailContact]("Organizations", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = CommsEmailContacts.Alias()
				}

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

					sm.From(DistrictSubscriptionEmails.Name()),
					sm.Where(psql.Quote(DistrictSubscriptionEmails.Alias(), "email_contact_address").EQ(psql.Quote(parent, "address"))),
					sm.InnerJoin(Organizations.Name()).On(
						psql.Quote(Organizations.Alias(), "id").EQ(psql.Quote(DistrictSubscriptionEmails.Alias(), "organization_id")),
					),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		EmailAddressNotifyEmailNuisances: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*CommsEmailContact]("EmailAddressNotifyEmailNuisances", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = CommsEmailContacts.Alias()
				}

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

					sm.From(PublicreportNotifyEmailNuisances.Name()),
					sm.Where(psql.Quote(PublicreportNotifyEmailNuisances.Alias(), "email_address").EQ(psql.Quote(parent, "address"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		EmailAddressNotifyEmailPools: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*CommsEmailContact]("EmailAddressNotifyEmailPools", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = CommsEmailContacts.Alias()
				}

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

					sm.From(PublicreportNotifyEmailPools.Name()),
					sm.Where(psql.Quote(PublicreportNotifyEmailPools.Alias(), "email_address").EQ(psql.Quote(parent, "address"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		EmailAddressSubscribeEmails: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*CommsEmailContact]("EmailAddressSubscribeEmails", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = CommsEmailContacts.Alias()
				}

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

					sm.From(PublicreportSubscribeEmails.Name()),
					sm.Where(psql.Quote(PublicreportSubscribeEmails.Alias(), "email_address").EQ(psql.Quote(parent, "address"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
	}
}

type commsEmailContactCountThenLoader[Q orm.Loadable] struct {
	DestinationEmailLogs             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organizations                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressNotifyEmailNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressNotifyEmailPools     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	EmailAddressSubscribeEmails      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsEmailContactCountThenLoader[Q orm.Loadable]() commsEmailContactCountThenLoader[Q] {
	type DestinationEmailLogsCountInterface interface {
		LoadCountDestinationEmailLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationsCountInterface interface {
		LoadCountOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressNotifyEmailNuisancesCountInterface interface {
		LoadCountEmailAddressNotifyEmailNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressNotifyEmailPoolsCountInterface interface {
		LoadCountEmailAddressNotifyEmailPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type EmailAddressSubscribeEmailsCountInterface interface {
		LoadCountEmailAddressSubscribeEmails(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsEmailContactCountThenLoader[Q]{
		DestinationEmailLogs: countThenLoadBuilder[Q](
			"DestinationEmailLogs",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationEmailLogsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountDestinationEmailLogs(ctx, exec, mods...)
			},
		),
		Organizations: countThenLoadBuilder[Q](
			"Organizations",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountOrganizations(ctx, exec, mods...)
			},
		),
		EmailAddressNotifyEmailNuisances: countThenLoadBuilder[Q](
			"EmailAddressNotifyEmailNuisances",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailNuisancesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountEmailAddressNotifyEmailNuisances(ctx, exec, mods...)
			},
		),
		EmailAddressNotifyEmailPools: countThenLoadBuilder[Q](
			"EmailAddressNotifyEmailPools",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailPoolsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountEmailAddressNotifyEmailPools(ctx, exec, mods...)
			},
		),
		EmailAddressSubscribeEmails: countThenLoadBuilder[Q](
			"EmailAddressSubscribeEmails",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressSubscribeEmailsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountEmailAddressSubscribeEmails(ctx, exec, mods...)
			},
		),
	}
}

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

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

	o.C.DestinationEmailLogs = &count
	return nil
}

// LoadCountDestinationEmailLogs loads the count of DestinationEmailLogs for a slice
func (os CommsEmailContactSlice) LoadCountDestinationEmailLogs(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.LoadCountDestinationEmailLogs(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

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

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

	o.C.Organizations = &count
	return nil
}

// LoadCountOrganizations loads the count of Organizations for a slice
func (os CommsEmailContactSlice) LoadCountOrganizations(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.LoadCountOrganizations(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

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

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

	o.C.EmailAddressNotifyEmailNuisances = &count
	return nil
}

// LoadCountEmailAddressNotifyEmailNuisances loads the count of EmailAddressNotifyEmailNuisances for a slice
func (os CommsEmailContactSlice) LoadCountEmailAddressNotifyEmailNuisances(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.LoadCountEmailAddressNotifyEmailNuisances(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

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

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

	o.C.EmailAddressNotifyEmailPools = &count
	return nil
}

// LoadCountEmailAddressNotifyEmailPools loads the count of EmailAddressNotifyEmailPools for a slice
func (os CommsEmailContactSlice) LoadCountEmailAddressNotifyEmailPools(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.LoadCountEmailAddressNotifyEmailPools(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

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

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

	o.C.EmailAddressSubscribeEmails = &count
	return nil
}

// LoadCountEmailAddressSubscribeEmails loads the count of EmailAddressSubscribeEmails for a slice
func (os CommsEmailContactSlice) LoadCountEmailAddressSubscribeEmails(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.LoadCountEmailAddressSubscribeEmails(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

type commsEmailContactJoins[Q dialect.Joinable] struct {
	typ                              string
	DestinationEmailLogs             modAs[Q, commsEmailLogColumns]
	Organizations                    modAs[Q, organizationColumns]
	EmailAddressNotifyEmailNuisances modAs[Q, publicreportNotifyEmailNuisanceColumns]
	EmailAddressNotifyEmailPools     modAs[Q, publicreportNotifyEmailPoolColumns]
	EmailAddressSubscribeEmails      modAs[Q, publicreportSubscribeEmailColumns]
}

func (j commsEmailContactJoins[Q]) aliasedAs(alias string) commsEmailContactJoins[Q] {
	return buildCommsEmailContactJoins[Q](buildCommsEmailContactColumns(alias), j.typ)
}

func buildCommsEmailContactJoins[Q dialect.Joinable](cols commsEmailContactColumns, typ string) commsEmailContactJoins[Q] {
	return commsEmailContactJoins[Q]{
		typ: typ,
		DestinationEmailLogs: modAs[Q, commsEmailLogColumns]{
			c: CommsEmailLogs.Columns,
			f: func(to commsEmailLogColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, CommsEmailLogs.Name().As(to.Alias())).On(
						to.Destination.EQ(cols.Address),
					))
				}

				return mods
			},
		},
		Organizations: modAs[Q, organizationColumns]{
			c: Organizations.Columns,
			f: func(to organizationColumns) bob.Mod[Q] {
				random := strconv.FormatInt(randInt(), 10)
				mods := make(mods.QueryMods[Q], 0, 2)

				{
					to := DistrictSubscriptionEmails.Columns.AliasedAs(DistrictSubscriptionEmails.Columns.Alias() + random)
					mods = append(mods, dialect.Join[Q](typ, DistrictSubscriptionEmails.Name().As(to.Alias())).On(
						to.EmailContactAddress.EQ(cols.Address),
					))
				}
				{
					cols := DistrictSubscriptionEmails.Columns.AliasedAs(DistrictSubscriptionEmails.Columns.Alias() + random)
					mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On(
						to.ID.EQ(cols.OrganizationID),
					))
				}

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

				{
					mods = append(mods, dialect.Join[Q](typ, PublicreportNotifyEmailNuisances.Name().As(to.Alias())).On(
						to.EmailAddress.EQ(cols.Address),
					))
				}

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

				{
					mods = append(mods, dialect.Join[Q](typ, PublicreportNotifyEmailPools.Name().As(to.Alias())).On(
						to.EmailAddress.EQ(cols.Address),
					))
				}

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

				{
					mods = append(mods, dialect.Join[Q](typ, PublicreportSubscribeEmails.Name().As(to.Alias())).On(
						to.EmailAddress.EQ(cols.Address),
					))
				}

				return mods
			},
		},
	}
}
