// 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"
	enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// FileuploadFlyoverAerialService is an object representing the database table.
type FileuploadFlyoverAerialService struct {
	Committed      bool                              `db:"committed" `
	Condition      enums.FileuploadPoolconditiontype `db:"condition" `
	Created        time.Time                         `db:"created" `
	CreatorID      int32                             `db:"creator_id" `
	CSVFile        int32                             `db:"csv_file" `
	Deleted        null.Val[time.Time]               `db:"deleted" `
	Geom           null.Val[string]                  `db:"geom" `
	H3cell         null.Val[string]                  `db:"h3cell" `
	ID             int32                             `db:"id,pk" `
	OrganizationID int32                             `db:"organization_id" `

	R fileuploadFlyoverAerialServiceR `db:"-" `
}

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

// FileuploadFlyoverAerialServices contains methods to work with the flyover_aerial_service table
var FileuploadFlyoverAerialServices = psql.NewTablex[*FileuploadFlyoverAerialService, FileuploadFlyoverAerialServiceSlice, *FileuploadFlyoverAerialServiceSetter]("fileupload", "flyover_aerial_service", buildFileuploadFlyoverAerialServiceColumns("fileupload.flyover_aerial_service"))

// FileuploadFlyoverAerialServicesQuery is a query on the flyover_aerial_service table
type FileuploadFlyoverAerialServicesQuery = *psql.ViewQuery[*FileuploadFlyoverAerialService, FileuploadFlyoverAerialServiceSlice]

// fileuploadFlyoverAerialServiceR is where relationships are stored.
type fileuploadFlyoverAerialServiceR struct {
	CreatorUser  *User          // fileupload.flyover_aerial_service.flyover_aerial_service_creator_id_fkey
	CSVFileCSV   *FileuploadCSV // fileupload.flyover_aerial_service.flyover_aerial_service_csv_file_fkey
	Organization *Organization  // fileupload.flyover_aerial_service.flyover_aerial_service_organization_id_fkey
}

func buildFileuploadFlyoverAerialServiceColumns(alias string) fileuploadFlyoverAerialServiceColumns {
	return fileuploadFlyoverAerialServiceColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"committed", "condition", "created", "creator_id", "csv_file", "deleted", "geom", "h3cell", "id", "organization_id",
		).WithParent("fileupload.flyover_aerial_service"),
		tableAlias:     alias,
		Committed:      psql.Quote(alias, "committed"),
		Condition:      psql.Quote(alias, "condition"),
		Created:        psql.Quote(alias, "created"),
		CreatorID:      psql.Quote(alias, "creator_id"),
		CSVFile:        psql.Quote(alias, "csv_file"),
		Deleted:        psql.Quote(alias, "deleted"),
		Geom:           psql.Quote(alias, "geom"),
		H3cell:         psql.Quote(alias, "h3cell"),
		ID:             psql.Quote(alias, "id"),
		OrganizationID: psql.Quote(alias, "organization_id"),
	}
}

type fileuploadFlyoverAerialServiceColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Committed      psql.Expression
	Condition      psql.Expression
	Created        psql.Expression
	CreatorID      psql.Expression
	CSVFile        psql.Expression
	Deleted        psql.Expression
	Geom           psql.Expression
	H3cell         psql.Expression
	ID             psql.Expression
	OrganizationID psql.Expression
}

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

func (fileuploadFlyoverAerialServiceColumns) AliasedAs(alias string) fileuploadFlyoverAerialServiceColumns {
	return buildFileuploadFlyoverAerialServiceColumns(alias)
}

// FileuploadFlyoverAerialServiceSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type FileuploadFlyoverAerialServiceSetter struct {
	Committed      omit.Val[bool]                              `db:"committed" `
	Condition      omit.Val[enums.FileuploadPoolconditiontype] `db:"condition" `
	Created        omit.Val[time.Time]                         `db:"created" `
	CreatorID      omit.Val[int32]                             `db:"creator_id" `
	CSVFile        omit.Val[int32]                             `db:"csv_file" `
	Deleted        omitnull.Val[time.Time]                     `db:"deleted" `
	Geom           omitnull.Val[string]                        `db:"geom" `
	H3cell         omitnull.Val[string]                        `db:"h3cell" `
	ID             omit.Val[int32]                             `db:"id,pk" `
	OrganizationID omit.Val[int32]                             `db:"organization_id" `
}

