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

// Script is an object representing the database table.
type Script struct {
	ScriptID        int32             `boil:"script_id" json:"script_id" toml:"script_id" yaml:"script_id"`
	Name            string            `boil:"name" json:"name" toml:"name" yaml:"name"`
	Descrip         null.String       `boil:"descrip" json:"descrip,omitempty" toml:"descrip" yaml:"descrip,omitempty"`
	ProjectID       int32             `boil:"project_id" json:"project_id" toml:"project_id" yaml:"project_id"`
	ScenarioID      int32             `boil:"scenario_id" json:"scenario_id" toml:"scenario_id" yaml:"scenario_id"`
	ScriptFile      null.String       `boil:"script_file" json:"script_file,omitempty" toml:"script_file" yaml:"script_file,omitempty"`
	AmmoID          null.String       `boil:"ammo_id" json:"ammo_id,omitempty" toml:"ammo_id" yaml:"ammo_id,omitempty"`
	BaseURL         null.String       `boil:"base_url" json:"base_url,omitempty" toml:"base_url" yaml:"base_url,omitempty"`
	OptionsRPS      null.Int          `boil:"options_rps" json:"options_rps,omitempty" toml:"options_rps" yaml:"options_rps,omitempty"`
	OptionsSteps    null.Int          `boil:"options_steps" json:"options_steps,omitempty" toml:"options_steps" yaml:"options_steps,omitempty"`
	OptionsDuration null.String       `boil:"options_duration" json:"options_duration,omitempty" toml:"options_duration" yaml:"options_duration,omitempty"`
	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"`
	Enabled         bool              `boil:"enabled" json:"enabled" toml:"enabled" yaml:"enabled"`
	GrafanaURL      types.StringArray `boil:"grafana_url" json:"grafana_url" toml:"grafana_url" yaml:"grafana_url"`
	Tag             string            `boil:"tag" json:"tag" toml:"tag" yaml:"tag"`
	ExprRPS         string            `boil:"expr_rps" json:"expr_rps" toml:"expr_rps" yaml:"expr_rps"`
	SourceRPS       string            `boil:"source_rps" json:"source_rps" toml:"source_rps" yaml:"source_rps"`
	CMTRPS          string            `boil:"cmt_rps" json:"cmt_rps" toml:"cmt_rps" yaml:"cmt_rps"`
	ExprRT          string            `boil:"expr_rt" json:"expr_rt" toml:"expr_rt" yaml:"expr_rt"`
	SourceRT        string            `boil:"source_rt" json:"source_rt" toml:"source_rt" yaml:"source_rt"`
	CMTRT           string            `boil:"cmt_rt" json:"cmt_rt" toml:"cmt_rt" yaml:"cmt_rt"`
	ExprErr         string            `boil:"expr_err" json:"expr_err" toml:"expr_err" yaml:"expr_err"`
	SourceErr       string            `boil:"source_err" json:"source_err" toml:"source_err" yaml:"source_err"`
	CMTErr          string            `boil:"cmt_err" json:"cmt_err" toml:"cmt_err" yaml:"cmt_err"`
	AdditionalEnv   string            `boil:"additional_env" json:"additional_env" toml:"additional_env" yaml:"additional_env"`
	Title           string            `boil:"title" json:"title" toml:"title" yaml:"title"`

	R *scriptR `boil:"-" json:"-" toml:"-" yaml:"-"`
	L scriptL  `boil:"-" json:"-" toml:"-" yaml:"-"`
}

