// 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/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// Communication is an object representing the database table.
type Communication struct {
	Created            time.Time                 `db:"created" `
	ID                 int32                     `db:"id,pk" `
	OrganizationID     int32                     `db:"organization_id" `
	ResponseEmailLogID null.Val[int32]           `db:"response_email_log_id" `
	ResponseTextLogID  null.Val[int32]           `db:"response_text_log_id" `
	SourceEmailLogID   null.Val[int32]           `db:"source_email_log_id" `
	SourceReportID     null.Val[int32]           `db:"source_report_id" `
	SourceTextLogID    null.Val[int32]           `db:"source_text_log_id" `
	Status             enums.Communicationstatus `db:"status" `

	R communicationR `db:"-" `
}

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

// Communications contains methods to work with the communication table
var Communications = psql.NewTablex[*Communication, CommunicationSlice, *CommunicationSetter]("", "communication", buildCommunicationColumns("communication"))

// CommunicationsQuery is a query on the communication table
type CommunicationsQuery = *psql.ViewQuery[*Communication, CommunicationSlice]

// communicationR is where relationships are stored.
type communicationR struct {
	Organization             *Organization              // communication.communication_organization_id_fkey
	ResponseEmailLogEmailLog *CommsEmailLog             // communication.communication_response_email_log_id_fkey
	ResponseTextLogTextLog   *CommsTextLog              // communication.communication_response_text_log_id_fkey
	SourceEmailLogEmailLog   *CommsEmailLog             // communication.communication_source_email_log_id_fkey
	SourceReportReport       *PublicreportReport        // communication.communication_source_report_id_fkey
	SourceTextLogTextLog     *CommsTextLog              // communication.communication_source_text_log_id_fkey
	CommunicationLogEntries  CommunicationLogEntrySlice // communication_log_entry.communication_log_entry_communication_id_fkey
}

func buildCommunicationColumns(alias string) communicationColumns {
	return communicationColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "id", "organization_id", "response_email_log_id", "response_text_log_id", "source_email_log_id", "source_report_id", "source_text_log_id", "status",
		).WithParent("communication"),
		tableAlias:         alias,
		Created:            psql.Quote(alias, "created"),
		ID:                 psql.Quote(alias, "id"),
		OrganizationID:     psql.Quote(alias, "organization_id"),
		ResponseEmailLogID: psql.Quote(alias, "response_email_log_id"),
		ResponseTextLogID:  psql.Quote(alias, "response_text_log_id"),
		SourceEmailLogID:   psql.Quote(alias, "source_email_log_id"),
		SourceReportID:     psql.Quote(alias, "source_report_id"),
		SourceTextLogID:    psql.Quote(alias, "source_text_log_id"),
		Status:             psql.Quote(alias, "status"),
	}
}

type communicationColumns struct {
	expr.ColumnsExpr
	tableAlias         string
	Created            psql.Expression
	ID                 psql.Expression
	OrganizationID     psql.Expression
	ResponseEmailLogID psql.Expression
	ResponseTextLogID  psql.Expression
	SourceEmailLogID   psql.Expression
	SourceReportID     psql.Expression
	SourceTextLogID    psql.Expression
	Status             psql.Expression
}

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

func (communicationColumns) AliasedAs(alias string) communicationColumns {
	return buildCommunicationColumns(alias)
}

// CommunicationSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommunicationSetter struct {
	Created            omit.Val[time.Time]                 `db:"created" `
	ID                 omit.Val[int32]                     `db:"id,pk" `
	OrganizationID     omit.Val[int32]                     `db:"organization_id" `
	ResponseEmailLogID omitnull.Val[int32]                 `db:"response_email_log_id" `
	ResponseTextLogID  omitnull.Val[int32]                 `db:"response_text_log_id" `
	SourceEmailLogID   omitnull.Val[int32]                 `db:"source_email_log_id" `
	SourceReportID     omitnull.Val[int32]                 `db:"source_report_id" `
	SourceTextLogID    omitnull.Val[int32]                 `db:"source_text_log_id" `
	Status             omit.Val[enums.Communicationstatus] `db:"status" `
}

