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

// LocationsEvent is an object representing the database table.
type LocationsEvent struct {
	ID           int32            `db:"id,pk,autoincr" `
	EventType    string           `db:"event_type" `
	EventReason  string           `db:"event_reason" `
	UserID       uint32           `db:"user_id" `
	UserEmail    string           `db:"user_email" `
	Status       string           `db:"status" `
	StatusReason null.Val[string] `db:"status_reason" `
	StatusTime   time.Time        `db:"status_time" `
	StoreData    null.Val[string] `db:"store_data" `
	AdminIDID    null.Val[int32]  `db:"admin_id_id" `
	PackageID    string           `db:"package_id" `
	PipelineID   string           `db:"pipeline_id" `

	R locationsEventR `db:"-" `
}

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

// LocationsEvents contains methods to work with the locations_event table
var LocationsEvents = mysql.NewTablex[*LocationsEvent, LocationsEventSlice, *LocationsEventSetter]("locations_event", buildLocationsEventColumns("locations_event"), []string{"id"})

// LocationsEventsQuery is a query on the locations_event table
type LocationsEventsQuery = *mysql.ViewQuery[*LocationsEvent, LocationsEventSlice]

// locationsEventR is where relationships are stored.
type locationsEventR struct {
	AdminIDAuthUser           *AuthUser          // locations_event_admin_id_id_4a50d36a_fk_auth_user_id
	PackageLocationsPackage   *LocationsPackage  // locations_event_package_id_50db610f_fk_locations_package_uuid
	PipelineLocationsPipeline *LocationsPipeline // locations_event_pipeline_id_5188361f_fk_locations_pipeline_uuid
}

func buildLocationsEventColumns(alias string) locationsEventColumns {
	return locationsEventColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "event_type", "event_reason", "user_id", "user_email", "status", "status_reason", "status_time", "store_data", "admin_id_id", "package_id", "pipeline_id",
		).WithParent("locations_event"),
		tableAlias:   alias,
		ID:           mysql.Quote(alias, "id"),
		EventType:    mysql.Quote(alias, "event_type"),
		EventReason:  mysql.Quote(alias, "event_reason"),
		UserID:       mysql.Quote(alias, "user_id"),
		UserEmail:    mysql.Quote(alias, "user_email"),
		Status:       mysql.Quote(alias, "status"),
		StatusReason: mysql.Quote(alias, "status_reason"),
		StatusTime:   mysql.Quote(alias, "status_time"),
		StoreData:    mysql.Quote(alias, "store_data"),
		AdminIDID:    mysql.Quote(alias, "admin_id_id"),
		PackageID:    mysql.Quote(alias, "package_id"),
		PipelineID:   mysql.Quote(alias, "pipeline_id"),
	}
}

type locationsEventColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	ID           mysql.Expression
	EventType    mysql.Expression
	EventReason  mysql.Expression
	UserID       mysql.Expression
	UserEmail    mysql.Expression
	Status       mysql.Expression
	StatusReason mysql.Expression
	StatusTime   mysql.Expression
	StoreData    mysql.Expression
	AdminIDID    mysql.Expression
	PackageID    mysql.Expression
	PipelineID   mysql.Expression
}

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

func (locationsEventColumns) AliasedAs(alias string) locationsEventColumns {
	return buildLocationsEventColumns(alias)
}

// LocationsEventSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsEventSetter struct {
	ID           omit.Val[int32]      `db:"id,pk,autoincr" `
	EventType    omit.Val[string]     `db:"event_type" `
	EventReason  omit.Val[string]     `db:"event_reason" `
	UserID       omit.Val[uint32]     `db:"user_id" `
	UserEmail    omit.Val[string]     `db:"user_email" `
	Status       omit.Val[string]     `db:"status" `
	StatusReason omitnull.Val[string] `db:"status_reason" `
	StatusTime   omit.Val[time.Time]  `db:"status_time" `
	StoreData    omitnull.Val[string] `db:"store_data" `
	AdminIDID    omitnull.Val[int32]  `db:"admin_id_id" `
	PackageID    omit.Val[string]     `db:"package_id" `
	PipelineID   omit.Val[string]     `db:"pipeline_id" `
}

func (s LocationsEventSetter) SetColumns() []string {
	vals := make([]string, 0, 12)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.EventType.IsValue() {
		vals = append(vals, "event_type")
	}
	if s.EventReason.IsValue() {
		vals = append(vals, "event_reason")
	}
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	if s.UserEmail.IsValue() {
		vals = append(vals, "user_email")
	}
	if s.Status.IsValue() {
		vals = append(vals, "status")
	}
	if !s.StatusReason.IsUnset() {
		vals = append(vals, "status_reason")
	}
	if s.StatusTime.IsValue() {
		vals = append(vals, "status_time")
	}
	if !s.StoreData.IsUnset() {
		vals = append(vals, "store_data")
	}
	if !s.AdminIDID.IsUnset() {
		vals = append(vals, "admin_id_id")
	}
	if s.PackageID.IsValue() {
		vals = append(vals, "package_id")
	}
	if s.PipelineID.IsValue() {
		vals = append(vals, "pipeline_id")
	}
	return vals
}

