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

package models

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

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// PublicreportNotifyEmailPool is an object representing the database table.
type PublicreportNotifyEmailPool struct {
	Created      time.Time           `db:"created" `
	Deleted      null.Val[time.Time] `db:"deleted" `
	PoolID       int32               `db:"pool_id,pk" `
	EmailAddress string              `db:"email_address,pk" `

	R publicreportNotifyEmailPoolR `db:"-" `
}

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

// PublicreportNotifyEmailPools contains methods to work with the notify_email_pool table
var PublicreportNotifyEmailPools = psql.NewTablex[*PublicreportNotifyEmailPool, PublicreportNotifyEmailPoolSlice, *PublicreportNotifyEmailPoolSetter]("publicreport", "notify_email_pool", buildPublicreportNotifyEmailPoolColumns("publicreport.notify_email_pool"))

// PublicreportNotifyEmailPoolsQuery is a query on the notify_email_pool table
type PublicreportNotifyEmailPoolsQuery = *psql.ViewQuery[*PublicreportNotifyEmailPool, PublicreportNotifyEmailPoolSlice]

// publicreportNotifyEmailPoolR is where relationships are stored.
type publicreportNotifyEmailPoolR struct {
	EmailAddressEmailContact *CommsEmailContact // publicreport.notify_email_pool.notify_email_pool_email_address_fkey
	Pool                     *PublicreportPool  // publicreport.notify_email_pool.notify_email_pool_pool_id_fkey
}

func buildPublicreportNotifyEmailPoolColumns(alias string) publicreportNotifyEmailPoolColumns {
	return publicreportNotifyEmailPoolColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "pool_id", "email_address",
		).WithParent("publicreport.notify_email_pool"),
		tableAlias:   alias,
		Created:      psql.Quote(alias, "created"),
		Deleted:      psql.Quote(alias, "deleted"),
		PoolID:       psql.Quote(alias, "pool_id"),
		EmailAddress: psql.Quote(alias, "email_address"),
	}
}

type publicreportNotifyEmailPoolColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Created      psql.Expression
	Deleted      psql.Expression
	PoolID       psql.Expression
	EmailAddress psql.Expression
}

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

func (publicreportNotifyEmailPoolColumns) AliasedAs(alias string) publicreportNotifyEmailPoolColumns {
	return buildPublicreportNotifyEmailPoolColumns(alias)
}

// PublicreportNotifyEmailPoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyEmailPoolSetter struct {
	Created      omit.Val[time.Time]     `db:"created" `
	Deleted      omitnull.Val[time.Time] `db:"deleted" `
	PoolID       omit.Val[int32]         `db:"pool_id,pk" `
	EmailAddress omit.Val[string]        `db:"email_address,pk" `
}

func (s PublicreportNotifyEmailPoolSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if !s.Deleted.IsUnset() {
		vals = append(vals, "deleted")
	}
	if s.PoolID.IsValue() {
		vals = append(vals, "pool_id")
	}
	if s.EmailAddress.IsValue() {
		vals = append(vals, "email_address")
	}
	return vals
}

