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

// Statistic is an object representing the database table.
type Statistic struct {
	StatisticID            int32             `boil:"statistic_id" json:"statistic_id" toml:"statistic_id" yaml:"statistic_id"`
	StatisticDumpID        int32             `boil:"statistic_dump_id" json:"statistic_dump_id" toml:"statistic_dump_id" yaml:"statistic_dump_id"`
	URLPath                string            `boil:"url_path" json:"url_path" toml:"url_path" yaml:"url_path"`
	URLMethod              string            `boil:"url_method" json:"url_method" toml:"url_method" yaml:"url_method"`
	ProjectIds             types.Int64Array  `boil:"project_ids" json:"project_ids" toml:"project_ids" yaml:"project_ids"`
	ScenarioIds            types.Int64Array  `boil:"scenario_ids" json:"scenario_ids" toml:"scenario_ids" yaml:"scenario_ids"`
	RunIds                 types.Int64Array  `boil:"run_ids" json:"run_ids" toml:"run_ids" yaml:"run_ids"`
	ScriptRunIds           types.Int64Array  `boil:"script_run_ids" json:"script_run_ids" toml:"script_run_ids" yaml:"script_run_ids"`
	ScriptIds              types.Int64Array  `boil:"script_ids" json:"script_ids" toml:"script_ids" yaml:"script_ids"`
	TraceIds               types.StringArray `boil:"trace_ids" json:"trace_ids" toml:"trace_ids" yaml:"trace_ids"`
	Agents                 types.StringArray `boil:"agents" json:"agents" toml:"agents" yaml:"agents"`
	RPS                    int32             `boil:"rps" json:"rps" toml:"rps" yaml:"rps"`
	RT90P                  int32             `boil:"rt_90_p" json:"rt_90_p" toml:"rt_90_p" yaml:"rt_90_p"`
	RT95P                  int32             `boil:"rt_95_p" json:"rt_95_p" toml:"rt_95_p" yaml:"rt_95_p"`
	RT99P                  int32             `boil:"rt_99_p" json:"rt_99_p" toml:"rt_99_p" yaml:"rt_99_p"`
	RTMax                  int32             `boil:"rt_max" json:"rt_max" toml:"rt_max" yaml:"rt_max"`
	Vus                    int32             `boil:"vus" json:"vus" toml:"vus" yaml:"vus"`
	Failed                 int32             `boil:"failed" json:"failed" toml:"failed" yaml:"failed"`
	DataSent               int32             `boil:"data_sent" json:"data_sent" toml:"data_sent" yaml:"data_sent"`
	DataReceived           int32             `boil:"data_received" json:"data_received" toml:"data_received" yaml:"data_received"`
	CurrentTestRunDuration string            `boil:"current_test_run_duration" json:"current_test_run_duration" toml:"current_test_run_duration" yaml:"current_test_run_duration"`

	R *statisticR `boil:"-" json:"-" toml:"-" yaml:"-"`
	L statisticL  `boil:"-" json:"-" toml:"-" yaml:"-"`
}

var StatisticColumns = struct {
	StatisticID            string
	StatisticDumpID        string
	URLPath                string
	URLMethod              string
	ProjectIds             string
	ScenarioIds            string
	RunIds                 string
	ScriptRunIds           string
	ScriptIds              string
	TraceIds               string
	Agents                 string
	RPS                    string
	RT90P                  string
	RT95P                  string
	RT99P                  string
	RTMax                  string
	Vus                    string
	Failed                 string
	DataSent               string
	DataReceived           string
	CurrentTestRunDuration string
}{
	StatisticID:            "statistic_id",
	StatisticDumpID:        "statistic_dump_id",
	URLPath:                "url_path",
	URLMethod:              "url_method",
	ProjectIds:             "project_ids",
	ScenarioIds:            "scenario_ids",
	RunIds:                 "run_ids",
	ScriptRunIds:           "script_run_ids",
	ScriptIds:              "script_ids",
	TraceIds:               "trace_ids",
	Agents:                 "agents",
	RPS:                    "rps",
	RT90P:                  "rt_90_p",
	RT95P:                  "rt_95_p",
	RT99P:                  "rt_99_p",
	RTMax:                  "rt_max",
	Vus:                    "vus",
	Failed:                 "failed",
	DataSent:               "data_sent",
	DataReceived:           "data_received",
	CurrentTestRunDuration: "current_test_run_duration",
}