func (s FileuploadFlyoverAerialServiceSetter) SetColumns() []string {
	vals := make([]string, 0, 10)
	if s.Committed.IsValue() {
		vals = append(vals, "committed")
	}
	if s.Condition.IsValue() {
		vals = append(vals, "condition")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.CreatorID.IsValue() {
		vals = append(vals, "creator_id")
	}
	if s.CSVFile.IsValue() {
		vals = append(vals, "csv_file")
	}
	if !s.Deleted.IsUnset() {
		vals = append(vals, "deleted")
	}
	if !s.Geom.IsUnset() {
		vals = append(vals, "geom")
	}
	if !s.H3cell.IsUnset() {
		vals = append(vals, "h3cell")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	return vals
}

func (s FileuploadFlyoverAerialServiceSetter) Overwrite(t *FileuploadFlyoverAerialService) {
	if s.Committed.IsValue() {
		t.Committed = s.Committed.MustGet()
	}
	if s.Condition.IsValue() {
		t.Condition = s.Condition.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.CreatorID.IsValue() {
		t.CreatorID = s.CreatorID.MustGet()
	}
	if s.CSVFile.IsValue() {
		t.CSVFile = s.CSVFile.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if !s.Geom.IsUnset() {
		t.Geom = s.Geom.MustGetNull()
	}
	if !s.H3cell.IsUnset() {
		t.H3cell = s.H3cell.MustGetNull()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	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
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// CSVFileCSV starts a query for related objects on fileupload.csv
func (o *FileuploadFlyoverAerialService) CSVFileCSV(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadCSVSQuery {
	return FileuploadCSVS.Query(append(mods,
		sm.Where(FileuploadCSVS.Columns.FileID.EQ(psql.Arg(o.CSVFile))),
	)...)
}

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

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

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

func (os FileuploadFlyoverAerialServiceSlice) 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 attachFileuploadFlyoverAerialServiceCreatorUser0(ctx context.Context, exec bob.Executor, count int, fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService, user1 *User) (*FileuploadFlyoverAerialService, error) {
	setter := &FileuploadFlyoverAerialServiceSetter{
		CreatorID: omit.From(user1.ID),
	}

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

	return fileuploadFlyoverAerialService0, nil
}

func (fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService) InsertCreatorUser(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 = attachFileuploadFlyoverAerialServiceCreatorUser0(ctx, exec, 1, fileuploadFlyoverAerialService0, user1)
	if err != nil {
		return err
	}

	fileuploadFlyoverAerialService0.R.CreatorUser = user1

	user1.R.CreatorFlyoverAerialServices = append(user1.R.CreatorFlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

func (fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

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

	fileuploadFlyoverAerialService0.R.CreatorUser = user1

	user1.R.CreatorFlyoverAerialServices = append(user1.R.CreatorFlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

func attachFileuploadFlyoverAerialServiceCSVFileCSV0(ctx context.Context, exec bob.Executor, count int, fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService, fileuploadCSV1 *FileuploadCSV) (*FileuploadFlyoverAerialService, error) {
	setter := &FileuploadFlyoverAerialServiceSetter{
		CSVFile: omit.From(fileuploadCSV1.FileID),
	}

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

	return fileuploadFlyoverAerialService0, nil
}

func (fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService) InsertCSVFileCSV(ctx context.Context, exec bob.Executor, related *FileuploadCSVSetter) error {
	var err error

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

	_, err = attachFileuploadFlyoverAerialServiceCSVFileCSV0(ctx, exec, 1, fileuploadFlyoverAerialService0, fileuploadCSV1)
	if err != nil {
		return err
	}

	fileuploadFlyoverAerialService0.R.CSVFileCSV = fileuploadCSV1

	fileuploadCSV1.R.CSVFileFlyoverAerialServices = append(fileuploadCSV1.R.CSVFileFlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

func (fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService) AttachCSVFileCSV(ctx context.Context, exec bob.Executor, fileuploadCSV1 *FileuploadCSV) error {
	var err error

	_, err = attachFileuploadFlyoverAerialServiceCSVFileCSV0(ctx, exec, 1, fileuploadFlyoverAerialService0, fileuploadCSV1)
	if err != nil {
		return err
	}

	fileuploadFlyoverAerialService0.R.CSVFileCSV = fileuploadCSV1

	fileuploadCSV1.R.CSVFileFlyoverAerialServices = append(fileuploadCSV1.R.CSVFileFlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

func attachFileuploadFlyoverAerialServiceOrganization0(ctx context.Context, exec bob.Executor, count int, fileuploadFlyoverAerialService0 *FileuploadFlyoverAerialService, organization1 *Organization) (*FileuploadFlyoverAerialService, error) {
	setter := &FileuploadFlyoverAerialServiceSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return fileuploadFlyoverAerialService0, nil
}

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

	fileuploadFlyoverAerialService0.R.Organization = organization1

	organization1.R.FlyoverAerialServices = append(organization1.R.FlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

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

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

	fileuploadFlyoverAerialService0.R.Organization = organization1

	organization1.R.FlyoverAerialServices = append(organization1.R.FlyoverAerialServices, fileuploadFlyoverAerialService0)

	return nil
}

type fileuploadFlyoverAerialServiceWhere[Q psql.Filterable] struct {
	Committed      psql.WhereMod[Q, bool]
	Condition      psql.WhereMod[Q, enums.FileuploadPoolconditiontype]
	Created        psql.WhereMod[Q, time.Time]
	CreatorID      psql.WhereMod[Q, int32]
	CSVFile        psql.WhereMod[Q, int32]
	Deleted        psql.WhereNullMod[Q, time.Time]
	Geom           psql.WhereNullMod[Q, string]
	H3cell         psql.WhereNullMod[Q, string]
	ID             psql.WhereMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
}

func (fileuploadFlyoverAerialServiceWhere[Q]) AliasedAs(alias string) fileuploadFlyoverAerialServiceWhere[Q] {
	return buildFileuploadFlyoverAerialServiceWhere[Q](buildFileuploadFlyoverAerialServiceColumns(alias))
}

func buildFileuploadFlyoverAerialServiceWhere[Q psql.Filterable](cols fileuploadFlyoverAerialServiceColumns) fileuploadFlyoverAerialServiceWhere[Q] {
	return fileuploadFlyoverAerialServiceWhere[Q]{
		Committed:      psql.Where[Q, bool](cols.Committed),
		Condition:      psql.Where[Q, enums.FileuploadPoolconditiontype](cols.Condition),
		Created:        psql.Where[Q, time.Time](cols.Created),
		CreatorID:      psql.Where[Q, int32](cols.CreatorID),
		CSVFile:        psql.Where[Q, int32](cols.CSVFile),
		Deleted:        psql.WhereNull[Q, time.Time](cols.Deleted),
		Geom:           psql.WhereNull[Q, string](cols.Geom),
		H3cell:         psql.WhereNull[Q, string](cols.H3cell),
		ID:             psql.Where[Q, int32](cols.ID),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorFlyoverAerialServices = FileuploadFlyoverAerialServiceSlice{o}
		}
		return nil
	case "CSVFileCSV":
		rel, ok := retrieved.(*FileuploadCSV)
		if !ok {
			return fmt.Errorf("fileuploadFlyoverAerialService cannot load %T as %q", retrieved, name)
		}

		o.R.CSVFileCSV = rel

		if rel != nil {
			rel.R.CSVFileFlyoverAerialServices = FileuploadFlyoverAerialServiceSlice{o}
		}
		return nil
	case "Organization":
		rel, ok := retrieved.(*Organization)
		if !ok {
			return fmt.Errorf("fileuploadFlyoverAerialService cannot load %T as %q", retrieved, name)
		}

		o.R.Organization = rel

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

type fileuploadFlyoverAerialServicePreloader struct {
	CreatorUser  func(...psql.PreloadOption) psql.Preloader
	CSVFileCSV   func(...psql.PreloadOption) psql.Preloader
	Organization func(...psql.PreloadOption) psql.Preloader
}

func buildFileuploadFlyoverAerialServicePreloader() fileuploadFlyoverAerialServicePreloader {
	return fileuploadFlyoverAerialServicePreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        FileuploadFlyoverAerialServices,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		CSVFileCSV: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FileuploadCSV, FileuploadCSVSlice](psql.PreloadRel{
				Name: "CSVFileCSV",
				Sides: []psql.PreloadSide{
					{
						From:        FileuploadFlyoverAerialServices,
						To:          FileuploadCSVS,
						FromColumns: []string{"csv_file"},
						ToColumns:   []string{"file_id"},
					},
				},
			}, FileuploadCSVS.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        FileuploadFlyoverAerialServices,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

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

func buildFileuploadFlyoverAerialServiceThenLoader[Q orm.Loadable]() fileuploadFlyoverAerialServiceThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CSVFileCSVLoadInterface interface {
		LoadCSVFileCSV(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return fileuploadFlyoverAerialServiceThenLoader[Q]{
		CreatorUser: thenLoadBuilder[Q](
			"CreatorUser",
			func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCreatorUser(ctx, exec, mods...)
			},
		),
		CSVFileCSV: thenLoadBuilder[Q](
			"CSVFileCSV",
			func(ctx context.Context, exec bob.Executor, retrieved CSVFileCSVLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCSVFileCSV(ctx, exec, mods...)
			},
		),
		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...)
			},
		),
	}
}

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

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

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

	related.R.CreatorFlyoverAerialServices = FileuploadFlyoverAerialServiceSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.CSVFileFlyoverAerialServices = FileuploadFlyoverAerialServiceSlice{o}

	o.R.CSVFileCSV = related
	return nil
}

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

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

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

		for _, rel := range fileuploadCSVS {

			if !(o.CSVFile == rel.FileID) {
				continue
			}

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

			o.R.CSVFileCSV = rel
			break
		}
	}

	return nil
}

// LoadOrganization loads the fileuploadFlyoverAerialService's Organization into the .R struct
func (o *FileuploadFlyoverAerialService) 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.FlyoverAerialServices = FileuploadFlyoverAerialServiceSlice{o}

	o.R.Organization = related
	return nil
}

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

type fileuploadFlyoverAerialServiceJoins[Q dialect.Joinable] struct {
	typ          string
	CreatorUser  modAs[Q, userColumns]
	CSVFileCSV   modAs[Q, fileuploadCSVColumns]
	Organization modAs[Q, organizationColumns]
}

func (j fileuploadFlyoverAerialServiceJoins[Q]) aliasedAs(alias string) fileuploadFlyoverAerialServiceJoins[Q] {
	return buildFileuploadFlyoverAerialServiceJoins[Q](buildFileuploadFlyoverAerialServiceColumns(alias), j.typ)
}

func buildFileuploadFlyoverAerialServiceJoins[Q dialect.Joinable](cols fileuploadFlyoverAerialServiceColumns, typ string) fileuploadFlyoverAerialServiceJoins[Q] {
	return fileuploadFlyoverAerialServiceJoins[Q]{
		typ: typ,
		CreatorUser: 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.CreatorID),
					))
				}

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

				{
					mods = append(mods, dialect.Join[Q](typ, FileuploadCSVS.Name().As(to.Alias())).On(
						to.FileID.EQ(cols.CSVFile),
					))
				}

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

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

				return mods
			},
		},
	}
}