func (s PublicreportNotifyEmailPoolSetter) Overwrite(t *PublicreportNotifyEmailPool) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.PoolID.IsValue() {
		t.PoolID = s.PoolID.MustGet()
	}
	if s.EmailAddress.IsValue() {
		t.EmailAddress = s.EmailAddress.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindPublicreportNotifyEmailPool retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyEmailPool(ctx context.Context, exec bob.Executor, PoolIDPK int32, EmailAddressPK string, cols ...string) (*PublicreportNotifyEmailPool, error) {
	if len(cols) == 0 {
		return PublicreportNotifyEmailPools.Query(
			sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
			sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
		).One(ctx, exec)
	}

	return PublicreportNotifyEmailPools.Query(
		sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
		sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
		sm.Columns(PublicreportNotifyEmailPools.Columns.Only(cols...)),
	).One(ctx, exec)
}

// PublicreportNotifyEmailPoolExists checks the presence of a single record by primary key
func PublicreportNotifyEmailPoolExists(ctx context.Context, exec bob.Executor, PoolIDPK int32, EmailAddressPK string) (bool, error) {
	return PublicreportNotifyEmailPools.Query(
		sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
		sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the PublicreportNotifyEmailPool
func (o *PublicreportNotifyEmailPool) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.PoolID,
		o.EmailAddress,
	)
}

func (o *PublicreportNotifyEmailPool) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("publicreport.notify_email_pool", "pool_id"), psql.Quote("publicreport.notify_email_pool", "email_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 PublicreportNotifyEmailPool
func (o *PublicreportNotifyEmailPool) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyEmailPoolSetter) error {
	v, err := PublicreportNotifyEmailPools.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 PublicreportNotifyEmailPool record with an executor
func (o *PublicreportNotifyEmailPool) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := PublicreportNotifyEmailPools.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("publicreport.notify_email_pool", "pool_id"), psql.Quote("publicreport.notify_email_pool", "email_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 PublicreportNotifyEmailPoolSlice) copyMatchingRows(from ...*PublicreportNotifyEmailPool) {
	for i, old := range o {
		for _, new := range from {
			if new.PoolID != old.PoolID {
				continue
			}
			if new.EmailAddress != old.EmailAddress {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// EmailAddressEmailContact starts a query for related objects on comms.email_contact
func (o *PublicreportNotifyEmailPool) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
	return CommsEmailContacts.Query(append(mods,
		sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(o.EmailAddress))),
	)...)
}

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

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

// Pool starts a query for related objects on publicreport.pool
func (o *PublicreportNotifyEmailPool) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
	return PublicreportPools.Query(append(mods,
		sm.Where(PublicreportPools.Columns.ID.EQ(psql.Arg(o.PoolID))),
	)...)
}

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

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

func attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailPool, error) {
	setter := &PublicreportNotifyEmailPoolSetter{
		EmailAddress: omit.From(commsEmailContact1.Address),
	}

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

	return publicreportNotifyEmailPool0, nil
}

func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) InsertEmailAddressEmailContact(ctx context.Context, exec bob.Executor, related *CommsEmailContactSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailPool0, commsEmailContact1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailPool0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailPools = append(commsEmailContact1.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPool0)

	return nil
}

func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) AttachEmailAddressEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
	var err error

	_, err = attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailPool0, commsEmailContact1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailPool0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailPools = append(commsEmailContact1.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPool0)

	return nil
}

func attachPublicreportNotifyEmailPoolPool0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool, publicreportPool1 *PublicreportPool) (*PublicreportNotifyEmailPool, error) {
	setter := &PublicreportNotifyEmailPoolSetter{
		PoolID: omit.From(publicreportPool1.ID),
	}

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

	return publicreportNotifyEmailPool0, nil
}

