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

// Agent is an object representing the database table.
type Agent struct {
	AgentID      int32             `boil:"agent_id" json:"agent_id" toml:"agent_id" yaml:"agent_id"`
	HostName     string            `boil:"host_name" json:"host_name" toml:"host_name" yaml:"host_name"`
	Port         string            `boil:"port" json:"port" toml:"port" yaml:"port"`
	Enabled      bool              `boil:"enabled" json:"enabled" toml:"enabled" yaml:"enabled"`
	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"`
	Tags         types.StringArray `boil:"tags" json:"tags" toml:"tags" yaml:"tags"`
	CPUUsed      int32             `boil:"cpu_used" json:"cpu_used" toml:"cpu_used" yaml:"cpu_used"`
	MemUsed      int32             `boil:"mem_used" json:"mem_used" toml:"mem_used" yaml:"mem_used"`
	PortsUsed    int32             `boil:"ports_used" json:"ports_used" toml:"ports_used" yaml:"ports_used"`
	TotalLoading int16             `boil:"total_loading" json:"total_loading" toml:"total_loading" yaml:"total_loading"`

	R *agentR `boil:"-" json:"-" toml:"-" yaml:"-"`
	L agentL  `boil:"-" json:"-" toml:"-" yaml:"-"`
}

var AgentColumns = struct {
	AgentID      string
	HostName     string
	Port         string
	Enabled      string
	CreatedAt    string
	UpdatedAt    string
	DeletedAt    string
	Tags         string
	CPUUsed      string
	MemUsed      string
	PortsUsed    string
	TotalLoading string
}{
	AgentID:      "agent_id",
	HostName:     "host_name",
	Port:         "port",
	Enabled:      "enabled",
	CreatedAt:    "created_at",
	UpdatedAt:    "updated_at",
	DeletedAt:    "deleted_at",
	Tags:         "tags",
	CPUUsed:      "cpu_used",
	MemUsed:      "mem_used",
	PortsUsed:    "ports_used",
	TotalLoading: "total_loading",
}

var AgentTableColumns = struct {
	AgentID      string
	HostName     string
	Port         string
	Enabled      string
	CreatedAt    string
	UpdatedAt    string
	DeletedAt    string
	Tags         string
	CPUUsed      string
	MemUsed      string
	PortsUsed    string
	TotalLoading string
}{
	AgentID:      "agent.agent_id",
	HostName:     "agent.host_name",
	Port:         "agent.port",
	Enabled:      "agent.enabled",
	CreatedAt:    "agent.created_at",
	UpdatedAt:    "agent.updated_at",
	DeletedAt:    "agent.deleted_at",
	Tags:         "agent.tags",
	CPUUsed:      "agent.cpu_used",
	MemUsed:      "agent.mem_used",
	PortsUsed:    "agent.ports_used",
	TotalLoading: "agent.total_loading",
}

// Generated where

type whereHelperint32 struct{ field string }

func (w whereHelperint32) EQ(x int32) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperint32) NEQ(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperint32) LT(x int32) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperint32) LTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperint32) GT(x int32) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperint32) GTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperint32) 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 whereHelperint32) 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...)
}

type whereHelperstring struct{ field string }

func (w whereHelperstring) EQ(x string) qm.QueryMod      { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperstring) NEQ(x string) qm.QueryMod     { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperstring) LT(x string) qm.QueryMod      { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperstring) LTE(x string) qm.QueryMod     { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperstring) GT(x string) qm.QueryMod      { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperstring) GTE(x string) qm.QueryMod     { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperstring) LIKE(x string) qm.QueryMod    { return qm.Where(w.field+" LIKE ?", x) }
func (w whereHelperstring) NLIKE(x string) qm.QueryMod   { return qm.Where(w.field+" NOT LIKE ?", x) }
func (w whereHelperstring) ILIKE(x string) qm.QueryMod   { return qm.Where(w.field+" ILIKE ?", x) }
func (w whereHelperstring) NILIKE(x string) qm.QueryMod  { return qm.Where(w.field+" NOT ILIKE ?", x) }
func (w whereHelperstring) SIMILAR(x string) qm.QueryMod { return qm.Where(w.field+" SIMILAR TO ?", x) }
func (w whereHelperstring) NSIMILAR(x string) qm.QueryMod {
	return qm.Where(w.field+" NOT SIMILAR TO ?", x)
}
func (w whereHelperstring) IN(slice []string) 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 whereHelperstring) NIN(slice []string) 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...)
}

type whereHelperbool struct{ field string }

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

type whereHelpertime_Time struct{ field string }

func (w whereHelpertime_Time) EQ(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.EQ, x)
}
func (w whereHelpertime_Time) NEQ(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.NEQ, x)
}
func (w whereHelpertime_Time) LT(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LT, x)
}
func (w whereHelpertime_Time) LTE(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LTE, x)
}
func (w whereHelpertime_Time) GT(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GT, x)
}
func (w whereHelpertime_Time) GTE(x time.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GTE, x)
}

