// 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"
	"time"

	"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"
)

// LocationsPackagedownloadtask is an object representing the database table.
type LocationsPackagedownloadtask struct {
	ID                     int32               `db:"id,pk,autoincr" `
	UUID                   string              `db:"uuid" `
	DownloadsAttempted     int32               `db:"downloads_attempted" `
	DownloadsCompleted     int32               `db:"downloads_completed" `
	DownloadCompletionTime null.Val[time.Time] `db:"download_completion_time" `
	PackageID              string              `db:"package_id" `

	R locationsPackagedownloadtaskR `db:"-" `
}

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

// LocationsPackagedownloadtasks contains methods to work with the locations_packagedownloadtask table
var LocationsPackagedownloadtasks = mysql.NewTablex[*LocationsPackagedownloadtask, LocationsPackagedownloadtaskSlice, *LocationsPackagedownloadtaskSetter]("locations_packagedownloadtask", buildLocationsPackagedownloadtaskColumns("locations_packagedownloadtask"), []string{"id"}, []string{"uuid"})

// LocationsPackagedownloadtasksQuery is a query on the locations_packagedownloadtask table
type LocationsPackagedownloadtasksQuery = *mysql.ViewQuery[*LocationsPackagedownloadtask, LocationsPackagedownloadtaskSlice]

// locationsPackagedownloadtaskR is where relationships are stored.
type locationsPackagedownloadtaskR struct {
	PackageLocationsPackage               *LocationsPackage                     // locations_packagedow_package_id_488c7751_fk_locations
	UUIDLocationsPackagedownloadtaskfiles LocationsPackagedownloadtaskfileSlice // locations_packagedow_task_id_a112c9ea_fk_locations
}

func buildLocationsPackagedownloadtaskColumns(alias string) locationsPackagedownloadtaskColumns {
	return locationsPackagedownloadtaskColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "uuid", "downloads_attempted", "downloads_completed", "download_completion_time", "package_id",
		).WithParent("locations_packagedownloadtask"),
		tableAlias:             alias,
		ID:                     mysql.Quote(alias, "id"),
		UUID:                   mysql.Quote(alias, "uuid"),
		DownloadsAttempted:     mysql.Quote(alias, "downloads_attempted"),
		DownloadsCompleted:     mysql.Quote(alias, "downloads_completed"),
		DownloadCompletionTime: mysql.Quote(alias, "download_completion_time"),
		PackageID:              mysql.Quote(alias, "package_id"),
	}
}

type locationsPackagedownloadtaskColumns struct {
	expr.ColumnsExpr
	tableAlias             string
	ID                     mysql.Expression
	UUID                   mysql.Expression
	DownloadsAttempted     mysql.Expression
	DownloadsCompleted     mysql.Expression
	DownloadCompletionTime mysql.Expression
	PackageID              mysql.Expression
}

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

func (locationsPackagedownloadtaskColumns) AliasedAs(alias string) locationsPackagedownloadtaskColumns {
	return buildLocationsPackagedownloadtaskColumns(alias)
}

// LocationsPackagedownloadtaskSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsPackagedownloadtaskSetter struct {
	ID                     omit.Val[int32]         `db:"id,pk,autoincr" `
	UUID                   omit.Val[string]        `db:"uuid" `
	DownloadsAttempted     omit.Val[int32]         `db:"downloads_attempted" `
	DownloadsCompleted     omit.Val[int32]         `db:"downloads_completed" `
	DownloadCompletionTime omitnull.Val[time.Time] `db:"download_completion_time" `
	PackageID              omit.Val[string]        `db:"package_id" `
}

func (s LocationsPackagedownloadtaskSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	if s.DownloadsAttempted.IsValue() {
		vals = append(vals, "downloads_attempted")
	}
	if s.DownloadsCompleted.IsValue() {
		vals = append(vals, "downloads_completed")
	}
	if !s.DownloadCompletionTime.IsUnset() {
		vals = append(vals, "download_completion_time")
	}
	if s.PackageID.IsValue() {
		vals = append(vals, "package_id")
	}
	return vals
}

func (s LocationsPackagedownloadtaskSetter) Overwrite(t *LocationsPackagedownloadtask) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
	if s.DownloadsAttempted.IsValue() {
		t.DownloadsAttempted = s.DownloadsAttempted.MustGet()
	}
	if s.DownloadsCompleted.IsValue() {
		t.DownloadsCompleted = s.DownloadsCompleted.MustGet()
	}
	if !s.DownloadCompletionTime.IsUnset() {
		t.DownloadCompletionTime = s.DownloadCompletionTime.MustGetNull()
	}
	if s.PackageID.IsValue() {
		t.PackageID = s.PackageID.MustGet()
	}
}

func (s *LocationsPackagedownloadtaskSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsPackagedownloadtasks.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.DownloadsAttempted.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.DownloadsAttempted.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.DownloadsCompleted.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.DownloadsCompleted.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.DownloadCompletionTime.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.DownloadCompletionTime.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.PackageID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.PackageID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

	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.DownloadsAttempted.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "downloads_attempted")...),
			mysql.Arg(s.DownloadsAttempted),
		}})
	}

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsPackagedownloadtaskSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsPackagedownloadtaskSetter) error {
	_, err := LocationsPackagedownloadtasks.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

	o2, err := LocationsPackagedownloadtasks.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 *LocationsPackagedownloadtask) PackageLocationsPackage(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagesQuery {
	return LocationsPackages.Query(append(mods,
		sm.Where(LocationsPackages.Columns.UUID.EQ(mysql.Arg(o.PackageID))),
	)...)
}

func (os LocationsPackagedownloadtaskSlice) 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.UUID).OP("IN", PKArgExpr)),
	)...)
}

// UUIDLocationsPackagedownloadtaskfiles starts a query for related objects on locations_packagedownloadtaskfile
func (o *LocationsPackagedownloadtask) UUIDLocationsPackagedownloadtaskfiles(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagedownloadtaskfilesQuery {
	return LocationsPackagedownloadtaskfiles.Query(append(mods,
		sm.Where(LocationsPackagedownloadtaskfiles.Columns.TaskID.EQ(mysql.Arg(o.UUID))),
	)...)
}

func (os LocationsPackagedownloadtaskSlice) UUIDLocationsPackagedownloadtaskfiles(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPackagedownloadtaskfilesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.UUID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachLocationsPackagedownloadtaskPackageLocationsPackage0(ctx context.Context, exec bob.Executor, count int, locationsPackagedownloadtask0 *LocationsPackagedownloadtask, locationsPackage1 *LocationsPackage) (*LocationsPackagedownloadtask, error) {
	setter := &LocationsPackagedownloadtaskSetter{
		PackageID: omit.From(locationsPackage1.UUID),
	}

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

	return locationsPackagedownloadtask0, nil
}

func (locationsPackagedownloadtask0 *LocationsPackagedownloadtask) 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 = attachLocationsPackagedownloadtaskPackageLocationsPackage0(ctx, exec, 1, locationsPackagedownloadtask0, locationsPackage1)
	if err != nil {
		return err
	}

	locationsPackagedownloadtask0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsPackagedownloadtasks = append(locationsPackage1.R.PackageLocationsPackagedownloadtasks, locationsPackagedownloadtask0)

	return nil
}

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

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

	locationsPackagedownloadtask0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsPackagedownloadtasks = append(locationsPackage1.R.PackageLocationsPackagedownloadtasks, locationsPackagedownloadtask0)

	return nil
}

func insertLocationsPackagedownloadtaskUUIDLocationsPackagedownloadtaskfiles0(ctx context.Context, exec bob.Executor, locationsPackagedownloadtaskfiles1 []*LocationsPackagedownloadtaskfileSetter, locationsPackagedownloadtask0 *LocationsPackagedownloadtask) (LocationsPackagedownloadtaskfileSlice, error) {
	for i := range locationsPackagedownloadtaskfiles1 {
		locationsPackagedownloadtaskfiles1[i].TaskID = omit.From(locationsPackagedownloadtask0.UUID)
	}

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

	return ret, nil
}

func attachLocationsPackagedownloadtaskUUIDLocationsPackagedownloadtaskfiles0(ctx context.Context, exec bob.Executor, count int, locationsPackagedownloadtaskfiles1 LocationsPackagedownloadtaskfileSlice, locationsPackagedownloadtask0 *LocationsPackagedownloadtask) (LocationsPackagedownloadtaskfileSlice, error) {
	setter := &LocationsPackagedownloadtaskfileSetter{
		TaskID: omit.From(locationsPackagedownloadtask0.UUID),
	}

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

	return locationsPackagedownloadtaskfiles1, nil
}

func (locationsPackagedownloadtask0 *LocationsPackagedownloadtask) InsertUUIDLocationsPackagedownloadtaskfiles(ctx context.Context, exec bob.Executor, related ...*LocationsPackagedownloadtaskfileSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	locationsPackagedownloadtaskfiles1, err := insertLocationsPackagedownloadtaskUUIDLocationsPackagedownloadtaskfiles0(ctx, exec, related, locationsPackagedownloadtask0)
	if err != nil {
		return err
	}

	locationsPackagedownloadtask0.R.UUIDLocationsPackagedownloadtaskfiles = append(locationsPackagedownloadtask0.R.UUIDLocationsPackagedownloadtaskfiles, locationsPackagedownloadtaskfiles1...)

	for _, rel := range locationsPackagedownloadtaskfiles1 {
		rel.R.TaskLocationsPackagedownloadtask = locationsPackagedownloadtask0
	}
	return nil
}

