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

// PublicreportNotifyPhoneWaterOld is an object representing the database table.
type PublicreportNotifyPhoneWaterOld struct {
	Created   time.Time           `db:"created" `
	Deleted   null.Val[time.Time] `db:"deleted" `
	PhoneE164 string              `db:"phone_e164,pk" `
	WaterID   int32               `db:"water_id,pk" `

	R publicreportNotifyPhoneWaterOldR `db:"-" `
}

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

// PublicreportNotifyPhoneWaterOlds contains methods to work with the notify_phone_water_old table
var PublicreportNotifyPhoneWaterOlds = psql.NewTablex[*PublicreportNotifyPhoneWaterOld, PublicreportNotifyPhoneWaterOldSlice, *PublicreportNotifyPhoneWaterOldSetter]("publicreport", "notify_phone_water_old", buildPublicreportNotifyPhoneWaterOldColumns("publicreport.notify_phone_water_old"))

// PublicreportNotifyPhoneWaterOldsQuery is a query on the notify_phone_water_old table
type PublicreportNotifyPhoneWaterOldsQuery = *psql.ViewQuery[*PublicreportNotifyPhoneWaterOld, PublicreportNotifyPhoneWaterOldSlice]

// publicreportNotifyPhoneWaterOldR is where relationships are stored.
type publicreportNotifyPhoneWaterOldR struct {
	PhoneE164Phone *CommsPhone           // publicreport.notify_phone_water_old.notify_phone_pool_phone_e164_fkey
	WaterWaterOld  *PublicreportWaterOld // publicreport.notify_phone_water_old.notify_phone_pool_pool_id_fkey
}

func buildPublicreportNotifyPhoneWaterOldColumns(alias string) publicreportNotifyPhoneWaterOldColumns {
	return publicreportNotifyPhoneWaterOldColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "phone_e164", "water_id",
		).WithParent("publicreport.notify_phone_water_old"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		Deleted:    psql.Quote(alias, "deleted"),
		PhoneE164:  psql.Quote(alias, "phone_e164"),
		WaterID:    psql.Quote(alias, "water_id"),
	}
}

type publicreportNotifyPhoneWaterOldColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	Deleted    psql.Expression
	PhoneE164  psql.Expression
	WaterID    psql.Expression
}

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

func (publicreportNotifyPhoneWaterOldColumns) AliasedAs(alias string) publicreportNotifyPhoneWaterOldColumns {
	return buildPublicreportNotifyPhoneWaterOldColumns(alias)
}

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

func (s PublicreportNotifyPhoneWaterOldSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if !s.Deleted.IsUnset() {
		vals = append(vals, "deleted")
	}
	if s.PhoneE164.IsValue() {
		vals = append(vals, "phone_e164")
	}
	if s.WaterID.IsValue() {
		vals = append(vals, "water_id")
	}
	return vals
}

func (s PublicreportNotifyPhoneWaterOldSetter) Overwrite(t *PublicreportNotifyPhoneWaterOld) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.PhoneE164.IsValue() {
		t.PhoneE164 = s.PhoneE164.MustGet()
	}
	if s.WaterID.IsValue() {
		t.WaterID = s.WaterID.MustGet()
	}
}

