// Code generated by SQLBoiler 4.19.5 (https://github.com/aarondl/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package models

import (
	"context"
	"database/sql"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/aarondl/null/v8"
	"github.com/aarondl/sqlboiler/v4/boil"
	"github.com/aarondl/sqlboiler/v4/queries"
	"github.com/aarondl/sqlboiler/v4/queries/qm"
	"github.com/aarondl/sqlboiler/v4/queries/qmhelper"
	"github.com/aarondl/sqlboiler/v4/types"
	"github.com/aarondl/strmangle"
	"github.com/friendsofgo/errors"
)

// Command is an object representing the database table.
type Command struct {
	CommandID          int32            `boil:"command_id" json:"command_id" toml:"command_id" yaml:"command_id"`
	Type               string           `boil:"type" json:"type" toml:"type" yaml:"type"`
	Scope              string           `boil:"scope" json:"scope" toml:"scope" yaml:"scope"`
	RunID              int32            `boil:"run_id" json:"run_id" toml:"run_id" yaml:"run_id"`
	Status             string           `boil:"status" json:"status" toml:"status" yaml:"status"`
	ErrorDescription   string           `boil:"error_description" json:"error_description" toml:"error_description" yaml:"error_description"`
	Hostname           string           `boil:"hostname" json:"hostname" toml:"hostname" yaml:"hostname"`
	CreatedAt          time.Time        `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"`
	UpdatedAt          null.Time        `boil:"updated_at" json:"updated_at,omitempty" toml:"updated_at" yaml:"updated_at,omitempty"`
	DeletedAt          null.Time        `boil:"deleted_at" json:"deleted_at,omitempty" toml:"deleted_at" yaml:"deleted_at,omitempty"`
	ScriptIds          types.Int64Array `boil:"script_ids" json:"script_ids" toml:"script_ids" yaml:"script_ids"`
	PercentageOfTarget null.Int32       `boil:"percentage_of_target" json:"percentage_of_target,omitempty" toml:"percentage_of_target" yaml:"percentage_of_target,omitempty"`
	IncreaseRPS        int32            `boil:"increase_rps" json:"increase_rps" toml:"increase_rps" yaml:"increase_rps"`

	R *commandR `boil:"-" json:"-" toml:"-" yaml:"-"`
	L commandL  `boil:"-" json:"-" toml:"-" yaml:"-"`
}

var CommandColumns = struct {
	CommandID          string
	Type               string
	Scope              string
	RunID              string
	Status             string
	ErrorDescription   string
	Hostname           string
	CreatedAt          string
	UpdatedAt          string
	DeletedAt          string
	ScriptIds          string
	PercentageOfTarget string
	IncreaseRPS        string
}{
	CommandID:          "command_id",
	Type:               "type",
	Scope:              "scope",
	RunID:              "run_id",
	Status:             "status",
	ErrorDescription:   "error_description",
	Hostname:           "hostname",
	CreatedAt:          "created_at",
	UpdatedAt:          "updated_at",
	DeletedAt:          "deleted_at",
	ScriptIds:          "script_ids",
	PercentageOfTarget: "percentage_of_target",
	IncreaseRPS:        "increase_rps",
}

var CommandTableColumns = struct {
	CommandID          string
	Type               string
	Scope              string
	RunID              string
	Status             string
	ErrorDescription   string
	Hostname           string
	CreatedAt          string
	UpdatedAt          string
	DeletedAt          string
	ScriptIds          string
	PercentageOfTarget string
	IncreaseRPS        string
}{
	CommandID:          "command.command_id",
	Type:               "command.type",
	Scope:              "command.scope",
	RunID:              "command.run_id",
	Status:             "command.status",
	ErrorDescription:   "command.error_description",
	Hostname:           "command.hostname",
	CreatedAt:          "command.created_at",
	UpdatedAt:          "command.updated_at",
	DeletedAt:          "command.deleted_at",
	ScriptIds:          "command.script_ids",
	PercentageOfTarget: "command.percentage_of_target",
	IncreaseRPS:        "command.increase_rps",
}

// Generated where

type whereHelpertypes_Int64Array struct{ field string }