func (locationsPackagedownloadtask0 *LocationsPackagedownloadtask) AttachUUIDLocationsPackagedownloadtaskfiles(ctx context.Context, exec bob.Executor, related ...*LocationsPackagedownloadtaskfile) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	locationsPackagedownloadtaskfiles1 := LocationsPackagedownloadtaskfileSlice(related)

	_, err = attachLocationsPackagedownloadtaskUUIDLocationsPackagedownloadtaskfiles0(ctx, exec, len(related), locationsPackagedownloadtaskfiles1, locationsPackagedownloadtask0)
	if err != nil {
		return err
	}

	locationsPackagedownloadtask0.R.UUIDLocationsPackagedownloadtaskfiles = append(locationsPackagedownloadtask0.R.UUIDLocationsPackagedownloadtaskfiles, locationsPackagedownloadtaskfiles1...)

	for _, rel := range related {
		rel.R.TaskLocationsPackagedownloadtask = locationsPackagedownloadtask0
	}

	return nil
}

type locationsPackagedownloadtaskWhere[Q mysql.Filterable] struct {
	ID                     mysql.WhereMod[Q, int32]
	UUID                   mysql.WhereMod[Q, string]
	DownloadsAttempted     mysql.WhereMod[Q, int32]
	DownloadsCompleted     mysql.WhereMod[Q, int32]
	DownloadCompletionTime mysql.WhereNullMod[Q, time.Time]
	PackageID              mysql.WhereMod[Q, string]
}

func (locationsPackagedownloadtaskWhere[Q]) AliasedAs(alias string) locationsPackagedownloadtaskWhere[Q] {
	return buildLocationsPackagedownloadtaskWhere[Q](buildLocationsPackagedownloadtaskColumns(alias))
}

func buildLocationsPackagedownloadtaskWhere[Q mysql.Filterable](cols locationsPackagedownloadtaskColumns) locationsPackagedownloadtaskWhere[Q] {
	return locationsPackagedownloadtaskWhere[Q]{
		ID:                     mysql.Where[Q, int32](cols.ID),
		UUID:                   mysql.Where[Q, string](cols.UUID),
		DownloadsAttempted:     mysql.Where[Q, int32](cols.DownloadsAttempted),
		DownloadsCompleted:     mysql.Where[Q, int32](cols.DownloadsCompleted),
		DownloadCompletionTime: mysql.WhereNull[Q, time.Time](cols.DownloadCompletionTime),
		PackageID:              mysql.Where[Q, string](cols.PackageID),
	}
}

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

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

		o.R.PackageLocationsPackage = rel

		if rel != nil {
			rel.R.PackageLocationsPackagedownloadtasks = LocationsPackagedownloadtaskSlice{o}
		}
		return nil
	case "UUIDLocationsPackagedownloadtaskfiles":
		rels, ok := retrieved.(LocationsPackagedownloadtaskfileSlice)
		if !ok {
			return fmt.Errorf("locationsPackagedownloadtask cannot load %T as %q", retrieved, name)
		}

		o.R.UUIDLocationsPackagedownloadtaskfiles = rels

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

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

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

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

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

	return locationsPackagedownloadtaskThenLoader[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...)
			},
		),
		UUIDLocationsPackagedownloadtaskfiles: thenLoadBuilder[Q](
			"UUIDLocationsPackagedownloadtaskfiles",
			func(ctx context.Context, exec bob.Executor, retrieved UUIDLocationsPackagedownloadtaskfilesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUUIDLocationsPackagedownloadtaskfiles(ctx, exec, mods...)
			},
		),
	}
}

// LoadPackageLocationsPackage loads the locationsPackagedownloadtask's PackageLocationsPackage into the .R struct
func (o *LocationsPackagedownloadtask) 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.PackageLocationsPackagedownloadtasks = LocationsPackagedownloadtaskSlice{o}

	o.R.PackageLocationsPackage = related
	return nil
}

// LoadPackageLocationsPackage loads the locationsPackagedownloadtask's PackageLocationsPackage into the .R struct
func (os LocationsPackagedownloadtaskSlice) 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 == rel.UUID) {
				continue
			}

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

			o.R.PackageLocationsPackage = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.UUIDLocationsPackagedownloadtaskfiles = related
	return nil
}

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

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

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

		o.R.UUIDLocationsPackagedownloadtaskfiles = nil
	}

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

		for _, rel := range locationsPackagedownloadtaskfiles {

			if !(o.UUID == rel.TaskID) {
				continue
			}

			rel.R.TaskLocationsPackagedownloadtask = o

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

	return nil
}

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

func (j locationsPackagedownloadtaskJoins[Q]) aliasedAs(alias string) locationsPackagedownloadtaskJoins[Q] {
	return buildLocationsPackagedownloadtaskJoins[Q](buildLocationsPackagedownloadtaskColumns(alias), j.typ)
}

func buildLocationsPackagedownloadtaskJoins[Q dialect.Joinable](cols locationsPackagedownloadtaskColumns, typ string) locationsPackagedownloadtaskJoins[Q] {
	return locationsPackagedownloadtaskJoins[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.UUID.EQ(cols.PackageID),
					))
				}

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

				{
					mods = append(mods, dialect.Join[Q](typ, LocationsPackagedownloadtaskfiles.Name().As(to.Alias())).On(
						to.TaskID.EQ(cols.UUID),
					))
				}

				return mods
			},
		},
	}
}