func (s *PublicreportNotifyPhoneWaterOldSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return PublicreportNotifyPhoneWaterOlds.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 4)
		if s.Created.IsValue() {
			vals[0] = psql.Arg(s.Created.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindPublicreportNotifyPhoneWaterOld retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyPhoneWaterOld(ctx context.Context, exec bob.Executor, WaterIDPK int32, PhoneE164PK string, cols ...string) (*PublicreportNotifyPhoneWaterOld, error) {
	if len(cols) == 0 {
		return PublicreportNotifyPhoneWaterOlds.Query(
			sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
			sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		).One(ctx, exec)
	}

	return PublicreportNotifyPhoneWaterOlds.Query(
		sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
		sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		sm.Columns(PublicreportNotifyPhoneWaterOlds.Columns.Only(cols...)),
	).One(ctx, exec)
}

// PublicreportNotifyPhoneWaterOldExists checks the presence of a single record by primary key
func PublicreportNotifyPhoneWaterOldExists(ctx context.Context, exec bob.Executor, WaterIDPK int32, PhoneE164PK string) (bool, error) {
	return PublicreportNotifyPhoneWaterOlds.Query(
		sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
		sm.Where(PublicreportNotifyPhoneWaterOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the PublicreportNotifyPhoneWaterOld
func (o *PublicreportNotifyPhoneWaterOld) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.WaterID,
		o.PhoneE164,
	)
}

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("publicreport.notify_phone_water_old", "water_id"), psql.Quote("publicreport.notify_phone_water_old", "phone_e164")).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 PublicreportNotifyPhoneWaterOldSlice) copyMatchingRows(from ...*PublicreportNotifyPhoneWaterOld) {
	for i, old := range o {
		for _, new := range from {
			if new.WaterID != old.WaterID {
				continue
			}
			if new.PhoneE164 != old.PhoneE164 {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// PhoneE164Phone starts a query for related objects on comms.phone
func (o *PublicreportNotifyPhoneWaterOld) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	return CommsPhones.Query(append(mods,
		sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneE164))),
	)...)
}

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

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

// WaterWaterOld starts a query for related objects on publicreport.water_old
func (o *PublicreportNotifyPhoneWaterOld) WaterWaterOld(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWaterOldsQuery {
	return PublicreportWaterOlds.Query(append(mods,
		sm.Where(PublicreportWaterOlds.Columns.ID.EQ(psql.Arg(o.WaterID))),
	)...)
}

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

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

func attachPublicreportNotifyPhoneWaterOldPhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld, commsPhone1 *CommsPhone) (*PublicreportNotifyPhoneWaterOld, error) {
	setter := &PublicreportNotifyPhoneWaterOldSetter{
		PhoneE164: omit.From(commsPhone1.E164),
	}

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

	return publicreportNotifyPhoneWaterOld0, nil
}

func (publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld) InsertPhoneE164Phone(ctx context.Context, exec bob.Executor, related *CommsPhoneSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyPhoneWaterOldPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhoneWaterOld0, commsPhone1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneWaterOld0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhoneWaterOlds = append(commsPhone1.R.PhoneE164NotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOld0)

	return nil
}

func (publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld) AttachPhoneE164Phone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

	_, err = attachPublicreportNotifyPhoneWaterOldPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhoneWaterOld0, commsPhone1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneWaterOld0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhoneWaterOlds = append(commsPhone1.R.PhoneE164NotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOld0)

	return nil
}

func attachPublicreportNotifyPhoneWaterOldWaterWaterOld0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld, publicreportWaterOld1 *PublicreportWaterOld) (*PublicreportNotifyPhoneWaterOld, error) {
	setter := &PublicreportNotifyPhoneWaterOldSetter{
		WaterID: omit.From(publicreportWaterOld1.ID),
	}

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

	return publicreportNotifyPhoneWaterOld0, nil
}

