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

// CommunicationLogEntry is an object representing the database table.
type CommunicationLogEntry struct {
	CommunicationID int32                       `db:"communication_id" `
	Created         time.Time                   `db:"created" `
	ID              int32                       `db:"id,pk" `
	Type            enums.Communicationlogentry `db:"type_" `
	User            null.Val[int32]             `db:"user_" `

	R communicationLogEntryR `db:"-" `
}

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

// CommunicationLogEntries contains methods to work with the communication_log_entry table
var CommunicationLogEntries = psql.NewTablex[*CommunicationLogEntry, CommunicationLogEntrySlice, *CommunicationLogEntrySetter]("", "communication_log_entry", buildCommunicationLogEntryColumns("communication_log_entry"))

// CommunicationLogEntriesQuery is a query on the communication_log_entry table
type CommunicationLogEntriesQuery = *psql.ViewQuery[*CommunicationLogEntry, CommunicationLogEntrySlice]

// communicationLogEntryR is where relationships are stored.
type communicationLogEntryR struct {
	Communication *Communication // communication_log_entry.communication_log_entry_communication_id_fkey
	User          *User          // communication_log_entry.communication_log_entry_user__fkey
}

func buildCommunicationLogEntryColumns(alias string) communicationLogEntryColumns {
	return communicationLogEntryColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"communication_id", "created", "id", "type_", "user_",
		).WithParent("communication_log_entry"),
		tableAlias:      alias,
		CommunicationID: psql.Quote(alias, "communication_id"),
		Created:         psql.Quote(alias, "created"),
		ID:              psql.Quote(alias, "id"),
		Type:            psql.Quote(alias, "type_"),
		User:            psql.Quote(alias, "user_"),
	}
}

type communicationLogEntryColumns struct {
	expr.ColumnsExpr
	tableAlias      string
	CommunicationID psql.Expression
	Created         psql.Expression
	ID              psql.Expression
	Type            psql.Expression
	User            psql.Expression
}

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

func (communicationLogEntryColumns) AliasedAs(alias string) communicationLogEntryColumns {
	return buildCommunicationLogEntryColumns(alias)
}

// CommunicationLogEntrySetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommunicationLogEntrySetter struct {
	CommunicationID omit.Val[int32]                       `db:"communication_id" `
	Created         omit.Val[time.Time]                   `db:"created" `
	ID              omit.Val[int32]                       `db:"id,pk" `
	Type            omit.Val[enums.Communicationlogentry] `db:"type_" `
	User            omitnull.Val[int32]                   `db:"user_" `
}

func (s CommunicationLogEntrySetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.CommunicationID.IsValue() {
		vals = append(vals, "communication_id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	if !s.User.IsUnset() {
		vals = append(vals, "user_")
	}
	return vals
}

func (s CommunicationLogEntrySetter) Overwrite(t *CommunicationLogEntry) {
	if s.CommunicationID.IsValue() {
		t.CommunicationID = s.CommunicationID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
	if !s.User.IsUnset() {
		t.User = s.User.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// User starts a query for related objects on user_
func (o *CommunicationLogEntry) RelatedUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.User))),
	)...)
}

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

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

func attachCommunicationLogEntryCommunication0(ctx context.Context, exec bob.Executor, count int, communicationLogEntry0 *CommunicationLogEntry, communication1 *Communication) (*CommunicationLogEntry, error) {
	setter := &CommunicationLogEntrySetter{
		CommunicationID: omit.From(communication1.ID),
	}

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

	return communicationLogEntry0, nil
}

func (communicationLogEntry0 *CommunicationLogEntry) InsertCommunication(ctx context.Context, exec bob.Executor, related *CommunicationSetter) error {
	var err error

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

	_, err = attachCommunicationLogEntryCommunication0(ctx, exec, 1, communicationLogEntry0, communication1)
	if err != nil {
		return err
	}

	communicationLogEntry0.R.Communication = communication1

	communication1.R.CommunicationLogEntries = append(communication1.R.CommunicationLogEntries, communicationLogEntry0)

	return nil
}

func (communicationLogEntry0 *CommunicationLogEntry) AttachCommunication(ctx context.Context, exec bob.Executor, communication1 *Communication) error {
	var err error

	_, err = attachCommunicationLogEntryCommunication0(ctx, exec, 1, communicationLogEntry0, communication1)
	if err != nil {
		return err
	}

	communicationLogEntry0.R.Communication = communication1

	communication1.R.CommunicationLogEntries = append(communication1.R.CommunicationLogEntries, communicationLogEntry0)

	return nil
}

