// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/buildbarn/bb-portal/ent/gen/ent/buildgraphmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/evaluationstat"
	"github.com/buildbarn/bb-portal/ent/gen/ent/metrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
)

// BuildGraphMetricsQuery is the builder for querying BuildGraphMetrics entities.
type BuildGraphMetricsQuery struct {
	config
	ctx                 *QueryContext
	order               []buildgraphmetrics.OrderOption
	inters              []Interceptor
	predicates          []predicate.BuildGraphMetrics
	withMetrics         *MetricsQuery
	withDirtiedValues   *EvaluationStatQuery
	withChangedValues   *EvaluationStatQuery
	withBuiltValues     *EvaluationStatQuery
	withCleanedValues   *EvaluationStatQuery
	withEvaluatedValues *EvaluationStatQuery
	withFKs             bool
	modifiers           []func(*sql.Selector)
	loadTotal           []func(context.Context, []*BuildGraphMetrics) error
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the BuildGraphMetricsQuery builder.
func (bgmq *BuildGraphMetricsQuery) Where(ps ...predicate.BuildGraphMetrics) *BuildGraphMetricsQuery {
	bgmq.predicates = append(bgmq.predicates, ps...)
	return bgmq
}

// Limit the number of records to be returned by this query.
func (bgmq *BuildGraphMetricsQuery) Limit(limit int) *BuildGraphMetricsQuery {
	bgmq.ctx.Limit = &limit
	return bgmq
}

// Offset to start from.
func (bgmq *BuildGraphMetricsQuery) Offset(offset int) *BuildGraphMetricsQuery {
	bgmq.ctx.Offset = &offset
	return bgmq
}

// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (bgmq *BuildGraphMetricsQuery) Unique(unique bool) *BuildGraphMetricsQuery {
	bgmq.ctx.Unique = &unique
	return bgmq
}

// Order specifies how the records should be ordered.
func (bgmq *BuildGraphMetricsQuery) Order(o ...buildgraphmetrics.OrderOption) *BuildGraphMetricsQuery {
	bgmq.order = append(bgmq.order, o...)
	return bgmq
}

