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

package models

import (
	"context"
	"fmt"
	"io"
	"time"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/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"
)

// ArcgisOauthToken is an object representing the database table.
type ArcgisOauthToken struct {
	AccessToken         string              `db:"access_token" `
	AccessTokenExpires  time.Time           `db:"access_token_expires" `
	ArcgisAccountID     null.Val[string]    `db:"arcgis_account_id" `
	ArcgisID            null.Val[string]    `db:"arcgis_id" `
	ArcgisLicenseTypeID null.Val[string]    `db:"arcgis_license_type_id" `
	Created             time.Time           `db:"created" `
	ID                  int32               `db:"id,pk" `
	InvalidatedAt       null.Val[time.Time] `db:"invalidated_at" `
	RefreshToken        string              `db:"refresh_token" `
	RefreshTokenExpires time.Time           `db:"refresh_token_expires" `
	UserID              int32               `db:"user_id" `
	Username            string              `db:"username" `

	R arcgisOauthTokenR `db:"-" `
}

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

// ArcgisOauthTokens contains methods to work with the oauth_token table
var ArcgisOauthTokens = psql.NewTablex[*ArcgisOauthToken, ArcgisOauthTokenSlice, *ArcgisOauthTokenSetter]("arcgis", "oauth_token", buildArcgisOauthTokenColumns("arcgis.oauth_token"))

// ArcgisOauthTokensQuery is a query on the oauth_token table
type ArcgisOauthTokensQuery = *psql.ViewQuery[*ArcgisOauthToken, ArcgisOauthTokenSlice]

// arcgisOauthTokenR is where relationships are stored.
type arcgisOauthTokenR struct {
	ArcgisAccountAccount *ArcgisAccount // arcgis.oauth_token.oauth_token_arcgis_account_id_fkey
	UserUser             *User          // arcgis.oauth_token.oauth_token_user_id_fkey
}

func buildArcgisOauthTokenColumns(alias string) arcgisOauthTokenColumns {
	return arcgisOauthTokenColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"access_token", "access_token_expires", "arcgis_account_id", "arcgis_id", "arcgis_license_type_id", "created", "id", "invalidated_at", "refresh_token", "refresh_token_expires", "user_id", "username",
		).WithParent("arcgis.oauth_token"),
		tableAlias:          alias,
		AccessToken:         psql.Quote(alias, "access_token"),
		AccessTokenExpires:  psql.Quote(alias, "access_token_expires"),
		ArcgisAccountID:     psql.Quote(alias, "arcgis_account_id"),
		ArcgisID:            psql.Quote(alias, "arcgis_id"),
		ArcgisLicenseTypeID: psql.Quote(alias, "arcgis_license_type_id"),
		Created:             psql.Quote(alias, "created"),
		ID:                  psql.Quote(alias, "id"),
		InvalidatedAt:       psql.Quote(alias, "invalidated_at"),
		RefreshToken:        psql.Quote(alias, "refresh_token"),
		RefreshTokenExpires: psql.Quote(alias, "refresh_token_expires"),
		UserID:              psql.Quote(alias, "user_id"),
		Username:            psql.Quote(alias, "username"),
	}
}

type arcgisOauthTokenColumns struct {
	expr.ColumnsExpr
	tableAlias          string
	AccessToken         psql.Expression
	AccessTokenExpires  psql.Expression
	ArcgisAccountID     psql.Expression
	ArcgisID            psql.Expression
	ArcgisLicenseTypeID psql.Expression
	Created             psql.Expression
	ID                  psql.Expression
	InvalidatedAt       psql.Expression
	RefreshToken        psql.Expression
	RefreshTokenExpires psql.Expression
	UserID              psql.Expression
	Username            psql.Expression
}

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

func (arcgisOauthTokenColumns) AliasedAs(alias string) arcgisOauthTokenColumns {
	return buildArcgisOauthTokenColumns(alias)
}

// ArcgisOauthTokenSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisOauthTokenSetter struct {
	AccessToken         omit.Val[string]        `db:"access_token" `
	AccessTokenExpires  omit.Val[time.Time]     `db:"access_token_expires" `
	ArcgisAccountID     omitnull.Val[string]    `db:"arcgis_account_id" `
	ArcgisID            omitnull.Val[string]    `db:"arcgis_id" `
	ArcgisLicenseTypeID omitnull.Val[string]    `db:"arcgis_license_type_id" `
	Created             omit.Val[time.Time]     `db:"created" `
	ID                  omit.Val[int32]         `db:"id,pk" `
	InvalidatedAt       omitnull.Val[time.Time] `db:"invalidated_at" `
	RefreshToken        omit.Val[string]        `db:"refresh_token" `
	RefreshTokenExpires omit.Val[time.Time]     `db:"refresh_token_expires" `
	UserID              omit.Val[int32]         `db:"user_id" `
	Username            omit.Val[string]        `db:"username" `
}

func (s ArcgisOauthTokenSetter) SetColumns() []string {
	vals := make([]string, 0, 12)
	if s.AccessToken.IsValue() {
		vals = append(vals, "access_token")
	}
	if s.AccessTokenExpires.IsValue() {
		vals = append(vals, "access_token_expires")
	}
	if !s.ArcgisAccountID.IsUnset() {
		vals = append(vals, "arcgis_account_id")
	}
	if !s.ArcgisID.IsUnset() {
		vals = append(vals, "arcgis_id")
	}
	if !s.ArcgisLicenseTypeID.IsUnset() {
		vals = append(vals, "arcgis_license_type_id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if !s.InvalidatedAt.IsUnset() {
		vals = append(vals, "invalidated_at")
	}
	if s.RefreshToken.IsValue() {
		vals = append(vals, "refresh_token")
	}
	if s.RefreshTokenExpires.IsValue() {
		vals = append(vals, "refresh_token_expires")
	}
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	if s.Username.IsValue() {
		vals = append(vals, "username")
	}
	return vals
}

func (s ArcgisOauthTokenSetter) Overwrite(t *ArcgisOauthToken) {
	if s.AccessToken.IsValue() {
		t.AccessToken = s.AccessToken.MustGet()
	}
	if s.AccessTokenExpires.IsValue() {
		t.AccessTokenExpires = s.AccessTokenExpires.MustGet()
	}
	if !s.ArcgisAccountID.IsUnset() {
		t.ArcgisAccountID = s.ArcgisAccountID.MustGetNull()
	}
	if !s.ArcgisID.IsUnset() {
		t.ArcgisID = s.ArcgisID.MustGetNull()
	}
	if !s.ArcgisLicenseTypeID.IsUnset() {
		t.ArcgisLicenseTypeID = s.ArcgisLicenseTypeID.MustGetNull()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if !s.InvalidatedAt.IsUnset() {
		t.InvalidatedAt = s.InvalidatedAt.MustGetNull()
	}
	if s.RefreshToken.IsValue() {
		t.RefreshToken = s.RefreshToken.MustGet()
	}
	if s.RefreshTokenExpires.IsValue() {
		t.RefreshTokenExpires = s.RefreshTokenExpires.MustGet()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
	if s.Username.IsValue() {
		t.Username = s.Username.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

// Reload refreshes the ArcgisOauthToken using the executor
func (o *ArcgisOauthToken) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := ArcgisOauthTokens.Query(
		sm.Where(ArcgisOauthTokens.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 ArcgisOauthTokenSlice is retrieved from the database
func (o ArcgisOauthTokenSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

	return psql.Quote("arcgis.oauth_token", "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 ArcgisOauthTokenSlice) copyMatchingRows(from ...*ArcgisOauthToken) {
	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 ArcgisOauthTokenSlice) 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 ArcgisOauthTokens.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 *ArcgisOauthToken:
				o.copyMatchingRows(retrieved)
			case []*ArcgisOauthToken:
				o.copyMatchingRows(retrieved...)
			case ArcgisOauthTokenSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ArcgisOauthToken or a slice of ArcgisOauthToken
				// then run the AfterUpdateHooks on the slice
				_, err = ArcgisOauthTokens.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// UserUser starts a query for related objects on user_
func (o *ArcgisOauthToken) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.UserID))),
	)...)
}

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

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

func attachArcgisOauthTokenArcgisAccountAccount0(ctx context.Context, exec bob.Executor, count int, arcgisOauthToken0 *ArcgisOauthToken, arcgisAccount1 *ArcgisAccount) (*ArcgisOauthToken, error) {
	setter := &ArcgisOauthTokenSetter{
		ArcgisAccountID: omitnull.From(arcgisAccount1.ID),
	}

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

	return arcgisOauthToken0, nil
}

func (arcgisOauthToken0 *ArcgisOauthToken) InsertArcgisAccountAccount(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 = attachArcgisOauthTokenArcgisAccountAccount0(ctx, exec, 1, arcgisOauthToken0, arcgisAccount1)
	if err != nil {
		return err
	}

	arcgisOauthToken0.R.ArcgisAccountAccount = arcgisAccount1

	arcgisAccount1.R.ArcgisAccountOauthTokens = append(arcgisAccount1.R.ArcgisAccountOauthTokens, arcgisOauthToken0)

	return nil
}

func (arcgisOauthToken0 *ArcgisOauthToken) AttachArcgisAccountAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error {
	var err error

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

	arcgisOauthToken0.R.ArcgisAccountAccount = arcgisAccount1

	arcgisAccount1.R.ArcgisAccountOauthTokens = append(arcgisAccount1.R.ArcgisAccountOauthTokens, arcgisOauthToken0)

	return nil
}

func attachArcgisOauthTokenUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisOauthToken0 *ArcgisOauthToken, user1 *User) (*ArcgisOauthToken, error) {
	setter := &ArcgisOauthTokenSetter{
		UserID: omit.From(user1.ID),
	}

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

	return arcgisOauthToken0, nil
}

func (arcgisOauthToken0 *ArcgisOauthToken) InsertUserUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachArcgisOauthTokenUserUser0(ctx, exec, 1, arcgisOauthToken0, user1)
	if err != nil {
		return err
	}

	arcgisOauthToken0.R.UserUser = user1

	user1.R.UserOauthTokens = append(user1.R.UserOauthTokens, arcgisOauthToken0)

	return nil
}

