// 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/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// ArcgisAccount is an object representing the database table.
type ArcgisAccount struct {
	ID             string           `db:"id,pk" `
	Name           string           `db:"name" `
	OrganizationID int32            `db:"organization_id" `
	URLFeatures    null.Val[string] `db:"url_features" `
	URLInsights    null.Val[string] `db:"url_insights" `
	URLGeometry    null.Val[string] `db:"url_geometry" `
	URLNotebooks   null.Val[string] `db:"url_notebooks" `
	URLTiles       null.Val[string] `db:"url_tiles" `

	R arcgisAccountR `db:"-" `
}

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

// ArcgisAccounts contains methods to work with the account table
var ArcgisAccounts = psql.NewTablex[*ArcgisAccount, ArcgisAccountSlice, *ArcgisAccountSetter]("arcgis", "account", buildArcgisAccountColumns("arcgis.account"))

// ArcgisAccountsQuery is a query on the account table
type ArcgisAccountsQuery = *psql.ViewQuery[*ArcgisAccount, ArcgisAccountSlice]

// arcgisAccountR is where relationships are stored.
type arcgisAccountR struct {
	Organization               *Organization             // arcgis.account.account_organization_id_fkey
	ArcgisAccountOauthTokens   ArcgisOauthTokenSlice     // arcgis.oauth_token.oauth_token_arcgis_account_id_fkey
	ServiceFeatures            ArcgisServiceFeatureSlice // arcgis.service_feature.service_feature_account_id_fkey
	ServiceMaps                ArcgisServiceMapSlice     // arcgis.service_map.service_map_account_id_fkey
	ArcgisAccountOrganizations OrganizationSlice         // organization.organization_arcgis_account_id_fkey
}

func buildArcgisAccountColumns(alias string) arcgisAccountColumns {
	return arcgisAccountColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "name", "organization_id", "url_features", "url_insights", "url_geometry", "url_notebooks", "url_tiles",
		).WithParent("arcgis.account"),
		tableAlias:     alias,
		ID:             psql.Quote(alias, "id"),
		Name:           psql.Quote(alias, "name"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		URLFeatures:    psql.Quote(alias, "url_features"),
		URLInsights:    psql.Quote(alias, "url_insights"),
		URLGeometry:    psql.Quote(alias, "url_geometry"),
		URLNotebooks:   psql.Quote(alias, "url_notebooks"),
		URLTiles:       psql.Quote(alias, "url_tiles"),
	}
}

type arcgisAccountColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	ID             psql.Expression
	Name           psql.Expression
	OrganizationID psql.Expression
	URLFeatures    psql.Expression
	URLInsights    psql.Expression
	URLGeometry    psql.Expression
	URLNotebooks   psql.Expression
	URLTiles       psql.Expression
}

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

func (arcgisAccountColumns) AliasedAs(alias string) arcgisAccountColumns {
	return buildArcgisAccountColumns(alias)
}

// ArcgisAccountSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisAccountSetter struct {
	ID             omit.Val[string]     `db:"id,pk" `
	Name           omit.Val[string]     `db:"name" `
	OrganizationID omit.Val[int32]      `db:"organization_id" `
	URLFeatures    omitnull.Val[string] `db:"url_features" `
	URLInsights    omitnull.Val[string] `db:"url_insights" `
	URLGeometry    omitnull.Val[string] `db:"url_geometry" `
	URLNotebooks   omitnull.Val[string] `db:"url_notebooks" `
	URLTiles       omitnull.Val[string] `db:"url_tiles" `
}

func (s ArcgisAccountSetter) SetColumns() []string {
	vals := make([]string, 0, 8)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if !s.URLFeatures.IsUnset() {
		vals = append(vals, "url_features")
	}
	if !s.URLInsights.IsUnset() {
		vals = append(vals, "url_insights")
	}
	if !s.URLGeometry.IsUnset() {
		vals = append(vals, "url_geometry")
	}
	if !s.URLNotebooks.IsUnset() {
		vals = append(vals, "url_notebooks")
	}
	if !s.URLTiles.IsUnset() {
		vals = append(vals, "url_tiles")
	}
	return vals
}

func (s ArcgisAccountSetter) Overwrite(t *ArcgisAccount) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if !s.URLFeatures.IsUnset() {
		t.URLFeatures = s.URLFeatures.MustGetNull()
	}
	if !s.URLInsights.IsUnset() {
		t.URLInsights = s.URLInsights.MustGetNull()
	}
	if !s.URLGeometry.IsUnset() {
		t.URLGeometry = s.URLGeometry.MustGetNull()
	}
	if !s.URLNotebooks.IsUnset() {
		t.URLNotebooks = s.URLNotebooks.MustGetNull()
	}
	if !s.URLTiles.IsUnset() {
		t.URLTiles = s.URLTiles.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os ArcgisAccountSlice) 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)),
	)...)
}