func (w whereHelpertypes_Int64Array) EQ(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.EQ, x)
}
func (w whereHelpertypes_Int64Array) NEQ(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.NEQ, x)
}
func (w whereHelpertypes_Int64Array) LT(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LT, x)
}
func (w whereHelpertypes_Int64Array) LTE(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LTE, x)
}
func (w whereHelpertypes_Int64Array) GT(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GT, x)
}
func (w whereHelpertypes_Int64Array) GTE(x types.Int64Array) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GTE, x)
}

type whereHelpernull_Int32 struct{ field string }

func (w whereHelpernull_Int32) EQ(x null.Int32) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, false, x)
}
func (w whereHelpernull_Int32) NEQ(x null.Int32) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, true, x)
}
func (w whereHelpernull_Int32) LT(x null.Int32) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LT, x)
}
func (w whereHelpernull_Int32) LTE(x null.Int32) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LTE, x)
}
func (w whereHelpernull_Int32) GT(x null.Int32) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GT, x)
}
func (w whereHelpernull_Int32) GTE(x null.Int32) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GTE, x)
}
func (w whereHelpernull_Int32) IN(slice []int32) qm.QueryMod {
	values := make([]interface{}, 0, len(slice))
	for _, value := range slice {
		values = append(values, value)
	}
	return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...)
}
func (w whereHelpernull_Int32) NIN(slice []int32) qm.QueryMod {
	values := make([]interface{}, 0, len(slice))
	for _, value := range slice {
		values = append(values, value)
	}
	return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...)
}

func (w whereHelpernull_Int32) IsNull() qm.QueryMod    { return qmhelper.WhereIsNull(w.field) }
func (w whereHelpernull_Int32) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) }

var CommandWhere = struct {
	CommandID          whereHelperint32
	Type               whereHelperstring
	Scope              whereHelperstring
	RunID              whereHelperint32
	Status             whereHelperstring
	ErrorDescription   whereHelperstring
	Hostname           whereHelperstring
	CreatedAt          whereHelpertime_Time
	UpdatedAt          whereHelpernull_Time
	DeletedAt          whereHelpernull_Time
	ScriptIds          whereHelpertypes_Int64Array
	PercentageOfTarget whereHelpernull_Int32
	IncreaseRPS        whereHelperint32
}{
	CommandID:          whereHelperint32{field: "\"command\".\"command_id\""},
	Type:               whereHelperstring{field: "\"command\".\"type\""},
	Scope:              whereHelperstring{field: "\"command\".\"scope\""},
	RunID:              whereHelperint32{field: "\"command\".\"run_id\""},
	Status:             whereHelperstring{field: "\"command\".\"status\""},
	ErrorDescription:   whereHelperstring{field: "\"command\".\"error_description\""},
	Hostname:           whereHelperstring{field: "\"command\".\"hostname\""},
	CreatedAt:          whereHelpertime_Time{field: "\"command\".\"created_at\""},
	UpdatedAt:          whereHelpernull_Time{field: "\"command\".\"updated_at\""},
	DeletedAt:          whereHelpernull_Time{field: "\"command\".\"deleted_at\""},
	ScriptIds:          whereHelpertypes_Int64Array{field: "\"command\".\"script_ids\""},
	PercentageOfTarget: whereHelpernull_Int32{field: "\"command\".\"percentage_of_target\""},
	IncreaseRPS:        whereHelperint32{field: "\"command\".\"increase_rps\""},
}

// CommandRels is where relationship names are stored.
var CommandRels = struct {
	Run string
}{
	Run: "Run",
}

// commandR is where relationships are stored.
type commandR struct {
	Run *Run `boil:"Run" json:"Run" toml:"Run" yaml:"Run"`
}

// NewStruct creates a new relationship struct
func (*commandR) NewStruct() *commandR {
	return &commandR{}
}

func (o *Command) GetRun() *Run {
	if o == nil {
		return nil
	}

	return o.R.GetRun()
}

func (r *commandR) GetRun() *Run {
	if r == nil {
		return nil
	}

	return r.Run
}

