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

package models

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

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

// CommsMailer is an object representing the database table.
type CommsMailer struct {
	AddressID  int32     `db:"address_id" `
	Created    time.Time `db:"created" `
	ID         int32     `db:"id,pk" `
	Recipient  string    `db:"recipient" `
	UUID       uuid.UUID `db:"uuid" `
	ExternalID string    `db:"external_id" `

	R commsMailerR `db:"-" `
}

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

// CommsMailers contains methods to work with the mailer table
var CommsMailers = psql.NewTablex[*CommsMailer, CommsMailerSlice, *CommsMailerSetter]("comms", "mailer", buildCommsMailerColumns("comms.mailer"))

// CommsMailersQuery is a query on the mailer table
type CommsMailersQuery = *psql.ViewQuery[*CommsMailer, CommsMailerSlice]

// commsMailerR is where relationships are stored.
type commsMailerR struct {
	Address                        *Address                           // comms.mailer.mailer_address_id_fkey
	ComplianceReportRequestMailers ComplianceReportRequestMailerSlice // compliance_report_request_mailer.compliance_report_request_mailer_mailer_id_fkey
}

func buildCommsMailerColumns(alias string) commsMailerColumns {
	return commsMailerColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"address_id", "created", "id", "recipient", "uuid", "external_id",
		).WithParent("comms.mailer"),
		tableAlias: alias,
		AddressID:  psql.Quote(alias, "address_id"),
		Created:    psql.Quote(alias, "created"),
		ID:         psql.Quote(alias, "id"),
		Recipient:  psql.Quote(alias, "recipient"),
		UUID:       psql.Quote(alias, "uuid"),
		ExternalID: psql.Quote(alias, "external_id"),
	}
}

type commsMailerColumns struct {
	expr.ColumnsExpr
	tableAlias string
	AddressID  psql.Expression
	Created    psql.Expression
	ID         psql.Expression
	Recipient  psql.Expression
	UUID       psql.Expression
	ExternalID psql.Expression
}

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

func (commsMailerColumns) AliasedAs(alias string) commsMailerColumns {
	return buildCommsMailerColumns(alias)
}

// CommsMailerSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsMailerSetter struct {
	AddressID  omit.Val[int32]     `db:"address_id" `
	Created    omit.Val[time.Time] `db:"created" `
	ID         omit.Val[int32]     `db:"id,pk" `
	Recipient  omit.Val[string]    `db:"recipient" `
	UUID       omit.Val[uuid.UUID] `db:"uuid" `
	ExternalID omit.Val[string]    `db:"external_id" `
}

func (s CommsMailerSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	if s.AddressID.IsValue() {
		vals = append(vals, "address_id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Recipient.IsValue() {
		vals = append(vals, "recipient")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	if s.ExternalID.IsValue() {
		vals = append(vals, "external_id")
	}
	return vals
}

func (s CommsMailerSetter) Overwrite(t *CommsMailer) {
	if s.AddressID.IsValue() {
		t.AddressID = s.AddressID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Recipient.IsValue() {
		t.Recipient = s.Recipient.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
	if s.ExternalID.IsValue() {
		t.ExternalID = s.ExternalID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *CommsMailer) pkEQ() dialect.Expression {
	return psql.Quote("comms.mailer", "id").EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
	}))
}

// Update uses an executor to update the CommsMailer
func (o *CommsMailer) Update(ctx context.Context, exec bob.Executor, s *CommsMailerSetter) error {
	v, err := CommsMailers.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 CommsMailer record with an executor
func (o *CommsMailer) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := CommsMailers.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("comms.mailer", "id").In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		pkPairs := make([]bob.Expression, len(o))
		for i, row := range o {
			pkPairs[i] = row.primaryKeyVals()
		}
		return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
	}))
}

// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o CommsMailerSlice) copyMatchingRows(from ...*CommsMailer) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// ComplianceReportRequestMailers starts a query for related objects on compliance_report_request_mailer
func (o *CommsMailer) ComplianceReportRequestMailers(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestMailersQuery {
	return ComplianceReportRequestMailers.Query(append(mods,
		sm.Where(ComplianceReportRequestMailers.Columns.MailerID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

func attachCommsMailerAddress0(ctx context.Context, exec bob.Executor, count int, commsMailer0 *CommsMailer, address1 *Address) (*CommsMailer, error) {
	setter := &CommsMailerSetter{
		AddressID: omit.From(address1.ID),
	}

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

	return commsMailer0, nil
}

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

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

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

	commsMailer0.R.Address = address1

	address1.R.Mailers = append(address1.R.Mailers, commsMailer0)

	return nil
}

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

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

	commsMailer0.R.Address = address1

	address1.R.Mailers = append(address1.R.Mailers, commsMailer0)

	return nil
}

func insertCommsMailerComplianceReportRequestMailers0(ctx context.Context, exec bob.Executor, complianceReportRequestMailers1 []*ComplianceReportRequestMailerSetter, commsMailer0 *CommsMailer) (ComplianceReportRequestMailerSlice, error) {
	for i := range complianceReportRequestMailers1 {
		complianceReportRequestMailers1[i].MailerID = omit.From(commsMailer0.ID)
	}

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

	return ret, nil
}

func attachCommsMailerComplianceReportRequestMailers0(ctx context.Context, exec bob.Executor, count int, complianceReportRequestMailers1 ComplianceReportRequestMailerSlice, commsMailer0 *CommsMailer) (ComplianceReportRequestMailerSlice, error) {
	setter := &ComplianceReportRequestMailerSetter{
		MailerID: omit.From(commsMailer0.ID),
	}

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

	return complianceReportRequestMailers1, nil
}

func (commsMailer0 *CommsMailer) InsertComplianceReportRequestMailers(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestMailerSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	complianceReportRequestMailers1, err := insertCommsMailerComplianceReportRequestMailers0(ctx, exec, related, commsMailer0)
	if err != nil {
		return err
	}

	commsMailer0.R.ComplianceReportRequestMailers = append(commsMailer0.R.ComplianceReportRequestMailers, complianceReportRequestMailers1...)

	for _, rel := range complianceReportRequestMailers1 {
		rel.R.Mailer = commsMailer0
	}
	return nil
}

func (commsMailer0 *CommsMailer) AttachComplianceReportRequestMailers(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestMailer) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	complianceReportRequestMailers1 := ComplianceReportRequestMailerSlice(related)

	_, err = attachCommsMailerComplianceReportRequestMailers0(ctx, exec, len(related), complianceReportRequestMailers1, commsMailer0)
	if err != nil {
		return err
	}

	commsMailer0.R.ComplianceReportRequestMailers = append(commsMailer0.R.ComplianceReportRequestMailers, complianceReportRequestMailers1...)

	for _, rel := range related {
		rel.R.Mailer = commsMailer0
	}

	return nil
}

type commsMailerWhere[Q psql.Filterable] struct {
	AddressID  psql.WhereMod[Q, int32]
	Created    psql.WhereMod[Q, time.Time]
	ID         psql.WhereMod[Q, int32]
	Recipient  psql.WhereMod[Q, string]
	UUID       psql.WhereMod[Q, uuid.UUID]
	ExternalID psql.WhereMod[Q, string]
}

func (commsMailerWhere[Q]) AliasedAs(alias string) commsMailerWhere[Q] {
	return buildCommsMailerWhere[Q](buildCommsMailerColumns(alias))
}

func buildCommsMailerWhere[Q psql.Filterable](cols commsMailerColumns) commsMailerWhere[Q] {
	return commsMailerWhere[Q]{
		AddressID:  psql.Where[Q, int32](cols.AddressID),
		Created:    psql.Where[Q, time.Time](cols.Created),
		ID:         psql.Where[Q, int32](cols.ID),
		Recipient:  psql.Where[Q, string](cols.Recipient),
		UUID:       psql.Where[Q, uuid.UUID](cols.UUID),
		ExternalID: psql.Where[Q, string](cols.ExternalID),
	}
}

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

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

		o.R.Address = rel

		if rel != nil {
			rel.R.Mailers = CommsMailerSlice{o}
		}
		return nil
	case "ComplianceReportRequestMailers":
		rels, ok := retrieved.(ComplianceReportRequestMailerSlice)
		if !ok {
			return fmt.Errorf("commsMailer cannot load %T as %q", retrieved, name)
		}

		o.R.ComplianceReportRequestMailers = rels

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

type commsMailerPreloader struct {
	Address func(...psql.PreloadOption) psql.Preloader
}

func buildCommsMailerPreloader() commsMailerPreloader {
	return commsMailerPreloader{
		Address: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Address, AddressSlice](psql.PreloadRel{
				Name: "Address",
				Sides: []psql.PreloadSide{
					{
						From:        CommsMailers,
						To:          Addresses,
						FromColumns: []string{"address_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Addresses.Columns.Names(), opts...)
		},
	}
}

type commsMailerThenLoader[Q orm.Loadable] struct {
	Address                        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ComplianceReportRequestMailers func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsMailerThenLoader[Q orm.Loadable]() commsMailerThenLoader[Q] {
	type AddressLoadInterface interface {
		LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ComplianceReportRequestMailersLoadInterface interface {
		LoadComplianceReportRequestMailers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsMailerThenLoader[Q]{
		Address: thenLoadBuilder[Q](
			"Address",
			func(ctx context.Context, exec bob.Executor, retrieved AddressLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAddress(ctx, exec, mods...)
			},
		),
		ComplianceReportRequestMailers: thenLoadBuilder[Q](
			"ComplianceReportRequestMailers",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestMailersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadComplianceReportRequestMailers(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.Mailers = CommsMailerSlice{o}

	o.R.Address = related
	return nil
}

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

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

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

		for _, rel := range addresses {

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

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

			o.R.Address = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.ComplianceReportRequestMailers = related
	return nil
}

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

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

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

		o.R.ComplianceReportRequestMailers = nil
	}

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

		for _, rel := range complianceReportRequestMailers {

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

			rel.R.Mailer = o

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

	return nil
}