type whereHelpernull_Time struct{ field string }

func (w whereHelpernull_Time) EQ(x null.Time) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, false, x)
}
func (w whereHelpernull_Time) NEQ(x null.Time) qm.QueryMod {
	return qmhelper.WhereNullEQ(w.field, true, x)
}
func (w whereHelpernull_Time) LT(x null.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LT, x)
}
func (w whereHelpernull_Time) LTE(x null.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.LTE, x)
}
func (w whereHelpernull_Time) GT(x null.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GT, x)
}
func (w whereHelpernull_Time) GTE(x null.Time) qm.QueryMod {
	return qmhelper.Where(w.field, qmhelper.GTE, x)
}

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

type whereHelpertypes_StringArray struct{ field string }

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

type whereHelperint16 struct{ field string }

func (w whereHelperint16) EQ(x int16) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperint16) NEQ(x int16) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperint16) LT(x int16) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperint16) LTE(x int16) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperint16) GT(x int16) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperint16) GTE(x int16) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperint16) IN(slice []int16) 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 whereHelperint16) NIN(slice []int16) 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...)
}

var AgentWhere = struct {
	AgentID      whereHelperint32
	HostName     whereHelperstring
	Port         whereHelperstring
	Enabled      whereHelperbool
	CreatedAt    whereHelpertime_Time
	UpdatedAt    whereHelpernull_Time
	DeletedAt    whereHelpernull_Time
	Tags         whereHelpertypes_StringArray
	CPUUsed      whereHelperint32
	MemUsed      whereHelperint32
	PortsUsed    whereHelperint32
	TotalLoading whereHelperint16
}{
	AgentID:      whereHelperint32{field: "\"agent\".\"agent_id\""},
	HostName:     whereHelperstring{field: "\"agent\".\"host_name\""},
	Port:         whereHelperstring{field: "\"agent\".\"port\""},
	Enabled:      whereHelperbool{field: "\"agent\".\"enabled\""},
	CreatedAt:    whereHelpertime_Time{field: "\"agent\".\"created_at\""},
	UpdatedAt:    whereHelpernull_Time{field: "\"agent\".\"updated_at\""},
	DeletedAt:    whereHelpernull_Time{field: "\"agent\".\"deleted_at\""},
	Tags:         whereHelpertypes_StringArray{field: "\"agent\".\"tags\""},
	CPUUsed:      whereHelperint32{field: "\"agent\".\"cpu_used\""},
	MemUsed:      whereHelperint32{field: "\"agent\".\"mem_used\""},
	PortsUsed:    whereHelperint32{field: "\"agent\".\"ports_used\""},
	TotalLoading: whereHelperint16{field: "\"agent\".\"total_loading\""},
}

// AgentRels is where relationship names are stored.
var AgentRels = struct {
}{}

// agentR is where relationships are stored.
type agentR struct {
}

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

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

var (
	agentAllColumns            = []string{"agent_id", "host_name", "port", "enabled", "created_at", "updated_at", "deleted_at", "tags", "cpu_used", "mem_used", "ports_used", "total_loading"}
	agentColumnsWithoutDefault = []string{}
	agentColumnsWithDefault    = []string{"agent_id", "host_name", "port", "enabled", "created_at", "updated_at", "deleted_at", "tags", "cpu_used", "mem_used", "ports_used", "total_loading"}
	agentPrimaryKeyColumns     = []string{"agent_id"}
	agentGeneratedColumns      = []string{}
)

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

	agentQuery struct {
		*queries.Query
	}
)

// Cache for insert, update and upsert
var (
	agentType                 = reflect.TypeOf(&Agent{})
	agentMapping              = queries.MakeStructMapping(agentType)
	agentPrimaryKeyMapping, _ = queries.BindMapping(agentType, agentMapping, agentPrimaryKeyColumns)
	agentInsertCacheMut       sync.RWMutex
	agentInsertCache          = make(map[string]insertCache)
	agentUpdateCacheMut       sync.RWMutex
	agentUpdateCache          = make(map[string]updateCache)
	agentUpsertCacheMut       sync.RWMutex
	agentUpsertCache          = 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 agentAfterSelectMu sync.Mutex
var agentAfterSelectHooks []AgentHook

var agentBeforeInsertMu sync.Mutex
var agentBeforeInsertHooks []AgentHook
var agentAfterInsertMu sync.Mutex
var agentAfterInsertHooks []AgentHook

var agentBeforeUpdateMu sync.Mutex
var agentBeforeUpdateHooks []AgentHook
var agentAfterUpdateMu sync.Mutex
var agentAfterUpdateHooks []AgentHook

var agentBeforeDeleteMu sync.Mutex
var agentBeforeDeleteHooks []AgentHook
var agentAfterDeleteMu sync.Mutex
var agentAfterDeleteHooks []AgentHook

var agentBeforeUpsertMu sync.Mutex
var agentBeforeUpsertHooks []AgentHook
var agentAfterUpsertMu sync.Mutex
var agentAfterUpsertHooks []AgentHook

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

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

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

	return nil
}

