// 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/dynamicexecutionmetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/metrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
	"github.com/buildbarn/bb-portal/ent/gen/ent/racestatistics"
)

// DynamicExecutionMetricsQuery is the builder for querying DynamicExecutionMetrics entities.
type DynamicExecutionMetricsQuery struct {
	config
	ctx                     *QueryContext
	order                   []dynamicexecutionmetrics.OrderOption
	inters                  []Interceptor
	predicates              []predicate.DynamicExecutionMetrics
	withMetrics             *MetricsQuery
	withRaceStatistics      *RaceStatisticsQuery
	withFKs                 bool
	modifiers               []func(*sql.Selector)
	loadTotal               []func(context.Context, []*DynamicExecutionMetrics) error
	withNamedRaceStatistics map[string]*RaceStatisticsQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the DynamicExecutionMetricsQuery builder.
func (demq *DynamicExecutionMetricsQuery) Where(ps ...predicate.DynamicExecutionMetrics) *DynamicExecutionMetricsQuery {
	demq.predicates = append(demq.predicates, ps...)
	return demq
}

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

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

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

// Order specifies how the records should be ordered.
func (demq *DynamicExecutionMetricsQuery) Order(o ...dynamicexecutionmetrics.OrderOption) *DynamicExecutionMetricsQuery {
	demq.order = append(demq.order, o...)
	return demq
}

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

// QueryRaceStatistics chains the current query on the "race_statistics" edge.
func (demq *DynamicExecutionMetricsQuery) QueryRaceStatistics() *RaceStatisticsQuery {
	query := (&RaceStatisticsClient{config: demq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := demq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := demq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(dynamicexecutionmetrics.Table, dynamicexecutionmetrics.FieldID, selector),
			sqlgraph.To(racestatistics.Table, racestatistics.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, dynamicexecutionmetrics.RaceStatisticsTable, dynamicexecutionmetrics.RaceStatisticsColumn),
		)
		fromU = sqlgraph.SetNeighbors(demq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the DynamicExecutionMetricsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (demq *DynamicExecutionMetricsQuery) Clone() *DynamicExecutionMetricsQuery {
	if demq == nil {
		return nil
	}
	return &DynamicExecutionMetricsQuery{
		config:             demq.config,
		ctx:                demq.ctx.Clone(),
		order:              append([]dynamicexecutionmetrics.OrderOption{}, demq.order...),
		inters:             append([]Interceptor{}, demq.inters...),
		predicates:         append([]predicate.DynamicExecutionMetrics{}, demq.predicates...),
		withMetrics:        demq.withMetrics.Clone(),
		withRaceStatistics: demq.withRaceStatistics.Clone(),
		// clone intermediate query.
		sql:  demq.sql.Clone(),
		path: demq.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 (demq *DynamicExecutionMetricsQuery) WithMetrics(opts ...func(*MetricsQuery)) *DynamicExecutionMetricsQuery {
	query := (&MetricsClient{config: demq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	demq.withMetrics = query
	return demq
}

// WithRaceStatistics tells the query-builder to eager-load the nodes that are connected to
// the "race_statistics" edge. The optional arguments are used to configure the query builder of the edge.
func (demq *DynamicExecutionMetricsQuery) WithRaceStatistics(opts ...func(*RaceStatisticsQuery)) *DynamicExecutionMetricsQuery {
	query := (&RaceStatisticsClient{config: demq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	demq.withRaceStatistics = query
	return demq
}

// 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 (demq *DynamicExecutionMetricsQuery) GroupBy(field string, fields ...string) *DynamicExecutionMetricsGroupBy {
	demq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DynamicExecutionMetricsGroupBy{build: demq}
	grbuild.flds = &demq.ctx.Fields
	grbuild.label = dynamicexecutionmetrics.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 (demq *DynamicExecutionMetricsQuery) Select(fields ...string) *DynamicExecutionMetricsSelect {
	demq.ctx.Fields = append(demq.ctx.Fields, fields...)
	sbuild := &DynamicExecutionMetricsSelect{DynamicExecutionMetricsQuery: demq}
	sbuild.label = dynamicexecutionmetrics.Label
	sbuild.flds, sbuild.scan = &demq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DynamicExecutionMetricsSelect configured with the given aggregations.
func (demq *DynamicExecutionMetricsQuery) Aggregate(fns ...AggregateFunc) *DynamicExecutionMetricsSelect {
	return demq.Select().Aggregate(fns...)
}

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

func (demq *DynamicExecutionMetricsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DynamicExecutionMetrics, error) {
	var (
		nodes       = []*DynamicExecutionMetrics{}
		withFKs     = demq.withFKs
		_spec       = demq.querySpec()
		loadedTypes = [2]bool{
			demq.withMetrics != nil,
			demq.withRaceStatistics != nil,
		}
	)
	if demq.withMetrics != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, dynamicexecutionmetrics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*DynamicExecutionMetrics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &DynamicExecutionMetrics{config: demq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(demq.modifiers) > 0 {
		_spec.Modifiers = demq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, demq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := demq.withMetrics; query != nil {
		if err := demq.loadMetrics(ctx, query, nodes, nil,
			func(n *DynamicExecutionMetrics, e *Metrics) { n.Edges.Metrics = e }); err != nil {
			return nil, err
		}
	}
	if query := demq.withRaceStatistics; query != nil {
		if err := demq.loadRaceStatistics(ctx, query, nodes,
			func(n *DynamicExecutionMetrics) { n.Edges.RaceStatistics = []*RaceStatistics{} },
			func(n *DynamicExecutionMetrics, e *RaceStatistics) {
				n.Edges.RaceStatistics = append(n.Edges.RaceStatistics, e)
			}); err != nil {
			return nil, err
		}
	}
	for name, query := range demq.withNamedRaceStatistics {
		if err := demq.loadRaceStatistics(ctx, query, nodes,
			func(n *DynamicExecutionMetrics) { n.appendNamedRaceStatistics(name) },
			func(n *DynamicExecutionMetrics, e *RaceStatistics) { n.appendNamedRaceStatistics(name, e) }); err != nil {
			return nil, err
		}
	}
	for i := range demq.loadTotal {
		if err := demq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (demq *DynamicExecutionMetricsQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*DynamicExecutionMetrics, init func(*DynamicExecutionMetrics), assign func(*DynamicExecutionMetrics, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*DynamicExecutionMetrics)
	for i := range nodes {
		if nodes[i].metrics_dynamic_execution_metrics == nil {
			continue
		}
		fk := *nodes[i].metrics_dynamic_execution_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_dynamic_execution_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (demq *DynamicExecutionMetricsQuery) loadRaceStatistics(ctx context.Context, query *RaceStatisticsQuery, nodes []*DynamicExecutionMetrics, init func(*DynamicExecutionMetrics), assign func(*DynamicExecutionMetrics, *RaceStatistics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*DynamicExecutionMetrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	query.withFKs = true
	query.Where(predicate.RaceStatistics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(dynamicexecutionmetrics.RaceStatisticsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.dynamic_execution_metrics_race_statistics
		if fk == nil {
			return fmt.Errorf(`foreign-key "dynamic_execution_metrics_race_statistics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "dynamic_execution_metrics_race_statistics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// WithNamedRaceStatistics tells the query-builder to eager-load the nodes that are connected to the "race_statistics"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (demq *DynamicExecutionMetricsQuery) WithNamedRaceStatistics(name string, opts ...func(*RaceStatisticsQuery)) *DynamicExecutionMetricsQuery {
	query := (&RaceStatisticsClient{config: demq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if demq.withNamedRaceStatistics == nil {
		demq.withNamedRaceStatistics = make(map[string]*RaceStatisticsQuery)
	}
	demq.withNamedRaceStatistics[name] = query
	return demq
}

// DynamicExecutionMetricsGroupBy is the group-by builder for DynamicExecutionMetrics entities.
type DynamicExecutionMetricsGroupBy struct {
	selector
	build *DynamicExecutionMetricsQuery
}

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

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

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

// DynamicExecutionMetricsSelect is the builder for selecting fields of DynamicExecutionMetrics entities.
type DynamicExecutionMetricsSelect struct {
	*DynamicExecutionMetricsQuery
	selector
}

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

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

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