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

// LocationsPipeline is an object representing the database table.
type LocationsPipeline struct {
	ID          int32            `db:"id,pk,autoincr" `
	UUID        string           `db:"uuid" `
	Description null.Val[string] `db:"description" `
	Enabled     bool             `db:"enabled" `
	APIKey      null.Val[string] `db:"api_key" `
	APIUsername null.Val[string] `db:"api_username" `
	RemoteName  null.Val[string] `db:"remote_name" `

	R locationsPipelineR `db:"-" `
}

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

// LocationsPipelines contains methods to work with the locations_pipeline table
var LocationsPipelines = mysql.NewTablex[*LocationsPipeline, LocationsPipelineSlice, *LocationsPipelineSetter]("locations_pipeline", buildLocationsPipelineColumns("locations_pipeline"), []string{"id"}, []string{"uuid"})

// LocationsPipelinesQuery is a query on the locations_pipeline table
type LocationsPipelinesQuery = *mysql.ViewQuery[*LocationsPipeline, LocationsPipelineSlice]

// locationsPipelineR is where relationships are stored.
type locationsPipelineR struct {
	PipelineLocationsEvents            LocationsEventSlice            // locations_event_pipeline_id_5188361f_fk_locations_pipeline_uuid
	PipelineLocationsLocationpipelines LocationsLocationpipelineSlice // locations_locationpi_pipeline_id_2ad721b4_fk_locations
	OriginPipelineLocationsPackages    LocationsPackageSlice          // locations_package_origin_pipeline_id_9f8d6473_fk_locations
}

func buildLocationsPipelineColumns(alias string) locationsPipelineColumns {
	return locationsPipelineColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "uuid", "description", "enabled", "api_key", "api_username", "remote_name",
		).WithParent("locations_pipeline"),
		tableAlias:  alias,
		ID:          mysql.Quote(alias, "id"),
		UUID:        mysql.Quote(alias, "uuid"),
		Description: mysql.Quote(alias, "description"),
		Enabled:     mysql.Quote(alias, "enabled"),
		APIKey:      mysql.Quote(alias, "api_key"),
		APIUsername: mysql.Quote(alias, "api_username"),
		RemoteName:  mysql.Quote(alias, "remote_name"),
	}
}

type locationsPipelineColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	ID          mysql.Expression
	UUID        mysql.Expression
	Description mysql.Expression
	Enabled     mysql.Expression
	APIKey      mysql.Expression
	APIUsername mysql.Expression
	RemoteName  mysql.Expression
}

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

func (locationsPipelineColumns) AliasedAs(alias string) locationsPipelineColumns {
	return buildLocationsPipelineColumns(alias)
}

// LocationsPipelineSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsPipelineSetter struct {
	ID          omit.Val[int32]      `db:"id,pk,autoincr" `
	UUID        omit.Val[string]     `db:"uuid" `
	Description omitnull.Val[string] `db:"description" `
	Enabled     omit.Val[bool]       `db:"enabled" `
	APIKey      omitnull.Val[string] `db:"api_key" `
	APIUsername omitnull.Val[string] `db:"api_username" `
	RemoteName  omitnull.Val[string] `db:"remote_name" `
}

func (s LocationsPipelineSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	if !s.Description.IsUnset() {
		vals = append(vals, "description")
	}
	if s.Enabled.IsValue() {
		vals = append(vals, "enabled")
	}
	if !s.APIKey.IsUnset() {
		vals = append(vals, "api_key")
	}
	if !s.APIUsername.IsUnset() {
		vals = append(vals, "api_username")
	}
	if !s.RemoteName.IsUnset() {
		vals = append(vals, "remote_name")
	}
	return vals
}