// QueryMetrics chains the current query on the "metrics" edge.
func (bgmq *BuildGraphMetricsQuery) QueryMetrics() *MetricsQuery {
	query := (&MetricsClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(metrics.Table, metrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, buildgraphmetrics.MetricsTable, buildgraphmetrics.MetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryDirtiedValues chains the current query on the "dirtied_values" edge.
func (bgmq *BuildGraphMetricsQuery) QueryDirtiedValues() *EvaluationStatQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(evaluationstat.Table, evaluationstat.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, buildgraphmetrics.DirtiedValuesTable, buildgraphmetrics.DirtiedValuesColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryChangedValues chains the current query on the "changed_values" edge.
func (bgmq *BuildGraphMetricsQuery) QueryChangedValues() *EvaluationStatQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(evaluationstat.Table, evaluationstat.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, buildgraphmetrics.ChangedValuesTable, buildgraphmetrics.ChangedValuesColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryBuiltValues chains the current query on the "built_values" edge.
func (bgmq *BuildGraphMetricsQuery) QueryBuiltValues() *EvaluationStatQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(evaluationstat.Table, evaluationstat.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, buildgraphmetrics.BuiltValuesTable, buildgraphmetrics.BuiltValuesColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryCleanedValues chains the current query on the "cleaned_values" edge.
func (bgmq *BuildGraphMetricsQuery) QueryCleanedValues() *EvaluationStatQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(evaluationstat.Table, evaluationstat.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, buildgraphmetrics.CleanedValuesTable, buildgraphmetrics.CleanedValuesColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryEvaluatedValues chains the current query on the "evaluated_values" edge.
func (bgmq *BuildGraphMetricsQuery) QueryEvaluatedValues() *EvaluationStatQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := bgmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := bgmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(buildgraphmetrics.Table, buildgraphmetrics.FieldID, selector),
			sqlgraph.To(evaluationstat.Table, evaluationstat.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, buildgraphmetrics.EvaluatedValuesTable, buildgraphmetrics.EvaluatedValuesColumn),
		)
		fromU = sqlgraph.SetNeighbors(bgmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// First returns the first BuildGraphMetrics entity from the query.
// Returns a *NotFoundError when no BuildGraphMetrics was found.
func (bgmq *BuildGraphMetricsQuery) First(ctx context.Context) (*BuildGraphMetrics, error) {
	nodes, err := bgmq.Limit(1).All(setContextOp(ctx, bgmq.ctx, ent.OpQueryFirst))
	if err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nil, &NotFoundError{buildgraphmetrics.Label}
	}
	return nodes[0], nil
}

// FirstX is like First, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) FirstX(ctx context.Context) *BuildGraphMetrics {
	node, err := bgmq.First(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return node
}

// FirstID returns the first BuildGraphMetrics ID from the query.
// Returns a *NotFoundError when no BuildGraphMetrics ID was found.
func (bgmq *BuildGraphMetricsQuery) FirstID(ctx context.Context) (id int, err error) {
	var ids []int
	if ids, err = bgmq.Limit(1).IDs(setContextOp(ctx, bgmq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{buildgraphmetrics.Label}
		return
	}
	return ids[0], nil
}

// FirstIDX is like FirstID, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) FirstIDX(ctx context.Context) int {
	id, err := bgmq.FirstID(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return id
}

// Only returns a single BuildGraphMetrics entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one BuildGraphMetrics entity is found.
// Returns a *NotFoundError when no BuildGraphMetrics entities are found.
func (bgmq *BuildGraphMetricsQuery) Only(ctx context.Context) (*BuildGraphMetrics, error) {
	nodes, err := bgmq.Limit(2).All(setContextOp(ctx, bgmq.ctx, ent.OpQueryOnly))
	if err != nil {
		return nil, err
	}
	switch len(nodes) {
	case 1:
		return nodes[0], nil
	case 0:
		return nil, &NotFoundError{buildgraphmetrics.Label}
	default:
		return nil, &NotSingularError{buildgraphmetrics.Label}
	}
}

// OnlyX is like Only, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) OnlyX(ctx context.Context) *BuildGraphMetrics {
	node, err := bgmq.Only(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// OnlyID is like Only, but returns the only BuildGraphMetrics ID in the query.
// Returns a *NotSingularError when more than one BuildGraphMetrics ID is found.
// Returns a *NotFoundError when no entities are found.
func (bgmq *BuildGraphMetricsQuery) OnlyID(ctx context.Context) (id int, err error) {
	var ids []int
	if ids, err = bgmq.Limit(2).IDs(setContextOp(ctx, bgmq.ctx, ent.OpQueryOnlyID)); err != nil {
		return
	}
	switch len(ids) {
	case 1:
		id = ids[0]
	case 0:
		err = &NotFoundError{buildgraphmetrics.Label}
	default:
		err = &NotSingularError{buildgraphmetrics.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) OnlyIDX(ctx context.Context) int {
	id, err := bgmq.OnlyID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// All executes the query and returns a list of BuildGraphMetricsSlice.
func (bgmq *BuildGraphMetricsQuery) All(ctx context.Context) ([]*BuildGraphMetrics, error) {
	ctx = setContextOp(ctx, bgmq.ctx, ent.OpQueryAll)
	if err := bgmq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*BuildGraphMetrics, *BuildGraphMetricsQuery]()
	return withInterceptors[[]*BuildGraphMetrics](ctx, bgmq, qr, bgmq.inters)
}

// AllX is like All, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) AllX(ctx context.Context) []*BuildGraphMetrics {
	nodes, err := bgmq.All(ctx)
	if err != nil {
		panic(err)
	}
	return nodes
}

// IDs executes the query and returns a list of BuildGraphMetrics IDs.
func (bgmq *BuildGraphMetricsQuery) IDs(ctx context.Context) (ids []int, err error) {
	if bgmq.ctx.Unique == nil && bgmq.path != nil {
		bgmq.Unique(true)
	}
	ctx = setContextOp(ctx, bgmq.ctx, ent.OpQueryIDs)
	if err = bgmq.Select(buildgraphmetrics.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) IDsX(ctx context.Context) []int {
	ids, err := bgmq.IDs(ctx)
	if err != nil {
		panic(err)
	}
	return ids
}

// Count returns the count of the given query.
func (bgmq *BuildGraphMetricsQuery) Count(ctx context.Context) (int, error) {
	ctx = setContextOp(ctx, bgmq.ctx, ent.OpQueryCount)
	if err := bgmq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return withInterceptors[int](ctx, bgmq, querierCount[*BuildGraphMetricsQuery](), bgmq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) CountX(ctx context.Context) int {
	count, err := bgmq.Count(ctx)
	if err != nil {
		panic(err)
	}
	return count
}

// Exist returns true if the query has elements in the graph.
func (bgmq *BuildGraphMetricsQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, bgmq.ctx, ent.OpQueryExist)
	switch _, err := bgmq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("ent: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (bgmq *BuildGraphMetricsQuery) ExistX(ctx context.Context) bool {
	exist, err := bgmq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the BuildGraphMetricsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (bgmq *BuildGraphMetricsQuery) Clone() *BuildGraphMetricsQuery {
	if bgmq == nil {
		return nil
	}
	return &BuildGraphMetricsQuery{
		config:              bgmq.config,
		ctx:                 bgmq.ctx.Clone(),
		order:               append([]buildgraphmetrics.OrderOption{}, bgmq.order...),
		inters:              append([]Interceptor{}, bgmq.inters...),
		predicates:          append([]predicate.BuildGraphMetrics{}, bgmq.predicates...),
		withMetrics:         bgmq.withMetrics.Clone(),
		withDirtiedValues:   bgmq.withDirtiedValues.Clone(),
		withChangedValues:   bgmq.withChangedValues.Clone(),
		withBuiltValues:     bgmq.withBuiltValues.Clone(),
		withCleanedValues:   bgmq.withCleanedValues.Clone(),
		withEvaluatedValues: bgmq.withEvaluatedValues.Clone(),
		// clone intermediate query.
		sql:  bgmq.sql.Clone(),
		path: bgmq.path,
	}
}

// WithMetrics tells the query-builder to eager-load the nodes that are connected to
// the "metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithMetrics(opts ...func(*MetricsQuery)) *BuildGraphMetricsQuery {
	query := (&MetricsClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withMetrics = query
	return bgmq
}

// WithDirtiedValues tells the query-builder to eager-load the nodes that are connected to
// the "dirtied_values" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithDirtiedValues(opts ...func(*EvaluationStatQuery)) *BuildGraphMetricsQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withDirtiedValues = query
	return bgmq
}

// WithChangedValues tells the query-builder to eager-load the nodes that are connected to
// the "changed_values" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithChangedValues(opts ...func(*EvaluationStatQuery)) *BuildGraphMetricsQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withChangedValues = query
	return bgmq
}

// WithBuiltValues tells the query-builder to eager-load the nodes that are connected to
// the "built_values" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithBuiltValues(opts ...func(*EvaluationStatQuery)) *BuildGraphMetricsQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withBuiltValues = query
	return bgmq
}

// WithCleanedValues tells the query-builder to eager-load the nodes that are connected to
// the "cleaned_values" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithCleanedValues(opts ...func(*EvaluationStatQuery)) *BuildGraphMetricsQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withCleanedValues = query
	return bgmq
}

// WithEvaluatedValues tells the query-builder to eager-load the nodes that are connected to
// the "evaluated_values" edge. The optional arguments are used to configure the query builder of the edge.
func (bgmq *BuildGraphMetricsQuery) WithEvaluatedValues(opts ...func(*EvaluationStatQuery)) *BuildGraphMetricsQuery {
	query := (&EvaluationStatClient{config: bgmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	bgmq.withEvaluatedValues = query
	return bgmq
}

// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
//	var v []struct {
//		ActionLookupValueCount int32 `json:"action_lookup_value_count,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.BuildGraphMetrics.Query().
//		GroupBy(buildgraphmetrics.FieldActionLookupValueCount).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (bgmq *BuildGraphMetricsQuery) GroupBy(field string, fields ...string) *BuildGraphMetricsGroupBy {
	bgmq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &BuildGraphMetricsGroupBy{build: bgmq}
	grbuild.flds = &bgmq.ctx.Fields
	grbuild.label = buildgraphmetrics.Label
	grbuild.scan = grbuild.Scan
	return grbuild
}

// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
//	var v []struct {
//		ActionLookupValueCount int32 `json:"action_lookup_value_count,omitempty"`
//	}
//
//	client.BuildGraphMetrics.Query().
//		Select(buildgraphmetrics.FieldActionLookupValueCount).
//		Scan(ctx, &v)
func (bgmq *BuildGraphMetricsQuery) Select(fields ...string) *BuildGraphMetricsSelect {
	bgmq.ctx.Fields = append(bgmq.ctx.Fields, fields...)
	sbuild := &BuildGraphMetricsSelect{BuildGraphMetricsQuery: bgmq}
	sbuild.label = buildgraphmetrics.Label
	sbuild.flds, sbuild.scan = &bgmq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a BuildGraphMetricsSelect configured with the given aggregations.
func (bgmq *BuildGraphMetricsQuery) Aggregate(fns ...AggregateFunc) *BuildGraphMetricsSelect {
	return bgmq.Select().Aggregate(fns...)
}

func (bgmq *BuildGraphMetricsQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range bgmq.inters {
		if inter == nil {
			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, bgmq); err != nil {
				return err
			}
		}
	}
	for _, f := range bgmq.ctx.Fields {
		if !buildgraphmetrics.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if bgmq.path != nil {
		prev, err := bgmq.path(ctx)
		if err != nil {
			return err
		}
		bgmq.sql = prev
	}
	return nil
}

func (bgmq *BuildGraphMetricsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BuildGraphMetrics, error) {
	var (
		nodes       = []*BuildGraphMetrics{}
		withFKs     = bgmq.withFKs
		_spec       = bgmq.querySpec()
		loadedTypes = [6]bool{
			bgmq.withMetrics != nil,
			bgmq.withDirtiedValues != nil,
			bgmq.withChangedValues != nil,
			bgmq.withBuiltValues != nil,
			bgmq.withCleanedValues != nil,
			bgmq.withEvaluatedValues != nil,
		}
	)
	if bgmq.withMetrics != nil || bgmq.withDirtiedValues != nil || bgmq.withChangedValues != nil || bgmq.withBuiltValues != nil || bgmq.withCleanedValues != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, buildgraphmetrics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*BuildGraphMetrics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &BuildGraphMetrics{config: bgmq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(bgmq.modifiers) > 0 {
		_spec.Modifiers = bgmq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, bgmq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := bgmq.withMetrics; query != nil {
		if err := bgmq.loadMetrics(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *Metrics) { n.Edges.Metrics = e }); err != nil {
			return nil, err
		}
	}
	if query := bgmq.withDirtiedValues; query != nil {
		if err := bgmq.loadDirtiedValues(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *EvaluationStat) { n.Edges.DirtiedValues = e }); err != nil {
			return nil, err
		}
	}
	if query := bgmq.withChangedValues; query != nil {
		if err := bgmq.loadChangedValues(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *EvaluationStat) { n.Edges.ChangedValues = e }); err != nil {
			return nil, err
		}
	}
	if query := bgmq.withBuiltValues; query != nil {
		if err := bgmq.loadBuiltValues(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *EvaluationStat) { n.Edges.BuiltValues = e }); err != nil {
			return nil, err
		}
	}
	if query := bgmq.withCleanedValues; query != nil {
		if err := bgmq.loadCleanedValues(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *EvaluationStat) { n.Edges.CleanedValues = e }); err != nil {
			return nil, err
		}
	}
	if query := bgmq.withEvaluatedValues; query != nil {
		if err := bgmq.loadEvaluatedValues(ctx, query, nodes, nil,
			func(n *BuildGraphMetrics, e *EvaluationStat) { n.Edges.EvaluatedValues = e }); err != nil {
			return nil, err
		}
	}
	for i := range bgmq.loadTotal {
		if err := bgmq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (bgmq *BuildGraphMetricsQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*BuildGraphMetrics)
	for i := range nodes {
		if nodes[i].metrics_build_graph_metrics == nil {
			continue
		}
		fk := *nodes[i].metrics_build_graph_metrics
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(metrics.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "metrics_build_graph_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (bgmq *BuildGraphMetricsQuery) loadDirtiedValues(ctx context.Context, query *EvaluationStatQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *EvaluationStat)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*BuildGraphMetrics)
	for i := range nodes {
		if nodes[i].build_graph_metrics_dirtied_values == nil {
			continue
		}
		fk := *nodes[i].build_graph_metrics_dirtied_values
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(evaluationstat.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "build_graph_metrics_dirtied_values" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (bgmq *BuildGraphMetricsQuery) loadChangedValues(ctx context.Context, query *EvaluationStatQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *EvaluationStat)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*BuildGraphMetrics)
	for i := range nodes {
		if nodes[i].build_graph_metrics_changed_values == nil {
			continue
		}
		fk := *nodes[i].build_graph_metrics_changed_values
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(evaluationstat.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "build_graph_metrics_changed_values" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (bgmq *BuildGraphMetricsQuery) loadBuiltValues(ctx context.Context, query *EvaluationStatQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *EvaluationStat)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*BuildGraphMetrics)
	for i := range nodes {
		if nodes[i].build_graph_metrics_built_values == nil {
			continue
		}
		fk := *nodes[i].build_graph_metrics_built_values
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(evaluationstat.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "build_graph_metrics_built_values" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (bgmq *BuildGraphMetricsQuery) loadCleanedValues(ctx context.Context, query *EvaluationStatQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *EvaluationStat)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*BuildGraphMetrics)
	for i := range nodes {
		if nodes[i].build_graph_metrics_cleaned_values == nil {
			continue
		}
		fk := *nodes[i].build_graph_metrics_cleaned_values
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(evaluationstat.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "build_graph_metrics_cleaned_values" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (bgmq *BuildGraphMetricsQuery) loadEvaluatedValues(ctx context.Context, query *EvaluationStatQuery, nodes []*BuildGraphMetrics, init func(*BuildGraphMetrics), assign func(*BuildGraphMetrics, *EvaluationStat)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*BuildGraphMetrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.EvaluationStat(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(buildgraphmetrics.EvaluatedValuesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.build_graph_metrics_evaluated_values
		if fk == nil {
			return fmt.Errorf(`foreign-key "build_graph_metrics_evaluated_values" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "build_graph_metrics_evaluated_values" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

func (bgmq *BuildGraphMetricsQuery) sqlCount(ctx context.Context) (int, error) {
	_spec := bgmq.querySpec()
	if len(bgmq.modifiers) > 0 {
		_spec.Modifiers = bgmq.modifiers
	}
	_spec.Node.Columns = bgmq.ctx.Fields
	if len(bgmq.ctx.Fields) > 0 {
		_spec.Unique = bgmq.ctx.Unique != nil && *bgmq.ctx.Unique
	}
	return sqlgraph.CountNodes(ctx, bgmq.driver, _spec)
}

func (bgmq *BuildGraphMetricsQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := sqlgraph.NewQuerySpec(buildgraphmetrics.Table, buildgraphmetrics.Columns, sqlgraph.NewFieldSpec(buildgraphmetrics.FieldID, field.TypeInt))
	_spec.From = bgmq.sql
	if unique := bgmq.ctx.Unique; unique != nil {
		_spec.Unique = *unique
	} else if bgmq.path != nil {
		_spec.Unique = true
	}
	if fields := bgmq.ctx.Fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, buildgraphmetrics.FieldID)
		for i := range fields {
			if fields[i] != buildgraphmetrics.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
			}
		}
	}
	if ps := bgmq.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if limit := bgmq.ctx.Limit; limit != nil {
		_spec.Limit = *limit
	}
	if offset := bgmq.ctx.Offset; offset != nil {
		_spec.Offset = *offset
	}
	if ps := bgmq.order; len(ps) > 0 {
		_spec.Order = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	return _spec
}

func (bgmq *BuildGraphMetricsQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(bgmq.driver.Dialect())
	t1 := builder.Table(buildgraphmetrics.Table)
	columns := bgmq.ctx.Fields
	if len(columns) == 0 {
		columns = buildgraphmetrics.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if bgmq.sql != nil {
		selector = bgmq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if bgmq.ctx.Unique != nil && *bgmq.ctx.Unique {
		selector.Distinct()
	}
	for _, p := range bgmq.predicates {
		p(selector)
	}
	for _, p := range bgmq.order {
		p(selector)
	}
	if offset := bgmq.ctx.Offset; offset != nil {
		// limit is mandatory for offset clause. We start
		// with default value, and override it below if needed.
		selector.Offset(*offset).Limit(math.MaxInt32)
	}
	if limit := bgmq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// BuildGraphMetricsGroupBy is the group-by builder for BuildGraphMetrics entities.
type BuildGraphMetricsGroupBy struct {
	selector
	build *BuildGraphMetricsQuery
}

// Aggregate adds the given aggregation functions to the group-by query.
func (bgmgb *BuildGraphMetricsGroupBy) Aggregate(fns ...AggregateFunc) *BuildGraphMetricsGroupBy {
	bgmgb.fns = append(bgmgb.fns, fns...)
	return bgmgb
}

// Scan applies the selector query and scans the result into the given value.
func (bgmgb *BuildGraphMetricsGroupBy) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, bgmgb.build.ctx, ent.OpQueryGroupBy)
	if err := bgmgb.build.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*BuildGraphMetricsQuery, *BuildGraphMetricsGroupBy](ctx, bgmgb.build, bgmgb, bgmgb.build.inters, v)
}

func (bgmgb *BuildGraphMetricsGroupBy) sqlScan(ctx context.Context, root *BuildGraphMetricsQuery, v any) error {
	selector := root.sqlQuery(ctx).Select()
	aggregation := make([]string, 0, len(bgmgb.fns))
	for _, fn := range bgmgb.fns {
		aggregation = append(aggregation, fn(selector))
	}
	if len(selector.SelectedColumns()) == 0 {
		columns := make([]string, 0, len(*bgmgb.flds)+len(bgmgb.fns))
		for _, f := range *bgmgb.flds {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	selector.GroupBy(selector.Columns(*bgmgb.flds...)...)
	if err := selector.Err(); err != nil {
		return err
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := bgmgb.build.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

// BuildGraphMetricsSelect is the builder for selecting fields of BuildGraphMetrics entities.
type BuildGraphMetricsSelect struct {
	*BuildGraphMetricsQuery
	selector
}

// Aggregate adds the given aggregation functions to the selector query.
func (bgms *BuildGraphMetricsSelect) Aggregate(fns ...AggregateFunc) *BuildGraphMetricsSelect {
	bgms.fns = append(bgms.fns, fns...)
	return bgms
}

// Scan applies the selector query and scans the result into the given value.
func (bgms *BuildGraphMetricsSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, bgms.ctx, ent.OpQuerySelect)
	if err := bgms.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*BuildGraphMetricsQuery, *BuildGraphMetricsSelect](ctx, bgms.BuildGraphMetricsQuery, bgms, bgms.inters, v)
}

func (bgms *BuildGraphMetricsSelect) sqlScan(ctx context.Context, root *BuildGraphMetricsQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(bgms.fns))
	for _, fn := range bgms.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*bgms.selector.flds); {
	case n == 0 && len(aggregation) > 0:
		selector.Select(aggregation...)
	case n != 0 && len(aggregation) > 0:
		selector.AppendSelect(aggregation...)
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := bgms.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
