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

package models

import (
	"context"
	"fmt"
	"io"

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

// ArcgisLayer is an object representing the database table.
type ArcgisLayer struct {
	Extent               string `db:"extent" `
	FeatureServiceItemID string `db:"feature_service_item_id,pk" `
	Index                int32  `db:"index_,pk" `

	R arcgisLayerR `db:"-" `
}

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

// ArcgisLayers contains methods to work with the layer table
var ArcgisLayers = psql.NewTablex[*ArcgisLayer, ArcgisLayerSlice, *ArcgisLayerSetter]("arcgis", "layer", buildArcgisLayerColumns("arcgis.layer"))

// ArcgisLayersQuery is a query on the layer table
type ArcgisLayersQuery = *psql.ViewQuery[*ArcgisLayer, ArcgisLayerSlice]

// arcgisLayerR is where relationships are stored.
type arcgisLayerR struct {
	FeatureServiceItemServiceFeature *ArcgisServiceFeature // arcgis.layer.layer_feature_service_item_id_fkey
	LayerFields                      ArcgisLayerFieldSlice // arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey
}

func buildArcgisLayerColumns(alias string) arcgisLayerColumns {
	return arcgisLayerColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"extent", "feature_service_item_id", "index_",
		).WithParent("arcgis.layer"),
		tableAlias:           alias,
		Extent:               psql.Quote(alias, "extent"),
		FeatureServiceItemID: psql.Quote(alias, "feature_service_item_id"),
		Index:                psql.Quote(alias, "index_"),
	}
}

type arcgisLayerColumns struct {
	expr.ColumnsExpr
	tableAlias           string
	Extent               psql.Expression
	FeatureServiceItemID psql.Expression
	Index                psql.Expression
}

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

func (arcgisLayerColumns) AliasedAs(alias string) arcgisLayerColumns {
	return buildArcgisLayerColumns(alias)
}

// ArcgisLayerSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisLayerSetter struct {
	Extent               omit.Val[string] `db:"extent" `
	FeatureServiceItemID omit.Val[string] `db:"feature_service_item_id,pk" `
	Index                omit.Val[int32]  `db:"index_,pk" `
}

func (s ArcgisLayerSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.Extent.IsValue() {
		vals = append(vals, "extent")
	}
	if s.FeatureServiceItemID.IsValue() {
		vals = append(vals, "feature_service_item_id")
	}
	if s.Index.IsValue() {
		vals = append(vals, "index_")
	}
	return vals
}

func (s ArcgisLayerSetter) Overwrite(t *ArcgisLayer) {
	if s.Extent.IsValue() {
		t.Extent = s.Extent.MustGet()
	}
	if s.FeatureServiceItemID.IsValue() {
		t.FeatureServiceItemID = s.FeatureServiceItemID.MustGet()
	}
	if s.Index.IsValue() {
		t.Index = s.Index.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindArcgisLayer retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindArcgisLayer(ctx context.Context, exec bob.Executor, FeatureServiceItemIDPK string, IndexPK int32, cols ...string) (*ArcgisLayer, error) {
	if len(cols) == 0 {
		return ArcgisLayers.Query(
			sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))),
			sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))),
		).One(ctx, exec)
	}

	return ArcgisLayers.Query(
		sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))),
		sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))),
		sm.Columns(ArcgisLayers.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ArcgisLayerExists checks the presence of a single record by primary key
func ArcgisLayerExists(ctx context.Context, exec bob.Executor, FeatureServiceItemIDPK string, IndexPK int32) (bool, error) {
	return ArcgisLayers.Query(
		sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))),
		sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the ArcgisLayer
func (o *ArcgisLayer) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.FeatureServiceItemID,
		o.Index,
	)
}

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("arcgis.layer", "feature_service_item_id"), psql.Quote("arcgis.layer", "index_")).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 ArcgisLayerSlice) copyMatchingRows(from ...*ArcgisLayer) {
	for i, old := range o {
		for _, new := range from {
			if new.FeatureServiceItemID != old.FeatureServiceItemID {
				continue
			}
			if new.Index != old.Index {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// FeatureServiceItemServiceFeature starts a query for related objects on arcgis.service_feature
func (o *ArcgisLayer) FeatureServiceItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery {
	return ArcgisServiceFeatures.Query(append(mods,
		sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(o.FeatureServiceItemID))),
	)...)
}

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

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

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

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

	pkIndex := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkFeatureServiceItemID = append(pkFeatureServiceItemID, o.FeatureServiceItemID)
		pkIndex = append(pkIndex, o.Index)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkFeatureServiceItemID), "text[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkIndex), "integer[]")),
	))

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

func attachArcgisLayerFeatureServiceItemServiceFeature0(ctx context.Context, exec bob.Executor, count int, arcgisLayer0 *ArcgisLayer, arcgisServiceFeature1 *ArcgisServiceFeature) (*ArcgisLayer, error) {
	setter := &ArcgisLayerSetter{
		FeatureServiceItemID: omit.From(arcgisServiceFeature1.ItemID),
	}

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

	return arcgisLayer0, nil
}

func (arcgisLayer0 *ArcgisLayer) InsertFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, related *ArcgisServiceFeatureSetter) error {
	var err error

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

	_, err = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1)
	if err != nil {
		return err
	}

	arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1

	arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0)

	return nil
}

func (arcgisLayer0 *ArcgisLayer) AttachFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, arcgisServiceFeature1 *ArcgisServiceFeature) error {
	var err error

	_, err = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1)
	if err != nil {
		return err
	}

	arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1

	arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0)

	return nil
}

