// Code generated by ent, DO NOT EDIT.

package ent

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

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

// Where adds a new predicate for the RaceStatisticsQuery builder.
func (rsq *RaceStatisticsQuery) Where(ps ...predicate.RaceStatistics) *RaceStatisticsQuery {
	rsq.predicates = append(rsq.predicates, ps...)
	return rsq
}

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

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

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

// Order specifies how the records should be ordered.
func (rsq *RaceStatisticsQuery) Order(o ...racestatistics.OrderOption) *RaceStatisticsQuery {
	rsq.order = append(rsq.order, o...)
	return rsq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the RaceStatisticsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (rsq *RaceStatisticsQuery) Clone() *RaceStatisticsQuery {
	if rsq == nil {
		return nil
	}
	return &RaceStatisticsQuery{
		config:                      rsq.config,
		ctx:                         rsq.ctx.Clone(),
		order:                       append([]racestatistics.OrderOption{}, rsq.order...),
		inters:                      append([]Interceptor{}, rsq.inters...),
		predicates:                  append([]predicate.RaceStatistics{}, rsq.predicates...),
		withDynamicExecutionMetrics: rsq.withDynamicExecutionMetrics.Clone(),
		// clone intermediate query.
		sql:  rsq.sql.Clone(),
		path: rsq.path,
	}
}

// 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 (rsq *RaceStatisticsQuery) WithDynamicExecutionMetrics(opts ...func(*DynamicExecutionMetricsQuery)) *RaceStatisticsQuery {
	query := (&DynamicExecutionMetricsClient{config: rsq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	rsq.withDynamicExecutionMetrics = query
	return rsq
}

// 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 {
//		Mnemonic string `json:"mnemonic,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.RaceStatistics.Query().
//		GroupBy(racestatistics.FieldMnemonic).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (rsq *RaceStatisticsQuery) GroupBy(field string, fields ...string) *RaceStatisticsGroupBy {
	rsq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &RaceStatisticsGroupBy{build: rsq}
	grbuild.flds = &rsq.ctx.Fields
	grbuild.label = racestatistics.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 {
//		Mnemonic string `json:"mnemonic,omitempty"`
//	}
//
//	client.RaceStatistics.Query().
//		Select(racestatistics.FieldMnemonic).
//		Scan(ctx, &v)
func (rsq *RaceStatisticsQuery) Select(fields ...string) *RaceStatisticsSelect {
	rsq.ctx.Fields = append(rsq.ctx.Fields, fields...)
	sbuild := &RaceStatisticsSelect{RaceStatisticsQuery: rsq}
	sbuild.label = racestatistics.Label
	sbuild.flds, sbuild.scan = &rsq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a RaceStatisticsSelect configured with the given aggregations.
func (rsq *RaceStatisticsQuery) Aggregate(fns ...AggregateFunc) *RaceStatisticsSelect {
	return rsq.Select().Aggregate(fns...)
}

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

func (rsq *RaceStatisticsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RaceStatistics, error) {
	var (
		nodes       = []*RaceStatistics{}
		withFKs     = rsq.withFKs
		_spec       = rsq.querySpec()
		loadedTypes = [1]bool{
			rsq.withDynamicExecutionMetrics != nil,
		}
	)
	if rsq.withDynamicExecutionMetrics != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, racestatistics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*RaceStatistics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &RaceStatistics{config: rsq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(rsq.modifiers) > 0 {
		_spec.Modifiers = rsq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, rsq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := rsq.withDynamicExecutionMetrics; query != nil {
		if err := rsq.loadDynamicExecutionMetrics(ctx, query, nodes, nil,
			func(n *RaceStatistics, e *DynamicExecutionMetrics) { n.Edges.DynamicExecutionMetrics = e }); err != nil {
			return nil, err
		}
	}
	for i := range rsq.loadTotal {
		if err := rsq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (rsq *RaceStatisticsQuery) loadDynamicExecutionMetrics(ctx context.Context, query *DynamicExecutionMetricsQuery, nodes []*RaceStatistics, init func(*RaceStatistics), assign func(*RaceStatistics, *DynamicExecutionMetrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*RaceStatistics)
	for i := range nodes {
		if nodes[i].dynamic_execution_metrics_race_statistics == nil {
			continue
		}
		fk := *nodes[i].dynamic_execution_metrics_race_statistics
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(dynamicexecutionmetrics.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 "dynamic_execution_metrics_race_statistics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// RaceStatisticsGroupBy is the group-by builder for RaceStatistics entities.
type RaceStatisticsGroupBy struct {
	selector
	build *RaceStatisticsQuery
}

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

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

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

// RaceStatisticsSelect is the builder for selecting fields of RaceStatistics entities.
type RaceStatisticsSelect struct {
	*RaceStatisticsQuery
	selector
}

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

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

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