func (s LocationsEventSetter) Overwrite(t *LocationsEvent) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.EventType.IsValue() {
		t.EventType = s.EventType.MustGet()
	}
	if s.EventReason.IsValue() {
		t.EventReason = s.EventReason.MustGet()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
	if s.UserEmail.IsValue() {
		t.UserEmail = s.UserEmail.MustGet()
	}
	if s.Status.IsValue() {
		t.Status = s.Status.MustGet()
	}
	if !s.StatusReason.IsUnset() {
		t.StatusReason = s.StatusReason.MustGetNull()
	}
	if s.StatusTime.IsValue() {
		t.StatusTime = s.StatusTime.MustGet()
	}
	if !s.StoreData.IsUnset() {
		t.StoreData = s.StoreData.MustGetNull()
	}
	if !s.AdminIDID.IsUnset() {
		t.AdminIDID = s.AdminIDID.MustGetNull()
	}
	if s.PackageID.IsValue() {
		t.PackageID = s.PackageID.MustGet()
	}
	if s.PipelineID.IsValue() {
		t.PipelineID = s.PipelineID.MustGet()
	}
}

func (s *LocationsEventSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsEvents.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.EventType.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.EventType.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.EventReason.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.EventReason.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.UserID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UserID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.UserEmail.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UserEmail.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Status.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Status.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.StatusReason.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.StatusReason.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.StatusTime.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.StatusTime.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.StoreData.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.StoreData.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.AdminIDID.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AdminIDID.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)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.PipelineID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.PipelineID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsEventSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsEventSetter) error {
	_, err := LocationsEvents.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// AdminIDAuthUser starts a query for related objects on auth_user
func (o *LocationsEvent) AdminIDAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	return AuthUsers.Query(append(mods,
		sm.Where(AuthUsers.Columns.ID.EQ(mysql.Arg(o.AdminIDID))),
	)...)
}

func (os LocationsEventSlice) AdminIDAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.AdminIDID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

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

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

// PipelineLocationsPipeline starts a query for related objects on locations_pipeline
func (o *LocationsEvent) PipelineLocationsPipeline(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPipelinesQuery {
	return LocationsPipelines.Query(append(mods,
		sm.Where(LocationsPipelines.Columns.UUID.EQ(mysql.Arg(o.PipelineID))),
	)...)
}

func (os LocationsEventSlice) PipelineLocationsPipeline(mods ...bob.Mod[*dialect.SelectQuery]) LocationsPipelinesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.PipelineID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachLocationsEventAdminIDAuthUser0(ctx context.Context, exec bob.Executor, count int, locationsEvent0 *LocationsEvent, authUser1 *AuthUser) (*LocationsEvent, error) {
	setter := &LocationsEventSetter{
		AdminIDID: omitnull.From(authUser1.ID),
	}

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

	return locationsEvent0, nil
}

func (locationsEvent0 *LocationsEvent) InsertAdminIDAuthUser(ctx context.Context, exec bob.Executor, related *AuthUserSetter) error {
	var err error

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

	_, err = attachLocationsEventAdminIDAuthUser0(ctx, exec, 1, locationsEvent0, authUser1)
	if err != nil {
		return err
	}

	locationsEvent0.R.AdminIDAuthUser = authUser1

	authUser1.R.AdminIDLocationsEvents = append(authUser1.R.AdminIDLocationsEvents, locationsEvent0)

	return nil
}

func (locationsEvent0 *LocationsEvent) AttachAdminIDAuthUser(ctx context.Context, exec bob.Executor, authUser1 *AuthUser) error {
	var err error

	_, err = attachLocationsEventAdminIDAuthUser0(ctx, exec, 1, locationsEvent0, authUser1)
	if err != nil {
		return err
	}

	locationsEvent0.R.AdminIDAuthUser = authUser1

	authUser1.R.AdminIDLocationsEvents = append(authUser1.R.AdminIDLocationsEvents, locationsEvent0)

	return nil
}

func attachLocationsEventPackageLocationsPackage0(ctx context.Context, exec bob.Executor, count int, locationsEvent0 *LocationsEvent, locationsPackage1 *LocationsPackage) (*LocationsEvent, error) {
	setter := &LocationsEventSetter{
		PackageID: omit.From(locationsPackage1.UUID),
	}

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

	return locationsEvent0, nil
}

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

	locationsEvent0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsEvents = append(locationsPackage1.R.PackageLocationsEvents, locationsEvent0)

	return nil
}

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

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

	locationsEvent0.R.PackageLocationsPackage = locationsPackage1

	locationsPackage1.R.PackageLocationsEvents = append(locationsPackage1.R.PackageLocationsEvents, locationsEvent0)

	return nil
}