var ScriptColumns = struct {
	ScriptID        string
	Name            string
	Descrip         string
	ProjectID       string
	ScenarioID      string
	ScriptFile      string
	AmmoID          string
	BaseURL         string
	OptionsRPS      string
	OptionsSteps    string
	OptionsDuration string
	CreatedAt       string
	UpdatedAt       string
	DeletedAt       string
	Enabled         string
	GrafanaURL      string
	Tag             string
	ExprRPS         string
	SourceRPS       string
	CMTRPS          string
	ExprRT          string
	SourceRT        string
	CMTRT           string
	ExprErr         string
	SourceErr       string
	CMTErr          string
	AdditionalEnv   string
	Title           string
}{
	ScriptID:        "script_id",
	Name:            "name",
	Descrip:         "descrip",
	ProjectID:       "project_id",
	ScenarioID:      "scenario_id",
	ScriptFile:      "script_file",
	AmmoID:          "ammo_id",
	BaseURL:         "base_url",
	OptionsRPS:      "options_rps",
	OptionsSteps:    "options_steps",
	OptionsDuration: "options_duration",
	CreatedAt:       "created_at",
	UpdatedAt:       "updated_at",
	DeletedAt:       "deleted_at",
	Enabled:         "enabled",
	GrafanaURL:      "grafana_url",
	Tag:             "tag",
	ExprRPS:         "expr_rps",
	SourceRPS:       "source_rps",
	CMTRPS:          "cmt_rps",
	ExprRT:          "expr_rt",
	SourceRT:        "source_rt",
	CMTRT:           "cmt_rt",
	ExprErr:         "expr_err",
	SourceErr:       "source_err",
	CMTErr:          "cmt_err",
	AdditionalEnv:   "additional_env",
	Title:           "title",
}

var ScriptTableColumns = struct {
	ScriptID        string
	Name            string
	Descrip         string
	ProjectID       string
	ScenarioID      string
	ScriptFile      string
	AmmoID          string
	BaseURL         string
	OptionsRPS      string
	OptionsSteps    string
	OptionsDuration string
	CreatedAt       string
	UpdatedAt       string
	DeletedAt       string
	Enabled         string
	GrafanaURL      string
	Tag             string
	ExprRPS         string
	SourceRPS       string
	CMTRPS          string
	ExprRT          string
	SourceRT        string
	CMTRT           string
	ExprErr         string
	SourceErr       string
	CMTErr          string
	AdditionalEnv   string
	Title           string
}{
	ScriptID:        "scripts.script_id",
	Name:            "scripts.name",
	Descrip:         "scripts.descrip",
	ProjectID:       "scripts.project_id",
	ScenarioID:      "scripts.scenario_id",
	ScriptFile:      "scripts.script_file",
	AmmoID:          "scripts.ammo_id",
	BaseURL:         "scripts.base_url",
	OptionsRPS:      "scripts.options_rps",
	OptionsSteps:    "scripts.options_steps",
	OptionsDuration: "scripts.options_duration",
	CreatedAt:       "scripts.created_at",
	UpdatedAt:       "scripts.updated_at",
	DeletedAt:       "scripts.deleted_at",
	Enabled:         "scripts.enabled",
	GrafanaURL:      "scripts.grafana_url",
	Tag:             "scripts.tag",
	ExprRPS:         "scripts.expr_rps",
	SourceRPS:       "scripts.source_rps",
	CMTRPS:          "scripts.cmt_rps",
	ExprRT:          "scripts.expr_rt",
	SourceRT:        "scripts.source_rt",
	CMTRT:           "scripts.cmt_rt",
	ExprErr:         "scripts.expr_err",
	SourceErr:       "scripts.source_err",
	CMTErr:          "scripts.cmt_err",
	AdditionalEnv:   "scripts.additional_env",
	Title:           "scripts.title",
}

// Generated where

type whereHelpernull_Int struct{ field string }

func (w whereHelpernull_Int) EQ(x null.Int) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, false, x)
}
func (w whereHelpernull_Int) NEQ(x null.Int) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, true, x)
}
func (w whereHelpernull_Int) LT(x null.Int) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LT, x)
}
func (w whereHelpernull_Int) LTE(x null.Int) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LTE, x)
}
func (w whereHelpernull_Int) GT(x null.Int) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GT, x)
}
func (w whereHelpernull_Int) GTE(x null.Int) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GTE, x)
}
func (w whereHelpernull_Int) IN(slice []int) 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_Int) NIN(slice []int) 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_Int) IsNull() qm.QueryMod    { return qmhelper.WhereIsNull(w.field) }
func (w whereHelpernull_Int) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) }

