// 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/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
)

// ArcgisUser is an object representing the database table.
type ArcgisUser struct {
	Access            string    `db:"access" `
	Created           time.Time `db:"created" `
	Email             string    `db:"email" `
	FullName          string    `db:"full_name" `
	ID                string    `db:"id,pk" `
	Level             string    `db:"level" `
	OrgID             string    `db:"org_id" `
	PublicUserID      int32     `db:"public_user_id" `
	Region            string    `db:"region" `
	Role              string    `db:"role" `
	RoleID            string    `db:"role_id" `
	Username          string    `db:"username" `
	UserLicenseTypeID string    `db:"user_license_type_id" `
	UserType          string    `db:"user_type" `

	R arcgisuserR `db:"-" `
}

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

// ArcgisUsers contains methods to work with the user_ table
var ArcgisUsers = psql.NewTablex[*ArcgisUser, ArcgisUserSlice, *ArcgisUserSetter]("arcgis", "user_", buildArcgisUserColumns("arcgis.user_"))

// ArcgisUsersQuery is a query on the user_ table
type ArcgisUsersQuery = *psql.ViewQuery[*ArcgisUser, ArcgisUserSlice]

// arcgisuserR is where relationships are stored.
type arcgisuserR struct {
	PublicUserUser     *User                    // arcgis.user_.user__public_user_id_fkey
	UserUserPrivileges ArcgisUserPrivilegeSlice // arcgis.user_privilege.user_privilege_user_id_fkey
}

func buildArcgisUserColumns(alias string) arcgisuserColumns {
	return arcgisuserColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"access", "created", "email", "full_name", "id", "level", "org_id", "public_user_id", "region", "role", "role_id", "username", "user_license_type_id", "user_type",
		).WithParent("arcgis.user_"),
		tableAlias:        alias,
		Access:            psql.Quote(alias, "access"),
		Created:           psql.Quote(alias, "created"),
		Email:             psql.Quote(alias, "email"),
		FullName:          psql.Quote(alias, "full_name"),
		ID:                psql.Quote(alias, "id"),
		Level:             psql.Quote(alias, "level"),
		OrgID:             psql.Quote(alias, "org_id"),
		PublicUserID:      psql.Quote(alias, "public_user_id"),
		Region:            psql.Quote(alias, "region"),
		Role:              psql.Quote(alias, "role"),
		RoleID:            psql.Quote(alias, "role_id"),
		Username:          psql.Quote(alias, "username"),
		UserLicenseTypeID: psql.Quote(alias, "user_license_type_id"),
		UserType:          psql.Quote(alias, "user_type"),
	}
}

type arcgisuserColumns struct {
	expr.ColumnsExpr
	tableAlias        string
	Access            psql.Expression
	Created           psql.Expression
	Email             psql.Expression
	FullName          psql.Expression
	ID                psql.Expression
	Level             psql.Expression
	OrgID             psql.Expression
	PublicUserID      psql.Expression
	Region            psql.Expression
	Role              psql.Expression
	RoleID            psql.Expression
	Username          psql.Expression
	UserLicenseTypeID psql.Expression
	UserType          psql.Expression
}

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

func (arcgisuserColumns) AliasedAs(alias string) arcgisuserColumns {
	return buildArcgisUserColumns(alias)
}

// ArcgisUserSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisUserSetter struct {
	Access            omit.Val[string]    `db:"access" `
	Created           omit.Val[time.Time] `db:"created" `
	Email             omit.Val[string]    `db:"email" `
	FullName          omit.Val[string]    `db:"full_name" `
	ID                omit.Val[string]    `db:"id,pk" `
	Level             omit.Val[string]    `db:"level" `
	OrgID             omit.Val[string]    `db:"org_id" `
	PublicUserID      omit.Val[int32]     `db:"public_user_id" `
	Region            omit.Val[string]    `db:"region" `
	Role              omit.Val[string]    `db:"role" `
	RoleID            omit.Val[string]    `db:"role_id" `
	Username          omit.Val[string]    `db:"username" `
	UserLicenseTypeID omit.Val[string]    `db:"user_license_type_id" `
	UserType          omit.Val[string]    `db:"user_type" `
}