func attachLocationsEventPipelineLocationsPipeline0(ctx context.Context, exec bob.Executor, count int, locationsEvent0 *LocationsEvent, locationsPipeline1 *LocationsPipeline) (*LocationsEvent, error) {
	setter := &LocationsEventSetter{
		PipelineID: omit.From(locationsPipeline1.UUID),
	}

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

	return locationsEvent0, nil
}

func (locationsEvent0 *LocationsEvent) InsertPipelineLocationsPipeline(ctx context.Context, exec bob.Executor, related *LocationsPipelineSetter) error {
	var err error

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

	_, err = attachLocationsEventPipelineLocationsPipeline0(ctx, exec, 1, locationsEvent0, locationsPipeline1)
	if err != nil {
		return err
	}

	locationsEvent0.R.PipelineLocationsPipeline = locationsPipeline1

	locationsPipeline1.R.PipelineLocationsEvents = append(locationsPipeline1.R.PipelineLocationsEvents, locationsEvent0)

	return nil
}

func (locationsEvent0 *LocationsEvent) AttachPipelineLocationsPipeline(ctx context.Context, exec bob.Executor, locationsPipeline1 *LocationsPipeline) error {
	var err error

	_, err = attachLocationsEventPipelineLocationsPipeline0(ctx, exec, 1, locationsEvent0, locationsPipeline1)
	if err != nil {
		return err
	}

	locationsEvent0.R.PipelineLocationsPipeline = locationsPipeline1

	locationsPipeline1.R.PipelineLocationsEvents = append(locationsPipeline1.R.PipelineLocationsEvents, locationsEvent0)

	return nil
}

type locationsEventWhere[Q mysql.Filterable] struct {
	ID           mysql.WhereMod[Q, int32]
	EventType    mysql.WhereMod[Q, string]
	EventReason  mysql.WhereMod[Q, string]
	UserID       mysql.WhereMod[Q, uint32]
	UserEmail    mysql.WhereMod[Q, string]
	Status       mysql.WhereMod[Q, string]
	StatusReason mysql.WhereNullMod[Q, string]
	StatusTime   mysql.WhereMod[Q, time.Time]
	StoreData    mysql.WhereNullMod[Q, string]
	AdminIDID    mysql.WhereNullMod[Q, int32]
	PackageID    mysql.WhereMod[Q, string]
	PipelineID   mysql.WhereMod[Q, string]
}

func (locationsEventWhere[Q]) AliasedAs(alias string) locationsEventWhere[Q] {
	return buildLocationsEventWhere[Q](buildLocationsEventColumns(alias))
}

func buildLocationsEventWhere[Q mysql.Filterable](cols locationsEventColumns) locationsEventWhere[Q] {
	return locationsEventWhere[Q]{
		ID:           mysql.Where[Q, int32](cols.ID),
		EventType:    mysql.Where[Q, string](cols.EventType),
		EventReason:  mysql.Where[Q, string](cols.EventReason),
		UserID:       mysql.Where[Q, uint32](cols.UserID),
		UserEmail:    mysql.Where[Q, string](cols.UserEmail),
		Status:       mysql.Where[Q, string](cols.Status),
		StatusReason: mysql.WhereNull[Q, string](cols.StatusReason),
		StatusTime:   mysql.Where[Q, time.Time](cols.StatusTime),
		StoreData:    mysql.WhereNull[Q, string](cols.StoreData),
		AdminIDID:    mysql.WhereNull[Q, int32](cols.AdminIDID),
		PackageID:    mysql.Where[Q, string](cols.PackageID),
		PipelineID:   mysql.Where[Q, string](cols.PipelineID),
	}
}

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

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

		o.R.AdminIDAuthUser = rel

		if rel != nil {
			rel.R.AdminIDLocationsEvents = LocationsEventSlice{o}
		}
		return nil
	case "PackageLocationsPackage":
		rel, ok := retrieved.(*LocationsPackage)
		if !ok {
			return fmt.Errorf("locationsEvent cannot load %T as %q", retrieved, name)
		}

		o.R.PackageLocationsPackage = rel

		if rel != nil {
			rel.R.PackageLocationsEvents = LocationsEventSlice{o}
		}
		return nil
	case "PipelineLocationsPipeline":
		rel, ok := retrieved.(*LocationsPipeline)
		if !ok {
			return fmt.Errorf("locationsEvent cannot load %T as %q", retrieved, name)
		}

		o.R.PipelineLocationsPipeline = rel

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

