// 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/exectioninfo"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
	"github.com/buildbarn/bb-portal/ent/gen/ent/resourceusage"
	"github.com/buildbarn/bb-portal/ent/gen/ent/testresultbes"
	"github.com/buildbarn/bb-portal/ent/gen/ent/timingbreakdown"
)

// ExectionInfoQuery is the builder for querying ExectionInfo entities.
type ExectionInfoQuery struct {
	config
	ctx                    *QueryContext
	order                  []exectioninfo.OrderOption
	inters                 []Interceptor
	predicates             []predicate.ExectionInfo
	withTestResult         *TestResultBESQuery
	withTimingBreakdown    *TimingBreakdownQuery
	withResourceUsage      *ResourceUsageQuery
	withFKs                bool
	modifiers              []func(*sql.Selector)
	loadTotal              []func(context.Context, []*ExectionInfo) error
	withNamedResourceUsage map[string]*ResourceUsageQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the ExectionInfoQuery builder.
func (eiq *ExectionInfoQuery) Where(ps ...predicate.ExectionInfo) *ExectionInfoQuery {
	eiq.predicates = append(eiq.predicates, ps...)
	return eiq
}

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

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

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

// Order specifies how the records should be ordered.
func (eiq *ExectionInfoQuery) Order(o ...exectioninfo.OrderOption) *ExectionInfoQuery {
	eiq.order = append(eiq.order, o...)
	return eiq
}

// QueryTestResult chains the current query on the "test_result" edge.
func (eiq *ExectionInfoQuery) QueryTestResult() *TestResultBESQuery {
	query := (&TestResultBESClient{config: eiq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := eiq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := eiq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(exectioninfo.Table, exectioninfo.FieldID, selector),
			sqlgraph.To(testresultbes.Table, testresultbes.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, exectioninfo.TestResultTable, exectioninfo.TestResultColumn),
		)
		fromU = sqlgraph.SetNeighbors(eiq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTimingBreakdown chains the current query on the "timing_breakdown" edge.
func (eiq *ExectionInfoQuery) QueryTimingBreakdown() *TimingBreakdownQuery {
	query := (&TimingBreakdownClient{config: eiq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := eiq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := eiq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(exectioninfo.Table, exectioninfo.FieldID, selector),
			sqlgraph.To(timingbreakdown.Table, timingbreakdown.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, exectioninfo.TimingBreakdownTable, exectioninfo.TimingBreakdownColumn),
		)
		fromU = sqlgraph.SetNeighbors(eiq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryResourceUsage chains the current query on the "resource_usage" edge.
func (eiq *ExectionInfoQuery) QueryResourceUsage() *ResourceUsageQuery {
	query := (&ResourceUsageClient{config: eiq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := eiq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := eiq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(exectioninfo.Table, exectioninfo.FieldID, selector),
			sqlgraph.To(resourceusage.Table, resourceusage.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, exectioninfo.ResourceUsageTable, exectioninfo.ResourceUsageColumn),
		)
		fromU = sqlgraph.SetNeighbors(eiq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithTestResult tells the query-builder to eager-load the nodes that are connected to
// the "test_result" edge. The optional arguments are used to configure the query builder of the edge.
func (eiq *ExectionInfoQuery) WithTestResult(opts ...func(*TestResultBESQuery)) *ExectionInfoQuery {
	query := (&TestResultBESClient{config: eiq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	eiq.withTestResult = query
	return eiq
}

// WithTimingBreakdown tells the query-builder to eager-load the nodes that are connected to
// the "timing_breakdown" edge. The optional arguments are used to configure the query builder of the edge.
func (eiq *ExectionInfoQuery) WithTimingBreakdown(opts ...func(*TimingBreakdownQuery)) *ExectionInfoQuery {
	query := (&TimingBreakdownClient{config: eiq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	eiq.withTimingBreakdown = query
	return eiq
}

// WithResourceUsage tells the query-builder to eager-load the nodes that are connected to
// the "resource_usage" edge. The optional arguments are used to configure the query builder of the edge.
func (eiq *ExectionInfoQuery) WithResourceUsage(opts ...func(*ResourceUsageQuery)) *ExectionInfoQuery {
	query := (&ResourceUsageClient{config: eiq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	eiq.withResourceUsage = query
	return eiq
}

// 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 {
//		TimeoutSeconds int32 `json:"timeout_seconds,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ExectionInfo.Query().
//		GroupBy(exectioninfo.FieldTimeoutSeconds).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (eiq *ExectionInfoQuery) GroupBy(field string, fields ...string) *ExectionInfoGroupBy {
	eiq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ExectionInfoGroupBy{build: eiq}
	grbuild.flds = &eiq.ctx.Fields
	grbuild.label = exectioninfo.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 {
//		TimeoutSeconds int32 `json:"timeout_seconds,omitempty"`
//	}
//
//	client.ExectionInfo.Query().
//		Select(exectioninfo.FieldTimeoutSeconds).
//		Scan(ctx, &v)
func (eiq *ExectionInfoQuery) Select(fields ...string) *ExectionInfoSelect {
	eiq.ctx.Fields = append(eiq.ctx.Fields, fields...)
	sbuild := &ExectionInfoSelect{ExectionInfoQuery: eiq}
	sbuild.label = exectioninfo.Label
	sbuild.flds, sbuild.scan = &eiq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ExectionInfoSelect configured with the given aggregations.
func (eiq *ExectionInfoQuery) Aggregate(fns ...AggregateFunc) *ExectionInfoSelect {
	return eiq.Select().Aggregate(fns...)
}

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

func (eiq *ExectionInfoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ExectionInfo, error) {
	var (
		nodes       = []*ExectionInfo{}
		withFKs     = eiq.withFKs
		_spec       = eiq.querySpec()
		loadedTypes = [3]bool{
			eiq.withTestResult != nil,
			eiq.withTimingBreakdown != nil,
			eiq.withResourceUsage != nil,
		}
	)
	if eiq.withTestResult != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, exectioninfo.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ExectionInfo).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ExectionInfo{config: eiq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(eiq.modifiers) > 0 {
		_spec.Modifiers = eiq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, eiq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := eiq.withTestResult; query != nil {
		if err := eiq.loadTestResult(ctx, query, nodes, nil,
			func(n *ExectionInfo, e *TestResultBES) { n.Edges.TestResult = e }); err != nil {
			return nil, err
		}
	}
	if query := eiq.withTimingBreakdown; query != nil {
		if err := eiq.loadTimingBreakdown(ctx, query, nodes, nil,
			func(n *ExectionInfo, e *TimingBreakdown) { n.Edges.TimingBreakdown = e }); err != nil {
			return nil, err
		}
	}
	if query := eiq.withResourceUsage; query != nil {
		if err := eiq.loadResourceUsage(ctx, query, nodes,
			func(n *ExectionInfo) { n.Edges.ResourceUsage = []*ResourceUsage{} },
			func(n *ExectionInfo, e *ResourceUsage) { n.Edges.ResourceUsage = append(n.Edges.ResourceUsage, e) }); err != nil {
			return nil, err
		}
	}
	for name, query := range eiq.withNamedResourceUsage {
		if err := eiq.loadResourceUsage(ctx, query, nodes,
			func(n *ExectionInfo) { n.appendNamedResourceUsage(name) },
			func(n *ExectionInfo, e *ResourceUsage) { n.appendNamedResourceUsage(name, e) }); err != nil {
			return nil, err
		}
	}
	for i := range eiq.loadTotal {
		if err := eiq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (eiq *ExectionInfoQuery) loadTestResult(ctx context.Context, query *TestResultBESQuery, nodes []*ExectionInfo, init func(*ExectionInfo), assign func(*ExectionInfo, *TestResultBES)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ExectionInfo)
	for i := range nodes {
		if nodes[i].test_result_bes_execution_info == nil {
			continue
		}
		fk := *nodes[i].test_result_bes_execution_info
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(testresultbes.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 "test_result_bes_execution_info" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (eiq *ExectionInfoQuery) loadTimingBreakdown(ctx context.Context, query *TimingBreakdownQuery, nodes []*ExectionInfo, init func(*ExectionInfo), assign func(*ExectionInfo, *TimingBreakdown)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ExectionInfo)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.TimingBreakdown(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(exectioninfo.TimingBreakdownColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.exection_info_timing_breakdown
		if fk == nil {
			return fmt.Errorf(`foreign-key "exection_info_timing_breakdown" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "exection_info_timing_breakdown" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (eiq *ExectionInfoQuery) loadResourceUsage(ctx context.Context, query *ResourceUsageQuery, nodes []*ExectionInfo, init func(*ExectionInfo), assign func(*ExectionInfo, *ResourceUsage)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ExectionInfo)
	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.ResourceUsage(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(exectioninfo.ResourceUsageColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.exection_info_resource_usage
		if fk == nil {
			return fmt.Errorf(`foreign-key "exection_info_resource_usage" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "exection_info_resource_usage" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// WithNamedResourceUsage tells the query-builder to eager-load the nodes that are connected to the "resource_usage"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (eiq *ExectionInfoQuery) WithNamedResourceUsage(name string, opts ...func(*ResourceUsageQuery)) *ExectionInfoQuery {
	query := (&ResourceUsageClient{config: eiq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if eiq.withNamedResourceUsage == nil {
		eiq.withNamedResourceUsage = make(map[string]*ResourceUsageQuery)
	}
	eiq.withNamedResourceUsage[name] = query
	return eiq
}

// ExectionInfoGroupBy is the group-by builder for ExectionInfo entities.
type ExectionInfoGroupBy struct {
	selector
	build *ExectionInfoQuery
}

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

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

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

// ExectionInfoSelect is the builder for selecting fields of ExectionInfo entities.
type ExectionInfoSelect struct {
	*ExectionInfoQuery
	selector
}

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

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

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