func (publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld) InsertWaterWaterOld(ctx context.Context, exec bob.Executor, related *PublicreportWaterOldSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyPhoneWaterOldWaterWaterOld0(ctx, exec, 1, publicreportNotifyPhoneWaterOld0, publicreportWaterOld1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneWaterOld0.R.WaterWaterOld = publicreportWaterOld1

	publicreportWaterOld1.R.WaterNotifyPhoneWaterOlds = append(publicreportWaterOld1.R.WaterNotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOld0)

	return nil
}

func (publicreportNotifyPhoneWaterOld0 *PublicreportNotifyPhoneWaterOld) AttachWaterWaterOld(ctx context.Context, exec bob.Executor, publicreportWaterOld1 *PublicreportWaterOld) error {
	var err error

	_, err = attachPublicreportNotifyPhoneWaterOldWaterWaterOld0(ctx, exec, 1, publicreportNotifyPhoneWaterOld0, publicreportWaterOld1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneWaterOld0.R.WaterWaterOld = publicreportWaterOld1

	publicreportWaterOld1.R.WaterNotifyPhoneWaterOlds = append(publicreportWaterOld1.R.WaterNotifyPhoneWaterOlds, publicreportNotifyPhoneWaterOld0)

	return nil
}

type publicreportNotifyPhoneWaterOldWhere[Q psql.Filterable] struct {
	Created   psql.WhereMod[Q, time.Time]
	Deleted   psql.WhereNullMod[Q, time.Time]
	PhoneE164 psql.WhereMod[Q, string]
	WaterID   psql.WhereMod[Q, int32]
}

func (publicreportNotifyPhoneWaterOldWhere[Q]) AliasedAs(alias string) publicreportNotifyPhoneWaterOldWhere[Q] {
	return buildPublicreportNotifyPhoneWaterOldWhere[Q](buildPublicreportNotifyPhoneWaterOldColumns(alias))
}

func buildPublicreportNotifyPhoneWaterOldWhere[Q psql.Filterable](cols publicreportNotifyPhoneWaterOldColumns) publicreportNotifyPhoneWaterOldWhere[Q] {
	return publicreportNotifyPhoneWaterOldWhere[Q]{
		Created:   psql.Where[Q, time.Time](cols.Created),
		Deleted:   psql.WhereNull[Q, time.Time](cols.Deleted),
		PhoneE164: psql.Where[Q, string](cols.PhoneE164),
		WaterID:   psql.Where[Q, int32](cols.WaterID),
	}
}

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

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

		o.R.PhoneE164Phone = rel

		if rel != nil {
			rel.R.PhoneE164NotifyPhoneWaterOlds = PublicreportNotifyPhoneWaterOldSlice{o}
		}
		return nil
	case "WaterWaterOld":
		rel, ok := retrieved.(*PublicreportWaterOld)
		if !ok {
			return fmt.Errorf("publicreportNotifyPhoneWaterOld cannot load %T as %q", retrieved, name)
		}

		o.R.WaterWaterOld = rel

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

type publicreportNotifyPhoneWaterOldPreloader struct {
	PhoneE164Phone func(...psql.PreloadOption) psql.Preloader
	WaterWaterOld  func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyPhoneWaterOldPreloader() publicreportNotifyPhoneWaterOldPreloader {
	return publicreportNotifyPhoneWaterOldPreloader{
		PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "PhoneE164Phone",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhoneWaterOlds,
						To:          CommsPhones,
						FromColumns: []string{"phone_e164"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
		WaterWaterOld: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportWaterOld, PublicreportWaterOldSlice](psql.PreloadRel{
				Name: "WaterWaterOld",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhoneWaterOlds,
						To:          PublicreportWaterOlds,
						FromColumns: []string{"water_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportWaterOlds.Columns.Names(), opts...)
		},
	}
}

type publicreportNotifyPhoneWaterOldThenLoader[Q orm.Loadable] struct {
	PhoneE164Phone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	WaterWaterOld  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPublicreportNotifyPhoneWaterOldThenLoader[Q orm.Loadable]() publicreportNotifyPhoneWaterOldThenLoader[Q] {
	type PhoneE164PhoneLoadInterface interface {
		LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type WaterWaterOldLoadInterface interface {
		LoadWaterWaterOld(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportNotifyPhoneWaterOldThenLoader[Q]{
		PhoneE164Phone: thenLoadBuilder[Q](
			"PhoneE164Phone",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164PhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164Phone(ctx, exec, mods...)
			},
		),
		WaterWaterOld: thenLoadBuilder[Q](
			"WaterWaterOld",
			func(ctx context.Context, exec bob.Executor, retrieved WaterWaterOldLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadWaterWaterOld(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.PhoneE164NotifyPhoneWaterOlds = PublicreportNotifyPhoneWaterOldSlice{o}

	o.R.PhoneE164Phone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {

			if !(o.PhoneE164 == rel.E164) {
				continue
			}

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

			o.R.PhoneE164Phone = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.WaterNotifyPhoneWaterOlds = PublicreportNotifyPhoneWaterOldSlice{o}

	o.R.WaterWaterOld = related
	return nil
}

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

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

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

		for _, rel := range publicreportWaterOlds {

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

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

			o.R.WaterWaterOld = rel
			break
		}
	}

	return nil
}