func (arcgisOauthToken0 *ArcgisOauthToken) AttachUserUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachArcgisOauthTokenUserUser0(ctx, exec, 1, arcgisOauthToken0, user1)
	if err != nil {
		return err
	}

	arcgisOauthToken0.R.UserUser = user1

	user1.R.UserOauthTokens = append(user1.R.UserOauthTokens, arcgisOauthToken0)

	return nil
}

type arcgisOauthTokenWhere[Q psql.Filterable] struct {
	AccessToken         psql.WhereMod[Q, string]
	AccessTokenExpires  psql.WhereMod[Q, time.Time]
	ArcgisAccountID     psql.WhereNullMod[Q, string]
	ArcgisID            psql.WhereNullMod[Q, string]
	ArcgisLicenseTypeID psql.WhereNullMod[Q, string]
	Created             psql.WhereMod[Q, time.Time]
	ID                  psql.WhereMod[Q, int32]
	InvalidatedAt       psql.WhereNullMod[Q, time.Time]
	RefreshToken        psql.WhereMod[Q, string]
	RefreshTokenExpires psql.WhereMod[Q, time.Time]
	UserID              psql.WhereMod[Q, int32]
	Username            psql.WhereMod[Q, string]
}

func (arcgisOauthTokenWhere[Q]) AliasedAs(alias string) arcgisOauthTokenWhere[Q] {
	return buildArcgisOauthTokenWhere[Q](buildArcgisOauthTokenColumns(alias))
}