func (s CommunicationSetter) SetColumns() []string {
	vals := make([]string, 0, 9)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if !s.ResponseEmailLogID.IsUnset() {
		vals = append(vals, "response_email_log_id")
	}
	if !s.ResponseTextLogID.IsUnset() {
		vals = append(vals, "response_text_log_id")
	}
	if !s.SourceEmailLogID.IsUnset() {
		vals = append(vals, "source_email_log_id")
	}
	if !s.SourceReportID.IsUnset() {
		vals = append(vals, "source_report_id")
	}
	if !s.SourceTextLogID.IsUnset() {
		vals = append(vals, "source_text_log_id")
	}
	if s.Status.IsValue() {
		vals = append(vals, "status")
	}
	return vals
}

func (s CommunicationSetter) Overwrite(t *Communication) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if !s.ResponseEmailLogID.IsUnset() {
		t.ResponseEmailLogID = s.ResponseEmailLogID.MustGetNull()
	}
	if !s.ResponseTextLogID.IsUnset() {
		t.ResponseTextLogID = s.ResponseTextLogID.MustGetNull()
	}
	if !s.SourceEmailLogID.IsUnset() {
		t.SourceEmailLogID = s.SourceEmailLogID.MustGetNull()
	}
	if !s.SourceReportID.IsUnset() {
		t.SourceReportID = s.SourceReportID.MustGetNull()
	}
	if !s.SourceTextLogID.IsUnset() {
		t.SourceTextLogID = s.SourceTextLogID.MustGetNull()
	}
	if s.Status.IsValue() {
		t.Status = s.Status.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

// Reload refreshes the Communication using the executor
func (o *Communication) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := Communications.Query(
		sm.Where(Communications.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 CommunicationSlice is retrieved from the database
func (o CommunicationSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

	return psql.Quote("communication", "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 CommunicationSlice) copyMatchingRows(from ...*Communication) {
	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 CommunicationSlice) 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 Communications.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 *Communication:
				o.copyMatchingRows(retrieved)
			case []*Communication:
				o.copyMatchingRows(retrieved...)
			case CommunicationSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a Communication or a slice of Communication
				// then run the AfterUpdateHooks on the slice
				_, err = Communications.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os CommunicationSlice) 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)),
	)...)
}

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

func (os CommunicationSlice) ResponseEmailLogEmailLog(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailLogsQuery {
	pkResponseEmailLogID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkResponseEmailLogID = append(pkResponseEmailLogID, o.ResponseEmailLogID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkResponseEmailLogID), "integer[]")),
	))

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

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

func (os CommunicationSlice) ResponseTextLogTextLog(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	pkResponseTextLogID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkResponseTextLogID = append(pkResponseTextLogID, o.ResponseTextLogID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkResponseTextLogID), "integer[]")),
	))

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

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

func (os CommunicationSlice) SourceEmailLogEmailLog(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailLogsQuery {
	pkSourceEmailLogID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkSourceEmailLogID = append(pkSourceEmailLogID, o.SourceEmailLogID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkSourceEmailLogID), "integer[]")),
	))

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

// SourceReportReport starts a query for related objects on publicreport.report
func (o *Communication) SourceReportReport(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportsQuery {
	return PublicreportReports.Query(append(mods,
		sm.Where(PublicreportReports.Columns.ID.EQ(psql.Arg(o.SourceReportID))),
	)...)
}

func (os CommunicationSlice) SourceReportReport(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportsQuery {
	pkSourceReportID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkSourceReportID = append(pkSourceReportID, o.SourceReportID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkSourceReportID), "integer[]")),
	))

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

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

func (os CommunicationSlice) SourceTextLogTextLog(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	pkSourceTextLogID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkSourceTextLogID = append(pkSourceTextLogID, o.SourceTextLogID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkSourceTextLogID), "integer[]")),
	))

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