// commandL is where Load methods for each relationship are stored.
type commandL struct{}

var (
	commandAllColumns            = []string{"command_id", "type", "scope", "run_id", "status", "error_description", "hostname", "created_at", "updated_at", "deleted_at", "script_ids", "percentage_of_target", "increase_rps"}
	commandColumnsWithoutDefault = []string{"run_id", "error_description", "hostname"}
	commandColumnsWithDefault    = []string{"command_id", "type", "scope", "status", "created_at", "updated_at", "deleted_at", "script_ids", "percentage_of_target", "increase_rps"}
	commandPrimaryKeyColumns     = []string{"command_id"}
	commandGeneratedColumns      = []string{}
)

type (
	// CommandSlice is an alias for a slice of pointers to Command.
	// This should almost always be used instead of []Command.
	CommandSlice []*Command
	// CommandHook is the signature for custom Command hook methods
	CommandHook func(context.Context, boil.ContextExecutor, *Command) error

	commandQuery struct {
		*queries.Query
	}
)

// Cache for insert, update and upsert
var (
	commandType                 = reflect.TypeOf(&Command{})
	commandMapping              = queries.MakeStructMapping(commandType)
	commandPrimaryKeyMapping, _ = queries.BindMapping(commandType, commandMapping, commandPrimaryKeyColumns)
	commandInsertCacheMut       sync.RWMutex
	commandInsertCache          = make(map[string]insertCache)
	commandUpdateCacheMut       sync.RWMutex
	commandUpdateCache          = make(map[string]updateCache)
	commandUpsertCacheMut       sync.RWMutex
	commandUpsertCache          = make(map[string]insertCache)
)

var (
	// Force time package dependency for automated UpdatedAt/CreatedAt.
	_ = time.Second
	// Force qmhelper dependency for where clause generation (which doesn't
	// always happen)
	_ = qmhelper.Where
)

var commandAfterSelectMu sync.Mutex
var commandAfterSelectHooks []CommandHook

var commandBeforeInsertMu sync.Mutex
var commandBeforeInsertHooks []CommandHook
var commandAfterInsertMu sync.Mutex
var commandAfterInsertHooks []CommandHook

var commandBeforeUpdateMu sync.Mutex
var commandBeforeUpdateHooks []CommandHook
var commandAfterUpdateMu sync.Mutex
var commandAfterUpdateHooks []CommandHook

var commandBeforeDeleteMu sync.Mutex
var commandBeforeDeleteHooks []CommandHook
var commandAfterDeleteMu sync.Mutex
var commandAfterDeleteHooks []CommandHook

var commandBeforeUpsertMu sync.Mutex
var commandBeforeUpsertHooks []CommandHook
var commandAfterUpsertMu sync.Mutex
var commandAfterUpsertHooks []CommandHook

// doAfterSelectHooks executes all "after Select" hooks.
func (o *Command) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandAfterSelectHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doBeforeInsertHooks executes all "before insert" hooks.
func (o *Command) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandBeforeInsertHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doAfterInsertHooks executes all "after Insert" hooks.
func (o *Command) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandAfterInsertHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *Command) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandBeforeUpdateHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doAfterUpdateHooks executes all "after Update" hooks.
func (o *Command) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandAfterUpdateHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *Command) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandBeforeDeleteHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *Command) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandAfterDeleteHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *Command) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandBeforeUpsertHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *Command) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
	if boil.HooksAreSkipped(ctx) {
		return nil
	}

	for _, hook := range commandAfterUpsertHooks {
		if err := hook(ctx, exec, o); err != nil {
			return err
		}
	}

	return nil
}