// ArcgisAccountOauthTokens starts a query for related objects on arcgis.oauth_token
func (o *ArcgisAccount) ArcgisAccountOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisOauthTokensQuery {
	return ArcgisOauthTokens.Query(append(mods,
		sm.Where(ArcgisOauthTokens.Columns.ArcgisAccountID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

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

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

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

// ServiceMaps starts a query for related objects on arcgis.service_map
func (o *ArcgisAccount) ServiceMaps(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery {
	return ArcgisServiceMaps.Query(append(mods,
		sm.Where(ArcgisServiceMaps.Columns.AccountID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

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

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

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

func attachArcgisAccountOrganization0(ctx context.Context, exec bob.Executor, count int, arcgisAccount0 *ArcgisAccount, organization1 *Organization) (*ArcgisAccount, error) {
	setter := &ArcgisAccountSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return arcgisAccount0, nil
}

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

	arcgisAccount0.R.Organization = organization1

	organization1.R.Accounts = append(organization1.R.Accounts, arcgisAccount0)

	return nil
}

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

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

	arcgisAccount0.R.Organization = organization1

	organization1.R.Accounts = append(organization1.R.Accounts, arcgisAccount0)

	return nil
}

func insertArcgisAccountArcgisAccountOauthTokens0(ctx context.Context, exec bob.Executor, arcgisOauthTokens1 []*ArcgisOauthTokenSetter, arcgisAccount0 *ArcgisAccount) (ArcgisOauthTokenSlice, error) {
	for i := range arcgisOauthTokens1 {
		arcgisOauthTokens1[i].ArcgisAccountID = omitnull.From(arcgisAccount0.ID)
	}

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

	return ret, nil
}

func attachArcgisAccountArcgisAccountOauthTokens0(ctx context.Context, exec bob.Executor, count int, arcgisOauthTokens1 ArcgisOauthTokenSlice, arcgisAccount0 *ArcgisAccount) (ArcgisOauthTokenSlice, error) {
	setter := &ArcgisOauthTokenSetter{
		ArcgisAccountID: omitnull.From(arcgisAccount0.ID),
	}

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

	return arcgisOauthTokens1, nil
}

func (arcgisAccount0 *ArcgisAccount) InsertArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthTokenSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisOauthTokens1, err := insertArcgisAccountArcgisAccountOauthTokens0(ctx, exec, related, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ArcgisAccountOauthTokens = append(arcgisAccount0.R.ArcgisAccountOauthTokens, arcgisOauthTokens1...)

	for _, rel := range arcgisOauthTokens1 {
		rel.R.ArcgisAccountAccount = arcgisAccount0
	}
	return nil
}

func (arcgisAccount0 *ArcgisAccount) AttachArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthToken) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisOauthTokens1 := ArcgisOauthTokenSlice(related)

	_, err = attachArcgisAccountArcgisAccountOauthTokens0(ctx, exec, len(related), arcgisOauthTokens1, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ArcgisAccountOauthTokens = append(arcgisAccount0.R.ArcgisAccountOauthTokens, arcgisOauthTokens1...)

	for _, rel := range related {
		rel.R.ArcgisAccountAccount = arcgisAccount0
	}

	return nil
}

func insertArcgisAccountServiceFeatures0(ctx context.Context, exec bob.Executor, arcgisServiceFeatures1 []*ArcgisServiceFeatureSetter, arcgisAccount0 *ArcgisAccount) (ArcgisServiceFeatureSlice, error) {
	for i := range arcgisServiceFeatures1 {
		arcgisServiceFeatures1[i].AccountID = omitnull.From(arcgisAccount0.ID)
	}

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

	return ret, nil
}

func attachArcgisAccountServiceFeatures0(ctx context.Context, exec bob.Executor, count int, arcgisServiceFeatures1 ArcgisServiceFeatureSlice, arcgisAccount0 *ArcgisAccount) (ArcgisServiceFeatureSlice, error) {
	setter := &ArcgisServiceFeatureSetter{
		AccountID: omitnull.From(arcgisAccount0.ID),
	}

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

	return arcgisServiceFeatures1, nil
}

func (arcgisAccount0 *ArcgisAccount) InsertServiceFeatures(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceFeatureSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisServiceFeatures1, err := insertArcgisAccountServiceFeatures0(ctx, exec, related, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ServiceFeatures = append(arcgisAccount0.R.ServiceFeatures, arcgisServiceFeatures1...)

	for _, rel := range arcgisServiceFeatures1 {
		rel.R.Account = arcgisAccount0
	}
	return nil
}

func (arcgisAccount0 *ArcgisAccount) AttachServiceFeatures(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceFeature) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisServiceFeatures1 := ArcgisServiceFeatureSlice(related)

	_, err = attachArcgisAccountServiceFeatures0(ctx, exec, len(related), arcgisServiceFeatures1, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ServiceFeatures = append(arcgisAccount0.R.ServiceFeatures, arcgisServiceFeatures1...)

	for _, rel := range related {
		rel.R.Account = arcgisAccount0
	}

	return nil
}

func insertArcgisAccountServiceMaps0(ctx context.Context, exec bob.Executor, arcgisServiceMaps1 []*ArcgisServiceMapSetter, arcgisAccount0 *ArcgisAccount) (ArcgisServiceMapSlice, error) {
	for i := range arcgisServiceMaps1 {
		arcgisServiceMaps1[i].AccountID = omit.From(arcgisAccount0.ID)
	}

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

	return ret, nil
}

func attachArcgisAccountServiceMaps0(ctx context.Context, exec bob.Executor, count int, arcgisServiceMaps1 ArcgisServiceMapSlice, arcgisAccount0 *ArcgisAccount) (ArcgisServiceMapSlice, error) {
	setter := &ArcgisServiceMapSetter{
		AccountID: omit.From(arcgisAccount0.ID),
	}

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

	return arcgisServiceMaps1, nil
}

func (arcgisAccount0 *ArcgisAccount) InsertServiceMaps(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceMapSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisServiceMaps1, err := insertArcgisAccountServiceMaps0(ctx, exec, related, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ServiceMaps = append(arcgisAccount0.R.ServiceMaps, arcgisServiceMaps1...)

	for _, rel := range arcgisServiceMaps1 {
		rel.R.Account = arcgisAccount0
	}
	return nil
}

func (arcgisAccount0 *ArcgisAccount) AttachServiceMaps(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceMap) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisServiceMaps1 := ArcgisServiceMapSlice(related)

	_, err = attachArcgisAccountServiceMaps0(ctx, exec, len(related), arcgisServiceMaps1, arcgisAccount0)
	if err != nil {
		return err
	}

	arcgisAccount0.R.ServiceMaps = append(arcgisAccount0.R.ServiceMaps, arcgisServiceMaps1...)

	for _, rel := range related {
		rel.R.Account = arcgisAccount0
	}

	return nil
}

func insertArcgisAccountArcgisAccountOrganizations0(ctx context.Context, exec bob.Executor, organizations1 []*OrganizationSetter, arcgisAccount0 *ArcgisAccount) (OrganizationSlice, error) {
	for i := range organizations1 {
		organizations1[i].ArcgisAccountID = omitnull.From(arcgisAccount0.ID)
	}

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

	return ret, nil
}

func attachArcgisAccountArcgisAccountOrganizations0(ctx context.Context, exec bob.Executor, count int, organizations1 OrganizationSlice, arcgisAccount0 *ArcgisAccount) (OrganizationSlice, error) {
	setter := &OrganizationSetter{
		ArcgisAccountID: omitnull.From(arcgisAccount0.ID),
	}

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

	return organizations1, nil
}

func (arcgisAccount0 *ArcgisAccount) InsertArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	arcgisAccount0.R.ArcgisAccountOrganizations = append(arcgisAccount0.R.ArcgisAccountOrganizations, organizations1...)

	for _, rel := range organizations1 {
		rel.R.ArcgisAccountAccount = arcgisAccount0
	}
	return nil
}

func (arcgisAccount0 *ArcgisAccount) AttachArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	organizations1 := OrganizationSlice(related)

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

	arcgisAccount0.R.ArcgisAccountOrganizations = append(arcgisAccount0.R.ArcgisAccountOrganizations, organizations1...)

	for _, rel := range related {
		rel.R.ArcgisAccountAccount = arcgisAccount0
	}

	return nil
}

type arcgisAccountWhere[Q psql.Filterable] struct {
	ID             psql.WhereMod[Q, string]
	Name           psql.WhereMod[Q, string]
	OrganizationID psql.WhereMod[Q, int32]
	URLFeatures    psql.WhereNullMod[Q, string]
	URLInsights    psql.WhereNullMod[Q, string]
	URLGeometry    psql.WhereNullMod[Q, string]
	URLNotebooks   psql.WhereNullMod[Q, string]
	URLTiles       psql.WhereNullMod[Q, string]
}

func (arcgisAccountWhere[Q]) AliasedAs(alias string) arcgisAccountWhere[Q] {
	return buildArcgisAccountWhere[Q](buildArcgisAccountColumns(alias))
}

func buildArcgisAccountWhere[Q psql.Filterable](cols arcgisAccountColumns) arcgisAccountWhere[Q] {
	return arcgisAccountWhere[Q]{
		ID:             psql.Where[Q, string](cols.ID),
		Name:           psql.Where[Q, string](cols.Name),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		URLFeatures:    psql.WhereNull[Q, string](cols.URLFeatures),
		URLInsights:    psql.WhereNull[Q, string](cols.URLInsights),
		URLGeometry:    psql.WhereNull[Q, string](cols.URLGeometry),
		URLNotebooks:   psql.WhereNull[Q, string](cols.URLNotebooks),
		URLTiles:       psql.WhereNull[Q, string](cols.URLTiles),
	}
}

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

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

		o.R.Organization = rel

		if rel != nil {
			rel.R.Accounts = ArcgisAccountSlice{o}
		}
		return nil
	case "ArcgisAccountOauthTokens":
		rels, ok := retrieved.(ArcgisOauthTokenSlice)
		if !ok {
			return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name)
		}

		o.R.ArcgisAccountOauthTokens = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.ArcgisAccountAccount = o
			}
		}
		return nil
	case "ServiceFeatures":
		rels, ok := retrieved.(ArcgisServiceFeatureSlice)
		if !ok {
			return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name)
		}

		o.R.ServiceFeatures = rels

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

		o.R.ServiceMaps = rels

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

		o.R.ArcgisAccountOrganizations = rels

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

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

func buildArcgisAccountPreloader() arcgisAccountPreloader {
	return arcgisAccountPreloader{
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisAccounts,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

type arcgisAccountThenLoader[Q orm.Loadable] struct {
	Organization               func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ArcgisAccountOauthTokens   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ServiceFeatures            func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ServiceMaps                func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ArcgisAccountOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisAccountThenLoader[Q orm.Loadable]() arcgisAccountThenLoader[Q] {
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ArcgisAccountOauthTokensLoadInterface interface {
		LoadArcgisAccountOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ServiceFeaturesLoadInterface interface {
		LoadServiceFeatures(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ServiceMapsLoadInterface interface {
		LoadServiceMaps(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ArcgisAccountOrganizationsLoadInterface interface {
		LoadArcgisAccountOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisAccountThenLoader[Q]{
		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...)
			},
		),
		ArcgisAccountOauthTokens: thenLoadBuilder[Q](
			"ArcgisAccountOauthTokens",
			func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOauthTokensLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadArcgisAccountOauthTokens(ctx, exec, mods...)
			},
		),
		ServiceFeatures: thenLoadBuilder[Q](
			"ServiceFeatures",
			func(ctx context.Context, exec bob.Executor, retrieved ServiceFeaturesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadServiceFeatures(ctx, exec, mods...)
			},
		),
		ServiceMaps: thenLoadBuilder[Q](
			"ServiceMaps",
			func(ctx context.Context, exec bob.Executor, retrieved ServiceMapsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadServiceMaps(ctx, exec, mods...)
			},
		),
		ArcgisAccountOrganizations: thenLoadBuilder[Q](
			"ArcgisAccountOrganizations",
			func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadArcgisAccountOrganizations(ctx, exec, mods...)
			},
		),
	}
}

// LoadOrganization loads the arcgisAccount's Organization into the .R struct
func (o *ArcgisAccount) 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.Accounts = ArcgisAccountSlice{o}

	o.R.Organization = related
	return nil
}

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.ArcgisAccountOauthTokens = related
	return nil
}

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

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

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

		o.R.ArcgisAccountOauthTokens = nil
	}

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

		for _, rel := range arcgisOauthTokens {

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

			rel.R.ArcgisAccountAccount = o

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

	return nil
}

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

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

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

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

	o.R.ServiceFeatures = related
	return nil
}

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

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

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

		o.R.ServiceFeatures = nil
	}

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

		for _, rel := range arcgisServiceFeatures {

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

			rel.R.Account = o

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

	return nil
}

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

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

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

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

	o.R.ServiceMaps = related
	return nil
}

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

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

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

		o.R.ServiceMaps = nil
	}

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

		for _, rel := range arcgisServiceMaps {

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

			rel.R.Account = o

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

	return nil
}

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

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

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

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

	o.R.ArcgisAccountOrganizations = related
	return nil
}

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

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

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

		o.R.ArcgisAccountOrganizations = nil
	}

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

		for _, rel := range organizations {

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

			rel.R.ArcgisAccountAccount = o

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

	return nil
}
