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

package models

import (
	"context"
	"fmt"
	"io"

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

// DistrictSubscriptionEmail is an object representing the database table.
type DistrictSubscriptionEmail struct {
	OrganizationID      int32  `db:"organization_id,pk" `
	EmailContactAddress string `db:"email_contact_address,pk" `

	R districtSubscriptionEmailR `db:"-" `
}

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

// DistrictSubscriptionEmails contains methods to work with the district_subscription_email table
var DistrictSubscriptionEmails = psql.NewTablex[*DistrictSubscriptionEmail, DistrictSubscriptionEmailSlice, *DistrictSubscriptionEmailSetter]("", "district_subscription_email", buildDistrictSubscriptionEmailColumns("district_subscription_email"))

// DistrictSubscriptionEmailsQuery is a query on the district_subscription_email table
type DistrictSubscriptionEmailsQuery = *psql.ViewQuery[*DistrictSubscriptionEmail, DistrictSubscriptionEmailSlice]

// districtSubscriptionEmailR is where relationships are stored.
type districtSubscriptionEmailR struct {
	EmailContactAddressEmailContact *CommsEmailContact // district_subscription_email.district_subscription_email_email_contact_address_fkey
	Organization                    *Organization      // district_subscription_email.district_subscription_email_organization_id_fkey
}

func buildDistrictSubscriptionEmailColumns(alias string) districtSubscriptionEmailColumns {
	return districtSubscriptionEmailColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"organization_id", "email_contact_address",
		).WithParent("district_subscription_email"),
		tableAlias:          alias,
		OrganizationID:      psql.Quote(alias, "organization_id"),
		EmailContactAddress: psql.Quote(alias, "email_contact_address"),
	}
}

type districtSubscriptionEmailColumns struct {
	expr.ColumnsExpr
	tableAlias          string
	OrganizationID      psql.Expression
	EmailContactAddress psql.Expression
}

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

func (districtSubscriptionEmailColumns) AliasedAs(alias string) districtSubscriptionEmailColumns {
	return buildDistrictSubscriptionEmailColumns(alias)
}

// DistrictSubscriptionEmailSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type DistrictSubscriptionEmailSetter struct {
	OrganizationID      omit.Val[int32]  `db:"organization_id,pk" `
	EmailContactAddress omit.Val[string] `db:"email_contact_address,pk" `
}

func (s DistrictSubscriptionEmailSetter) SetColumns() []string {
	vals := make([]string, 0, 2)
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.EmailContactAddress.IsValue() {
		vals = append(vals, "email_contact_address")
	}
	return vals
}

func (s DistrictSubscriptionEmailSetter) Overwrite(t *DistrictSubscriptionEmail) {
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.EmailContactAddress.IsValue() {
		t.EmailContactAddress = s.EmailContactAddress.MustGet()
	}
}

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

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

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

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

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

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

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

	return exprs
}