// AddCommandHook registers your hook function for all future operations.
func AddCommandHook(hookPoint boil.HookPoint, commandHook CommandHook) {
	switch hookPoint {
	case boil.AfterSelectHook:
		commandAfterSelectMu.Lock()
		commandAfterSelectHooks = append(commandAfterSelectHooks, commandHook)
		commandAfterSelectMu.Unlock()
	case boil.BeforeInsertHook:
		commandBeforeInsertMu.Lock()
		commandBeforeInsertHooks = append(commandBeforeInsertHooks, commandHook)
		commandBeforeInsertMu.Unlock()
	case boil.AfterInsertHook:
		commandAfterInsertMu.Lock()
		commandAfterInsertHooks = append(commandAfterInsertHooks, commandHook)
		commandAfterInsertMu.Unlock()
	case boil.BeforeUpdateHook:
		commandBeforeUpdateMu.Lock()
		commandBeforeUpdateHooks = append(commandBeforeUpdateHooks, commandHook)
		commandBeforeUpdateMu.Unlock()
	case boil.AfterUpdateHook:
		commandAfterUpdateMu.Lock()
		commandAfterUpdateHooks = append(commandAfterUpdateHooks, commandHook)
		commandAfterUpdateMu.Unlock()
	case boil.BeforeDeleteHook:
		commandBeforeDeleteMu.Lock()
		commandBeforeDeleteHooks = append(commandBeforeDeleteHooks, commandHook)
		commandBeforeDeleteMu.Unlock()
	case boil.AfterDeleteHook:
		commandAfterDeleteMu.Lock()
		commandAfterDeleteHooks = append(commandAfterDeleteHooks, commandHook)
		commandAfterDeleteMu.Unlock()
	case boil.BeforeUpsertHook:
		commandBeforeUpsertMu.Lock()
		commandBeforeUpsertHooks = append(commandBeforeUpsertHooks, commandHook)
		commandBeforeUpsertMu.Unlock()
	case boil.AfterUpsertHook:
		commandAfterUpsertMu.Lock()
		commandAfterUpsertHooks = append(commandAfterUpsertHooks, commandHook)
		commandAfterUpsertMu.Unlock()
	}
}

// One returns a single command record from the query.
func (q commandQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Command, error) {
	o := &Command{}

	queries.SetLimit(q.Query, 1)

	err := q.Bind(ctx, exec, o)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, sql.ErrNoRows
		}
		return nil, errors.Wrap(err, "models: failed to execute a one query for command")
	}

	if err := o.doAfterSelectHooks(ctx, exec); err != nil {
		return o, err
	}

	return o, nil
}

// All returns all Command records from the query.
func (q commandQuery) All(ctx context.Context, exec boil.ContextExecutor) (CommandSlice, error) {
	var o []*Command

	err := q.Bind(ctx, exec, &o)
	if err != nil {
		return nil, errors.Wrap(err, "models: failed to assign all query results to Command slice")
	}

	if len(commandAfterSelectHooks) != 0 {
		for _, obj := range o {
			if err := obj.doAfterSelectHooks(ctx, exec); err != nil {
				return o, err
			}
		}
	}

	return o, nil
}

// Count returns the count of all Command records in the query.
func (q commandQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	var count int64

	queries.SetSelect(q.Query, nil)
	queries.SetCount(q.Query)

	err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
	if err != nil {
		return 0, errors.Wrap(err, "models: failed to count command rows")
	}

	return count, nil
}

// Exists checks if the row exists in the table.
func (q commandQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
	var count int64

	queries.SetSelect(q.Query, nil)
	queries.SetCount(q.Query)
	queries.SetLimit(q.Query, 1)

	err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
	if err != nil {
		return false, errors.Wrap(err, "models: failed to check if command exists")
	}

	return count > 0, nil
}

// Run pointed to by the foreign key.
func (o *Command) Run(mods ...qm.QueryMod) runQuery {
	queryMods := []qm.QueryMod{
		qm.Where("\"run_id\" = ?", o.RunID),
	}

	queryMods = append(queryMods, mods...)

	return Runs(queryMods...)
}