func buildArcgisOauthTokenWhere[Q psql.Filterable](cols arcgisOauthTokenColumns) arcgisOauthTokenWhere[Q] {
	return arcgisOauthTokenWhere[Q]{
		AccessToken:         psql.Where[Q, string](cols.AccessToken),
		AccessTokenExpires:  psql.Where[Q, time.Time](cols.AccessTokenExpires),
		ArcgisAccountID:     psql.WhereNull[Q, string](cols.ArcgisAccountID),
		ArcgisID:            psql.WhereNull[Q, string](cols.ArcgisID),
		ArcgisLicenseTypeID: psql.WhereNull[Q, string](cols.ArcgisLicenseTypeID),
		Created:             psql.Where[Q, time.Time](cols.Created),
		ID:                  psql.Where[Q, int32](cols.ID),
		InvalidatedAt:       psql.WhereNull[Q, time.Time](cols.InvalidatedAt),
		RefreshToken:        psql.Where[Q, string](cols.RefreshToken),
		RefreshTokenExpires: psql.Where[Q, time.Time](cols.RefreshTokenExpires),
		UserID:              psql.Where[Q, int32](cols.UserID),
		Username:            psql.Where[Q, string](cols.Username),
	}
}

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

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

		o.R.ArcgisAccountAccount = rel

		if rel != nil {
			rel.R.ArcgisAccountOauthTokens = ArcgisOauthTokenSlice{o}
		}
		return nil
	case "UserUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("arcgisOauthToken cannot load %T as %q", retrieved, name)
		}

		o.R.UserUser = rel

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

type arcgisOauthTokenPreloader struct {
	ArcgisAccountAccount func(...psql.PreloadOption) psql.Preloader
	UserUser             func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisOauthTokenPreloader() arcgisOauthTokenPreloader {
	return arcgisOauthTokenPreloader{
		ArcgisAccountAccount: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{
				Name: "ArcgisAccountAccount",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisOauthTokens,
						To:          ArcgisAccounts,
						FromColumns: []string{"arcgis_account_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, ArcgisAccounts.Columns.Names(), opts...)
		},
		UserUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "UserUser",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisOauthTokens,
						To:          Users,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
	}
}

type arcgisOauthTokenThenLoader[Q orm.Loadable] struct {
	ArcgisAccountAccount func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserUser             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisOauthTokenThenLoader[Q orm.Loadable]() arcgisOauthTokenThenLoader[Q] {
	type ArcgisAccountAccountLoadInterface interface {
		LoadArcgisAccountAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserUserLoadInterface interface {
		LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisOauthTokenThenLoader[Q]{
		ArcgisAccountAccount: thenLoadBuilder[Q](
			"ArcgisAccountAccount",
			func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountAccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadArcgisAccountAccount(ctx, exec, mods...)
			},
		),
		UserUser: thenLoadBuilder[Q](
			"UserUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserUser(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.ArcgisAccountOauthTokens = ArcgisOauthTokenSlice{o}

	o.R.ArcgisAccountAccount = related
	return nil
}

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

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

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

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

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

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

			o.R.ArcgisAccountAccount = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.UserOauthTokens = ArcgisOauthTokenSlice{o}

	o.R.UserUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.UserUser = rel
			break
		}
	}

	return nil
}

type arcgisOauthTokenJoins[Q dialect.Joinable] struct {
	typ                  string
	ArcgisAccountAccount modAs[Q, arcgisAccountColumns]
	UserUser             modAs[Q, userColumns]
}

func (j arcgisOauthTokenJoins[Q]) aliasedAs(alias string) arcgisOauthTokenJoins[Q] {
	return buildArcgisOauthTokenJoins[Q](buildArcgisOauthTokenColumns(alias), j.typ)
}

func buildArcgisOauthTokenJoins[Q dialect.Joinable](cols arcgisOauthTokenColumns, typ string) arcgisOauthTokenJoins[Q] {
	return arcgisOauthTokenJoins[Q]{
		typ: typ,
		ArcgisAccountAccount: 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.ArcgisAccountID),
					))
				}

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

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

				return mods
			},
		},
	}
}
