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

// ArcgisServiceFeature is an object representing the database table.
type ArcgisServiceFeature struct {
	Extent           string           `db:"extent" `
	ItemID           string           `db:"item_id,pk" `
	SpatialReference int32            `db:"spatial_reference" `
	URL              string           `db:"url" `
	AccountID        null.Val[string] `db:"account_id" `

	R arcgisServiceFeatureR `db:"-" `

	C arcgisServiceFeatureC `db:"-" `
}

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

// ArcgisServiceFeatures contains methods to work with the service_feature table
var ArcgisServiceFeatures = psql.NewTablex[*ArcgisServiceFeature, ArcgisServiceFeatureSlice, *ArcgisServiceFeatureSetter]("arcgis", "service_feature", buildArcgisServiceFeatureColumns("arcgis.service_feature"))

// ArcgisServiceFeaturesQuery is a query on the service_feature table
type ArcgisServiceFeaturesQuery = *psql.ViewQuery[*ArcgisServiceFeature, ArcgisServiceFeatureSlice]

// arcgisServiceFeatureR is where relationships are stored.
type arcgisServiceFeatureR struct {
	FeatureServiceItemLayers                   ArcgisLayerSlice  // arcgis.layer.layer_feature_service_item_id_fkey
	Account                                    *ArcgisAccount    // arcgis.service_feature.service_feature_account_id_fkey
	FieldseekerServiceFeatureItemOrganizations OrganizationSlice // organization.organization_fieldseeker_service_feature_item_id_fkey
}

func buildArcgisServiceFeatureColumns(alias string) arcgisServiceFeatureColumns {
	return arcgisServiceFeatureColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"extent", "item_id", "spatial_reference", "url", "account_id",
		).WithParent("arcgis.service_feature"),
		tableAlias:       alias,
		Extent:           psql.Quote(alias, "extent"),
		ItemID:           psql.Quote(alias, "item_id"),
		SpatialReference: psql.Quote(alias, "spatial_reference"),
		URL:              psql.Quote(alias, "url"),
		AccountID:        psql.Quote(alias, "account_id"),
	}
}

type arcgisServiceFeatureColumns struct {
	expr.ColumnsExpr
	tableAlias       string
	Extent           psql.Expression
	ItemID           psql.Expression
	SpatialReference psql.Expression
	URL              psql.Expression
	AccountID        psql.Expression
}

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

func (arcgisServiceFeatureColumns) AliasedAs(alias string) arcgisServiceFeatureColumns {
	return buildArcgisServiceFeatureColumns(alias)
}

// ArcgisServiceFeatureSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisServiceFeatureSetter struct {
	Extent           omit.Val[string]     `db:"extent" `
	ItemID           omit.Val[string]     `db:"item_id,pk" `
	SpatialReference omit.Val[int32]      `db:"spatial_reference" `
	URL              omit.Val[string]     `db:"url" `
	AccountID        omitnull.Val[string] `db:"account_id" `
}

func (s ArcgisServiceFeatureSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.Extent.IsValue() {
		vals = append(vals, "extent")
	}
	if s.ItemID.IsValue() {
		vals = append(vals, "item_id")
	}
	if s.SpatialReference.IsValue() {
		vals = append(vals, "spatial_reference")
	}
	if s.URL.IsValue() {
		vals = append(vals, "url")
	}
	if !s.AccountID.IsUnset() {
		vals = append(vals, "account_id")
	}
	return vals
}