var StatisticTableColumns = struct {
	StatisticID            string
	StatisticDumpID        string
	URLPath                string
	URLMethod              string
	ProjectIds             string
	ScenarioIds            string
	RunIds                 string
	ScriptRunIds           string
	ScriptIds              string
	TraceIds               string
	Agents                 string
	RPS                    string
	RT90P                  string
	RT95P                  string
	RT99P                  string
	RTMax                  string
	Vus                    string
	Failed                 string
	DataSent               string
	DataReceived           string
	CurrentTestRunDuration string
}{
	StatisticID:            "statistic.statistic_id",
	StatisticDumpID:        "statistic.statistic_dump_id",
	URLPath:                "statistic.url_path",
	URLMethod:              "statistic.url_method",
	ProjectIds:             "statistic.project_ids",
	ScenarioIds:            "statistic.scenario_ids",
	RunIds:                 "statistic.run_ids",
	ScriptRunIds:           "statistic.script_run_ids",
	ScriptIds:              "statistic.script_ids",
	TraceIds:               "statistic.trace_ids",
	Agents:                 "statistic.agents",
	RPS:                    "statistic.rps",
	RT90P:                  "statistic.rt_90_p",
	RT95P:                  "statistic.rt_95_p",
	RT99P:                  "statistic.rt_99_p",
	RTMax:                  "statistic.rt_max",
	Vus:                    "statistic.vus",
	Failed:                 "statistic.failed",
	DataSent:               "statistic.data_sent",
	DataReceived:           "statistic.data_received",
	CurrentTestRunDuration: "statistic.current_test_run_duration",
}

// Generated where

var StatisticWhere = struct {
	StatisticID            whereHelperint32
	StatisticDumpID        whereHelperint32
	URLPath                whereHelperstring
	URLMethod              whereHelperstring
	ProjectIds             whereHelpertypes_Int64Array
	ScenarioIds            whereHelpertypes_Int64Array
	RunIds                 whereHelpertypes_Int64Array
	ScriptRunIds           whereHelpertypes_Int64Array
	ScriptIds              whereHelpertypes_Int64Array
	TraceIds               whereHelpertypes_StringArray
	Agents                 whereHelpertypes_StringArray
	RPS                    whereHelperint32
	RT90P                  whereHelperint32
	RT95P                  whereHelperint32
	RT99P                  whereHelperint32
	RTMax                  whereHelperint32
	Vus                    whereHelperint32
	Failed                 whereHelperint32
	DataSent               whereHelperint32
	DataReceived           whereHelperint32
	CurrentTestRunDuration whereHelperstring
}{
	StatisticID:            whereHelperint32{field: "\"statistic\".\"statistic_id\""},
	StatisticDumpID:        whereHelperint32{field: "\"statistic\".\"statistic_dump_id\""},
	URLPath:                whereHelperstring{field: "\"statistic\".\"url_path\""},
	URLMethod:              whereHelperstring{field: "\"statistic\".\"url_method\""},
	ProjectIds:             whereHelpertypes_Int64Array{field: "\"statistic\".\"project_ids\""},
	ScenarioIds:            whereHelpertypes_Int64Array{field: "\"statistic\".\"scenario_ids\""},
	RunIds:                 whereHelpertypes_Int64Array{field: "\"statistic\".\"run_ids\""},
	ScriptRunIds:           whereHelpertypes_Int64Array{field: "\"statistic\".\"script_run_ids\""},
	ScriptIds:              whereHelpertypes_Int64Array{field: "\"statistic\".\"script_ids\""},
	TraceIds:               whereHelpertypes_StringArray{field: "\"statistic\".\"trace_ids\""},
	Agents:                 whereHelpertypes_StringArray{field: "\"statistic\".\"agents\""},
	RPS:                    whereHelperint32{field: "\"statistic\".\"rps\""},
	RT90P:                  whereHelperint32{field: "\"statistic\".\"rt_90_p\""},
	RT95P:                  whereHelperint32{field: "\"statistic\".\"rt_95_p\""},
	RT99P:                  whereHelperint32{field: "\"statistic\".\"rt_99_p\""},
	RTMax:                  whereHelperint32{field: "\"statistic\".\"rt_max\""},
	Vus:                    whereHelperint32{field: "\"statistic\".\"vus\""},
	Failed:                 whereHelperint32{field: "\"statistic\".\"failed\""},
	DataSent:               whereHelperint32{field: "\"statistic\".\"data_sent\""},
	DataReceived:           whereHelperint32{field: "\"statistic\".\"data_received\""},
	CurrentTestRunDuration: whereHelperstring{field: "\"statistic\".\"current_test_run_duration\""},
}

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

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

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