func (s LocationsPipelineSetter) Overwrite(t *LocationsPipeline) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
	if !s.Description.IsUnset() {
		t.Description = s.Description.MustGetNull()
	}
	if s.Enabled.IsValue() {
		t.Enabled = s.Enabled.MustGet()
	}
	if !s.APIKey.IsUnset() {
		t.APIKey = s.APIKey.MustGetNull()
	}
	if !s.APIUsername.IsUnset() {
		t.APIUsername = s.APIUsername.MustGetNull()
	}
	if !s.RemoteName.IsUnset() {
		t.RemoteName = s.RemoteName.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsPipelineSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsPipelineSetter) error {
	_, err := LocationsPipelines.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// PipelineLocationsEvents starts a query for related objects on locations_event
func (o *LocationsPipeline) PipelineLocationsEvents(mods ...bob.Mod[*dialect.SelectQuery]) LocationsEventsQuery {
	return LocationsEvents.Query(append(mods,
		sm.Where(LocationsEvents.Columns.PipelineID.EQ(mysql.Arg(o.UUID))),
	)...)
}

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

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

// PipelineLocationsLocationpipelines starts a query for related objects on locations_locationpipeline
func (o *LocationsPipeline) PipelineLocationsLocationpipelines(mods ...bob.Mod[*dialect.SelectQuery]) LocationsLocationpipelinesQuery {
	return LocationsLocationpipelines.Query(append(mods,
		sm.Where(LocationsLocationpipelines.Columns.PipelineID.EQ(mysql.Arg(o.UUID))),
	)...)
}

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

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

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

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

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

func insertLocationsPipelinePipelineLocationsEvents0(ctx context.Context, exec bob.Executor, locationsEvents1 []*LocationsEventSetter, locationsPipeline0 *LocationsPipeline) (LocationsEventSlice, error) {
	for i := range locationsEvents1 {
		locationsEvents1[i].PipelineID = omit.From(locationsPipeline0.UUID)
	}

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

	return ret, nil
}

func attachLocationsPipelinePipelineLocationsEvents0(ctx context.Context, exec bob.Executor, count int, locationsEvents1 LocationsEventSlice, locationsPipeline0 *LocationsPipeline) (LocationsEventSlice, error) {
	setter := &LocationsEventSetter{
		PipelineID: omit.From(locationsPipeline0.UUID),
	}

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

	return locationsEvents1, nil
}

func (locationsPipeline0 *LocationsPipeline) InsertPipelineLocationsEvents(ctx context.Context, exec bob.Executor, related ...*LocationsEventSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	locationsEvents1, err := insertLocationsPipelinePipelineLocationsEvents0(ctx, exec, related, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.PipelineLocationsEvents = append(locationsPipeline0.R.PipelineLocationsEvents, locationsEvents1...)

	for _, rel := range locationsEvents1 {
		rel.R.PipelineLocationsPipeline = locationsPipeline0
	}
	return nil
}

func (locationsPipeline0 *LocationsPipeline) AttachPipelineLocationsEvents(ctx context.Context, exec bob.Executor, related ...*LocationsEvent) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	locationsEvents1 := LocationsEventSlice(related)

	_, err = attachLocationsPipelinePipelineLocationsEvents0(ctx, exec, len(related), locationsEvents1, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.PipelineLocationsEvents = append(locationsPipeline0.R.PipelineLocationsEvents, locationsEvents1...)

	for _, rel := range related {
		rel.R.PipelineLocationsPipeline = locationsPipeline0
	}

	return nil
}

func insertLocationsPipelinePipelineLocationsLocationpipelines0(ctx context.Context, exec bob.Executor, locationsLocationpipelines1 []*LocationsLocationpipelineSetter, locationsPipeline0 *LocationsPipeline) (LocationsLocationpipelineSlice, error) {
	for i := range locationsLocationpipelines1 {
		locationsLocationpipelines1[i].PipelineID = omit.From(locationsPipeline0.UUID)
	}

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

	return ret, nil
}

func attachLocationsPipelinePipelineLocationsLocationpipelines0(ctx context.Context, exec bob.Executor, count int, locationsLocationpipelines1 LocationsLocationpipelineSlice, locationsPipeline0 *LocationsPipeline) (LocationsLocationpipelineSlice, error) {
	setter := &LocationsLocationpipelineSetter{
		PipelineID: omit.From(locationsPipeline0.UUID),
	}

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

	return locationsLocationpipelines1, nil
}

func (locationsPipeline0 *LocationsPipeline) InsertPipelineLocationsLocationpipelines(ctx context.Context, exec bob.Executor, related ...*LocationsLocationpipelineSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	locationsLocationpipelines1, err := insertLocationsPipelinePipelineLocationsLocationpipelines0(ctx, exec, related, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.PipelineLocationsLocationpipelines = append(locationsPipeline0.R.PipelineLocationsLocationpipelines, locationsLocationpipelines1...)

	for _, rel := range locationsLocationpipelines1 {
		rel.R.PipelineLocationsPipeline = locationsPipeline0
	}
	return nil
}

func (locationsPipeline0 *LocationsPipeline) AttachPipelineLocationsLocationpipelines(ctx context.Context, exec bob.Executor, related ...*LocationsLocationpipeline) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	locationsLocationpipelines1 := LocationsLocationpipelineSlice(related)

	_, err = attachLocationsPipelinePipelineLocationsLocationpipelines0(ctx, exec, len(related), locationsLocationpipelines1, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.PipelineLocationsLocationpipelines = append(locationsPipeline0.R.PipelineLocationsLocationpipelines, locationsLocationpipelines1...)

	for _, rel := range related {
		rel.R.PipelineLocationsPipeline = locationsPipeline0
	}

	return nil
}

func insertLocationsPipelineOriginPipelineLocationsPackages0(ctx context.Context, exec bob.Executor, locationsPackages1 []*LocationsPackageSetter, locationsPipeline0 *LocationsPipeline) (LocationsPackageSlice, error) {
	for i := range locationsPackages1 {
		locationsPackages1[i].OriginPipelineID = omitnull.From(locationsPipeline0.UUID)
	}

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

	return ret, nil
}

func attachLocationsPipelineOriginPipelineLocationsPackages0(ctx context.Context, exec bob.Executor, count int, locationsPackages1 LocationsPackageSlice, locationsPipeline0 *LocationsPipeline) (LocationsPackageSlice, error) {
	setter := &LocationsPackageSetter{
		OriginPipelineID: omitnull.From(locationsPipeline0.UUID),
	}

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

	return locationsPackages1, nil
}

func (locationsPipeline0 *LocationsPipeline) InsertOriginPipelineLocationsPackages(ctx context.Context, exec bob.Executor, related ...*LocationsPackageSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	locationsPackages1, err := insertLocationsPipelineOriginPipelineLocationsPackages0(ctx, exec, related, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.OriginPipelineLocationsPackages = append(locationsPipeline0.R.OriginPipelineLocationsPackages, locationsPackages1...)

	for _, rel := range locationsPackages1 {
		rel.R.OriginPipelineLocationsPipeline = locationsPipeline0
	}
	return nil
}

func (locationsPipeline0 *LocationsPipeline) AttachOriginPipelineLocationsPackages(ctx context.Context, exec bob.Executor, related ...*LocationsPackage) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	locationsPackages1 := LocationsPackageSlice(related)

	_, err = attachLocationsPipelineOriginPipelineLocationsPackages0(ctx, exec, len(related), locationsPackages1, locationsPipeline0)
	if err != nil {
		return err
	}

	locationsPipeline0.R.OriginPipelineLocationsPackages = append(locationsPipeline0.R.OriginPipelineLocationsPackages, locationsPackages1...)

	for _, rel := range related {
		rel.R.OriginPipelineLocationsPipeline = locationsPipeline0
	}

	return nil
}

type locationsPipelineWhere[Q mysql.Filterable] struct {
	ID          mysql.WhereMod[Q, int32]
	UUID        mysql.WhereMod[Q, string]
	Description mysql.WhereNullMod[Q, string]
	Enabled     mysql.WhereMod[Q, bool]
	APIKey      mysql.WhereNullMod[Q, string]
	APIUsername mysql.WhereNullMod[Q, string]
	RemoteName  mysql.WhereNullMod[Q, string]
}

func (locationsPipelineWhere[Q]) AliasedAs(alias string) locationsPipelineWhere[Q] {
	return buildLocationsPipelineWhere[Q](buildLocationsPipelineColumns(alias))
}

func buildLocationsPipelineWhere[Q mysql.Filterable](cols locationsPipelineColumns) locationsPipelineWhere[Q] {
	return locationsPipelineWhere[Q]{
		ID:          mysql.Where[Q, int32](cols.ID),
		UUID:        mysql.Where[Q, string](cols.UUID),
		Description: mysql.WhereNull[Q, string](cols.Description),
		Enabled:     mysql.Where[Q, bool](cols.Enabled),
		APIKey:      mysql.WhereNull[Q, string](cols.APIKey),
		APIUsername: mysql.WhereNull[Q, string](cols.APIUsername),
		RemoteName:  mysql.WhereNull[Q, string](cols.RemoteName),
	}
}

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

	switch name {
	case "PipelineLocationsEvents":
		rels, ok := retrieved.(LocationsEventSlice)
		if !ok {
			return fmt.Errorf("locationsPipeline cannot load %T as %q", retrieved, name)
		}

		o.R.PipelineLocationsEvents = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.PipelineLocationsPipeline = o
			}
		}
		return nil
	case "PipelineLocationsLocationpipelines":
		rels, ok := retrieved.(LocationsLocationpipelineSlice)
		if !ok {
			return fmt.Errorf("locationsPipeline cannot load %T as %q", retrieved, name)
		}

		o.R.PipelineLocationsLocationpipelines = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.PipelineLocationsPipeline = o
			}
		}
		return nil
	case "OriginPipelineLocationsPackages":
		rels, ok := retrieved.(LocationsPackageSlice)
		if !ok {
			return fmt.Errorf("locationsPipeline cannot load %T as %q", retrieved, name)
		}

		o.R.OriginPipelineLocationsPackages = rels

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