func attachCommunicationLogEntryUser0(ctx context.Context, exec bob.Executor, count int, communicationLogEntry0 *CommunicationLogEntry, user1 *User) (*CommunicationLogEntry, error) {
	setter := &CommunicationLogEntrySetter{
		User: omitnull.From(user1.ID),
	}

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

	return communicationLogEntry0, nil
}

func (communicationLogEntry0 *CommunicationLogEntry) InsertUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachCommunicationLogEntryUser0(ctx, exec, 1, communicationLogEntry0, user1)
	if err != nil {
		return err
	}

	communicationLogEntry0.R.User = user1

	user1.R.CommunicationLogEntries = append(user1.R.CommunicationLogEntries, communicationLogEntry0)

	return nil
}

func (communicationLogEntry0 *CommunicationLogEntry) AttachUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachCommunicationLogEntryUser0(ctx, exec, 1, communicationLogEntry0, user1)
	if err != nil {
		return err
	}

	communicationLogEntry0.R.User = user1

	user1.R.CommunicationLogEntries = append(user1.R.CommunicationLogEntries, communicationLogEntry0)

	return nil
}

type communicationLogEntryWhere[Q psql.Filterable] struct {
	CommunicationID psql.WhereMod[Q, int32]
	Created         psql.WhereMod[Q, time.Time]
	ID              psql.WhereMod[Q, int32]
	Type            psql.WhereMod[Q, enums.Communicationlogentry]
	User            psql.WhereNullMod[Q, int32]
}

func (communicationLogEntryWhere[Q]) AliasedAs(alias string) communicationLogEntryWhere[Q] {
	return buildCommunicationLogEntryWhere[Q](buildCommunicationLogEntryColumns(alias))
}

func buildCommunicationLogEntryWhere[Q psql.Filterable](cols communicationLogEntryColumns) communicationLogEntryWhere[Q] {
	return communicationLogEntryWhere[Q]{
		CommunicationID: psql.Where[Q, int32](cols.CommunicationID),
		Created:         psql.Where[Q, time.Time](cols.Created),
		ID:              psql.Where[Q, int32](cols.ID),
		Type:            psql.Where[Q, enums.Communicationlogentry](cols.Type),
		User:            psql.WhereNull[Q, int32](cols.User),
	}
}

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

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

		o.R.Communication = rel

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

		o.R.User = rel

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

type communicationLogEntryPreloader struct {
	Communication func(...psql.PreloadOption) psql.Preloader
	User          func(...psql.PreloadOption) psql.Preloader
}

func buildCommunicationLogEntryPreloader() communicationLogEntryPreloader {
	return communicationLogEntryPreloader{
		Communication: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Communication, CommunicationSlice](psql.PreloadRel{
				Name: "Communication",
				Sides: []psql.PreloadSide{
					{
						From:        CommunicationLogEntries,
						To:          Communications,
						FromColumns: []string{"communication_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Communications.Columns.Names(), opts...)
		},
		User: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "User",
				Sides: []psql.PreloadSide{
					{
						From:        CommunicationLogEntries,
						To:          Users,
						FromColumns: []string{"user_"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
	}
}

type communicationLogEntryThenLoader[Q orm.Loadable] struct {
	Communication func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	User          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommunicationLogEntryThenLoader[Q orm.Loadable]() communicationLogEntryThenLoader[Q] {
	type CommunicationLoadInterface interface {
		LoadCommunication(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserLoadInterface interface {
		LoadUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return communicationLogEntryThenLoader[Q]{
		Communication: thenLoadBuilder[Q](
			"Communication",
			func(ctx context.Context, exec bob.Executor, retrieved CommunicationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCommunication(ctx, exec, mods...)
			},
		),
		User: thenLoadBuilder[Q](
			"User",
			func(ctx context.Context, exec bob.Executor, retrieved UserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUser(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.CommunicationLogEntries = CommunicationLogEntrySlice{o}

	o.R.Communication = related
	return nil
}

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

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

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

		for _, rel := range communications {

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

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

			o.R.Communication = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.CommunicationLogEntries = CommunicationLogEntrySlice{o}

	o.R.User = related
	return nil
}

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

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

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

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

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

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

			o.R.User = rel
			break
		}
	}

	return nil
}