func (s ArcgisServiceFeatureSetter) Overwrite(t *ArcgisServiceFeature) {
	if s.Extent.IsValue() {
		t.Extent = s.Extent.MustGet()
	}
	if s.ItemID.IsValue() {
		t.ItemID = s.ItemID.MustGet()
	}
	if s.SpatialReference.IsValue() {
		t.SpatialReference = s.SpatialReference.MustGet()
	}
	if s.URL.IsValue() {
		t.URL = s.URL.MustGet()
	}
	if !s.AccountID.IsUnset() {
		t.AccountID = s.AccountID.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return ArcgisServiceFeatures.Query(
		sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(ItemIDPK))),
		sm.Columns(ArcgisServiceFeatures.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ArcgisServiceFeatureExists checks the presence of a single record by primary key
func ArcgisServiceFeatureExists(ctx context.Context, exec bob.Executor, ItemIDPK string) (bool, error) {
	return ArcgisServiceFeatures.Query(
		sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(ItemIDPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("arcgis.service_feature", "item_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 ArcgisServiceFeatureSlice) copyMatchingRows(from ...*ArcgisServiceFeature) {
	for i, old := range o {
		for _, new := range from {
			if new.ItemID != old.ItemID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// FeatureServiceItemLayers starts a query for related objects on arcgis.layer
func (o *ArcgisServiceFeature) FeatureServiceItemLayers(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayersQuery {
	return ArcgisLayers.Query(append(mods,
		sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(o.ItemID))),
	)...)
}

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

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

// Account starts a query for related objects on arcgis.account
func (o *ArcgisServiceFeature) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery {
	return ArcgisAccounts.Query(append(mods,
		sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.AccountID))),
	)...)
}

func (os ArcgisServiceFeatureSlice) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery {
	pkAccountID := make(pgtypes.Array[null.Val[string]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkAccountID = append(pkAccountID, o.AccountID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkAccountID), "text[]")),
	))

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

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

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

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

func insertArcgisServiceFeatureFeatureServiceItemLayers0(ctx context.Context, exec bob.Executor, arcgisLayers1 []*ArcgisLayerSetter, arcgisServiceFeature0 *ArcgisServiceFeature) (ArcgisLayerSlice, error) {
	for i := range arcgisLayers1 {
		arcgisLayers1[i].FeatureServiceItemID = omit.From(arcgisServiceFeature0.ItemID)
	}

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

	return ret, nil
}

func attachArcgisServiceFeatureFeatureServiceItemLayers0(ctx context.Context, exec bob.Executor, count int, arcgisLayers1 ArcgisLayerSlice, arcgisServiceFeature0 *ArcgisServiceFeature) (ArcgisLayerSlice, error) {
	setter := &ArcgisLayerSetter{
		FeatureServiceItemID: omit.From(arcgisServiceFeature0.ItemID),
	}

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

	return arcgisLayers1, nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisLayers1, err := insertArcgisServiceFeatureFeatureServiceItemLayers0(ctx, exec, related, arcgisServiceFeature0)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.FeatureServiceItemLayers = append(arcgisServiceFeature0.R.FeatureServiceItemLayers, arcgisLayers1...)

	for _, rel := range arcgisLayers1 {
		rel.R.FeatureServiceItemServiceFeature = arcgisServiceFeature0
	}
	return nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, related ...*ArcgisLayer) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisLayers1 := ArcgisLayerSlice(related)

	_, err = attachArcgisServiceFeatureFeatureServiceItemLayers0(ctx, exec, len(related), arcgisLayers1, arcgisServiceFeature0)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.FeatureServiceItemLayers = append(arcgisServiceFeature0.R.FeatureServiceItemLayers, arcgisLayers1...)

	for _, rel := range related {
		rel.R.FeatureServiceItemServiceFeature = arcgisServiceFeature0
	}

	return nil
}

func attachArcgisServiceFeatureAccount0(ctx context.Context, exec bob.Executor, count int, arcgisServiceFeature0 *ArcgisServiceFeature, arcgisAccount1 *ArcgisAccount) (*ArcgisServiceFeature, error) {
	setter := &ArcgisServiceFeatureSetter{
		AccountID: omitnull.From(arcgisAccount1.ID),
	}

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

	return arcgisServiceFeature0, nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertAccount(ctx context.Context, exec bob.Executor, related *ArcgisAccountSetter) error {
	var err error

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

	_, err = attachArcgisServiceFeatureAccount0(ctx, exec, 1, arcgisServiceFeature0, arcgisAccount1)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.Account = arcgisAccount1

	arcgisAccount1.R.ServiceFeatures = append(arcgisAccount1.R.ServiceFeatures, arcgisServiceFeature0)

	return nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error {
	var err error

	_, err = attachArcgisServiceFeatureAccount0(ctx, exec, 1, arcgisServiceFeature0, arcgisAccount1)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.Account = arcgisAccount1

	arcgisAccount1.R.ServiceFeatures = append(arcgisAccount1.R.ServiceFeatures, arcgisServiceFeature0)

	return nil
}

func insertArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx context.Context, exec bob.Executor, organizations1 []*OrganizationSetter, arcgisServiceFeature0 *ArcgisServiceFeature) (OrganizationSlice, error) {
	for i := range organizations1 {
		organizations1[i].FieldseekerServiceFeatureItemID = omitnull.From(arcgisServiceFeature0.ItemID)
	}

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

	return ret, nil
}

func attachArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx context.Context, exec bob.Executor, count int, organizations1 OrganizationSlice, arcgisServiceFeature0 *ArcgisServiceFeature) (OrganizationSlice, error) {
	setter := &OrganizationSetter{
		FieldseekerServiceFeatureItemID: omitnull.From(arcgisServiceFeature0.ItemID),
	}

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

	return organizations1, nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	organizations1, err := insertArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx, exec, related, arcgisServiceFeature0)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations, organizations1...)

	for _, rel := range organizations1 {
		rel.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature0
	}
	return nil
}

