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

package models

import (
	"context"
	"fmt"
	"io"

	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	"github.com/stephenafamo/bob"
	"github.com/stephenafamo/bob/dialect/mysql"
	"github.com/stephenafamo/bob/dialect/mysql/dialect"
	"github.com/stephenafamo/bob/dialect/mysql/dm"
	"github.com/stephenafamo/bob/dialect/mysql/sm"
	"github.com/stephenafamo/bob/dialect/mysql/um"
	"github.com/stephenafamo/bob/expr"
	"github.com/stephenafamo/bob/mods"
	"github.com/stephenafamo/bob/orm"
)

// LocationsFile is an object representing the database table.
type LocationsFile struct {
	ID            int32           `db:"id,pk,autoincr" `
	UUID          string          `db:"uuid" `
	Name          string          `db:"name" `
	SourceID      string          `db:"source_id" `
	Checksum      string          `db:"checksum" `
	Stored        bool            `db:"stored" `
	Accessionid   string          `db:"accessionid" `
	Origin        string          `db:"origin" `
	PackageID     null.Val[int32] `db:"package_id" `
	SourcePackage string          `db:"source_package" `

	R locationsFileR `db:"-" `
}

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

// LocationsFiles contains methods to work with the locations_file table
var LocationsFiles = mysql.NewTablex[*LocationsFile, LocationsFileSlice, *LocationsFileSetter]("locations_file", buildLocationsFileColumns("locations_file"), []string{"id"}, []string{"uuid"})

// LocationsFilesQuery is a query on the locations_file table
type LocationsFilesQuery = *mysql.ViewQuery[*LocationsFile, LocationsFileSlice]

// locationsFileR is where relationships are stored.
type locationsFileR struct {
	PackageLocationsPackage *LocationsPackage // locations_file_package_id_dd478d69_fk_locations_package_id
}

func buildLocationsFileColumns(alias string) locationsFileColumns {
	return locationsFileColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "uuid", "name", "source_id", "checksum", "stored", "accessionid", "origin", "package_id", "source_package",
		).WithParent("locations_file"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		UUID:          mysql.Quote(alias, "uuid"),
		Name:          mysql.Quote(alias, "name"),
		SourceID:      mysql.Quote(alias, "source_id"),
		Checksum:      mysql.Quote(alias, "checksum"),
		Stored:        mysql.Quote(alias, "stored"),
		Accessionid:   mysql.Quote(alias, "accessionid"),
		Origin:        mysql.Quote(alias, "origin"),
		PackageID:     mysql.Quote(alias, "package_id"),
		SourcePackage: mysql.Quote(alias, "source_package"),
	}
}

type locationsFileColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	UUID          mysql.Expression
	Name          mysql.Expression
	SourceID      mysql.Expression
	Checksum      mysql.Expression
	Stored        mysql.Expression
	Accessionid   mysql.Expression
	Origin        mysql.Expression
	PackageID     mysql.Expression
	SourcePackage mysql.Expression
}

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

func (locationsFileColumns) AliasedAs(alias string) locationsFileColumns {
	return buildLocationsFileColumns(alias)
}

// LocationsFileSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsFileSetter struct {
	ID            omit.Val[int32]     `db:"id,pk,autoincr" `
	UUID          omit.Val[string]    `db:"uuid" `
	Name          omit.Val[string]    `db:"name" `
	SourceID      omit.Val[string]    `db:"source_id" `
	Checksum      omit.Val[string]    `db:"checksum" `
	Stored        omit.Val[bool]      `db:"stored" `
	Accessionid   omit.Val[string]    `db:"accessionid" `
	Origin        omit.Val[string]    `db:"origin" `
	PackageID     omitnull.Val[int32] `db:"package_id" `
	SourcePackage omit.Val[string]    `db:"source_package" `
}

func (s LocationsFileSetter) SetColumns() []string {
	vals := make([]string, 0, 10)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if s.SourceID.IsValue() {
		vals = append(vals, "source_id")
	}
	if s.Checksum.IsValue() {
		vals = append(vals, "checksum")
	}
	if s.Stored.IsValue() {
		vals = append(vals, "stored")
	}
	if s.Accessionid.IsValue() {
		vals = append(vals, "accessionid")
	}
	if s.Origin.IsValue() {
		vals = append(vals, "origin")
	}
	if !s.PackageID.IsUnset() {
		vals = append(vals, "package_id")
	}
	if s.SourcePackage.IsValue() {
		vals = append(vals, "source_package")
	}
	return vals
}

func (s LocationsFileSetter) Overwrite(t *LocationsFile) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if s.SourceID.IsValue() {
		t.SourceID = s.SourceID.MustGet()
	}
	if s.Checksum.IsValue() {
		t.Checksum = s.Checksum.MustGet()
	}
	if s.Stored.IsValue() {
		t.Stored = s.Stored.MustGet()
	}
	if s.Accessionid.IsValue() {
		t.Accessionid = s.Accessionid.MustGet()
	}
	if s.Origin.IsValue() {
		t.Origin = s.Origin.MustGet()
	}
	if !s.PackageID.IsUnset() {
		t.PackageID = s.PackageID.MustGetNull()
	}
	if s.SourcePackage.IsValue() {
		t.SourcePackage = s.SourcePackage.MustGet()
	}
}