// LoadRun allows an eager lookup of values, cached into the
// loaded structs of the objects. This is for an N-1 relationship.
func (commandL) LoadRun(ctx context.Context, e boil.ContextExecutor, singular bool, maybeCommand interface{}, mods queries.Applicator) error {
	var slice []*Command
	var object *Command

	if singular {
		var ok bool
		object, ok = maybeCommand.(*Command)
		if !ok {
			object = new(Command)
			ok = queries.SetFromEmbeddedStruct(&object, &maybeCommand)
			if !ok {
				return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeCommand))
			}
		}
	} else {
		s, ok := maybeCommand.(*[]*Command)
		if ok {
			slice = *s
		} else {
			ok = queries.SetFromEmbeddedStruct(&slice, maybeCommand)
			if !ok {
				return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeCommand))
			}
		}
	}

	args := make(map[interface{}]struct{})
	if singular {
		if object.R == nil {
			object.R = &commandR{}
		}
		args[object.RunID] = struct{}{}

	} else {
		for _, obj := range slice {
			if obj.R == nil {
				obj.R = &commandR{}
			}

			args[obj.RunID] = struct{}{}

		}
	}

	if len(args) == 0 {
		return nil
	}

	argsSlice := make([]interface{}, len(args))
	i := 0
	for arg := range args {
		argsSlice[i] = arg
		i++
	}

	query := NewQuery(
		qm.From(`runs`),
		qm.WhereIn(`runs.run_id in ?`, argsSlice...),
	)
	if mods != nil {
		mods.Apply(query)
	}

	results, err := query.QueryContext(ctx, e)
	if err != nil {
		return errors.Wrap(err, "failed to eager load Run")
	}

	var resultSlice []*Run
	if err = queries.Bind(results, &resultSlice); err != nil {
		return errors.Wrap(err, "failed to bind eager loaded slice Run")
	}

	if err = results.Close(); err != nil {
		return errors.Wrap(err, "failed to close results of eager load for runs")
	}
	if err = results.Err(); err != nil {
		return errors.Wrap(err, "error occurred during iteration of eager loaded relations for runs")
	}

	if len(runAfterSelectHooks) != 0 {
		for _, obj := range resultSlice {
			if err := obj.doAfterSelectHooks(ctx, e); err != nil {
				return err
			}
		}
	}

	if len(resultSlice) == 0 {
		return nil
	}

	if singular {
		foreign := resultSlice[0]
		object.R.Run = foreign
		if foreign.R == nil {
			foreign.R = &runR{}
		}
		foreign.R.Commands = append(foreign.R.Commands, object)
		return nil
	}

	for _, local := range slice {
		for _, foreign := range resultSlice {
			if local.RunID == foreign.RunID {
				local.R.Run = foreign
				if foreign.R == nil {
					foreign.R = &runR{}
				}
				foreign.R.Commands = append(foreign.R.Commands, local)
				break
			}
		}
	}

	return nil
}

// SetRun of the command to the related item.
// Sets o.R.Run to related.
// Adds o to related.R.Commands.
func (o *Command) SetRun(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Run) error {
	var err error
	if insert {
		if err = related.Insert(ctx, exec, boil.Infer()); err != nil {
			return errors.Wrap(err, "failed to insert into foreign table")
		}
	}

	updateQuery := fmt.Sprintf(
		"UPDATE \"command\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 1, []string{"run_id"}),
		strmangle.WhereClause("\"", "\"", 2, commandPrimaryKeyColumns),
	)
	values := []interface{}{related.RunID, o.CommandID}

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, updateQuery)
		fmt.Fprintln(writer, values)
	}
	if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {
		return errors.Wrap(err, "failed to update local table")
	}

	o.RunID = related.RunID
	if o.R == nil {
		o.R = &commandR{
			Run: related,
		}
	} else {
		o.R.Run = related
	}

	if related.R == nil {
		related.R = &runR{
			Commands: CommandSlice{o},
		}
	} else {
		related.R.Commands = append(related.R.Commands, o)
	}

	return nil
}

// Commands retrieves all the records using an executor.
func Commands(mods ...qm.QueryMod) commandQuery {
	mods = append(mods, qm.From("\"command\""))
	q := NewQuery(mods...)
	if len(queries.GetSelect(q)) == 0 {
		queries.SetSelect(q, []string{"\"command\".*"})
	}

	return commandQuery{q}
}

