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

package models

import (
	"context"
	"fmt"
	"io"

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

// ArcgisAddressMapping is an object representing the database table.
type ArcgisAddressMapping struct {
	Destination               enums.ArcgisMappingdestinationaddress `db:"destination,pk" `
	LayerFeatureServiceItemID string                                `db:"layer_feature_service_item_id" `
	LayerIndex                int32                                 `db:"layer_index" `
	LayerFieldName            string                                `db:"layer_field_name" `
	OrganizationID            int32                                 `db:"organization_id,pk" `

	R arcgisAddressMappingR `db:"-" `
}

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

// ArcgisAddressMappings contains methods to work with the address_mapping table
var ArcgisAddressMappings = psql.NewTablex[*ArcgisAddressMapping, ArcgisAddressMappingSlice, *ArcgisAddressMappingSetter]("arcgis", "address_mapping", buildArcgisAddressMappingColumns("arcgis.address_mapping"))

// ArcgisAddressMappingsQuery is a query on the address_mapping table
type ArcgisAddressMappingsQuery = *psql.ViewQuery[*ArcgisAddressMapping, ArcgisAddressMappingSlice]

// arcgisAddressMappingR is where relationships are stored.
type arcgisAddressMappingR struct {
	LayerField   *ArcgisLayerField // arcgis.address_mapping.address_mapping_layer_feature_service_item_id_layer_index__fkey
	Organization *Organization     // arcgis.address_mapping.address_mapping_organization_id_fkey
}

func buildArcgisAddressMappingColumns(alias string) arcgisAddressMappingColumns {
	return arcgisAddressMappingColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"destination", "layer_feature_service_item_id", "layer_index", "layer_field_name", "organization_id",
		).WithParent("arcgis.address_mapping"),
		tableAlias:                alias,
		Destination:               psql.Quote(alias, "destination"),
		LayerFeatureServiceItemID: psql.Quote(alias, "layer_feature_service_item_id"),
		LayerIndex:                psql.Quote(alias, "layer_index"),
		LayerFieldName:            psql.Quote(alias, "layer_field_name"),
		OrganizationID:            psql.Quote(alias, "organization_id"),
	}
}

type arcgisAddressMappingColumns struct {
	expr.ColumnsExpr
	tableAlias                string
	Destination               psql.Expression
	LayerFeatureServiceItemID psql.Expression
	LayerIndex                psql.Expression
	LayerFieldName            psql.Expression
	OrganizationID            psql.Expression
}

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

func (arcgisAddressMappingColumns) AliasedAs(alias string) arcgisAddressMappingColumns {
	return buildArcgisAddressMappingColumns(alias)
}

// ArcgisAddressMappingSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisAddressMappingSetter struct {
	Destination               omit.Val[enums.ArcgisMappingdestinationaddress] `db:"destination,pk" `
	LayerFeatureServiceItemID omit.Val[string]                                `db:"layer_feature_service_item_id" `
	LayerIndex                omit.Val[int32]                                 `db:"layer_index" `
	LayerFieldName            omit.Val[string]                                `db:"layer_field_name" `
	OrganizationID            omit.Val[int32]                                 `db:"organization_id,pk" `
}

func (s ArcgisAddressMappingSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.Destination.IsValue() {
		vals = append(vals, "destination")
	}
	if s.LayerFeatureServiceItemID.IsValue() {
		vals = append(vals, "layer_feature_service_item_id")
	}
	if s.LayerIndex.IsValue() {
		vals = append(vals, "layer_index")
	}
	if s.LayerFieldName.IsValue() {
		vals = append(vals, "layer_field_name")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	return vals
}

func (s ArcgisAddressMappingSetter) Overwrite(t *ArcgisAddressMapping) {
	if s.Destination.IsValue() {
		t.Destination = s.Destination.MustGet()
	}
	if s.LayerFeatureServiceItemID.IsValue() {
		t.LayerFeatureServiceItemID = s.LayerFeatureServiceItemID.MustGet()
	}
	if s.LayerIndex.IsValue() {
		t.LayerIndex = s.LayerIndex.MustGet()
	}
	if s.LayerFieldName.IsValue() {
		t.LayerFieldName = s.LayerFieldName.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return ArcgisAddressMappings.Query(
		sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))),
		sm.Columns(ArcgisAddressMappings.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ArcgisAddressMappingExists checks the presence of a single record by primary key
func ArcgisAddressMappingExists(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, DestinationPK enums.ArcgisMappingdestinationaddress) (bool, error) {
	return ArcgisAddressMappings.Query(
		sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// LayerField starts a query for related objects on arcgis.layer_field
func (o *ArcgisAddressMapping) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery {
	return ArcgisLayerFields.Query(append(mods,
		sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(o.LayerFieldName))),
	)...)
}

func (os ArcgisAddressMappingSlice) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery {
	pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os))

	pkLayerIndex := make(pgtypes.Array[int32], 0, len(os))

	pkLayerFieldName := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID)
		pkLayerIndex = append(pkLayerIndex, o.LayerIndex)
		pkLayerFieldName = append(pkLayerFieldName, o.LayerFieldName)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkLayerFieldName), "text[]")),
	))

	return ArcgisLayerFields.Query(append(mods,
		sm.Where(psql.Group(ArcgisLayerFields.Columns.LayerFeatureServiceItemID, ArcgisLayerFields.Columns.LayerIndex, ArcgisLayerFields.Columns.Name).OP("IN", PKArgExpr)),
	)...)
}

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

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

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

