// 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/actionsummary"
	"github.com/buildbarn/bb-portal/ent/gen/ent/artifactmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/bazelinvocation"
	"github.com/buildbarn/bb-portal/ent/gen/ent/buildgraphmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/cumulativemetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/dynamicexecutionmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/memorymetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/metrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/networkmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/packagemetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
	"github.com/buildbarn/bb-portal/ent/gen/ent/targetmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/timingmetrics"
)

// MetricsQuery is the builder for querying Metrics entities.
type MetricsQuery struct {
	config
	ctx                         *QueryContext
	order                       []metrics.OrderOption
	inters                      []Interceptor
	predicates                  []predicate.Metrics
	withBazelInvocation         *BazelInvocationQuery
	withActionSummary           *ActionSummaryQuery
	withMemoryMetrics           *MemoryMetricsQuery
	withTargetMetrics           *TargetMetricsQuery
	withPackageMetrics          *PackageMetricsQuery
	withTimingMetrics           *TimingMetricsQuery
	withCumulativeMetrics       *CumulativeMetricsQuery
	withArtifactMetrics         *ArtifactMetricsQuery
	withNetworkMetrics          *NetworkMetricsQuery
	withDynamicExecutionMetrics *DynamicExecutionMetricsQuery
	withBuildGraphMetrics       *BuildGraphMetricsQuery
	withFKs                     bool
	modifiers                   []func(*sql.Selector)
	loadTotal                   []func(context.Context, []*Metrics) error
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the MetricsQuery builder.
func (mq *MetricsQuery) Where(ps ...predicate.Metrics) *MetricsQuery {
	mq.predicates = append(mq.predicates, ps...)
	return mq
}

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

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

// 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 (mq *MetricsQuery) Unique(unique bool) *MetricsQuery {
	mq.ctx.Unique = &unique
	return mq
}

// Order specifies how the records should be ordered.
func (mq *MetricsQuery) Order(o ...metrics.OrderOption) *MetricsQuery {
	mq.order = append(mq.order, o...)
	return mq
}