func (o *Statistic) GetStatisticDump() *StatisticDump {
	if o == nil {
		return nil
	}

	return o.R.GetStatisticDump()
}

func (r *statisticR) GetStatisticDump() *StatisticDump {
	if r == nil {
		return nil
	}

	return r.StatisticDump
}

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

var (
	statisticAllColumns            = []string{"statistic_id", "statistic_dump_id", "url_path", "url_method", "project_ids", "scenario_ids", "run_ids", "script_run_ids", "script_ids", "trace_ids", "agents", "rps", "rt_90_p", "rt_95_p", "rt_99_p", "rt_max", "vus", "failed", "data_sent", "data_received", "current_test_run_duration"}
	statisticColumnsWithoutDefault = []string{"statistic_dump_id", "url_path", "url_method", "rps", "rt_90_p", "rt_95_p", "rt_99_p", "rt_max", "vus", "failed", "data_sent", "data_received", "current_test_run_duration"}
	statisticColumnsWithDefault    = []string{"statistic_id", "project_ids", "scenario_ids", "run_ids", "script_run_ids", "script_ids", "trace_ids", "agents"}
	statisticPrimaryKeyColumns     = []string{"statistic_id"}
	statisticGeneratedColumns      = []string{}
)

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

	statisticQuery struct {
		*queries.Query
	}
)

