// 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"
	"encoding/json"
	"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"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	"github.com/google/uuid"
)

// FieldseekerLocationtracking is an object representing the database table.
type FieldseekerLocationtracking struct {
	Objectid int64 `db:"objectid" `
	// Original attribute from ArcGIS API is Accuracy
	Accuracy null.Val[float64] `db:"accuracy" `
	// Original attribute from ArcGIS API is created_user
	CreatedUser null.Val[string] `db:"created_user" `
	// Original attribute from ArcGIS API is created_date
	CreatedDate null.Val[time.Time] `db:"created_date" `
	// Original attribute from ArcGIS API is last_edited_user
	LastEditedUser null.Val[string] `db:"last_edited_user" `
	// Original attribute from ArcGIS API is last_edited_date
	LastEditedDate null.Val[time.Time] `db:"last_edited_date" `
	// Original attribute from ArcGIS API is GlobalID
	Globalid uuid.UUID `db:"globalid,pk" `
	// Original attribute from ArcGIS API is FIELDTECH
	Fieldtech null.Val[string] `db:"fieldtech" `
	// Original attribute from ArcGIS API is CreationDate
	Creationdate null.Val[time.Time] `db:"creationdate" `
	// Original attribute from ArcGIS API is Creator
	Creator null.Val[string] `db:"creator" `
	// Original attribute from ArcGIS API is EditDate
	Editdate null.Val[time.Time] `db:"editdate" `
	// Original attribute from ArcGIS API is Editor
	Editor         null.Val[string]            `db:"editor" `
	Geometry       types.JSON[json.RawMessage] `db:"geometry" `
	Geospatial     null.Val[string]            `db:"geospatial" `
	Version        int32                       `db:"version,pk" `
	OrganizationID int32                       `db:"organization_id" `

	R fieldseekerLocationtrackingR `db:"-" `
}

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

// FieldseekerLocationtrackings contains methods to work with the locationtracking table
var FieldseekerLocationtrackings = psql.NewTablex[*FieldseekerLocationtracking, FieldseekerLocationtrackingSlice, *FieldseekerLocationtrackingSetter]("fieldseeker", "locationtracking", buildFieldseekerLocationtrackingColumns("fieldseeker.locationtracking"))

// FieldseekerLocationtrackingsQuery is a query on the locationtracking table
type FieldseekerLocationtrackingsQuery = *psql.ViewQuery[*FieldseekerLocationtracking, FieldseekerLocationtrackingSlice]

// fieldseekerLocationtrackingR is where relationships are stored.
type fieldseekerLocationtrackingR struct {
	Organization *Organization // fieldseeker.locationtracking.locationtracking_organization_id_fkey
}

func buildFieldseekerLocationtrackingColumns(alias string) fieldseekerLocationtrackingColumns {
	return fieldseekerLocationtrackingColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"objectid", "accuracy", "created_user", "created_date", "last_edited_user", "last_edited_date", "globalid", "fieldtech", "creationdate", "creator", "editdate", "editor", "geometry", "geospatial", "version", "organization_id",
		).WithParent("fieldseeker.locationtracking"),
		tableAlias:     alias,
		Objectid:       psql.Quote(alias, "objectid"),
		Accuracy:       psql.Quote(alias, "accuracy"),
		CreatedUser:    psql.Quote(alias, "created_user"),
		CreatedDate:    psql.Quote(alias, "created_date"),
		LastEditedUser: psql.Quote(alias, "last_edited_user"),
		LastEditedDate: psql.Quote(alias, "last_edited_date"),
		Globalid:       psql.Quote(alias, "globalid"),
		Fieldtech:      psql.Quote(alias, "fieldtech"),
		Creationdate:   psql.Quote(alias, "creationdate"),
		Creator:        psql.Quote(alias, "creator"),
		Editdate:       psql.Quote(alias, "editdate"),
		Editor:         psql.Quote(alias, "editor"),
		Geometry:       psql.Quote(alias, "geometry"),
		Geospatial:     psql.Quote(alias, "geospatial"),
		Version:        psql.Quote(alias, "version"),
		OrganizationID: psql.Quote(alias, "organization_id"),
	}
}

type fieldseekerLocationtrackingColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Objectid       psql.Expression
	Accuracy       psql.Expression
	CreatedUser    psql.Expression
	CreatedDate    psql.Expression
	LastEditedUser psql.Expression
	LastEditedDate psql.Expression
	Globalid       psql.Expression
	Fieldtech      psql.Expression
	Creationdate   psql.Expression
	Creator        psql.Expression
	Editdate       psql.Expression
	Editor         psql.Expression
	Geometry       psql.Expression
	Geospatial     psql.Expression
	Version        psql.Expression
	OrganizationID psql.Expression
}

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

func (fieldseekerLocationtrackingColumns) AliasedAs(alias string) fieldseekerLocationtrackingColumns {
	return buildFieldseekerLocationtrackingColumns(alias)
}

// FieldseekerLocationtrackingSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type FieldseekerLocationtrackingSetter struct {
	Objectid       omit.Val[int64]                       `db:"objectid" `
	Accuracy       omitnull.Val[float64]                 `db:"accuracy" `
	CreatedUser    omitnull.Val[string]                  `db:"created_user" `
	CreatedDate    omitnull.Val[time.Time]               `db:"created_date" `
	LastEditedUser omitnull.Val[string]                  `db:"last_edited_user" `
	LastEditedDate omitnull.Val[time.Time]               `db:"last_edited_date" `
	Globalid       omit.Val[uuid.UUID]                   `db:"globalid,pk" `
	Fieldtech      omitnull.Val[string]                  `db:"fieldtech" `
	Creationdate   omitnull.Val[time.Time]               `db:"creationdate" `
	Creator        omitnull.Val[string]                  `db:"creator" `
	Editdate       omitnull.Val[time.Time]               `db:"editdate" `
	Editor         omitnull.Val[string]                  `db:"editor" `
	Geometry       omit.Val[types.JSON[json.RawMessage]] `db:"geometry" `
	Geospatial     omitnull.Val[string]                  `db:"geospatial" `
	Version        omit.Val[int32]                       `db:"version,pk" `
	OrganizationID omit.Val[int32]                       `db:"organization_id" `
}