// FindDistrictSubscriptionEmail retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindDistrictSubscriptionEmail(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, EmailContactAddressPK string, cols ...string) (*DistrictSubscriptionEmail, error) {
	if len(cols) == 0 {
		return DistrictSubscriptionEmails.Query(
			sm.Where(DistrictSubscriptionEmails.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
			sm.Where(DistrictSubscriptionEmails.Columns.EmailContactAddress.EQ(psql.Arg(EmailContactAddressPK))),
		).One(ctx, exec)
	}

	return DistrictSubscriptionEmails.Query(
		sm.Where(DistrictSubscriptionEmails.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(DistrictSubscriptionEmails.Columns.EmailContactAddress.EQ(psql.Arg(EmailContactAddressPK))),
		sm.Columns(DistrictSubscriptionEmails.Columns.Only(cols...)),
	).One(ctx, exec)
}

// DistrictSubscriptionEmailExists checks the presence of a single record by primary key
func DistrictSubscriptionEmailExists(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, EmailContactAddressPK string) (bool, error) {
	return DistrictSubscriptionEmails.Query(
		sm.Where(DistrictSubscriptionEmails.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(DistrictSubscriptionEmails.Columns.EmailContactAddress.EQ(psql.Arg(EmailContactAddressPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the DistrictSubscriptionEmail
func (o *DistrictSubscriptionEmail) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.OrganizationID,
		o.EmailContactAddress,
	)
}

func (o *DistrictSubscriptionEmail) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("district_subscription_email", "organization_id"), psql.Quote("district_subscription_email", "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 DistrictSubscriptionEmail
func (o *DistrictSubscriptionEmail) Update(ctx context.Context, exec bob.Executor, s *DistrictSubscriptionEmailSetter) error {
	v, err := DistrictSubscriptionEmails.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 DistrictSubscriptionEmail record with an executor
func (o *DistrictSubscriptionEmail) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := DistrictSubscriptionEmails.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("district_subscription_email", "organization_id"), psql.Quote("district_subscription_email", "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 DistrictSubscriptionEmailSlice) copyMatchingRows(from ...*DistrictSubscriptionEmail) {
	for i, old := range o {
		for _, new := range from {
			if new.OrganizationID != old.OrganizationID {
				continue
			}
			if new.EmailContactAddress != old.EmailContactAddress {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

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

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

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

func attachDistrictSubscriptionEmailEmailContactAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, districtSubscriptionEmail0 *DistrictSubscriptionEmail, commsEmailContact1 *CommsEmailContact) (*DistrictSubscriptionEmail, error) {
	setter := &DistrictSubscriptionEmailSetter{
		EmailContactAddress: omit.From(commsEmailContact1.Address),
	}

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

	return districtSubscriptionEmail0, nil
}

func (districtSubscriptionEmail0 *DistrictSubscriptionEmail) InsertEmailContactAddressEmailContact(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 = attachDistrictSubscriptionEmailEmailContactAddressEmailContact0(ctx, exec, 1, districtSubscriptionEmail0, commsEmailContact1)
	if err != nil {
		return err
	}

	districtSubscriptionEmail0.R.EmailContactAddressEmailContact = commsEmailContact1

	return nil
}

func (districtSubscriptionEmail0 *DistrictSubscriptionEmail) AttachEmailContactAddressEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
	var err error

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

	districtSubscriptionEmail0.R.EmailContactAddressEmailContact = commsEmailContact1

	return nil
}

func attachDistrictSubscriptionEmailOrganization0(ctx context.Context, exec bob.Executor, count int, districtSubscriptionEmail0 *DistrictSubscriptionEmail, organization1 *Organization) (*DistrictSubscriptionEmail, error) {
	setter := &DistrictSubscriptionEmailSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return districtSubscriptionEmail0, nil
}

func (districtSubscriptionEmail0 *DistrictSubscriptionEmail) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error {
	var err error

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

	_, err = attachDistrictSubscriptionEmailOrganization0(ctx, exec, 1, districtSubscriptionEmail0, organization1)
	if err != nil {
		return err
	}

	districtSubscriptionEmail0.R.Organization = organization1

	return nil
}

func (districtSubscriptionEmail0 *DistrictSubscriptionEmail) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error {
	var err error

	_, err = attachDistrictSubscriptionEmailOrganization0(ctx, exec, 1, districtSubscriptionEmail0, organization1)
	if err != nil {
		return err
	}

	districtSubscriptionEmail0.R.Organization = organization1

	return nil
}

type districtSubscriptionEmailWhere[Q psql.Filterable] struct {
	OrganizationID      psql.WhereMod[Q, int32]
	EmailContactAddress psql.WhereMod[Q, string]
}

func (districtSubscriptionEmailWhere[Q]) AliasedAs(alias string) districtSubscriptionEmailWhere[Q] {
	return buildDistrictSubscriptionEmailWhere[Q](buildDistrictSubscriptionEmailColumns(alias))
}

func buildDistrictSubscriptionEmailWhere[Q psql.Filterable](cols districtSubscriptionEmailColumns) districtSubscriptionEmailWhere[Q] {
	return districtSubscriptionEmailWhere[Q]{
		OrganizationID:      psql.Where[Q, int32](cols.OrganizationID),
		EmailContactAddress: psql.Where[Q, string](cols.EmailContactAddress),
	}
}

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

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

		o.R.EmailContactAddressEmailContact = rel

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

		o.R.Organization = rel

		return nil
	default:
		return fmt.Errorf("districtSubscriptionEmail has no relationship %q", name)
	}
}

type districtSubscriptionEmailPreloader struct {
	EmailContactAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	Organization                    func(...psql.PreloadOption) psql.Preloader
}

func buildDistrictSubscriptionEmailPreloader() districtSubscriptionEmailPreloader {
	return districtSubscriptionEmailPreloader{
		EmailContactAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailContactAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        DistrictSubscriptionEmails,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_contact_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        DistrictSubscriptionEmails,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

type districtSubscriptionEmailThenLoader[Q orm.Loadable] struct {
	EmailContactAddressEmailContact func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organization                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildDistrictSubscriptionEmailThenLoader[Q orm.Loadable]() districtSubscriptionEmailThenLoader[Q] {
	type EmailContactAddressEmailContactLoadInterface interface {
		LoadEmailContactAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return districtSubscriptionEmailThenLoader[Q]{
		EmailContactAddressEmailContact: thenLoadBuilder[Q](
			"EmailContactAddressEmailContact",
			func(ctx context.Context, exec bob.Executor, retrieved EmailContactAddressEmailContactLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailContactAddressEmailContact(ctx, exec, mods...)
			},
		),
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	o.R.EmailContactAddressEmailContact = related
	return nil
}

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

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

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

		for _, rel := range commsEmailContacts {

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

			o.R.EmailContactAddressEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	o.R.Organization = related
	return nil
}

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

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

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

		for _, rel := range organizations {

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}