var ScriptWhere = struct {
	ScriptID        whereHelperint32
	Name            whereHelperstring
	Descrip         whereHelpernull_String
	ProjectID       whereHelperint32
	ScenarioID      whereHelperint32
	ScriptFile      whereHelpernull_String
	AmmoID          whereHelpernull_String
	BaseURL         whereHelpernull_String
	OptionsRPS      whereHelpernull_Int
	OptionsSteps    whereHelpernull_Int
	OptionsDuration whereHelpernull_String
	CreatedAt       whereHelpertime_Time
	UpdatedAt       whereHelpernull_Time
	DeletedAt       whereHelpernull_Time
	Enabled         whereHelperbool
	GrafanaURL      whereHelpertypes_StringArray
	Tag             whereHelperstring
	ExprRPS         whereHelperstring
	SourceRPS       whereHelperstring
	CMTRPS          whereHelperstring
	ExprRT          whereHelperstring
	SourceRT        whereHelperstring
	CMTRT           whereHelperstring
	ExprErr         whereHelperstring
	SourceErr       whereHelperstring
	CMTErr          whereHelperstring
	AdditionalEnv   whereHelperstring
	Title           whereHelperstring
}{
	ScriptID:        whereHelperint32{field: "\"scripts\".\"script_id\""},
	Name:            whereHelperstring{field: "\"scripts\".\"name\""},
	Descrip:         whereHelpernull_String{field: "\"scripts\".\"descrip\""},
	ProjectID:       whereHelperint32{field: "\"scripts\".\"project_id\""},
	ScenarioID:      whereHelperint32{field: "\"scripts\".\"scenario_id\""},
	ScriptFile:      whereHelpernull_String{field: "\"scripts\".\"script_file\""},
	AmmoID:          whereHelpernull_String{field: "\"scripts\".\"ammo_id\""},
	BaseURL:         whereHelpernull_String{field: "\"scripts\".\"base_url\""},
	OptionsRPS:      whereHelpernull_Int{field: "\"scripts\".\"options_rps\""},
	OptionsSteps:    whereHelpernull_Int{field: "\"scripts\".\"options_steps\""},
	OptionsDuration: whereHelpernull_String{field: "\"scripts\".\"options_duration\""},
	CreatedAt:       whereHelpertime_Time{field: "\"scripts\".\"created_at\""},
	UpdatedAt:       whereHelpernull_Time{field: "\"scripts\".\"updated_at\""},
	DeletedAt:       whereHelpernull_Time{field: "\"scripts\".\"deleted_at\""},
	Enabled:         whereHelperbool{field: "\"scripts\".\"enabled\""},
	GrafanaURL:      whereHelpertypes_StringArray{field: "\"scripts\".\"grafana_url\""},
	Tag:             whereHelperstring{field: "\"scripts\".\"tag\""},
	ExprRPS:         whereHelperstring{field: "\"scripts\".\"expr_rps\""},
	SourceRPS:       whereHelperstring{field: "\"scripts\".\"source_rps\""},
	CMTRPS:          whereHelperstring{field: "\"scripts\".\"cmt_rps\""},
	ExprRT:          whereHelperstring{field: "\"scripts\".\"expr_rt\""},
	SourceRT:        whereHelperstring{field: "\"scripts\".\"source_rt\""},
	CMTRT:           whereHelperstring{field: "\"scripts\".\"cmt_rt\""},
	ExprErr:         whereHelperstring{field: "\"scripts\".\"expr_err\""},
	SourceErr:       whereHelperstring{field: "\"scripts\".\"source_err\""},
	CMTErr:          whereHelperstring{field: "\"scripts\".\"cmt_err\""},
	AdditionalEnv:   whereHelperstring{field: "\"scripts\".\"additional_env\""},
	Title:           whereHelperstring{field: "\"scripts\".\"title\""},
}

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

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

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

func (o *Script) GetScenario() *Scenario {
	if o == nil {
		return nil
	}

	return o.R.GetScenario()
}

func (r *scriptR) GetScenario() *Scenario {
	if r == nil {
		return nil
	}

	return r.Scenario
}

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