func (s FieldseekerLocationtrackingSetter) SetColumns() []string {
	vals := make([]string, 0, 16)
	if s.Objectid.IsValue() {
		vals = append(vals, "objectid")
	}
	if !s.Accuracy.IsUnset() {
		vals = append(vals, "accuracy")
	}
	if !s.CreatedUser.IsUnset() {
		vals = append(vals, "created_user")
	}
	if !s.CreatedDate.IsUnset() {
		vals = append(vals, "created_date")
	}
	if !s.LastEditedUser.IsUnset() {
		vals = append(vals, "last_edited_user")
	}
	if !s.LastEditedDate.IsUnset() {
		vals = append(vals, "last_edited_date")
	}
	if s.Globalid.IsValue() {
		vals = append(vals, "globalid")
	}
	if !s.Fieldtech.IsUnset() {
		vals = append(vals, "fieldtech")
	}
	if !s.Creationdate.IsUnset() {
		vals = append(vals, "creationdate")
	}
	if !s.Creator.IsUnset() {
		vals = append(vals, "creator")
	}
	if !s.Editdate.IsUnset() {
		vals = append(vals, "editdate")
	}
	if !s.Editor.IsUnset() {
		vals = append(vals, "editor")
	}
	if s.Geometry.IsValue() {
		vals = append(vals, "geometry")
	}
	if !s.Geospatial.IsUnset() {
		vals = append(vals, "geospatial")
	}
	if s.Version.IsValue() {
		vals = append(vals, "version")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	return vals
}

func (s FieldseekerLocationtrackingSetter) Overwrite(t *FieldseekerLocationtracking) {
	if s.Objectid.IsValue() {
		t.Objectid = s.Objectid.MustGet()
	}
	if !s.Accuracy.IsUnset() {
		t.Accuracy = s.Accuracy.MustGetNull()
	}
	if !s.CreatedUser.IsUnset() {
		t.CreatedUser = s.CreatedUser.MustGetNull()
	}
	if !s.CreatedDate.IsUnset() {
		t.CreatedDate = s.CreatedDate.MustGetNull()
	}
	if !s.LastEditedUser.IsUnset() {
		t.LastEditedUser = s.LastEditedUser.MustGetNull()
	}
	if !s.LastEditedDate.IsUnset() {
		t.LastEditedDate = s.LastEditedDate.MustGetNull()
	}
	if s.Globalid.IsValue() {
		t.Globalid = s.Globalid.MustGet()
	}
	if !s.Fieldtech.IsUnset() {
		t.Fieldtech = s.Fieldtech.MustGetNull()
	}
	if !s.Creationdate.IsUnset() {
		t.Creationdate = s.Creationdate.MustGetNull()
	}
	if !s.Creator.IsUnset() {
		t.Creator = s.Creator.MustGetNull()
	}
	if !s.Editdate.IsUnset() {
		t.Editdate = s.Editdate.MustGetNull()
	}
	if !s.Editor.IsUnset() {
		t.Editor = s.Editor.MustGetNull()
	}
	if s.Geometry.IsValue() {
		t.Geometry = s.Geometry.MustGet()
	}
	if !s.Geospatial.IsUnset() {
		t.Geospatial = s.Geospatial.MustGetNull()
	}
	if s.Version.IsValue() {
		t.Version = s.Version.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindFieldseekerLocationtracking retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindFieldseekerLocationtracking(ctx context.Context, exec bob.Executor, GlobalidPK uuid.UUID, VersionPK int32, cols ...string) (*FieldseekerLocationtracking, error) {
	if len(cols) == 0 {
		return FieldseekerLocationtrackings.Query(
			sm.Where(FieldseekerLocationtrackings.Columns.Globalid.EQ(psql.Arg(GlobalidPK))),
			sm.Where(FieldseekerLocationtrackings.Columns.Version.EQ(psql.Arg(VersionPK))),
		).One(ctx, exec)
	}

	return FieldseekerLocationtrackings.Query(
		sm.Where(FieldseekerLocationtrackings.Columns.Globalid.EQ(psql.Arg(GlobalidPK))),
		sm.Where(FieldseekerLocationtrackings.Columns.Version.EQ(psql.Arg(VersionPK))),
		sm.Columns(FieldseekerLocationtrackings.Columns.Only(cols...)),
	).One(ctx, exec)
}

// FieldseekerLocationtrackingExists checks the presence of a single record by primary key
func FieldseekerLocationtrackingExists(ctx context.Context, exec bob.Executor, GlobalidPK uuid.UUID, VersionPK int32) (bool, error) {
	return FieldseekerLocationtrackings.Query(
		sm.Where(FieldseekerLocationtrackings.Columns.Globalid.EQ(psql.Arg(GlobalidPK))),
		sm.Where(FieldseekerLocationtrackings.Columns.Version.EQ(psql.Arg(VersionPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the FieldseekerLocationtracking
func (o *FieldseekerLocationtracking) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.Globalid,
		o.Version,
	)
}

func (o *FieldseekerLocationtracking) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("fieldseeker.locationtracking", "globalid"), psql.Quote("fieldseeker.locationtracking", "version")).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 FieldseekerLocationtracking
func (o *FieldseekerLocationtracking) Update(ctx context.Context, exec bob.Executor, s *FieldseekerLocationtrackingSetter) error {
	v, err := FieldseekerLocationtrackings.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 FieldseekerLocationtracking record with an executor
func (o *FieldseekerLocationtracking) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := FieldseekerLocationtrackings.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("fieldseeker.locationtracking", "globalid"), psql.Quote("fieldseeker.locationtracking", "version")).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 FieldseekerLocationtrackingSlice) copyMatchingRows(from ...*FieldseekerLocationtracking) {
	for i, old := range o {
		for _, new := range from {
			if new.Globalid != old.Globalid {
				continue
			}
			if new.Version != old.Version {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := FieldseekerLocationtrackings.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 *FieldseekerLocationtracking) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

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

func attachFieldseekerLocationtrackingOrganization0(ctx context.Context, exec bob.Executor, count int, fieldseekerLocationtracking0 *FieldseekerLocationtracking, organization1 *Organization) (*FieldseekerLocationtracking, error) {
	setter := &FieldseekerLocationtrackingSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return fieldseekerLocationtracking0, nil
}

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

	fieldseekerLocationtracking0.R.Organization = organization1

	organization1.R.Locationtrackings = append(organization1.R.Locationtrackings, fieldseekerLocationtracking0)

	return nil
}

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

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

	fieldseekerLocationtracking0.R.Organization = organization1

	organization1.R.Locationtrackings = append(organization1.R.Locationtrackings, fieldseekerLocationtracking0)

	return nil
}

type fieldseekerLocationtrackingWhere[Q psql.Filterable] struct {
	Objectid       psql.WhereMod[Q, int64]
	Accuracy       psql.WhereNullMod[Q, float64]
	CreatedUser    psql.WhereNullMod[Q, string]
	CreatedDate    psql.WhereNullMod[Q, time.Time]
	LastEditedUser psql.WhereNullMod[Q, string]
	LastEditedDate psql.WhereNullMod[Q, time.Time]
	Globalid       psql.WhereMod[Q, uuid.UUID]
	Fieldtech      psql.WhereNullMod[Q, string]
	Creationdate   psql.WhereNullMod[Q, time.Time]
	Creator        psql.WhereNullMod[Q, string]
	Editdate       psql.WhereNullMod[Q, time.Time]
	Editor         psql.WhereNullMod[Q, string]
	Geometry       psql.WhereMod[Q, types.JSON[json.RawMessage]]
	Geospatial     psql.WhereNullMod[Q, string]
	Version        psql.WhereMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
}

func (fieldseekerLocationtrackingWhere[Q]) AliasedAs(alias string) fieldseekerLocationtrackingWhere[Q] {
	return buildFieldseekerLocationtrackingWhere[Q](buildFieldseekerLocationtrackingColumns(alias))
}

func buildFieldseekerLocationtrackingWhere[Q psql.Filterable](cols fieldseekerLocationtrackingColumns) fieldseekerLocationtrackingWhere[Q] {
	return fieldseekerLocationtrackingWhere[Q]{
		Objectid:       psql.Where[Q, int64](cols.Objectid),
		Accuracy:       psql.WhereNull[Q, float64](cols.Accuracy),
		CreatedUser:    psql.WhereNull[Q, string](cols.CreatedUser),
		CreatedDate:    psql.WhereNull[Q, time.Time](cols.CreatedDate),
		LastEditedUser: psql.WhereNull[Q, string](cols.LastEditedUser),
		LastEditedDate: psql.WhereNull[Q, time.Time](cols.LastEditedDate),
		Globalid:       psql.Where[Q, uuid.UUID](cols.Globalid),
		Fieldtech:      psql.WhereNull[Q, string](cols.Fieldtech),
		Creationdate:   psql.WhereNull[Q, time.Time](cols.Creationdate),
		Creator:        psql.WhereNull[Q, string](cols.Creator),
		Editdate:       psql.WhereNull[Q, time.Time](cols.Editdate),
		Editor:         psql.WhereNull[Q, string](cols.Editor),
		Geometry:       psql.Where[Q, types.JSON[json.RawMessage]](cols.Geometry),
		Geospatial:     psql.WhereNull[Q, string](cols.Geospatial),
		Version:        psql.Where[Q, int32](cols.Version),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
	}
}

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

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

		o.R.Organization = rel

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

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

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

type fieldseekerLocationtrackingThenLoader[Q orm.Loadable] struct {
	Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildFieldseekerLocationtrackingThenLoader[Q orm.Loadable]() fieldseekerLocationtrackingThenLoader[Q] {
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return fieldseekerLocationtrackingThenLoader[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...)
			},
		),
	}
}

// LoadOrganization loads the fieldseekerLocationtracking's Organization into the .R struct
func (o *FieldseekerLocationtracking) 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.Locationtrackings = FieldseekerLocationtrackingSlice{o}

	o.R.Organization = related
	return nil
}

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}