// FindCommand retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func FindCommand(ctx context.Context, exec boil.ContextExecutor, commandID int32, selectCols ...string) (*Command, error) {
	commandObj := &Command{}

	sel := "*"
	if len(selectCols) > 0 {
		sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
	}
	query := fmt.Sprintf(
		"select %s from \"command\" where \"command_id\"=$1", sel,
	)

	q := queries.Raw(query, commandID)

	err := q.Bind(ctx, exec, commandObj)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, sql.ErrNoRows
		}
		return nil, errors.Wrap(err, "models: unable to select from command")
	}

	if err = commandObj.doAfterSelectHooks(ctx, exec); err != nil {
		return commandObj, err
	}

	return commandObj, nil
}

// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *Command) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
	if o == nil {
		return errors.New("models: no command provided for insertion")
	}

	var err error
	if !boil.TimestampsAreSkipped(ctx) {
		currTime := time.Now().In(boil.GetLocation())

		if o.CreatedAt.IsZero() {
			o.CreatedAt = currTime
		}
		if queries.MustTime(o.UpdatedAt).IsZero() {
			queries.SetScanner(&o.UpdatedAt, currTime)
		}
	}

	if err := o.doBeforeInsertHooks(ctx, exec); err != nil {
		return err
	}

	nzDefaults := queries.NonZeroDefaultSet(commandColumnsWithDefault, o)

	key := makeCacheKey(columns, nzDefaults)
	commandInsertCacheMut.RLock()
	cache, cached := commandInsertCache[key]
	commandInsertCacheMut.RUnlock()

	if !cached {
		wl, returnColumns := columns.InsertColumnSet(
			commandAllColumns,
			commandColumnsWithDefault,
			commandColumnsWithoutDefault,
			nzDefaults,
		)

		cache.valueMapping, err = queries.BindMapping(commandType, commandMapping, wl)
		if err != nil {
			return err
		}
		cache.retMapping, err = queries.BindMapping(commandType, commandMapping, returnColumns)
		if err != nil {
			return err
		}
		if len(wl) != 0 {
			cache.query = fmt.Sprintf("INSERT INTO \"command\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
		} else {
			cache.query = "INSERT INTO \"command\" %sDEFAULT VALUES%s"
		}

		var queryOutput, queryReturning string

		if len(cache.retMapping) != 0 {
			queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\""))
		}

		cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
	}

	value := reflect.Indirect(reflect.ValueOf(o))
	vals := queries.ValuesFromMapping(value, cache.valueMapping)

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, vals)
	}

	if len(cache.retMapping) != 0 {
		err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
	} else {
		_, err = exec.ExecContext(ctx, cache.query, vals...)
	}

	if err != nil {
		return errors.Wrap(err, "models: unable to insert into command")
	}

	if !cached {
		commandInsertCacheMut.Lock()
		commandInsertCache[key] = cache
		commandInsertCacheMut.Unlock()
	}

	return o.doAfterInsertHooks(ctx, exec)
}

// Update uses an executor to update the Command.
// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates.
// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records.
func (o *Command) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
	if !boil.TimestampsAreSkipped(ctx) {
		currTime := time.Now().In(boil.GetLocation())

		queries.SetScanner(&o.UpdatedAt, currTime)
	}

	var err error
	if err = o.doBeforeUpdateHooks(ctx, exec); err != nil {
		return 0, err
	}
	key := makeCacheKey(columns, nil)
	commandUpdateCacheMut.RLock()
	cache, cached := commandUpdateCache[key]
	commandUpdateCacheMut.RUnlock()

	if !cached {
		wl := columns.UpdateColumnSet(
			commandAllColumns,
			commandPrimaryKeyColumns,
		)

		if !columns.IsWhitelist() {
			wl = strmangle.SetComplement(wl, []string{"created_at"})
		}
		if len(wl) == 0 {
			return 0, errors.New("models: unable to update command, could not build whitelist")
		}

		cache.query = fmt.Sprintf("UPDATE \"command\" SET %s WHERE %s",
			strmangle.SetParamNames("\"", "\"", 1, wl),
			strmangle.WhereClause("\"", "\"", len(wl)+1, commandPrimaryKeyColumns),
		)
		cache.valueMapping, err = queries.BindMapping(commandType, commandMapping, append(wl, commandPrimaryKeyColumns...))
		if err != nil {
			return 0, err
		}
	}

	values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, values)
	}
	var result sql.Result
	result, err = exec.ExecContext(ctx, cache.query, values...)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to update command row")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: failed to get rows affected by update for command")
	}

	if !cached {
		commandUpdateCacheMut.Lock()
		commandUpdateCache[key] = cache
		commandUpdateCacheMut.Unlock()
	}

	return rowsAff, o.doAfterUpdateHooks(ctx, exec)
}