func attachArcgisAddressMappingLayerField0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMapping0 *ArcgisAddressMapping, arcgisLayerField1 *ArcgisLayerField) (*ArcgisAddressMapping, error) {
	setter := &ArcgisAddressMappingSetter{
		LayerFeatureServiceItemID: omit.From(arcgisLayerField1.LayerFeatureServiceItemID),
		LayerIndex:                omit.From(arcgisLayerField1.LayerIndex),
		LayerFieldName:            omit.From(arcgisLayerField1.Name),
	}

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

	return arcgisAddressMapping0, nil
}

func (arcgisAddressMapping0 *ArcgisAddressMapping) InsertLayerField(ctx context.Context, exec bob.Executor, related *ArcgisLayerFieldSetter) error {
	var err error

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

	_, err = attachArcgisAddressMappingLayerField0(ctx, exec, 1, arcgisAddressMapping0, arcgisLayerField1)
	if err != nil {
		return err
	}

	arcgisAddressMapping0.R.LayerField = arcgisLayerField1

	arcgisLayerField1.R.AddressMappings = append(arcgisLayerField1.R.AddressMappings, arcgisAddressMapping0)

	return nil
}

func (arcgisAddressMapping0 *ArcgisAddressMapping) AttachLayerField(ctx context.Context, exec bob.Executor, arcgisLayerField1 *ArcgisLayerField) error {
	var err error

	_, err = attachArcgisAddressMappingLayerField0(ctx, exec, 1, arcgisAddressMapping0, arcgisLayerField1)
	if err != nil {
		return err
	}

	arcgisAddressMapping0.R.LayerField = arcgisLayerField1

	arcgisLayerField1.R.AddressMappings = append(arcgisLayerField1.R.AddressMappings, arcgisAddressMapping0)

	return nil
}

func attachArcgisAddressMappingOrganization0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMapping0 *ArcgisAddressMapping, organization1 *Organization) (*ArcgisAddressMapping, error) {
	setter := &ArcgisAddressMappingSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return arcgisAddressMapping0, nil
}

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

	arcgisAddressMapping0.R.Organization = organization1

	organization1.R.AddressMappings = append(organization1.R.AddressMappings, arcgisAddressMapping0)

	return nil
}

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

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

	arcgisAddressMapping0.R.Organization = organization1

	organization1.R.AddressMappings = append(organization1.R.AddressMappings, arcgisAddressMapping0)

	return nil
}

type arcgisAddressMappingWhere[Q psql.Filterable] struct {
	Destination               psql.WhereMod[Q, enums.ArcgisMappingdestinationaddress]
	LayerFeatureServiceItemID psql.WhereMod[Q, string]
	LayerIndex                psql.WhereMod[Q, int32]
	LayerFieldName            psql.WhereMod[Q, string]
	OrganizationID            psql.WhereMod[Q, int32]
}

func (arcgisAddressMappingWhere[Q]) AliasedAs(alias string) arcgisAddressMappingWhere[Q] {
	return buildArcgisAddressMappingWhere[Q](buildArcgisAddressMappingColumns(alias))
}

func buildArcgisAddressMappingWhere[Q psql.Filterable](cols arcgisAddressMappingColumns) arcgisAddressMappingWhere[Q] {
	return arcgisAddressMappingWhere[Q]{
		Destination:               psql.Where[Q, enums.ArcgisMappingdestinationaddress](cols.Destination),
		LayerFeatureServiceItemID: psql.Where[Q, string](cols.LayerFeatureServiceItemID),
		LayerIndex:                psql.Where[Q, int32](cols.LayerIndex),
		LayerFieldName:            psql.Where[Q, string](cols.LayerFieldName),
		OrganizationID:            psql.Where[Q, int32](cols.OrganizationID),
	}
}

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

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

		o.R.LayerField = rel

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

		o.R.Organization = rel

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

type arcgisAddressMappingPreloader struct {
	LayerField   func(...psql.PreloadOption) psql.Preloader
	Organization func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisAddressMappingPreloader() arcgisAddressMappingPreloader {
	return arcgisAddressMappingPreloader{
		LayerField: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ArcgisLayerField, ArcgisLayerFieldSlice](psql.PreloadRel{
				Name: "LayerField",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisAddressMappings,
						To:          ArcgisLayerFields,
						FromColumns: []string{"layer_feature_service_item_id", "layer_index", "layer_field_name"},
						ToColumns:   []string{"layer_feature_service_item_id", "layer_index", "name"},
					},
				},
			}, ArcgisLayerFields.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisAddressMappings,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

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

func buildArcgisAddressMappingThenLoader[Q orm.Loadable]() arcgisAddressMappingThenLoader[Q] {
	type LayerFieldLoadInterface interface {
		LoadLayerField(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisAddressMappingThenLoader[Q]{
		LayerField: thenLoadBuilder[Q](
			"LayerField",
			func(ctx context.Context, exec bob.Executor, retrieved LayerFieldLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadLayerField(ctx, exec, mods...)
			},
		),
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.AddressMappings = ArcgisAddressMappingSlice{o}

	o.R.LayerField = related
	return nil
}

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

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

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

		for _, rel := range arcgisLayerFields {

			if !(o.LayerFeatureServiceItemID == rel.LayerFeatureServiceItemID) {
				continue
			}

			if !(o.LayerIndex == rel.LayerIndex) {
				continue
			}

			if !(o.LayerFieldName == rel.Name) {
				continue
			}

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

			o.R.LayerField = rel
			break
		}
	}

	return nil
}

// LoadOrganization loads the arcgisAddressMapping's Organization into the .R struct
func (o *ArcgisAddressMapping) 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.AddressMappings = ArcgisAddressMappingSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the arcgisAddressMapping's Organization into the .R struct
func (os ArcgisAddressMappingSlice) 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.AddressMappings = append(rel.R.AddressMappings, o)

			o.R.Organization = rel
			break
		}
	}

	return nil
}