func (s ArcgisUserSetter) SetColumns() []string {
	vals := make([]string, 0, 14)
	if s.Access.IsValue() {
		vals = append(vals, "access")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Email.IsValue() {
		vals = append(vals, "email")
	}
	if s.FullName.IsValue() {
		vals = append(vals, "full_name")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Level.IsValue() {
		vals = append(vals, "level")
	}
	if s.OrgID.IsValue() {
		vals = append(vals, "org_id")
	}
	if s.PublicUserID.IsValue() {
		vals = append(vals, "public_user_id")
	}
	if s.Region.IsValue() {
		vals = append(vals, "region")
	}
	if s.Role.IsValue() {
		vals = append(vals, "role")
	}
	if s.RoleID.IsValue() {
		vals = append(vals, "role_id")
	}
	if s.Username.IsValue() {
		vals = append(vals, "username")
	}
	if s.UserLicenseTypeID.IsValue() {
		vals = append(vals, "user_license_type_id")
	}
	if s.UserType.IsValue() {
		vals = append(vals, "user_type")
	}
	return vals
}

func (s ArcgisUserSetter) Overwrite(t *ArcgisUser) {
	if s.Access.IsValue() {
		t.Access = s.Access.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Email.IsValue() {
		t.Email = s.Email.MustGet()
	}
	if s.FullName.IsValue() {
		t.FullName = s.FullName.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Level.IsValue() {
		t.Level = s.Level.MustGet()
	}
	if s.OrgID.IsValue() {
		t.OrgID = s.OrgID.MustGet()
	}
	if s.PublicUserID.IsValue() {
		t.PublicUserID = s.PublicUserID.MustGet()
	}
	if s.Region.IsValue() {
		t.Region = s.Region.MustGet()
	}
	if s.Role.IsValue() {
		t.Role = s.Role.MustGet()
	}
	if s.RoleID.IsValue() {
		t.RoleID = s.RoleID.MustGet()
	}
	if s.Username.IsValue() {
		t.Username = s.Username.MustGet()
	}
	if s.UserLicenseTypeID.IsValue() {
		t.UserLicenseTypeID = s.UserLicenseTypeID.MustGet()
	}
	if s.UserType.IsValue() {
		t.UserType = s.UserType.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// UserUserPrivileges starts a query for related objects on arcgis.user_privilege
func (o *ArcgisUser) UserUserPrivileges(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUserPrivilegesQuery {
	return ArcgisUserPrivileges.Query(append(mods,
		sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os ArcgisUserSlice) UserUserPrivileges(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUserPrivilegesQuery {
	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 ArcgisUserPrivileges.Query(append(mods,
		sm.Where(psql.Group(ArcgisUserPrivileges.Columns.UserID).OP("IN", PKArgExpr)),
	)...)
}

func attachArcgisUserPublicUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisuser0 *ArcgisUser, user1 *User) (*ArcgisUser, error) {
	setter := &ArcgisUserSetter{
		PublicUserID: omit.From(user1.ID),
	}

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

	return arcgisuser0, nil
}

func (arcgisuser0 *ArcgisUser) InsertPublicUserUser(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 = attachArcgisUserPublicUserUser0(ctx, exec, 1, arcgisuser0, user1)
	if err != nil {
		return err
	}

	arcgisuser0.R.PublicUserUser = user1

	user1.R.PublicUserUser = append(user1.R.PublicUserUser, arcgisuser0)

	return nil
}

func (arcgisuser0 *ArcgisUser) AttachPublicUserUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

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

	arcgisuser0.R.PublicUserUser = user1

	user1.R.PublicUserUser = append(user1.R.PublicUserUser, arcgisuser0)

	return nil
}

func insertArcgisUserUserUserPrivileges0(ctx context.Context, exec bob.Executor, arcgisUserPrivileges1 []*ArcgisUserPrivilegeSetter, arcgisuser0 *ArcgisUser) (ArcgisUserPrivilegeSlice, error) {
	for i := range arcgisUserPrivileges1 {
		arcgisUserPrivileges1[i].UserID = omit.From(arcgisuser0.ID)
	}

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

	return ret, nil
}

func attachArcgisUserUserUserPrivileges0(ctx context.Context, exec bob.Executor, count int, arcgisUserPrivileges1 ArcgisUserPrivilegeSlice, arcgisuser0 *ArcgisUser) (ArcgisUserPrivilegeSlice, error) {
	setter := &ArcgisUserPrivilegeSetter{
		UserID: omit.From(arcgisuser0.ID),
	}

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

	return arcgisUserPrivileges1, nil
}

func (arcgisuser0 *ArcgisUser) InsertUserUserPrivileges(ctx context.Context, exec bob.Executor, related ...*ArcgisUserPrivilegeSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	arcgisUserPrivileges1, err := insertArcgisUserUserUserPrivileges0(ctx, exec, related, arcgisuser0)
	if err != nil {
		return err
	}

	arcgisuser0.R.UserUserPrivileges = append(arcgisuser0.R.UserUserPrivileges, arcgisUserPrivileges1...)

	for _, rel := range arcgisUserPrivileges1 {
		rel.R.UserUser = arcgisuser0
	}
	return nil
}

func (arcgisuser0 *ArcgisUser) AttachUserUserPrivileges(ctx context.Context, exec bob.Executor, related ...*ArcgisUserPrivilege) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	arcgisUserPrivileges1 := ArcgisUserPrivilegeSlice(related)

	_, err = attachArcgisUserUserUserPrivileges0(ctx, exec, len(related), arcgisUserPrivileges1, arcgisuser0)
	if err != nil {
		return err
	}

	arcgisuser0.R.UserUserPrivileges = append(arcgisuser0.R.UserUserPrivileges, arcgisUserPrivileges1...)

	for _, rel := range related {
		rel.R.UserUser = arcgisuser0
	}

	return nil
}

type arcgisuserWhere[Q psql.Filterable] struct {
	Access            psql.WhereMod[Q, string]
	Created           psql.WhereMod[Q, time.Time]
	Email             psql.WhereMod[Q, string]
	FullName          psql.WhereMod[Q, string]
	ID                psql.WhereMod[Q, string]
	Level             psql.WhereMod[Q, string]
	OrgID             psql.WhereMod[Q, string]
	PublicUserID      psql.WhereMod[Q, int32]
	Region            psql.WhereMod[Q, string]
	Role              psql.WhereMod[Q, string]
	RoleID            psql.WhereMod[Q, string]
	Username          psql.WhereMod[Q, string]
	UserLicenseTypeID psql.WhereMod[Q, string]
	UserType          psql.WhereMod[Q, string]
}

func (arcgisuserWhere[Q]) AliasedAs(alias string) arcgisuserWhere[Q] {
	return buildArcgisUserWhere[Q](buildArcgisUserColumns(alias))
}

func buildArcgisUserWhere[Q psql.Filterable](cols arcgisuserColumns) arcgisuserWhere[Q] {
	return arcgisuserWhere[Q]{
		Access:            psql.Where[Q, string](cols.Access),
		Created:           psql.Where[Q, time.Time](cols.Created),
		Email:             psql.Where[Q, string](cols.Email),
		FullName:          psql.Where[Q, string](cols.FullName),
		ID:                psql.Where[Q, string](cols.ID),
		Level:             psql.Where[Q, string](cols.Level),
		OrgID:             psql.Where[Q, string](cols.OrgID),
		PublicUserID:      psql.Where[Q, int32](cols.PublicUserID),
		Region:            psql.Where[Q, string](cols.Region),
		Role:              psql.Where[Q, string](cols.Role),
		RoleID:            psql.Where[Q, string](cols.RoleID),
		Username:          psql.Where[Q, string](cols.Username),
		UserLicenseTypeID: psql.Where[Q, string](cols.UserLicenseTypeID),
		UserType:          psql.Where[Q, string](cols.UserType),
	}
}

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

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

		o.R.PublicUserUser = rel

		if rel != nil {
			rel.R.PublicUserUser = ArcgisUserSlice{o}
		}
		return nil
	case "UserUserPrivileges":
		rels, ok := retrieved.(ArcgisUserPrivilegeSlice)
		if !ok {
			return fmt.Errorf("arcgisuser cannot load %T as %q", retrieved, name)
		}

		o.R.UserUserPrivileges = rels

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

type arcgisuserPreloader struct {
	PublicUserUser func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisUserPreloader() arcgisuserPreloader {
	return arcgisuserPreloader{
		PublicUserUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "PublicUserUser",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisUsers,
						To:          Users,
						FromColumns: []string{"public_user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
	}
}

type arcgisuserThenLoader[Q orm.Loadable] struct {
	PublicUserUser     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserUserPrivileges func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildArcgisUserThenLoader[Q orm.Loadable]() arcgisuserThenLoader[Q] {
	type PublicUserUserLoadInterface interface {
		LoadPublicUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserUserPrivilegesLoadInterface interface {
		LoadUserUserPrivileges(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisuserThenLoader[Q]{
		PublicUserUser: thenLoadBuilder[Q](
			"PublicUserUser",
			func(ctx context.Context, exec bob.Executor, retrieved PublicUserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPublicUserUser(ctx, exec, mods...)
			},
		),
		UserUserPrivileges: thenLoadBuilder[Q](
			"UserUserPrivileges",
			func(ctx context.Context, exec bob.Executor, retrieved UserUserPrivilegesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserUserPrivileges(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.PublicUserUser = ArcgisUserSlice{o}

	o.R.PublicUserUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.PublicUserUser = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.UserUserPrivileges = related
	return nil
}

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

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

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

		o.R.UserUserPrivileges = nil
	}

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

		for _, rel := range arcgisUserPrivileges {

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

			rel.R.UserUser = o

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

	return nil
}