// UpdateAll updates all rows with the specified column values.
func (q commandQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
	queries.SetUpdate(q.Query, cols)

	result, err := q.Query.ExecContext(ctx, exec)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to update all for command")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to retrieve rows affected for command")
	}

	return rowsAff, nil
}

// UpdateAll updates all rows with the specified column values, using an executor.
func (o CommandSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
	ln := int64(len(o))
	if ln == 0 {
		return 0, nil
	}

	if len(cols) == 0 {
		return 0, errors.New("models: update all requires at least one column argument")
	}

	colNames := make([]string, len(cols))
	args := make([]interface{}, len(cols))

	i := 0
	for name, value := range cols {
		colNames[i] = name
		args[i] = value
		i++
	}

	// Append all of the primary key values for each column
	for _, obj := range o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), commandPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := fmt.Sprintf("UPDATE \"command\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 1, colNames),
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, commandPrimaryKeyColumns, len(o)))

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args...)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to update all in command slice")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all command")
	}
	return rowsAff, nil
}

// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *Command) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error {
	if o == nil {
		return errors.New("models: no command provided for upsert")
	}
	if !boil.TimestampsAreSkipped(ctx) {
		currTime := time.Now().In(boil.GetLocation())

		if o.CreatedAt.IsZero() {
			o.CreatedAt = currTime
		}
		queries.SetScanner(&o.UpdatedAt, currTime)
	}

	if err := o.doBeforeUpsertHooks(ctx, exec); err != nil {
		return err
	}

	nzDefaults := queries.NonZeroDefaultSet(commandColumnsWithDefault, o)

	// Build cache key in-line uglily - mysql vs psql problems
	buf := strmangle.GetBuffer()
	if updateOnConflict {
		buf.WriteByte('t')
	} else {
		buf.WriteByte('f')
	}
	buf.WriteByte('.')
	for _, c := range conflictColumns {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	buf.WriteString(strconv.Itoa(updateColumns.Kind))
	for _, c := range updateColumns.Cols {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	buf.WriteString(strconv.Itoa(insertColumns.Kind))
	for _, c := range insertColumns.Cols {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	for _, c := range nzDefaults {
		buf.WriteString(c)
	}
	key := buf.String()
	strmangle.PutBuffer(buf)

	commandUpsertCacheMut.RLock()
	cache, cached := commandUpsertCache[key]
	commandUpsertCacheMut.RUnlock()

	var err error

	if !cached {
		insert, _ := insertColumns.InsertColumnSet(
			commandAllColumns,
			commandColumnsWithDefault,
			commandColumnsWithoutDefault,
			nzDefaults,
		)

		update := updateColumns.UpdateColumnSet(
			commandAllColumns,
			commandPrimaryKeyColumns,
		)

		if updateOnConflict && len(update) == 0 {
			return errors.New("models: unable to upsert command, could not build update column list")
		}

		ret := strmangle.SetComplement(commandAllColumns, strmangle.SetIntersect(insert, update))

		conflict := conflictColumns
		if len(conflict) == 0 && updateOnConflict && len(update) != 0 {
			if len(commandPrimaryKeyColumns) == 0 {
				return errors.New("models: unable to upsert command, could not build conflict column list")
			}

			conflict = make([]string, len(commandPrimaryKeyColumns))
			copy(conflict, commandPrimaryKeyColumns)
		}
		cache.query = buildUpsertQueryPostgres(dialect, "\"command\"", updateOnConflict, ret, update, conflict, insert, opts...)

		cache.valueMapping, err = queries.BindMapping(commandType, commandMapping, insert)
		if err != nil {
			return err
		}
		if len(ret) != 0 {
			cache.retMapping, err = queries.BindMapping(commandType, commandMapping, ret)
			if err != nil {
				return err
			}
		}
	}

	value := reflect.Indirect(reflect.ValueOf(o))
	vals := queries.ValuesFromMapping(value, cache.valueMapping)
	var returns []interface{}
	if len(cache.retMapping) != 0 {
		returns = queries.PtrsFromMapping(value, cache.retMapping)
	}

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, vals)
	}
	if len(cache.retMapping) != 0 {
		err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...)
		if errors.Is(err, sql.ErrNoRows) {
			err = nil // Postgres doesn't return anything when there's no update
		}
	} else {
		_, err = exec.ExecContext(ctx, cache.query, vals...)
	}
	if err != nil {
		return errors.Wrap(err, "models: unable to upsert command")
	}

	if !cached {
		commandUpsertCacheMut.Lock()
		commandUpsertCache[key] = cache
		commandUpsertCacheMut.Unlock()
	}

	return o.doAfterUpsertHooks(ctx, exec)
}