type locationsEventPreloader struct {
	AdminIDAuthUser           func(...mysql.PreloadOption) mysql.Preloader
	PackageLocationsPackage   func(...mysql.PreloadOption) mysql.Preloader
	PipelineLocationsPipeline func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsEventPreloader() locationsEventPreloader {
	return locationsEventPreloader{
		AdminIDAuthUser: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthUser, AuthUserSlice](mysql.PreloadRel{
				Name: "AdminIDAuthUser",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsEvents,
						To:          AuthUsers,
						FromColumns: []string{"admin_id_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthUsers.Columns.Names(), opts...)
		},
		PackageLocationsPackage: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsPackage, LocationsPackageSlice](mysql.PreloadRel{
				Name: "PackageLocationsPackage",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsEvents,
						To:          LocationsPackages,
						FromColumns: []string{"package_id"},
						ToColumns:   []string{"uuid"},
					},
				},
			}, LocationsPackages.Columns.Names(), opts...)
		},
		PipelineLocationsPipeline: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsPipeline, LocationsPipelineSlice](mysql.PreloadRel{
				Name: "PipelineLocationsPipeline",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsEvents,
						To:          LocationsPipelines,
						FromColumns: []string{"pipeline_id"},
						ToColumns:   []string{"uuid"},
					},
				},
			}, LocationsPipelines.Columns.Names(), opts...)
		},
	}
}

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

func buildLocationsEventThenLoader[Q orm.Loadable]() locationsEventThenLoader[Q] {
	type AdminIDAuthUserLoadInterface interface {
		LoadAdminIDAuthUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PackageLocationsPackageLoadInterface interface {
		LoadPackageLocationsPackage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PipelineLocationsPipelineLoadInterface interface {
		LoadPipelineLocationsPipeline(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsEventThenLoader[Q]{
		AdminIDAuthUser: thenLoadBuilder[Q](
			"AdminIDAuthUser",
			func(ctx context.Context, exec bob.Executor, retrieved AdminIDAuthUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAdminIDAuthUser(ctx, exec, mods...)
			},
		),
		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...)
			},
		),
		PipelineLocationsPipeline: thenLoadBuilder[Q](
			"PipelineLocationsPipeline",
			func(ctx context.Context, exec bob.Executor, retrieved PipelineLocationsPipelineLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPipelineLocationsPipeline(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.AdminIDLocationsEvents = LocationsEventSlice{o}

	o.R.AdminIDAuthUser = related
	return nil
}

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

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

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

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

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

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

			o.R.AdminIDAuthUser = rel
			break
		}
	}

	return nil
}

// LoadPackageLocationsPackage loads the locationsEvent's PackageLocationsPackage into the .R struct
func (o *LocationsEvent) 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.PackageLocationsEvents = LocationsEventSlice{o}

	o.R.PackageLocationsPackage = related
	return nil
}

// LoadPackageLocationsPackage loads the locationsEvent's PackageLocationsPackage into the .R struct
func (os LocationsEventSlice) 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.PackageLocationsEvents = append(rel.R.PackageLocationsEvents, o)

			o.R.PackageLocationsPackage = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.PipelineLocationsEvents = LocationsEventSlice{o}

	o.R.PipelineLocationsPipeline = related
	return nil
}

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

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

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

		for _, rel := range locationsPipelines {

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

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

			o.R.PipelineLocationsPipeline = rel
			break
		}
	}

	return nil
}

type locationsEventJoins[Q dialect.Joinable] struct {
	typ                       string
	AdminIDAuthUser           modAs[Q, authUserColumns]
	PackageLocationsPackage   modAs[Q, locationsPackageColumns]
	PipelineLocationsPipeline modAs[Q, locationsPipelineColumns]
}

func (j locationsEventJoins[Q]) aliasedAs(alias string) locationsEventJoins[Q] {
	return buildLocationsEventJoins[Q](buildLocationsEventColumns(alias), j.typ)
}

func buildLocationsEventJoins[Q dialect.Joinable](cols locationsEventColumns, typ string) locationsEventJoins[Q] {
	return locationsEventJoins[Q]{
		typ: typ,
		AdminIDAuthUser: modAs[Q, authUserColumns]{
			c: AuthUsers.Columns,
			f: func(to authUserColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
		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
			},
		},
		PipelineLocationsPipeline: modAs[Q, locationsPipelineColumns]{
			c: LocationsPipelines.Columns,
			f: func(to locationsPipelineColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
	}
}
