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

// LocationsAsync is an object representing the database table.
type LocationsAsync struct {
	ID            int32               `db:"id,pk,autoincr" `
	Completed     bool                `db:"completed" `
	WasError      bool                `db:"was_error" `
	Result        null.Val[[]byte]    `db:"result" `
	Error         null.Val[[]byte]    `db:"error" `
	CreatedTime   time.Time           `db:"created_time" `
	UpdatedTime   time.Time           `db:"updated_time" `
	CompletedTime null.Val[time.Time] `db:"completed_time" `
}

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

// LocationsAsyncs contains methods to work with the locations_async table
var LocationsAsyncs = mysql.NewTablex[*LocationsAsync, LocationsAsyncSlice, *LocationsAsyncSetter]("locations_async", buildLocationsAsyncColumns("locations_async"), []string{"id"})

// LocationsAsyncsQuery is a query on the locations_async table
type LocationsAsyncsQuery = *mysql.ViewQuery[*LocationsAsync, LocationsAsyncSlice]

func buildLocationsAsyncColumns(alias string) locationsAsyncColumns {
	return locationsAsyncColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "completed", "was_error", "result", "error", "created_time", "updated_time", "completed_time",
		).WithParent("locations_async"),
		tableAlias:    alias,
		ID:            mysql.Quote(alias, "id"),
		Completed:     mysql.Quote(alias, "completed"),
		WasError:      mysql.Quote(alias, "was_error"),
		Result:        mysql.Quote(alias, "result"),
		Error:         mysql.Quote(alias, "error"),
		CreatedTime:   mysql.Quote(alias, "created_time"),
		UpdatedTime:   mysql.Quote(alias, "updated_time"),
		CompletedTime: mysql.Quote(alias, "completed_time"),
	}
}

type locationsAsyncColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	ID            mysql.Expression
	Completed     mysql.Expression
	WasError      mysql.Expression
	Result        mysql.Expression
	Error         mysql.Expression
	CreatedTime   mysql.Expression
	UpdatedTime   mysql.Expression
	CompletedTime mysql.Expression
}

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

func (locationsAsyncColumns) AliasedAs(alias string) locationsAsyncColumns {
	return buildLocationsAsyncColumns(alias)
}

// LocationsAsyncSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsAsyncSetter struct {
	ID            omit.Val[int32]         `db:"id,pk,autoincr" `
	Completed     omit.Val[bool]          `db:"completed" `
	WasError      omit.Val[bool]          `db:"was_error" `
	Result        omitnull.Val[[]byte]    `db:"result" `
	Error         omitnull.Val[[]byte]    `db:"error" `
	CreatedTime   omit.Val[time.Time]     `db:"created_time" `
	UpdatedTime   omit.Val[time.Time]     `db:"updated_time" `
	CompletedTime omitnull.Val[time.Time] `db:"completed_time" `
}

func (s LocationsAsyncSetter) SetColumns() []string {
	vals := make([]string, 0, 8)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Completed.IsValue() {
		vals = append(vals, "completed")
	}
	if s.WasError.IsValue() {
		vals = append(vals, "was_error")
	}
	if !s.Result.IsUnset() {
		vals = append(vals, "result")
	}
	if !s.Error.IsUnset() {
		vals = append(vals, "error")
	}
	if s.CreatedTime.IsValue() {
		vals = append(vals, "created_time")
	}
	if s.UpdatedTime.IsValue() {
		vals = append(vals, "updated_time")
	}
	if !s.CompletedTime.IsUnset() {
		vals = append(vals, "completed_time")
	}
	return vals
}

func (s LocationsAsyncSetter) Overwrite(t *LocationsAsync) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Completed.IsValue() {
		t.Completed = s.Completed.MustGet()
	}
	if s.WasError.IsValue() {
		t.WasError = s.WasError.MustGet()
	}
	if !s.Result.IsUnset() {
		t.Result = s.Result.MustGetNull()
	}
	if !s.Error.IsUnset() {
		t.Error = s.Error.MustGetNull()
	}
	if s.CreatedTime.IsValue() {
		t.CreatedTime = s.CreatedTime.MustGet()
	}
	if s.UpdatedTime.IsValue() {
		t.UpdatedTime = s.UpdatedTime.MustGet()
	}
	if !s.CompletedTime.IsUnset() {
		t.CompletedTime = s.CompletedTime.MustGetNull()
	}
}

func (s *LocationsAsyncSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsAsyncs.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.Completed.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Completed.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.WasError.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.WasError.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Result.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Result.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Error.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Error.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.CreatedTime.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.CreatedTime.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.UpdatedTime.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UpdatedTime.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.CompletedTime.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.CompletedTime.MustGetNull()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

	return mysql.Quote("locations_async", "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 LocationsAsyncSlice) copyMatchingRows(from ...*LocationsAsync) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}

			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsAsyncSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsAsyncSetter) error {
	_, err := LocationsAsyncs.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type locationsAsyncWhere[Q mysql.Filterable] struct {
	ID            mysql.WhereMod[Q, int32]
	Completed     mysql.WhereMod[Q, bool]
	WasError      mysql.WhereMod[Q, bool]
	Result        mysql.WhereNullMod[Q, []byte]
	Error         mysql.WhereNullMod[Q, []byte]
	CreatedTime   mysql.WhereMod[Q, time.Time]
	UpdatedTime   mysql.WhereMod[Q, time.Time]
	CompletedTime mysql.WhereNullMod[Q, time.Time]
}

func (locationsAsyncWhere[Q]) AliasedAs(alias string) locationsAsyncWhere[Q] {
	return buildLocationsAsyncWhere[Q](buildLocationsAsyncColumns(alias))
}

func buildLocationsAsyncWhere[Q mysql.Filterable](cols locationsAsyncColumns) locationsAsyncWhere[Q] {
	return locationsAsyncWhere[Q]{
		ID:            mysql.Where[Q, int32](cols.ID),
		Completed:     mysql.Where[Q, bool](cols.Completed),
		WasError:      mysql.Where[Q, bool](cols.WasError),
		Result:        mysql.WhereNull[Q, []byte](cols.Result),
		Error:         mysql.WhereNull[Q, []byte](cols.Error),
		CreatedTime:   mysql.Where[Q, time.Time](cols.CreatedTime),
		UpdatedTime:   mysql.Where[Q, time.Time](cols.UpdatedTime),
		CompletedTime: mysql.WhereNull[Q, time.Time](cols.CompletedTime),
	}
}