type locationsPipelinePreloader struct{}

func buildLocationsPipelinePreloader() locationsPipelinePreloader {
	return locationsPipelinePreloader{}
}

type locationsPipelineThenLoader[Q orm.Loadable] struct {
	PipelineLocationsEvents            func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PipelineLocationsLocationpipelines func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	OriginPipelineLocationsPackages    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildLocationsPipelineThenLoader[Q orm.Loadable]() locationsPipelineThenLoader[Q] {
	type PipelineLocationsEventsLoadInterface interface {
		LoadPipelineLocationsEvents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PipelineLocationsLocationpipelinesLoadInterface interface {
		LoadPipelineLocationsLocationpipelines(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OriginPipelineLocationsPackagesLoadInterface interface {
		LoadOriginPipelineLocationsPackages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsPipelineThenLoader[Q]{
		PipelineLocationsEvents: thenLoadBuilder[Q](
			"PipelineLocationsEvents",
			func(ctx context.Context, exec bob.Executor, retrieved PipelineLocationsEventsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPipelineLocationsEvents(ctx, exec, mods...)
			},
		),
		PipelineLocationsLocationpipelines: thenLoadBuilder[Q](
			"PipelineLocationsLocationpipelines",
			func(ctx context.Context, exec bob.Executor, retrieved PipelineLocationsLocationpipelinesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPipelineLocationsLocationpipelines(ctx, exec, mods...)
			},
		),
		OriginPipelineLocationsPackages: thenLoadBuilder[Q](
			"OriginPipelineLocationsPackages",
			func(ctx context.Context, exec bob.Executor, retrieved OriginPipelineLocationsPackagesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOriginPipelineLocationsPackages(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.PipelineLocationsEvents = related
	return nil
}

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

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

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

		o.R.PipelineLocationsEvents = nil
	}

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

		for _, rel := range locationsEvents {

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

			rel.R.PipelineLocationsPipeline = o

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

	return nil
}

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

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

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

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

	o.R.PipelineLocationsLocationpipelines = related
	return nil
}

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

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

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

		o.R.PipelineLocationsLocationpipelines = nil
	}

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

		for _, rel := range locationsLocationpipelines {

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

			rel.R.PipelineLocationsPipeline = o

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

	return nil
}

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

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

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

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

	o.R.OriginPipelineLocationsPackages = related
	return nil
}

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

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

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

		o.R.OriginPipelineLocationsPackages = nil
	}

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

		for _, rel := range locationsPackages {

			if !rel.OriginPipelineID.IsValue() {
				continue
			}
			if !(rel.OriginPipelineID.IsValue() && o.UUID == rel.OriginPipelineID.MustGet()) {
				continue
			}

			rel.R.OriginPipelineLocationsPipeline = o

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

	return nil
}

type locationsPipelineJoins[Q dialect.Joinable] struct {
	typ                                string
	PipelineLocationsEvents            modAs[Q, locationsEventColumns]
	PipelineLocationsLocationpipelines modAs[Q, locationsLocationpipelineColumns]
	OriginPipelineLocationsPackages    modAs[Q, locationsPackageColumns]
}

func (j locationsPipelineJoins[Q]) aliasedAs(alias string) locationsPipelineJoins[Q] {
	return buildLocationsPipelineJoins[Q](buildLocationsPipelineColumns(alias), j.typ)
}

func buildLocationsPipelineJoins[Q dialect.Joinable](cols locationsPipelineColumns, typ string) locationsPipelineJoins[Q] {
	return locationsPipelineJoins[Q]{
		typ: typ,
		PipelineLocationsEvents: modAs[Q, locationsEventColumns]{
			c: LocationsEvents.Columns,
			f: func(to locationsEventColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

				return mods
			},
		},
		OriginPipelineLocationsPackages: 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.OriginPipelineID.EQ(cols.UUID),
					))
				}

				return mods
			},
		},
	}
}