var (
	scriptAllColumns            = []string{"script_id", "name", "descrip", "project_id", "scenario_id", "script_file", "ammo_id", "base_url", "options_rps", "options_steps", "options_duration", "created_at", "updated_at", "deleted_at", "enabled", "grafana_url", "tag", "expr_rps", "source_rps", "cmt_rps", "expr_rt", "source_rt", "cmt_rt", "expr_err", "source_err", "cmt_err", "additional_env", "title"}
	scriptColumnsWithoutDefault = []string{"name", "project_id", "scenario_id", "title"}
	scriptColumnsWithDefault    = []string{"script_id", "descrip", "script_file", "ammo_id", "base_url", "options_rps", "options_steps", "options_duration", "created_at", "updated_at", "deleted_at", "enabled", "grafana_url", "tag", "expr_rps", "source_rps", "cmt_rps", "expr_rt", "source_rt", "cmt_rt", "expr_err", "source_err", "cmt_err", "additional_env"}
	scriptPrimaryKeyColumns     = []string{"script_id"}
	scriptGeneratedColumns      = []string{}
)

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

	scriptQuery struct {
		*queries.Query
	}
)

// Cache for insert, update and upsert
var (
	scriptType                 = reflect.TypeOf(&Script{})
	scriptMapping              = queries.MakeStructMapping(scriptType)
	scriptPrimaryKeyMapping, _ = queries.BindMapping(scriptType, scriptMapping, scriptPrimaryKeyColumns)
	scriptInsertCacheMut       sync.RWMutex
	scriptInsertCache          = make(map[string]insertCache)
	scriptUpdateCacheMut       sync.RWMutex
	scriptUpdateCache          = make(map[string]updateCache)
	scriptUpsertCacheMut       sync.RWMutex
	scriptUpsertCache          = 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 scriptAfterSelectMu sync.Mutex
var scriptAfterSelectHooks []ScriptHook

var scriptBeforeInsertMu sync.Mutex
var scriptBeforeInsertHooks []ScriptHook
var scriptAfterInsertMu sync.Mutex
var scriptAfterInsertHooks []ScriptHook

var scriptBeforeUpdateMu sync.Mutex
var scriptBeforeUpdateHooks []ScriptHook
var scriptAfterUpdateMu sync.Mutex
var scriptAfterUpdateHooks []ScriptHook

var scriptBeforeDeleteMu sync.Mutex
var scriptBeforeDeleteHooks []ScriptHook
var scriptAfterDeleteMu sync.Mutex
var scriptAfterDeleteHooks []ScriptHook

var scriptBeforeUpsertMu sync.Mutex
var scriptBeforeUpsertHooks []ScriptHook
var scriptAfterUpsertMu sync.Mutex
var scriptAfterUpsertHooks []ScriptHook

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

// AddScriptHook registers your hook function for all future operations.
func AddScriptHook(hookPoint boil.HookPoint, scriptHook ScriptHook) {
	switch hookPoint {
	case boil.AfterSelectHook:
		scriptAfterSelectMu.Lock()
		scriptAfterSelectHooks = append(scriptAfterSelectHooks, scriptHook)
		scriptAfterSelectMu.Unlock()
	case boil.BeforeInsertHook:
		scriptBeforeInsertMu.Lock()
		scriptBeforeInsertHooks = append(scriptBeforeInsertHooks, scriptHook)
		scriptBeforeInsertMu.Unlock()
	case boil.AfterInsertHook:
		scriptAfterInsertMu.Lock()
		scriptAfterInsertHooks = append(scriptAfterInsertHooks, scriptHook)
		scriptAfterInsertMu.Unlock()
	case boil.BeforeUpdateHook:
		scriptBeforeUpdateMu.Lock()
		scriptBeforeUpdateHooks = append(scriptBeforeUpdateHooks, scriptHook)
		scriptBeforeUpdateMu.Unlock()
	case boil.AfterUpdateHook:
		scriptAfterUpdateMu.Lock()
		scriptAfterUpdateHooks = append(scriptAfterUpdateHooks, scriptHook)
		scriptAfterUpdateMu.Unlock()
	case boil.BeforeDeleteHook:
		scriptBeforeDeleteMu.Lock()
		scriptBeforeDeleteHooks = append(scriptBeforeDeleteHooks, scriptHook)
		scriptBeforeDeleteMu.Unlock()
	case boil.AfterDeleteHook:
		scriptAfterDeleteMu.Lock()
		scriptAfterDeleteHooks = append(scriptAfterDeleteHooks, scriptHook)
		scriptAfterDeleteMu.Unlock()
	case boil.BeforeUpsertHook:
		scriptBeforeUpsertMu.Lock()
		scriptBeforeUpsertHooks = append(scriptBeforeUpsertHooks, scriptHook)
		scriptBeforeUpsertMu.Unlock()
	case boil.AfterUpsertHook:
		scriptAfterUpsertMu.Lock()
		scriptAfterUpsertHooks = append(scriptAfterUpsertHooks, scriptHook)
		scriptAfterUpsertMu.Unlock()
	}
}

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

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

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

	return o, nil
}

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

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

	if len(scriptAfterSelectHooks) != 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 Script records in the query.