// CommunicationLogEntries starts a query for related objects on communication_log_entry
func (o *Communication) CommunicationLogEntries(mods ...bob.Mod[*dialect.SelectQuery]) CommunicationLogEntriesQuery {
	return CommunicationLogEntries.Query(append(mods,
		sm.Where(CommunicationLogEntries.Columns.CommunicationID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os CommunicationSlice) CommunicationLogEntries(mods ...bob.Mod[*dialect.SelectQuery]) CommunicationLogEntriesQuery {
	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 CommunicationLogEntries.Query(append(mods,
		sm.Where(psql.Group(CommunicationLogEntries.Columns.CommunicationID).OP("IN", PKArgExpr)),
	)...)
}

func attachCommunicationOrganization0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, organization1 *Organization) (*Communication, error) {
	setter := &CommunicationSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) 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 = attachCommunicationOrganization0(ctx, exec, 1, communication0, organization1)
	if err != nil {
		return err
	}

	communication0.R.Organization = organization1

	organization1.R.Communications = append(organization1.R.Communications, communication0)

	return nil
}

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

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

	communication0.R.Organization = organization1

	organization1.R.Communications = append(organization1.R.Communications, communication0)

	return nil
}

func attachCommunicationResponseEmailLogEmailLog0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, commsEmailLog1 *CommsEmailLog) (*Communication, error) {
	setter := &CommunicationSetter{
		ResponseEmailLogID: omitnull.From(commsEmailLog1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) InsertResponseEmailLogEmailLog(ctx context.Context, exec bob.Executor, related *CommsEmailLogSetter) error {
	var err error

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

	_, err = attachCommunicationResponseEmailLogEmailLog0(ctx, exec, 1, communication0, commsEmailLog1)
	if err != nil {
		return err
	}

	communication0.R.ResponseEmailLogEmailLog = commsEmailLog1

	commsEmailLog1.R.ResponseEmailLogCommunications = append(commsEmailLog1.R.ResponseEmailLogCommunications, communication0)

	return nil
}

func (communication0 *Communication) AttachResponseEmailLogEmailLog(ctx context.Context, exec bob.Executor, commsEmailLog1 *CommsEmailLog) error {
	var err error

	_, err = attachCommunicationResponseEmailLogEmailLog0(ctx, exec, 1, communication0, commsEmailLog1)
	if err != nil {
		return err
	}

	communication0.R.ResponseEmailLogEmailLog = commsEmailLog1

	commsEmailLog1.R.ResponseEmailLogCommunications = append(commsEmailLog1.R.ResponseEmailLogCommunications, communication0)

	return nil
}

func attachCommunicationResponseTextLogTextLog0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, commsTextLog1 *CommsTextLog) (*Communication, error) {
	setter := &CommunicationSetter{
		ResponseTextLogID: omitnull.From(commsTextLog1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) InsertResponseTextLogTextLog(ctx context.Context, exec bob.Executor, related *CommsTextLogSetter) error {
	var err error

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

	_, err = attachCommunicationResponseTextLogTextLog0(ctx, exec, 1, communication0, commsTextLog1)
	if err != nil {
		return err
	}

	communication0.R.ResponseTextLogTextLog = commsTextLog1

	commsTextLog1.R.ResponseTextLogCommunications = append(commsTextLog1.R.ResponseTextLogCommunications, communication0)

	return nil
}

func (communication0 *Communication) AttachResponseTextLogTextLog(ctx context.Context, exec bob.Executor, commsTextLog1 *CommsTextLog) error {
	var err error

	_, err = attachCommunicationResponseTextLogTextLog0(ctx, exec, 1, communication0, commsTextLog1)
	if err != nil {
		return err
	}

	communication0.R.ResponseTextLogTextLog = commsTextLog1

	commsTextLog1.R.ResponseTextLogCommunications = append(commsTextLog1.R.ResponseTextLogCommunications, communication0)

	return nil
}

func attachCommunicationSourceEmailLogEmailLog0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, commsEmailLog1 *CommsEmailLog) (*Communication, error) {
	setter := &CommunicationSetter{
		SourceEmailLogID: omitnull.From(commsEmailLog1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) InsertSourceEmailLogEmailLog(ctx context.Context, exec bob.Executor, related *CommsEmailLogSetter) error {
	var err error

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

	_, err = attachCommunicationSourceEmailLogEmailLog0(ctx, exec, 1, communication0, commsEmailLog1)
	if err != nil {
		return err
	}

	communication0.R.SourceEmailLogEmailLog = commsEmailLog1

	commsEmailLog1.R.SourceEmailLogCommunications = append(commsEmailLog1.R.SourceEmailLogCommunications, communication0)

	return nil
}

func (communication0 *Communication) AttachSourceEmailLogEmailLog(ctx context.Context, exec bob.Executor, commsEmailLog1 *CommsEmailLog) error {
	var err error

	_, err = attachCommunicationSourceEmailLogEmailLog0(ctx, exec, 1, communication0, commsEmailLog1)
	if err != nil {
		return err
	}

	communication0.R.SourceEmailLogEmailLog = commsEmailLog1

	commsEmailLog1.R.SourceEmailLogCommunications = append(commsEmailLog1.R.SourceEmailLogCommunications, communication0)

	return nil
}

func attachCommunicationSourceReportReport0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, publicreportReport1 *PublicreportReport) (*Communication, error) {
	setter := &CommunicationSetter{
		SourceReportID: omitnull.From(publicreportReport1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) InsertSourceReportReport(ctx context.Context, exec bob.Executor, related *PublicreportReportSetter) error {
	var err error

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

	_, err = attachCommunicationSourceReportReport0(ctx, exec, 1, communication0, publicreportReport1)
	if err != nil {
		return err
	}

	communication0.R.SourceReportReport = publicreportReport1

	publicreportReport1.R.SourceReportCommunications = append(publicreportReport1.R.SourceReportCommunications, communication0)

	return nil
}

func (communication0 *Communication) AttachSourceReportReport(ctx context.Context, exec bob.Executor, publicreportReport1 *PublicreportReport) error {
	var err error

	_, err = attachCommunicationSourceReportReport0(ctx, exec, 1, communication0, publicreportReport1)
	if err != nil {
		return err
	}

	communication0.R.SourceReportReport = publicreportReport1

	publicreportReport1.R.SourceReportCommunications = append(publicreportReport1.R.SourceReportCommunications, communication0)

	return nil
}

func attachCommunicationSourceTextLogTextLog0(ctx context.Context, exec bob.Executor, count int, communication0 *Communication, commsTextLog1 *CommsTextLog) (*Communication, error) {
	setter := &CommunicationSetter{
		SourceTextLogID: omitnull.From(commsTextLog1.ID),
	}

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

	return communication0, nil
}

func (communication0 *Communication) InsertSourceTextLogTextLog(ctx context.Context, exec bob.Executor, related *CommsTextLogSetter) error {
	var err error

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

	_, err = attachCommunicationSourceTextLogTextLog0(ctx, exec, 1, communication0, commsTextLog1)
	if err != nil {
		return err
	}

	communication0.R.SourceTextLogTextLog = commsTextLog1

	commsTextLog1.R.SourceTextLogCommunications = append(commsTextLog1.R.SourceTextLogCommunications, communication0)

	return nil
}

func (communication0 *Communication) AttachSourceTextLogTextLog(ctx context.Context, exec bob.Executor, commsTextLog1 *CommsTextLog) error {
	var err error

	_, err = attachCommunicationSourceTextLogTextLog0(ctx, exec, 1, communication0, commsTextLog1)
	if err != nil {
		return err
	}

	communication0.R.SourceTextLogTextLog = commsTextLog1

	commsTextLog1.R.SourceTextLogCommunications = append(commsTextLog1.R.SourceTextLogCommunications, communication0)

	return nil
}

func insertCommunicationCommunicationLogEntries0(ctx context.Context, exec bob.Executor, communicationLogEntries1 []*CommunicationLogEntrySetter, communication0 *Communication) (CommunicationLogEntrySlice, error) {
	for i := range communicationLogEntries1 {
		communicationLogEntries1[i].CommunicationID = omit.From(communication0.ID)
	}

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

	return ret, nil
}

func attachCommunicationCommunicationLogEntries0(ctx context.Context, exec bob.Executor, count int, communicationLogEntries1 CommunicationLogEntrySlice, communication0 *Communication) (CommunicationLogEntrySlice, error) {
	setter := &CommunicationLogEntrySetter{
		CommunicationID: omit.From(communication0.ID),
	}

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

	return communicationLogEntries1, nil
}

func (communication0 *Communication) InsertCommunicationLogEntries(ctx context.Context, exec bob.Executor, related ...*CommunicationLogEntrySetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	communicationLogEntries1, err := insertCommunicationCommunicationLogEntries0(ctx, exec, related, communication0)
	if err != nil {
		return err
	}

	communication0.R.CommunicationLogEntries = append(communication0.R.CommunicationLogEntries, communicationLogEntries1...)

	for _, rel := range communicationLogEntries1 {
		rel.R.Communication = communication0
	}
	return nil
}

func (communication0 *Communication) AttachCommunicationLogEntries(ctx context.Context, exec bob.Executor, related ...*CommunicationLogEntry) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	communicationLogEntries1 := CommunicationLogEntrySlice(related)

	_, err = attachCommunicationCommunicationLogEntries0(ctx, exec, len(related), communicationLogEntries1, communication0)
	if err != nil {
		return err
	}

	communication0.R.CommunicationLogEntries = append(communication0.R.CommunicationLogEntries, communicationLogEntries1...)

	for _, rel := range related {
		rel.R.Communication = communication0
	}

	return nil
}

type communicationWhere[Q psql.Filterable] struct {
	Created            psql.WhereMod[Q, time.Time]
	ID                 psql.WhereMod[Q, int32]
	OrganizationID     psql.WhereMod[Q, int32]
	ResponseEmailLogID psql.WhereNullMod[Q, int32]
	ResponseTextLogID  psql.WhereNullMod[Q, int32]
	SourceEmailLogID   psql.WhereNullMod[Q, int32]
	SourceReportID     psql.WhereNullMod[Q, int32]
	SourceTextLogID    psql.WhereNullMod[Q, int32]
	Status             psql.WhereMod[Q, enums.Communicationstatus]
}

func (communicationWhere[Q]) AliasedAs(alias string) communicationWhere[Q] {
	return buildCommunicationWhere[Q](buildCommunicationColumns(alias))
}

func buildCommunicationWhere[Q psql.Filterable](cols communicationColumns) communicationWhere[Q] {
	return communicationWhere[Q]{
		Created:            psql.Where[Q, time.Time](cols.Created),
		ID:                 psql.Where[Q, int32](cols.ID),
		OrganizationID:     psql.Where[Q, int32](cols.OrganizationID),
		ResponseEmailLogID: psql.WhereNull[Q, int32](cols.ResponseEmailLogID),
		ResponseTextLogID:  psql.WhereNull[Q, int32](cols.ResponseTextLogID),
		SourceEmailLogID:   psql.WhereNull[Q, int32](cols.SourceEmailLogID),
		SourceReportID:     psql.WhereNull[Q, int32](cols.SourceReportID),
		SourceTextLogID:    psql.WhereNull[Q, int32](cols.SourceTextLogID),
		Status:             psql.Where[Q, enums.Communicationstatus](cols.Status),
	}
}

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

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

		o.R.Organization = rel

		if rel != nil {
			rel.R.Communications = CommunicationSlice{o}
		}
		return nil
	case "ResponseEmailLogEmailLog":
		rel, ok := retrieved.(*CommsEmailLog)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.ResponseEmailLogEmailLog = rel

		if rel != nil {
			rel.R.ResponseEmailLogCommunications = CommunicationSlice{o}
		}
		return nil
	case "ResponseTextLogTextLog":
		rel, ok := retrieved.(*CommsTextLog)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.ResponseTextLogTextLog = rel

		if rel != nil {
			rel.R.ResponseTextLogCommunications = CommunicationSlice{o}
		}
		return nil
	case "SourceEmailLogEmailLog":
		rel, ok := retrieved.(*CommsEmailLog)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.SourceEmailLogEmailLog = rel

		if rel != nil {
			rel.R.SourceEmailLogCommunications = CommunicationSlice{o}
		}
		return nil
	case "SourceReportReport":
		rel, ok := retrieved.(*PublicreportReport)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.SourceReportReport = rel

		if rel != nil {
			rel.R.SourceReportCommunications = CommunicationSlice{o}
		}
		return nil
	case "SourceTextLogTextLog":
		rel, ok := retrieved.(*CommsTextLog)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.SourceTextLogTextLog = rel

		if rel != nil {
			rel.R.SourceTextLogCommunications = CommunicationSlice{o}
		}
		return nil
	case "CommunicationLogEntries":
		rels, ok := retrieved.(CommunicationLogEntrySlice)
		if !ok {
			return fmt.Errorf("communication cannot load %T as %q", retrieved, name)
		}

		o.R.CommunicationLogEntries = rels

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

type communicationPreloader struct {
	Organization             func(...psql.PreloadOption) psql.Preloader
	ResponseEmailLogEmailLog func(...psql.PreloadOption) psql.Preloader
	ResponseTextLogTextLog   func(...psql.PreloadOption) psql.Preloader
	SourceEmailLogEmailLog   func(...psql.PreloadOption) psql.Preloader
	SourceReportReport       func(...psql.PreloadOption) psql.Preloader
	SourceTextLogTextLog     func(...psql.PreloadOption) psql.Preloader
}

func buildCommunicationPreloader() communicationPreloader {
	return communicationPreloader{
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		ResponseEmailLogEmailLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailLog, CommsEmailLogSlice](psql.PreloadRel{
				Name: "ResponseEmailLogEmailLog",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          CommsEmailLogs,
						FromColumns: []string{"response_email_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsEmailLogs.Columns.Names(), opts...)
		},
		ResponseTextLogTextLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsTextLog, CommsTextLogSlice](psql.PreloadRel{
				Name: "ResponseTextLogTextLog",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          CommsTextLogs,
						FromColumns: []string{"response_text_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsTextLogs.Columns.Names(), opts...)
		},
		SourceEmailLogEmailLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailLog, CommsEmailLogSlice](psql.PreloadRel{
				Name: "SourceEmailLogEmailLog",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          CommsEmailLogs,
						FromColumns: []string{"source_email_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsEmailLogs.Columns.Names(), opts...)
		},
		SourceReportReport: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "SourceReportReport",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          PublicreportReports,
						FromColumns: []string{"source_report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
		SourceTextLogTextLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsTextLog, CommsTextLogSlice](psql.PreloadRel{
				Name: "SourceTextLogTextLog",
				Sides: []psql.PreloadSide{
					{
						From:        Communications,
						To:          CommsTextLogs,
						FromColumns: []string{"source_text_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsTextLogs.Columns.Names(), opts...)
		},
	}
}

type communicationThenLoader[Q orm.Loadable] struct {
	Organization             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ResponseEmailLogEmailLog func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ResponseTextLogTextLog   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceEmailLogEmailLog   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceReportReport       func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceTextLogTextLog     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	CommunicationLogEntries  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommunicationThenLoader[Q orm.Loadable]() communicationThenLoader[Q] {
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResponseEmailLogEmailLogLoadInterface interface {
		LoadResponseEmailLogEmailLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResponseTextLogTextLogLoadInterface interface {
		LoadResponseTextLogTextLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceEmailLogEmailLogLoadInterface interface {
		LoadSourceEmailLogEmailLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceReportReportLoadInterface interface {
		LoadSourceReportReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceTextLogTextLogLoadInterface interface {
		LoadSourceTextLogTextLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CommunicationLogEntriesLoadInterface interface {
		LoadCommunicationLogEntries(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return communicationThenLoader[Q]{
		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...)
			},
		),
		ResponseEmailLogEmailLog: thenLoadBuilder[Q](
			"ResponseEmailLogEmailLog",
			func(ctx context.Context, exec bob.Executor, retrieved ResponseEmailLogEmailLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResponseEmailLogEmailLog(ctx, exec, mods...)
			},
		),
		ResponseTextLogTextLog: thenLoadBuilder[Q](
			"ResponseTextLogTextLog",
			func(ctx context.Context, exec bob.Executor, retrieved ResponseTextLogTextLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResponseTextLogTextLog(ctx, exec, mods...)
			},
		),
		SourceEmailLogEmailLog: thenLoadBuilder[Q](
			"SourceEmailLogEmailLog",
			func(ctx context.Context, exec bob.Executor, retrieved SourceEmailLogEmailLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceEmailLogEmailLog(ctx, exec, mods...)
			},
		),
		SourceReportReport: thenLoadBuilder[Q](
			"SourceReportReport",
			func(ctx context.Context, exec bob.Executor, retrieved SourceReportReportLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceReportReport(ctx, exec, mods...)
			},
		),
		SourceTextLogTextLog: thenLoadBuilder[Q](
			"SourceTextLogTextLog",
			func(ctx context.Context, exec bob.Executor, retrieved SourceTextLogTextLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceTextLogTextLog(ctx, exec, mods...)
			},
		),
		CommunicationLogEntries: thenLoadBuilder[Q](
			"CommunicationLogEntries",
			func(ctx context.Context, exec bob.Executor, retrieved CommunicationLogEntriesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCommunicationLogEntries(ctx, exec, mods...)
			},
		),
	}
}

// LoadOrganization loads the communication's Organization into the .R struct
func (o *Communication) 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
	}

	related.R.Communications = CommunicationSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the communication's Organization into the .R struct
func (os CommunicationSlice) 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
			}

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ResponseEmailLogCommunications = CommunicationSlice{o}

	o.R.ResponseEmailLogEmailLog = related
	return nil
}

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

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

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

		for _, rel := range commsEmailLogs {
			if !o.ResponseEmailLogID.IsValue() {
				continue
			}

			if !(o.ResponseEmailLogID.IsValue() && o.ResponseEmailLogID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.ResponseEmailLogEmailLog = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ResponseTextLogCommunications = CommunicationSlice{o}

	o.R.ResponseTextLogTextLog = related
	return nil
}

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

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

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

		for _, rel := range commsTextLogs {
			if !o.ResponseTextLogID.IsValue() {
				continue
			}

			if !(o.ResponseTextLogID.IsValue() && o.ResponseTextLogID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.ResponseTextLogTextLog = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.SourceEmailLogCommunications = CommunicationSlice{o}

	o.R.SourceEmailLogEmailLog = related
	return nil
}

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

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

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

		for _, rel := range commsEmailLogs {
			if !o.SourceEmailLogID.IsValue() {
				continue
			}

			if !(o.SourceEmailLogID.IsValue() && o.SourceEmailLogID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.SourceEmailLogEmailLog = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.SourceReportCommunications = CommunicationSlice{o}

	o.R.SourceReportReport = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {
			if !o.SourceReportID.IsValue() {
				continue
			}

			if !(o.SourceReportID.IsValue() && o.SourceReportID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.SourceReportReport = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.SourceTextLogCommunications = CommunicationSlice{o}

	o.R.SourceTextLogTextLog = related
	return nil
}

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

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

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

		for _, rel := range commsTextLogs {
			if !o.SourceTextLogID.IsValue() {
				continue
			}

			if !(o.SourceTextLogID.IsValue() && o.SourceTextLogID.MustGet() == rel.ID) {
				continue
			}

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

			o.R.SourceTextLogTextLog = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.CommunicationLogEntries = related
	return nil
}

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

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

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

		o.R.CommunicationLogEntries = nil
	}

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

		for _, rel := range communicationLogEntries {

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

			rel.R.Communication = o

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

	return nil
}