func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) InsertPool(ctx context.Context, exec bob.Executor, related *PublicreportPoolSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailPoolPool0(ctx, exec, 1, publicreportNotifyEmailPool0, publicreportPool1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailPool0.R.Pool = publicreportPool1

	publicreportPool1.R.NotifyEmailPools = append(publicreportPool1.R.NotifyEmailPools, publicreportNotifyEmailPool0)

	return nil
}

func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) AttachPool(ctx context.Context, exec bob.Executor, publicreportPool1 *PublicreportPool) error {
	var err error

	_, err = attachPublicreportNotifyEmailPoolPool0(ctx, exec, 1, publicreportNotifyEmailPool0, publicreportPool1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailPool0.R.Pool = publicreportPool1

	publicreportPool1.R.NotifyEmailPools = append(publicreportPool1.R.NotifyEmailPools, publicreportNotifyEmailPool0)

	return nil
}

type publicreportNotifyEmailPoolWhere[Q psql.Filterable] struct {
	Created      psql.WhereMod[Q, time.Time]
	Deleted      psql.WhereNullMod[Q, time.Time]
	PoolID       psql.WhereMod[Q, int32]
	EmailAddress psql.WhereMod[Q, string]
}

func (publicreportNotifyEmailPoolWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailPoolWhere[Q] {
	return buildPublicreportNotifyEmailPoolWhere[Q](buildPublicreportNotifyEmailPoolColumns(alias))
}

func buildPublicreportNotifyEmailPoolWhere[Q psql.Filterable](cols publicreportNotifyEmailPoolColumns) publicreportNotifyEmailPoolWhere[Q] {
	return publicreportNotifyEmailPoolWhere[Q]{
		Created:      psql.Where[Q, time.Time](cols.Created),
		Deleted:      psql.WhereNull[Q, time.Time](cols.Deleted),
		PoolID:       psql.Where[Q, int32](cols.PoolID),
		EmailAddress: psql.Where[Q, string](cols.EmailAddress),
	}
}

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

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

		o.R.EmailAddressEmailContact = rel

		if rel != nil {
			rel.R.EmailAddressNotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}
		}
		return nil
	case "Pool":
		rel, ok := retrieved.(*PublicreportPool)
		if !ok {
			return fmt.Errorf("publicreportNotifyEmailPool cannot load %T as %q", retrieved, name)
		}

		o.R.Pool = rel

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

type publicreportNotifyEmailPoolPreloader struct {
	EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	Pool                     func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyEmailPoolPreloader() publicreportNotifyEmailPoolPreloader {
	return publicreportNotifyEmailPoolPreloader{
		EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailPools,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		Pool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportPool, PublicreportPoolSlice](psql.PreloadRel{
				Name: "Pool",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailPools,
						To:          PublicreportPools,
						FromColumns: []string{"pool_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportPools.Columns.Names(), opts...)
		},
	}
}

type publicreportNotifyEmailPoolThenLoader[Q orm.Loadable] struct {
	EmailAddressEmailContact func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Pool                     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPublicreportNotifyEmailPoolThenLoader[Q orm.Loadable]() publicreportNotifyEmailPoolThenLoader[Q] {
	type EmailAddressEmailContactLoadInterface interface {
		LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PoolLoadInterface interface {
		LoadPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportNotifyEmailPoolThenLoader[Q]{
		EmailAddressEmailContact: thenLoadBuilder[Q](
			"EmailAddressEmailContact",
			func(ctx context.Context, exec bob.Executor, retrieved EmailAddressEmailContactLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailAddressEmailContact(ctx, exec, mods...)
			},
		),
		Pool: thenLoadBuilder[Q](
			"Pool",
			func(ctx context.Context, exec bob.Executor, retrieved PoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPool(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.EmailAddressNotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}

	o.R.EmailAddressEmailContact = related
	return nil
}

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

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

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

		for _, rel := range commsEmailContacts {

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

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

			o.R.EmailAddressEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.NotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}

	o.R.Pool = related
	return nil
}

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

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

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

		for _, rel := range publicreportPools {

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

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

			o.R.Pool = rel
			break
		}
	}

	return nil
}

type publicreportNotifyEmailPoolJoins[Q dialect.Joinable] struct {
	typ                      string
	EmailAddressEmailContact modAs[Q, commsEmailContactColumns]
	Pool                     modAs[Q, publicreportPoolColumns]
}

func (j publicreportNotifyEmailPoolJoins[Q]) aliasedAs(alias string) publicreportNotifyEmailPoolJoins[Q] {
	return buildPublicreportNotifyEmailPoolJoins[Q](buildPublicreportNotifyEmailPoolColumns(alias), j.typ)
}

func buildPublicreportNotifyEmailPoolJoins[Q dialect.Joinable](cols publicreportNotifyEmailPoolColumns, typ string) publicreportNotifyEmailPoolJoins[Q] {
	return publicreportNotifyEmailPoolJoins[Q]{
		typ: typ,
		EmailAddressEmailContact: modAs[Q, commsEmailContactColumns]{
			c: CommsEmailContacts.Columns,
			f: func(to commsEmailContactColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

				return mods
			},
		},
	}
}