func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	organizations1 := OrganizationSlice(related)

	_, err = attachArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx, exec, len(related), organizations1, arcgisServiceFeature0)
	if err != nil {
		return err
	}

	arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations, organizations1...)

	for _, rel := range related {
		rel.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature0
	}

	return nil
}

type arcgisServiceFeatureWhere[Q psql.Filterable] struct {
	Extent           psql.WhereMod[Q, string]
	ItemID           psql.WhereMod[Q, string]
	SpatialReference psql.WhereMod[Q, int32]
	URL              psql.WhereMod[Q, string]
	AccountID        psql.WhereNullMod[Q, string]
}

func (arcgisServiceFeatureWhere[Q]) AliasedAs(alias string) arcgisServiceFeatureWhere[Q] {
	return buildArcgisServiceFeatureWhere[Q](buildArcgisServiceFeatureColumns(alias))
}

func buildArcgisServiceFeatureWhere[Q psql.Filterable](cols arcgisServiceFeatureColumns) arcgisServiceFeatureWhere[Q] {
	return arcgisServiceFeatureWhere[Q]{
		Extent:           psql.Where[Q, string](cols.Extent),
		ItemID:           psql.Where[Q, string](cols.ItemID),
		SpatialReference: psql.Where[Q, int32](cols.SpatialReference),
		URL:              psql.Where[Q, string](cols.URL),
		AccountID:        psql.WhereNull[Q, string](cols.AccountID),
	}
}

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

	switch name {
	case "FeatureServiceItemLayers":
		rels, ok := retrieved.(ArcgisLayerSlice)
		if !ok {
			return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name)
		}

		o.R.FeatureServiceItemLayers = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.FeatureServiceItemServiceFeature = o
			}
		}
		return nil
	case "Account":
		rel, ok := retrieved.(*ArcgisAccount)
		if !ok {
			return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name)
		}

		o.R.Account = rel

		if rel != nil {
			rel.R.ServiceFeatures = ArcgisServiceFeatureSlice{o}
		}
		return nil
	case "FieldseekerServiceFeatureItemOrganizations":
		rels, ok := retrieved.(OrganizationSlice)
		if !ok {
			return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name)
		}

		o.R.FieldseekerServiceFeatureItemOrganizations = rels

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