func (q scriptQuery) 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 scripts rows")
	}

	return count, nil
}

// Exists checks if the row exists in the table.
func (q scriptQuery) 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 scripts exists")
	}

	return count > 0, nil
}

// Scenario pointed to by the foreign key.
func (o *Script) Scenario(mods ...qm.QueryMod) scenarioQuery {
	queryMods := []qm.QueryMod{
		qm.Where("\"scenario_id\" = ?", o.ScenarioID),
	}

	queryMods = append(queryMods, mods...)

	return Scenarios(queryMods...)
}

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

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

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

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

			args[obj.ScenarioID] = 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(`scenarios`),
		qm.WhereIn(`scenarios.scenario_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 Scenario")
	}

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

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

	if len(scenarioAfterSelectHooks) != 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.Scenario = foreign
		if foreign.R == nil {
			foreign.R = &scenarioR{}
		}
		foreign.R.Scripts = append(foreign.R.Scripts, object)
		return nil
	}

	for _, local := range slice {
		for _, foreign := range resultSlice {
			if local.ScenarioID == foreign.ScenarioID {
				local.R.Scenario = foreign
				if foreign.R == nil {
					foreign.R = &scenarioR{}
				}
				foreign.R.Scripts = append(foreign.R.Scripts, local)
				break
			}
		}
	}

	return nil
}

// SetScenario of the script to the related item.
// Sets o.R.Scenario to related.
// Adds o to related.R.Scripts.
func (o *Script) SetScenario(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Scenario) 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 \"scripts\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 1, []string{"scenario_id"}),
		strmangle.WhereClause("\"", "\"", 2, scriptPrimaryKeyColumns),
	)
	values := []interface{}{related.ScenarioID, o.ScriptID}

	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.ScenarioID = related.ScenarioID
	if o.R == nil {
		o.R = &scriptR{
			Scenario: related,
		}
	} else {
		o.R.Scenario = related
	}

	if related.R == nil {
		related.R = &scenarioR{
			Scripts: ScriptSlice{o},
		}
	} else {
		related.R.Scripts = append(related.R.Scripts, o)
	}

	return nil
}

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

	return scriptQuery{q}
}

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

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

	q := queries.Raw(query, scriptID)

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

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

	return scriptObj, nil
}

// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *Script) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
	if o == nil {
		return errors.New("models: no scripts 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(scriptColumnsWithDefault, o)

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

	if !cached {
		wl, returnColumns := columns.InsertColumnSet(
			scriptAllColumns,
			scriptColumnsWithDefault,
			scriptColumnsWithoutDefault,
			nzDefaults,
		)

		cache.valueMapping, err = queries.BindMapping(scriptType, scriptMapping, wl)
		if err != nil {
			return err
		}
		cache.retMapping, err = queries.BindMapping(scriptType, scriptMapping, returnColumns)
		if err != nil {
			return err
		}
		if len(wl) != 0 {
			cache.query = fmt.Sprintf("INSERT INTO \"scripts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
		} else {
			cache.query = "INSERT INTO \"scripts\" %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 scripts")
	}

	if !cached {
		scriptInsertCacheMut.Lock()
		scriptInsertCache[key] = cache
		scriptInsertCacheMut.Unlock()
	}

	return o.doAfterInsertHooks(ctx, exec)
}

// Update uses an executor to update the Script.
// 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 *Script) 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)
	scriptUpdateCacheMut.RLock()
	cache, cached := scriptUpdateCache[key]
	scriptUpdateCacheMut.RUnlock()

	if !cached {
		wl := columns.UpdateColumnSet(
			scriptAllColumns,
			scriptPrimaryKeyColumns,
		)

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

		cache.query = fmt.Sprintf("UPDATE \"scripts\" SET %s WHERE %s",
			strmangle.SetParamNames("\"", "\"", 1, wl),
			strmangle.WhereClause("\"", "\"", len(wl)+1, scriptPrimaryKeyColumns),
		)
		cache.valueMapping, err = queries.BindMapping(scriptType, scriptMapping, append(wl, scriptPrimaryKeyColumns...))
		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 scripts row")
	}

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

	if !cached {
		scriptUpdateCacheMut.Lock()
		scriptUpdateCache[key] = cache
		scriptUpdateCacheMut.Unlock()
	}

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

// UpdateAll updates all rows with the specified column values.
func (q scriptQuery) 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 scripts")
	}

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

	return rowsAff, nil
}

// UpdateAll updates all rows with the specified column values, using an executor.
func (o ScriptSlice) 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)), scriptPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := fmt.Sprintf("UPDATE \"scripts\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 1, colNames),
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, scriptPrimaryKeyColumns, 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 script slice")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all script")
	}
	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 *Script) 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 scripts 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(scriptColumnsWithDefault, 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)

	scriptUpsertCacheMut.RLock()
	cache, cached := scriptUpsertCache[key]
	scriptUpsertCacheMut.RUnlock()

	var err error

	if !cached {
		insert, _ := insertColumns.InsertColumnSet(
			scriptAllColumns,
			scriptColumnsWithDefault,
			scriptColumnsWithoutDefault,
			nzDefaults,
		)

		update := updateColumns.UpdateColumnSet(
			scriptAllColumns,
			scriptPrimaryKeyColumns,
		)

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

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

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

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

		cache.valueMapping, err = queries.BindMapping(scriptType, scriptMapping, insert)
		if err != nil {
			return err
		}
		if len(ret) != 0 {
			cache.retMapping, err = queries.BindMapping(scriptType, scriptMapping, 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 scripts")
	}

	if !cached {
		scriptUpsertCacheMut.Lock()
		scriptUpsertCache[key] = cache
		scriptUpsertCacheMut.Unlock()
	}

	return o.doAfterUpsertHooks(ctx, exec)
}

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

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

	args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), scriptPrimaryKeyMapping)
	sql := "DELETE FROM \"scripts\" WHERE \"script_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 scripts")
	}

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

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

	return rowsAff, nil
}

// DeleteAll deletes all matching rows.
func (q scriptQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if q.Query == nil {
		return 0, errors.New("models: no scriptQuery 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 scripts")
	}

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

	return rowsAff, nil
}

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

	if len(scriptBeforeDeleteHooks) != 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)), scriptPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := "DELETE FROM \"scripts\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, scriptPrimaryKeyColumns, 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 script slice")
	}

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

	if len(scriptAfterDeleteHooks) != 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 *Script) Reload(ctx context.Context, exec boil.ContextExecutor) error {
	ret, err := FindScript(ctx, exec, o.ScriptID)
	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 *ScriptSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
	if o == nil || len(*o) == 0 {
		return nil
	}

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

	sql := "SELECT \"scripts\".* FROM \"scripts\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, scriptPrimaryKeyColumns, 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 ScriptSlice")
	}

	*o = slice

	return nil
}

// ScriptExists checks if the Script row exists.
func ScriptExists(ctx context.Context, exec boil.ContextExecutor, scriptID int32) (bool, error) {
	var exists bool
	sql := "select exists(select 1 from \"scripts\" where \"script_id\"=$1 limit 1)"

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

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

	return exists, nil
}

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