// Cache for insert, update and upsert
var (
	statisticType                 = reflect.TypeOf(&Statistic{})
	statisticMapping              = queries.MakeStructMapping(statisticType)
	statisticPrimaryKeyMapping, _ = queries.BindMapping(statisticType, statisticMapping, statisticPrimaryKeyColumns)
	statisticInsertCacheMut       sync.RWMutex
	statisticInsertCache          = make(map[string]insertCache)
	statisticUpdateCacheMut       sync.RWMutex
	statisticUpdateCache          = make(map[string]updateCache)
	statisticUpsertCacheMut       sync.RWMutex
	statisticUpsertCache          = 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 statisticAfterSelectMu sync.Mutex
var statisticAfterSelectHooks []StatisticHook

var statisticBeforeInsertMu sync.Mutex
var statisticBeforeInsertHooks []StatisticHook
var statisticAfterInsertMu sync.Mutex
var statisticAfterInsertHooks []StatisticHook

var statisticBeforeUpdateMu sync.Mutex
var statisticBeforeUpdateHooks []StatisticHook
var statisticAfterUpdateMu sync.Mutex
var statisticAfterUpdateHooks []StatisticHook

var statisticBeforeDeleteMu sync.Mutex
var statisticBeforeDeleteHooks []StatisticHook
var statisticAfterDeleteMu sync.Mutex
var statisticAfterDeleteHooks []StatisticHook

var statisticBeforeUpsertMu sync.Mutex
var statisticBeforeUpsertHooks []StatisticHook
var statisticAfterUpsertMu sync.Mutex
var statisticAfterUpsertHooks []StatisticHook

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

// AddStatisticHook registers your hook function for all future operations.
func AddStatisticHook(hookPoint boil.HookPoint, statisticHook StatisticHook) {
	switch hookPoint {
	case boil.AfterSelectHook:
		statisticAfterSelectMu.Lock()
		statisticAfterSelectHooks = append(statisticAfterSelectHooks, statisticHook)
		statisticAfterSelectMu.Unlock()
	case boil.BeforeInsertHook:
		statisticBeforeInsertMu.Lock()
		statisticBeforeInsertHooks = append(statisticBeforeInsertHooks, statisticHook)
		statisticBeforeInsertMu.Unlock()
	case boil.AfterInsertHook:
		statisticAfterInsertMu.Lock()
		statisticAfterInsertHooks = append(statisticAfterInsertHooks, statisticHook)
		statisticAfterInsertMu.Unlock()
	case boil.BeforeUpdateHook:
		statisticBeforeUpdateMu.Lock()
		statisticBeforeUpdateHooks = append(statisticBeforeUpdateHooks, statisticHook)
		statisticBeforeUpdateMu.Unlock()
	case boil.AfterUpdateHook:
		statisticAfterUpdateMu.Lock()
		statisticAfterUpdateHooks = append(statisticAfterUpdateHooks, statisticHook)
		statisticAfterUpdateMu.Unlock()
	case boil.BeforeDeleteHook:
		statisticBeforeDeleteMu.Lock()
		statisticBeforeDeleteHooks = append(statisticBeforeDeleteHooks, statisticHook)
		statisticBeforeDeleteMu.Unlock()
	case boil.AfterDeleteHook:
		statisticAfterDeleteMu.Lock()
		statisticAfterDeleteHooks = append(statisticAfterDeleteHooks, statisticHook)
		statisticAfterDeleteMu.Unlock()
	case boil.BeforeUpsertHook:
		statisticBeforeUpsertMu.Lock()
		statisticBeforeUpsertHooks = append(statisticBeforeUpsertHooks, statisticHook)
		statisticBeforeUpsertMu.Unlock()
	case boil.AfterUpsertHook:
		statisticAfterUpsertMu.Lock()
		statisticAfterUpsertHooks = append(statisticAfterUpsertHooks, statisticHook)
		statisticAfterUpsertMu.Unlock()
	}
}

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

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

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

	return o, nil
}

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

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

	if len(statisticAfterSelectHooks) != 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 Statistic records in the query.
func (q statisticQuery) 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 statistic rows")
	}

	return count, nil
}

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

	return count > 0, nil
}