// AddAgentHook registers your hook function for all future operations.
func AddAgentHook(hookPoint boil.HookPoint, agentHook AgentHook) {
	switch hookPoint {
	case boil.AfterSelectHook:
		agentAfterSelectMu.Lock()
		agentAfterSelectHooks = append(agentAfterSelectHooks, agentHook)
		agentAfterSelectMu.Unlock()
	case boil.BeforeInsertHook:
		agentBeforeInsertMu.Lock()
		agentBeforeInsertHooks = append(agentBeforeInsertHooks, agentHook)
		agentBeforeInsertMu.Unlock()
	case boil.AfterInsertHook:
		agentAfterInsertMu.Lock()
		agentAfterInsertHooks = append(agentAfterInsertHooks, agentHook)
		agentAfterInsertMu.Unlock()
	case boil.BeforeUpdateHook:
		agentBeforeUpdateMu.Lock()
		agentBeforeUpdateHooks = append(agentBeforeUpdateHooks, agentHook)
		agentBeforeUpdateMu.Unlock()
	case boil.AfterUpdateHook:
		agentAfterUpdateMu.Lock()
		agentAfterUpdateHooks = append(agentAfterUpdateHooks, agentHook)
		agentAfterUpdateMu.Unlock()
	case boil.BeforeDeleteHook:
		agentBeforeDeleteMu.Lock()
		agentBeforeDeleteHooks = append(agentBeforeDeleteHooks, agentHook)
		agentBeforeDeleteMu.Unlock()
	case boil.AfterDeleteHook:
		agentAfterDeleteMu.Lock()
		agentAfterDeleteHooks = append(agentAfterDeleteHooks, agentHook)
		agentAfterDeleteMu.Unlock()
	case boil.BeforeUpsertHook:
		agentBeforeUpsertMu.Lock()
		agentBeforeUpsertHooks = append(agentBeforeUpsertHooks, agentHook)
		agentBeforeUpsertMu.Unlock()
	case boil.AfterUpsertHook:
		agentAfterUpsertMu.Lock()
		agentAfterUpsertHooks = append(agentAfterUpsertHooks, agentHook)
		agentAfterUpsertMu.Unlock()
	}
}

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

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

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

	return o, nil
}

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

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

	if len(agentAfterSelectHooks) != 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 Agent records in the query.
func (q agentQuery) 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 agent rows")
	}

	return count, nil
}

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

	return count > 0, nil
}

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

	return agentQuery{q}
}

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

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

	q := queries.Raw(query, agentID)

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

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

	return agentObj, nil
}

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

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

	if !cached {
		wl, returnColumns := columns.InsertColumnSet(
			agentAllColumns,
			agentColumnsWithDefault,
			agentColumnsWithoutDefault,
			nzDefaults,
		)

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

	if !cached {
		agentInsertCacheMut.Lock()
		agentInsertCache[key] = cache
		agentInsertCacheMut.Unlock()
	}

	return o.doAfterInsertHooks(ctx, exec)
}

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

	if !cached {
		wl := columns.UpdateColumnSet(
			agentAllColumns,
			agentPrimaryKeyColumns,
		)

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

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

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

	if !cached {
		agentUpdateCacheMut.Lock()
		agentUpdateCache[key] = cache
		agentUpdateCacheMut.Unlock()
	}

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

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

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

	return rowsAff, nil
}

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

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

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

	agentUpsertCacheMut.RLock()
	cache, cached := agentUpsertCache[key]
	agentUpsertCacheMut.RUnlock()

	var err error

	if !cached {
		insert, _ := insertColumns.InsertColumnSet(
			agentAllColumns,
			agentColumnsWithDefault,
			agentColumnsWithoutDefault,
			nzDefaults,
		)

		update := updateColumns.UpdateColumnSet(
			agentAllColumns,
			agentPrimaryKeyColumns,
		)

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

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

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

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

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

	if !cached {
		agentUpsertCacheMut.Lock()
		agentUpsertCache[key] = cache
		agentUpsertCacheMut.Unlock()
	}

	return o.doAfterUpsertHooks(ctx, exec)
}

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

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

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

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

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

	return rowsAff, nil
}

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

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

	return rowsAff, nil
}

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

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

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

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

	if len(agentAfterDeleteHooks) != 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 *Agent) Reload(ctx context.Context, exec boil.ContextExecutor) error {
	ret, err := FindAgent(ctx, exec, o.AgentID)
	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 *AgentSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
	if o == nil || len(*o) == 0 {
		return nil
	}

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

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

	*o = slice

	return nil
}

// AgentExists checks if the Agent row exists.
func AgentExists(ctx context.Context, exec boil.ContextExecutor, agentID int32) (bool, error) {
	var exists bool
	sql := "select exists(select 1 from \"agent\" where \"agent_id\"=$1 limit 1)"

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

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

	return exists, nil
}

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