type arcgisServiceFeaturePreloader struct {
	Account func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisServiceFeaturePreloader() arcgisServiceFeaturePreloader {
	return arcgisServiceFeaturePreloader{
		Account: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{
				Name: "Account",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisServiceFeatures,
						To:          ArcgisAccounts,
						FromColumns: []string{"account_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, ArcgisAccounts.Columns.Names(), opts...)
		},
	}
}

type arcgisServiceFeatureThenLoader[Q orm.Loadable] struct {
	FeatureServiceItemLayers                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Account                                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisServiceFeatureThenLoader[Q orm.Loadable]() arcgisServiceFeatureThenLoader[Q] {
	type FeatureServiceItemLayersLoadInterface interface {
		LoadFeatureServiceItemLayers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type AccountLoadInterface interface {
		LoadAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FieldseekerServiceFeatureItemOrganizationsLoadInterface interface {
		LoadFieldseekerServiceFeatureItemOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisServiceFeatureThenLoader[Q]{
		FeatureServiceItemLayers: thenLoadBuilder[Q](
			"FeatureServiceItemLayers",
			func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemLayersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeatureServiceItemLayers(ctx, exec, mods...)
			},
		),
		Account: thenLoadBuilder[Q](
			"Account",
			func(ctx context.Context, exec bob.Executor, retrieved AccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAccount(ctx, exec, mods...)
			},
		),
		FieldseekerServiceFeatureItemOrganizations: thenLoadBuilder[Q](
			"FieldseekerServiceFeatureItemOrganizations",
			func(ctx context.Context, exec bob.Executor, retrieved FieldseekerServiceFeatureItemOrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.FeatureServiceItemLayers = related
	return nil
}

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

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

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

		o.R.FeatureServiceItemLayers = nil
	}

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

		for _, rel := range arcgisLayers {

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

			rel.R.FeatureServiceItemServiceFeature = o

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

	return nil
}

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

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

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

	related.R.ServiceFeatures = ArcgisServiceFeatureSlice{o}

	o.R.Account = related
	return nil
}

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

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

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

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

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

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

			o.R.Account = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.FieldseekerServiceFeatureItemOrganizations = related
	return nil
}

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

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

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

		o.R.FieldseekerServiceFeatureItemOrganizations = nil
	}

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

		for _, rel := range organizations {

			if !rel.FieldseekerServiceFeatureItemID.IsValue() {
				continue
			}
			if !(rel.FieldseekerServiceFeatureItemID.IsValue() && o.ItemID == rel.FieldseekerServiceFeatureItemID.MustGet()) {
				continue
			}

			rel.R.FieldseekerServiceFeatureItemServiceFeature = o

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

	return nil
}

// arcgisServiceFeatureC is where relationship counts are stored.
type arcgisServiceFeatureC struct {
	FeatureServiceItemLayers                   *int64
	FieldseekerServiceFeatureItemOrganizations *int64
}

// PreloadCount sets a count in the C struct by name
func (o *ArcgisServiceFeature) PreloadCount(name string, count int64) error {
	if o == nil {
		return nil
	}

	switch name {
	case "FeatureServiceItemLayers":
		o.C.FeatureServiceItemLayers = &count
	case "FieldseekerServiceFeatureItemOrganizations":
		o.C.FieldseekerServiceFeatureItemOrganizations = &count
	}
	return nil
}

type arcgisServiceFeatureCountPreloader struct {
	FeatureServiceItemLayers                   func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
	FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
}

func buildArcgisServiceFeatureCountPreloader() arcgisServiceFeatureCountPreloader {
	return arcgisServiceFeatureCountPreloader{
		FeatureServiceItemLayers: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*ArcgisServiceFeature]("FeatureServiceItemLayers", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = ArcgisServiceFeatures.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(ArcgisLayers.Name()),
					sm.Where(psql.Quote(ArcgisLayers.Alias(), "feature_service_item_id").EQ(psql.Quote(parent, "item_id"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
		FieldseekerServiceFeatureItemOrganizations: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*ArcgisServiceFeature]("FieldseekerServiceFeatureItemOrganizations", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = ArcgisServiceFeatures.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(Organizations.Name()),
					sm.Where(psql.Quote(Organizations.Alias(), "fieldseeker_service_feature_item_id").EQ(psql.Quote(parent, "item_id"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
	}
}

type arcgisServiceFeatureCountThenLoader[Q orm.Loadable] struct {
	FeatureServiceItemLayers                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisServiceFeatureCountThenLoader[Q orm.Loadable]() arcgisServiceFeatureCountThenLoader[Q] {
	type FeatureServiceItemLayersCountInterface interface {
		LoadCountFeatureServiceItemLayers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type FieldseekerServiceFeatureItemOrganizationsCountInterface interface {
		LoadCountFieldseekerServiceFeatureItemOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisServiceFeatureCountThenLoader[Q]{
		FeatureServiceItemLayers: countThenLoadBuilder[Q](
			"FeatureServiceItemLayers",
			func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemLayersCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountFeatureServiceItemLayers(ctx, exec, mods...)
			},
		),
		FieldseekerServiceFeatureItemOrganizations: countThenLoadBuilder[Q](
			"FieldseekerServiceFeatureItemOrganizations",
			func(ctx context.Context, exec bob.Executor, retrieved FieldseekerServiceFeatureItemOrganizationsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...)
			},
		),
	}
}

// LoadCountFeatureServiceItemLayers loads the count of FeatureServiceItemLayers into the C struct
func (o *ArcgisServiceFeature) LoadCountFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.FeatureServiceItemLayers(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.FeatureServiceItemLayers = &count
	return nil
}

// LoadCountFeatureServiceItemLayers loads the count of FeatureServiceItemLayers for a slice
func (os ArcgisServiceFeatureSlice) LoadCountFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountFeatureServiceItemLayers(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

// LoadCountFieldseekerServiceFeatureItemOrganizations loads the count of FieldseekerServiceFeatureItemOrganizations into the C struct
func (o *ArcgisServiceFeature) LoadCountFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.FieldseekerServiceFeatureItemOrganizations(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.FieldseekerServiceFeatureItemOrganizations = &count
	return nil
}

// LoadCountFieldseekerServiceFeatureItemOrganizations loads the count of FieldseekerServiceFeatureItemOrganizations for a slice
func (os ArcgisServiceFeatureSlice) LoadCountFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

type arcgisServiceFeatureJoins[Q dialect.Joinable] struct {
	typ                                        string
	FeatureServiceItemLayers                   modAs[Q, arcgisLayerColumns]
	Account                                    modAs[Q, arcgisAccountColumns]
	FieldseekerServiceFeatureItemOrganizations modAs[Q, organizationColumns]
}

func (j arcgisServiceFeatureJoins[Q]) aliasedAs(alias string) arcgisServiceFeatureJoins[Q] {
	return buildArcgisServiceFeatureJoins[Q](buildArcgisServiceFeatureColumns(alias), j.typ)
}

func buildArcgisServiceFeatureJoins[Q dialect.Joinable](cols arcgisServiceFeatureColumns, typ string) arcgisServiceFeatureJoins[Q] {
	return arcgisServiceFeatureJoins[Q]{
		typ: typ,
		FeatureServiceItemLayers: modAs[Q, arcgisLayerColumns]{
			c: ArcgisLayers.Columns,
			f: func(to arcgisLayerColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, ArcgisLayers.Name().As(to.Alias())).On(
						to.FeatureServiceItemID.EQ(cols.ItemID),
					))
				}

				return mods
			},
		},
		Account: modAs[Q, arcgisAccountColumns]{
			c: ArcgisAccounts.Columns,
			f: func(to arcgisAccountColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On(
						to.ID.EQ(cols.AccountID),
					))
				}

				return mods
			},
		},
		FieldseekerServiceFeatureItemOrganizations: modAs[Q, organizationColumns]{
			c: Organizations.Columns,
			f: func(to organizationColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On(
						to.FieldseekerServiceFeatureItemID.EQ(cols.ItemID),
					))
				}

				return mods
			},
		},
	}
}