// StatisticDump pointed to by the foreign key.
func (o *Statistic) StatisticDump(mods ...qm.QueryMod) statisticDumpQuery {
	queryMods := []qm.QueryMod{
		qm.Where("\"statistic_dump_id\" = ?", o.StatisticDumpID),
	}

	queryMods = append(queryMods, mods...)

	return StatisticDumps(queryMods...)
}

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

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

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

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

			args[obj.StatisticDumpID] = 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(`statistic_dump`),
		qm.WhereIn(`statistic_dump.statistic_dump_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 StatisticDump")
	}

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

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

	if len(statisticDumpAfterSelectHooks) != 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.StatisticDump = foreign
		if foreign.R == nil {
			foreign.R = &statisticDumpR{}
		}
		foreign.R.Statistics = append(foreign.R.Statistics, object)
		return nil
	}

	for _, local := range slice {
		for _, foreign := range resultSlice {
			if local.StatisticDumpID == foreign.StatisticDumpID {
				local.R.StatisticDump = foreign
				if foreign.R == nil {
					foreign.R = &statisticDumpR{}
				}
				foreign.R.Statistics = append(foreign.R.Statistics, local)
				break
			}
		}
	}

	return nil
}

// SetStatisticDump of the statistic to the related item.
// Sets o.R.StatisticDump to related.
// Adds o to related.R.Statistics.
func (o *Statistic) SetStatisticDump(ctx context.Context, exec boil.ContextExecutor, insert bool, related *StatisticDump) 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 \"statistic\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 1, []string{"statistic_dump_id"}),
		strmangle.WhereClause("\"", "\"", 2, statisticPrimaryKeyColumns),
	)
	values := []interface{}{related.StatisticDumpID, o.StatisticID}

	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.StatisticDumpID = related.StatisticDumpID
	if o.R == nil {
		o.R = &statisticR{
			StatisticDump: related,
		}
	} else {
		o.R.StatisticDump = related
	}

	if related.R == nil {
		related.R = &statisticDumpR{
			Statistics: StatisticSlice{o},
		}
	} else {
		related.R.Statistics = append(related.R.Statistics, o)
	}

	return nil
}

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

	return statisticQuery{q}
}

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

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

	q := queries.Raw(query, statisticID)

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

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

	return statisticObj, nil
}

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

	var err error

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

	nzDefaults := queries.NonZeroDefaultSet(statisticColumnsWithDefault, o)

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

	if !cached {
		wl, returnColumns := columns.InsertColumnSet(
			statisticAllColumns,
			statisticColumnsWithDefault,
			statisticColumnsWithoutDefault,
			nzDefaults,
		)

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

	if !cached {
		statisticInsertCacheMut.Lock()
		statisticInsertCache[key] = cache
		statisticInsertCacheMut.Unlock()
	}

	return o.doAfterInsertHooks(ctx, exec)
}

// Update uses an executor to update the Statistic.
// 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 *Statistic) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
	var err error
	if err = o.doBeforeUpdateHooks(ctx, exec); err != nil {
		return 0, err
	}
	key := makeCacheKey(columns, nil)
	statisticUpdateCacheMut.RLock()
	cache, cached := statisticUpdateCache[key]
	statisticUpdateCacheMut.RUnlock()

	if !cached {
		wl := columns.UpdateColumnSet(
			statisticAllColumns,
			statisticPrimaryKeyColumns,
		)

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

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

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

	if !cached {
		statisticUpdateCacheMut.Lock()
		statisticUpdateCache[key] = cache
		statisticUpdateCacheMut.Unlock()
	}

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

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

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

	return rowsAff, nil
}

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

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

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

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

	nzDefaults := queries.NonZeroDefaultSet(statisticColumnsWithDefault, 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)

	statisticUpsertCacheMut.RLock()
	cache, cached := statisticUpsertCache[key]
	statisticUpsertCacheMut.RUnlock()

	var err error

	if !cached {
		insert, _ := insertColumns.InsertColumnSet(
			statisticAllColumns,
			statisticColumnsWithDefault,
			statisticColumnsWithoutDefault,
			nzDefaults,
		)

		update := updateColumns.UpdateColumnSet(
			statisticAllColumns,
			statisticPrimaryKeyColumns,
		)

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

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

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

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

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

	if !cached {
		statisticUpsertCacheMut.Lock()
		statisticUpsertCache[key] = cache
		statisticUpsertCacheMut.Unlock()
	}

	return o.doAfterUpsertHooks(ctx, exec)
}

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

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

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

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

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

	return rowsAff, nil
}

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

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

	return rowsAff, nil
}

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

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

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

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

	if len(statisticAfterDeleteHooks) != 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 *Statistic) Reload(ctx context.Context, exec boil.ContextExecutor) error {
	ret, err := FindStatistic(ctx, exec, o.StatisticID)
	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 *StatisticSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
	if o == nil || len(*o) == 0 {
		return nil
	}

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

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

	*o = slice

	return nil
}

// StatisticExists checks if the Statistic row exists.
func StatisticExists(ctx context.Context, exec boil.ContextExecutor, statisticID int32) (bool, error) {
	var exists bool
	sql := "select exists(select 1 from \"statistic\" where \"statistic_id\"=$1 limit 1)"

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

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

	return exists, nil
}

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