// QueryBazelInvocation chains the current query on the "bazel_invocation" edge.
func (mq *MetricsQuery) QueryBazelInvocation() *BazelInvocationQuery {
	query := (&BazelInvocationClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(bazelinvocation.Table, bazelinvocation.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, metrics.BazelInvocationTable, metrics.BazelInvocationColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryActionSummary chains the current query on the "action_summary" edge.
func (mq *MetricsQuery) QueryActionSummary() *ActionSummaryQuery {
	query := (&ActionSummaryClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(actionsummary.Table, actionsummary.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.ActionSummaryTable, metrics.ActionSummaryColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryMemoryMetrics chains the current query on the "memory_metrics" edge.
func (mq *MetricsQuery) QueryMemoryMetrics() *MemoryMetricsQuery {
	query := (&MemoryMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(memorymetrics.Table, memorymetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.MemoryMetricsTable, metrics.MemoryMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTargetMetrics chains the current query on the "target_metrics" edge.
func (mq *MetricsQuery) QueryTargetMetrics() *TargetMetricsQuery {
	query := (&TargetMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(targetmetrics.Table, targetmetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.TargetMetricsTable, metrics.TargetMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPackageMetrics chains the current query on the "package_metrics" edge.
func (mq *MetricsQuery) QueryPackageMetrics() *PackageMetricsQuery {
	query := (&PackageMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(packagemetrics.Table, packagemetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.PackageMetricsTable, metrics.PackageMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTimingMetrics chains the current query on the "timing_metrics" edge.
func (mq *MetricsQuery) QueryTimingMetrics() *TimingMetricsQuery {
	query := (&TimingMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(timingmetrics.Table, timingmetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.TimingMetricsTable, metrics.TimingMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryCumulativeMetrics chains the current query on the "cumulative_metrics" edge.
func (mq *MetricsQuery) QueryCumulativeMetrics() *CumulativeMetricsQuery {
	query := (&CumulativeMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(cumulativemetrics.Table, cumulativemetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.CumulativeMetricsTable, metrics.CumulativeMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryArtifactMetrics chains the current query on the "artifact_metrics" edge.
func (mq *MetricsQuery) QueryArtifactMetrics() *ArtifactMetricsQuery {
	query := (&ArtifactMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(artifactmetrics.Table, artifactmetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.ArtifactMetricsTable, metrics.ArtifactMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryNetworkMetrics chains the current query on the "network_metrics" edge.
func (mq *MetricsQuery) QueryNetworkMetrics() *NetworkMetricsQuery {
	query := (&NetworkMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(networkmetrics.Table, networkmetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.NetworkMetricsTable, metrics.NetworkMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryDynamicExecutionMetrics chains the current query on the "dynamic_execution_metrics" edge.
func (mq *MetricsQuery) QueryDynamicExecutionMetrics() *DynamicExecutionMetricsQuery {
	query := (&DynamicExecutionMetricsClient{config: mq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(metrics.Table, metrics.FieldID, selector),
			sqlgraph.To(dynamicexecutionmetrics.Table, dynamicexecutionmetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, metrics.DynamicExecutionMetricsTable, metrics.DynamicExecutionMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (mq *MetricsQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, mq.ctx, ent.OpQueryExist)
	switch _, err := mq.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 (mq *MetricsQuery) ExistX(ctx context.Context) bool {
	exist, err := mq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the MetricsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (mq *MetricsQuery) Clone() *MetricsQuery {
	if mq == nil {
		return nil
	}
	return &MetricsQuery{
		config:                      mq.config,
		ctx:                         mq.ctx.Clone(),
		order:                       append([]metrics.OrderOption{}, mq.order...),
		inters:                      append([]Interceptor{}, mq.inters...),
		predicates:                  append([]predicate.Metrics{}, mq.predicates...),
		withBazelInvocation:         mq.withBazelInvocation.Clone(),
		withActionSummary:           mq.withActionSummary.Clone(),
		withMemoryMetrics:           mq.withMemoryMetrics.Clone(),
		withTargetMetrics:           mq.withTargetMetrics.Clone(),
		withPackageMetrics:          mq.withPackageMetrics.Clone(),
		withTimingMetrics:           mq.withTimingMetrics.Clone(),
		withCumulativeMetrics:       mq.withCumulativeMetrics.Clone(),
		withArtifactMetrics:         mq.withArtifactMetrics.Clone(),
		withNetworkMetrics:          mq.withNetworkMetrics.Clone(),
		withDynamicExecutionMetrics: mq.withDynamicExecutionMetrics.Clone(),
		withBuildGraphMetrics:       mq.withBuildGraphMetrics.Clone(),
		// clone intermediate query.
		sql:  mq.sql.Clone(),
		path: mq.path,
	}
}

// WithBazelInvocation tells the query-builder to eager-load the nodes that are connected to
// the "bazel_invocation" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithBazelInvocation(opts ...func(*BazelInvocationQuery)) *MetricsQuery {
	query := (&BazelInvocationClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withBazelInvocation = query
	return mq
}

// WithActionSummary tells the query-builder to eager-load the nodes that are connected to
// the "action_summary" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithActionSummary(opts ...func(*ActionSummaryQuery)) *MetricsQuery {
	query := (&ActionSummaryClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withActionSummary = query
	return mq
}

// WithMemoryMetrics tells the query-builder to eager-load the nodes that are connected to
// the "memory_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithMemoryMetrics(opts ...func(*MemoryMetricsQuery)) *MetricsQuery {
	query := (&MemoryMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withMemoryMetrics = query
	return mq
}

// WithTargetMetrics tells the query-builder to eager-load the nodes that are connected to
// the "target_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithTargetMetrics(opts ...func(*TargetMetricsQuery)) *MetricsQuery {
	query := (&TargetMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withTargetMetrics = query
	return mq
}

// WithPackageMetrics tells the query-builder to eager-load the nodes that are connected to
// the "package_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithPackageMetrics(opts ...func(*PackageMetricsQuery)) *MetricsQuery {
	query := (&PackageMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withPackageMetrics = query
	return mq
}

// WithTimingMetrics tells the query-builder to eager-load the nodes that are connected to
// the "timing_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithTimingMetrics(opts ...func(*TimingMetricsQuery)) *MetricsQuery {
	query := (&TimingMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withTimingMetrics = query
	return mq
}

// WithCumulativeMetrics tells the query-builder to eager-load the nodes that are connected to
// the "cumulative_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithCumulativeMetrics(opts ...func(*CumulativeMetricsQuery)) *MetricsQuery {
	query := (&CumulativeMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withCumulativeMetrics = query
	return mq
}

// WithArtifactMetrics tells the query-builder to eager-load the nodes that are connected to
// the "artifact_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithArtifactMetrics(opts ...func(*ArtifactMetricsQuery)) *MetricsQuery {
	query := (&ArtifactMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withArtifactMetrics = query
	return mq
}

// WithNetworkMetrics tells the query-builder to eager-load the nodes that are connected to
// the "network_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithNetworkMetrics(opts ...func(*NetworkMetricsQuery)) *MetricsQuery {
	query := (&NetworkMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withNetworkMetrics = query
	return mq
}

// WithDynamicExecutionMetrics tells the query-builder to eager-load the nodes that are connected to
// the "dynamic_execution_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mq *MetricsQuery) WithDynamicExecutionMetrics(opts ...func(*DynamicExecutionMetricsQuery)) *MetricsQuery {
	query := (&DynamicExecutionMetricsClient{config: mq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mq.withDynamicExecutionMetrics = query
	return mq
}

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

// 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.
func (mq *MetricsQuery) GroupBy(field string, fields ...string) *MetricsGroupBy {
	mq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &MetricsGroupBy{build: mq}
	grbuild.flds = &mq.ctx.Fields
	grbuild.label = metrics.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.
func (mq *MetricsQuery) Select(fields ...string) *MetricsSelect {
	mq.ctx.Fields = append(mq.ctx.Fields, fields...)
	sbuild := &MetricsSelect{MetricsQuery: mq}
	sbuild.label = metrics.Label
	sbuild.flds, sbuild.scan = &mq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a MetricsSelect configured with the given aggregations.
func (mq *MetricsQuery) Aggregate(fns ...AggregateFunc) *MetricsSelect {
	return mq.Select().Aggregate(fns...)
}

func (mq *MetricsQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range mq.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, mq); err != nil {
				return err
			}
		}
	}
	for _, f := range mq.ctx.Fields {
		if !metrics.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if mq.path != nil {
		prev, err := mq.path(ctx)
		if err != nil {
			return err
		}
		mq.sql = prev
	}
	return nil
}

func (mq *MetricsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Metrics, error) {
	var (
		nodes       = []*Metrics{}
		withFKs     = mq.withFKs
		_spec       = mq.querySpec()
		loadedTypes = [11]bool{
			mq.withBazelInvocation != nil,
			mq.withActionSummary != nil,
			mq.withMemoryMetrics != nil,
			mq.withTargetMetrics != nil,
			mq.withPackageMetrics != nil,
			mq.withTimingMetrics != nil,
			mq.withCumulativeMetrics != nil,
			mq.withArtifactMetrics != nil,
			mq.withNetworkMetrics != nil,
			mq.withDynamicExecutionMetrics != nil,
			mq.withBuildGraphMetrics != nil,
		}
	)
	if mq.withBazelInvocation != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, metrics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*Metrics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &Metrics{config: mq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(mq.modifiers) > 0 {
		_spec.Modifiers = mq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, mq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := mq.withBazelInvocation; query != nil {
		if err := mq.loadBazelInvocation(ctx, query, nodes, nil,
			func(n *Metrics, e *BazelInvocation) { n.Edges.BazelInvocation = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withActionSummary; query != nil {
		if err := mq.loadActionSummary(ctx, query, nodes, nil,
			func(n *Metrics, e *ActionSummary) { n.Edges.ActionSummary = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withMemoryMetrics; query != nil {
		if err := mq.loadMemoryMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *MemoryMetrics) { n.Edges.MemoryMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withTargetMetrics; query != nil {
		if err := mq.loadTargetMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *TargetMetrics) { n.Edges.TargetMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withPackageMetrics; query != nil {
		if err := mq.loadPackageMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *PackageMetrics) { n.Edges.PackageMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withTimingMetrics; query != nil {
		if err := mq.loadTimingMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *TimingMetrics) { n.Edges.TimingMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withCumulativeMetrics; query != nil {
		if err := mq.loadCumulativeMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *CumulativeMetrics) { n.Edges.CumulativeMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withArtifactMetrics; query != nil {
		if err := mq.loadArtifactMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *ArtifactMetrics) { n.Edges.ArtifactMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withNetworkMetrics; query != nil {
		if err := mq.loadNetworkMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *NetworkMetrics) { n.Edges.NetworkMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withDynamicExecutionMetrics; query != nil {
		if err := mq.loadDynamicExecutionMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *DynamicExecutionMetrics) { n.Edges.DynamicExecutionMetrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mq.withBuildGraphMetrics; query != nil {
		if err := mq.loadBuildGraphMetrics(ctx, query, nodes, nil,
			func(n *Metrics, e *BuildGraphMetrics) { n.Edges.BuildGraphMetrics = e }); err != nil {
			return nil, err
		}
	}
	for i := range mq.loadTotal {
		if err := mq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (mq *MetricsQuery) loadBazelInvocation(ctx context.Context, query *BazelInvocationQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *BazelInvocation)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*Metrics)
	for i := range nodes {
		if nodes[i].bazel_invocation_metrics == nil {
			continue
		}
		fk := *nodes[i].bazel_invocation_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(bazelinvocation.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 "bazel_invocation_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (mq *MetricsQuery) loadActionSummary(ctx context.Context, query *ActionSummaryQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *ActionSummary)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.ActionSummary(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.ActionSummaryColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_action_summary
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_action_summary" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_action_summary" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadMemoryMetrics(ctx context.Context, query *MemoryMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *MemoryMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.MemoryMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.MemoryMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_memory_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_memory_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_memory_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadTargetMetrics(ctx context.Context, query *TargetMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *TargetMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.TargetMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.TargetMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_target_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_target_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_target_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadPackageMetrics(ctx context.Context, query *PackageMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *PackageMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.PackageMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.PackageMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_package_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_package_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_package_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadTimingMetrics(ctx context.Context, query *TimingMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *TimingMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.TimingMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.TimingMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_timing_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_timing_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_timing_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadCumulativeMetrics(ctx context.Context, query *CumulativeMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *CumulativeMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.CumulativeMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.CumulativeMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_cumulative_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_cumulative_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_cumulative_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadArtifactMetrics(ctx context.Context, query *ArtifactMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *ArtifactMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.ArtifactMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.ArtifactMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_artifact_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_artifact_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_artifact_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadNetworkMetrics(ctx context.Context, query *NetworkMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *NetworkMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.NetworkMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.NetworkMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_network_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_network_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_network_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadDynamicExecutionMetrics(ctx context.Context, query *DynamicExecutionMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *DynamicExecutionMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.DynamicExecutionMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.DynamicExecutionMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_dynamic_execution_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_dynamic_execution_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_dynamic_execution_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (mq *MetricsQuery) loadBuildGraphMetrics(ctx context.Context, query *BuildGraphMetricsQuery, nodes []*Metrics, init func(*Metrics), assign func(*Metrics, *BuildGraphMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*Metrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.BuildGraphMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(metrics.BuildGraphMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.metrics_build_graph_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "metrics_build_graph_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "metrics_build_graph_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

func (mq *MetricsQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(mq.driver.Dialect())
	t1 := builder.Table(metrics.Table)
	columns := mq.ctx.Fields
	if len(columns) == 0 {
		columns = metrics.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if mq.sql != nil {
		selector = mq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if mq.ctx.Unique != nil && *mq.ctx.Unique {
		selector.Distinct()
	}
	for _, p := range mq.predicates {
		p(selector)
	}
	for _, p := range mq.order {
		p(selector)
	}
	if offset := mq.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 := mq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// MetricsGroupBy is the group-by builder for Metrics entities.
type MetricsGroupBy struct {
	selector
	build *MetricsQuery
}

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

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

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

// MetricsSelect is the builder for selecting fields of Metrics entities.
type MetricsSelect struct {
	*MetricsQuery
	selector
}

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

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

func (ms *MetricsSelect) sqlScan(ctx context.Context, root *MetricsQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(ms.fns))
	for _, fn := range ms.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*ms.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 := ms.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