func insertArcgisLayerLayerFields0(ctx context.Context, exec bob.Executor, arcgisLayerFields1 []*ArcgisLayerFieldSetter, arcgisLayer0 *ArcgisLayer) (ArcgisLayerFieldSlice, error) {
	for i := range arcgisLayerFields1 {
		arcgisLayerFields1[i].LayerFeatureServiceItemID = omit.From(arcgisLayer0.FeatureServiceItemID)
		arcgisLayerFields1[i].LayerIndex = omit.From(arcgisLayer0.Index)
	}

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

	return ret, nil
}

func attachArcgisLayerLayerFields0(ctx context.Context, exec bob.Executor, count int, arcgisLayerFields1 ArcgisLayerFieldSlice, arcgisLayer0 *ArcgisLayer) (ArcgisLayerFieldSlice, error) {
	setter := &ArcgisLayerFieldSetter{
		LayerFeatureServiceItemID: omit.From(arcgisLayer0.FeatureServiceItemID),
		LayerIndex:                omit.From(arcgisLayer0.Index),
	}

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

	return arcgisLayerFields1, nil
}

func (arcgisLayer0 *ArcgisLayer) InsertLayerFields(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerFieldSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisLayerFields1, err := insertArcgisLayerLayerFields0(ctx, exec, related, arcgisLayer0)
	if err != nil {
		return err
	}

	arcgisLayer0.R.LayerFields = append(arcgisLayer0.R.LayerFields, arcgisLayerFields1...)

	for _, rel := range arcgisLayerFields1 {
		rel.R.Layer = arcgisLayer0
	}
	return nil
}

func (arcgisLayer0 *ArcgisLayer) AttachLayerFields(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerField) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisLayerFields1 := ArcgisLayerFieldSlice(related)

	_, err = attachArcgisLayerLayerFields0(ctx, exec, len(related), arcgisLayerFields1, arcgisLayer0)
	if err != nil {
		return err
	}

	arcgisLayer0.R.LayerFields = append(arcgisLayer0.R.LayerFields, arcgisLayerFields1...)

	for _, rel := range related {
		rel.R.Layer = arcgisLayer0
	}

	return nil
}

type arcgisLayerWhere[Q psql.Filterable] struct {
	Extent               psql.WhereMod[Q, string]
	FeatureServiceItemID psql.WhereMod[Q, string]
	Index                psql.WhereMod[Q, int32]
}

func (arcgisLayerWhere[Q]) AliasedAs(alias string) arcgisLayerWhere[Q] {
	return buildArcgisLayerWhere[Q](buildArcgisLayerColumns(alias))
}

func buildArcgisLayerWhere[Q psql.Filterable](cols arcgisLayerColumns) arcgisLayerWhere[Q] {
	return arcgisLayerWhere[Q]{
		Extent:               psql.Where[Q, string](cols.Extent),
		FeatureServiceItemID: psql.Where[Q, string](cols.FeatureServiceItemID),
		Index:                psql.Where[Q, int32](cols.Index),
	}
}

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

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

		o.R.FeatureServiceItemServiceFeature = rel

		if rel != nil {
			rel.R.FeatureServiceItemLayers = ArcgisLayerSlice{o}
		}
		return nil
	case "LayerFields":
		rels, ok := retrieved.(ArcgisLayerFieldSlice)
		if !ok {
			return fmt.Errorf("arcgisLayer cannot load %T as %q", retrieved, name)
		}

		o.R.LayerFields = rels

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

type arcgisLayerPreloader struct {
	FeatureServiceItemServiceFeature func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisLayerPreloader() arcgisLayerPreloader {
	return arcgisLayerPreloader{
		FeatureServiceItemServiceFeature: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ArcgisServiceFeature, ArcgisServiceFeatureSlice](psql.PreloadRel{
				Name: "FeatureServiceItemServiceFeature",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisLayers,
						To:          ArcgisServiceFeatures,
						FromColumns: []string{"feature_service_item_id"},
						ToColumns:   []string{"item_id"},
					},
				},
			}, ArcgisServiceFeatures.Columns.Names(), opts...)
		},
	}
}

type arcgisLayerThenLoader[Q orm.Loadable] struct {
	FeatureServiceItemServiceFeature func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	LayerFields                      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisLayerThenLoader[Q orm.Loadable]() arcgisLayerThenLoader[Q] {
	type FeatureServiceItemServiceFeatureLoadInterface interface {
		LoadFeatureServiceItemServiceFeature(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type LayerFieldsLoadInterface interface {
		LoadLayerFields(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisLayerThenLoader[Q]{
		FeatureServiceItemServiceFeature: thenLoadBuilder[Q](
			"FeatureServiceItemServiceFeature",
			func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemServiceFeatureLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeatureServiceItemServiceFeature(ctx, exec, mods...)
			},
		),
		LayerFields: thenLoadBuilder[Q](
			"LayerFields",
			func(ctx context.Context, exec bob.Executor, retrieved LayerFieldsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadLayerFields(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.FeatureServiceItemLayers = ArcgisLayerSlice{o}

	o.R.FeatureServiceItemServiceFeature = related
	return nil
}

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

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

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

		for _, rel := range arcgisServiceFeatures {

			if !(o.FeatureServiceItemID == rel.ItemID) {
				continue
			}

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

			o.R.FeatureServiceItemServiceFeature = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.LayerFields = related
	return nil
}

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

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

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

		o.R.LayerFields = nil
	}

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

		for _, rel := range arcgisLayerFields {

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

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

			rel.R.Layer = o

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

	return nil
}