// Delete deletes a single Command record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *Command) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if o == nil {
		return 0, errors.New("models: no Command provided for delete")
	}

	if err := o.doBeforeDeleteHooks(ctx, exec); err != nil {
		return 0, err
	}

	args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), commandPrimaryKeyMapping)
	sql := "DELETE FROM \"command\" WHERE \"command_id\"=$1"

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args...)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to delete from command")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: failed to get rows affected by delete for command")
	}

	if err := o.doAfterDeleteHooks(ctx, exec); err != nil {
		return 0, err
	}

	return rowsAff, nil
}

// DeleteAll deletes all matching rows.
func (q commandQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if q.Query == nil {
		return 0, errors.New("models: no commandQuery provided for delete all")
	}

	queries.SetDelete(q.Query)

	result, err := q.Query.ExecContext(ctx, exec)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to delete all from command")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for command")
	}

	return rowsAff, nil
}

// DeleteAll deletes all rows in the slice, using an executor.
func (o CommandSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if len(o) == 0 {
		return 0, nil
	}

	if len(commandBeforeDeleteHooks) != 0 {
		for _, obj := range o {
			if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil {
				return 0, err
			}
		}
	}

	var args []interface{}
	for _, obj := range o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), commandPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := "DELETE FROM \"command\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, commandPrimaryKeyColumns, len(o))

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to delete all from command slice")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for command")
	}

	if len(commandAfterDeleteHooks) != 0 {
		for _, obj := range o {
			if err := obj.doAfterDeleteHooks(ctx, exec); err != nil {
				return 0, err
			}
		}
	}

	return rowsAff, nil
}

// Reload refetches the object from the database
// using the primary keys with an executor.
func (o *Command) Reload(ctx context.Context, exec boil.ContextExecutor) error {
	ret, err := FindCommand(ctx, exec, o.CommandID)
	if err != nil {
		return err
	}

	*o = *ret
	return nil
}

// ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice.
func (o *CommandSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
	if o == nil || len(*o) == 0 {
		return nil
	}

	slice := CommandSlice{}
	var args []interface{}
	for _, obj := range *o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), commandPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := "SELECT \"command\".* FROM \"command\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, commandPrimaryKeyColumns, len(*o))

	q := queries.Raw(sql, args...)

	err := q.Bind(ctx, exec, &slice)
	if err != nil {
		return errors.Wrap(err, "models: unable to reload all in CommandSlice")
	}

	*o = slice

	return nil
}

// CommandExists checks if the Command row exists.
func CommandExists(ctx context.Context, exec boil.ContextExecutor, commandID int32) (bool, error) {
	var exists bool
	sql := "select exists(select 1 from \"command\" where \"command_id\"=$1 limit 1)"

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, commandID)
	}
	row := exec.QueryRowContext(ctx, sql, commandID)

	err := row.Scan(&exists)
	if err != nil {
		return false, errors.Wrap(err, "models: unable to check if command exists")
	}

	return exists, nil
}

// Exists checks if the Command row exists.
func (o *Command) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
	return CommandExists(ctx, exec, o.CommandID)
}