func (s *LocationsFileSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsFiles.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(
		bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.UUID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UUID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Name.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Name.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SourceID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SourceID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Checksum.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Checksum.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Stored.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Stored.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Accessionid.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Accessionid.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Origin.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Origin.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.PackageID.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.PackageID.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SourcePackage.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SourcePackage.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *LocationsFile) pkEQ() dialect.Expression {
	return mysql.Quote("locations_file", "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 LocationsFile
func (o *LocationsFile) Update(ctx context.Context, exec bob.Executor, s *LocationsFileSetter) error {
	_, err := LocationsFiles.Update(s.UpdateMod(), um.Where(o.pkEQ())).Exec(ctx, exec)
	if err != nil {
		return err
	}

	s.Overwrite(o)

	return nil
}

// Delete deletes a single LocationsFile record with an executor
func (o *LocationsFile) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := LocationsFiles.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsFileSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsFileSetter) error {
	_, err := LocationsFiles.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

	for i := range o {
		vals.Overwrite(o[i])
	}

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// PackageLocationsPackage starts a query for related objects on locations_package
func (o *LocationsFile) PackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	return LocationsPackages.Query(append(mods,
		sm.Where(LocationsPackages.Columns.ID.EQ(mysql.Arg(o.PackageID))),
	)...)
}

func (os LocationsFileSlice) PackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.PackageID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachLocationsFilePackageLocationsPackage0(ctx context.Context, exec bob.Executor, count int, locationsFile0 *LocationsFile, locationsPackage1 *LocationsPackage) (*LocationsFile, error) {
	setter := &LocationsFileSetter{
		PackageID: omitnull.From(locationsPackage1.ID),
	}

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

	return locationsFile0, nil
}

func (locationsFile0 *LocationsFile) InsertPackageLocationsPackage(ctx context.Context, exec bob.Executor, related *LocationsPackageSetter) error {
	var err error

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

	_, err = attachLocationsFilePackageLocationsPackage0(ctx, exec, 1, locationsFile0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsFile0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsFiles = append(locationsPackage1.R.PackageLocationsFiles, locationsFile0)

	return nil
}

func (locationsFile0 *LocationsFile) AttachPackageLocationsPackage(ctx context.Context, exec bob.Executor, locationsPackage1 *LocationsPackage) error {
	var err error

	_, err = attachLocationsFilePackageLocationsPackage0(ctx, exec, 1, locationsFile0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsFile0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsFiles = append(locationsPackage1.R.PackageLocationsFiles, locationsFile0)

	return nil
}

type locationsFileWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	UUID          mysql.WhereMod[Q, string]
	Name          mysql.WhereMod[Q, string]
	SourceID      mysql.WhereMod[Q, string]
	Checksum      mysql.WhereMod[Q, string]
	Stored        mysql.WhereMod[Q, bool]
	Accessionid   mysql.WhereMod[Q, string]
	Origin        mysql.WhereMod[Q, string]
	PackageID     mysql.WhereNullMod[Q, int32]
	SourcePackage mysql.WhereMod[Q, string]
}

func (locationsFileWhere[Q]) AliasedAs(alias string) locationsFileWhere[Q] {
	return buildLocationsFileWhere[Q](buildLocationsFileColumns(alias))
}

func buildLocationsFileWhere[Q mysql.Filterable](cols locationsFileColumns) locationsFileWhere[Q] {
	return locationsFileWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		UUID:          mysql.Where[Q, string](cols.UUID),
		Name:          mysql.Where[Q, string](cols.Name),
		SourceID:      mysql.Where[Q, string](cols.SourceID),
		Checksum:      mysql.Where[Q, string](cols.Checksum),
		Stored:        mysql.Where[Q, bool](cols.Stored),
		Accessionid:   mysql.Where[Q, string](cols.Accessionid),
		Origin:        mysql.Where[Q, string](cols.Origin),
		PackageID:     mysql.WhereNull[Q, int32](cols.PackageID),
		SourcePackage: mysql.Where[Q, string](cols.SourcePackage),
	}
}

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

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

		o.R.PackageLocationsPackage = rel

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

type locationsFilePreloader struct {
	PackageLocationsPackage func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsFilePreloader() locationsFilePreloader {
	return locationsFilePreloader{
		PackageLocationsPackage: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsPackage, LocationsPackageSlice](mysql.PreloadRel{
				Name: "PackageLocationsPackage",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsFiles,
						To:          LocationsPackages,
						FromColumns: []string{"package_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, LocationsPackages.Columns.Names(), opts...)
		},
	}
}

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

func buildLocationsFileThenLoader[Q orm.Loadable]() locationsFileThenLoader[Q] {
	type PackageLocationsPackageLoadInterface interface {
		LoadPackageLocationsPackage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsFileThenLoader[Q]{
		PackageLocationsPackage: thenLoadBuilder[Q](
			"PackageLocationsPackage",
			func(ctx context.Context, exec bob.Executor, retrieved PackageLocationsPackageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPackageLocationsPackage(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.PackageLocationsFiles = LocationsFileSlice{o}

	o.R.PackageLocationsPackage = related
	return nil
}

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

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

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

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

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

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

			o.R.PackageLocationsPackage = rel
			break
		}
	}

	return nil
}

type locationsFileJoins[Q dialect.Joinable] struct {
	typ                     string
	PackageLocationsPackage modAs[Q, locationsPackageColumns]
}

func (j locationsFileJoins[Q]) aliasedAs(alias string) locationsFileJoins[Q] {
	return buildLocationsFileJoins[Q](buildLocationsFileColumns(alias), j.typ)
}

func buildLocationsFileJoins[Q dialect.Joinable](cols locationsFileColumns, typ string) locationsFileJoins[Q] {
	return locationsFileJoins[Q]{
		typ: typ,
		PackageLocationsPackage: modAs[Q, locationsPackageColumns]{
			c: LocationsPackages.Columns,
			f: func(to locationsPackageColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
	}
}
