// 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/actioncachestatistics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/actiondata"
	"github.com/buildbarn/bb-portal/ent/gen/ent/actionsummary"
	"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/runnercount"
)

// ActionSummaryQuery is the builder for querying ActionSummary entities.
type ActionSummaryQuery struct {
	config
	ctx                       *QueryContext
	order                     []actionsummary.OrderOption
	inters                    []Interceptor
	predicates                []predicate.ActionSummary
	withMetrics               *MetricsQuery
	withActionData            *ActionDataQuery
	withRunnerCount           *RunnerCountQuery
	withActionCacheStatistics *ActionCacheStatisticsQuery
	withFKs                   bool
	modifiers                 []func(*sql.Selector)
	loadTotal                 []func(context.Context, []*ActionSummary) error
	withNamedActionData       map[string]*ActionDataQuery
	withNamedRunnerCount      map[string]*RunnerCountQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the ActionSummaryQuery builder.
func (asq *ActionSummaryQuery) Where(ps ...predicate.ActionSummary) *ActionSummaryQuery {
	asq.predicates = append(asq.predicates, ps...)
	return asq
}

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

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

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

// Order specifies how the records should be ordered.
func (asq *ActionSummaryQuery) Order(o ...actionsummary.OrderOption) *ActionSummaryQuery {
	asq.order = append(asq.order, o...)
	return asq
}

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

// QueryActionData chains the current query on the "action_data" edge.
func (asq *ActionSummaryQuery) QueryActionData() *ActionDataQuery {
	query := (&ActionDataClient{config: asq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := asq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := asq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(actionsummary.Table, actionsummary.FieldID, selector),
			sqlgraph.To(actiondata.Table, actiondata.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, actionsummary.ActionDataTable, actionsummary.ActionDataColumn),
		)
		fromU = sqlgraph.SetNeighbors(asq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryRunnerCount chains the current query on the "runner_count" edge.
func (asq *ActionSummaryQuery) QueryRunnerCount() *RunnerCountQuery {
	query := (&RunnerCountClient{config: asq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := asq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := asq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(actionsummary.Table, actionsummary.FieldID, selector),
			sqlgraph.To(runnercount.Table, runnercount.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, actionsummary.RunnerCountTable, actionsummary.RunnerCountColumn),
		)
		fromU = sqlgraph.SetNeighbors(asq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryActionCacheStatistics chains the current query on the "action_cache_statistics" edge.
func (asq *ActionSummaryQuery) QueryActionCacheStatistics() *ActionCacheStatisticsQuery {
	query := (&ActionCacheStatisticsClient{config: asq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := asq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := asq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(actionsummary.Table, actionsummary.FieldID, selector),
			sqlgraph.To(actioncachestatistics.Table, actioncachestatistics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, actionsummary.ActionCacheStatisticsTable, actionsummary.ActionCacheStatisticsColumn),
		)
		fromU = sqlgraph.SetNeighbors(asq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithActionData tells the query-builder to eager-load the nodes that are connected to
// the "action_data" edge. The optional arguments are used to configure the query builder of the edge.
func (asq *ActionSummaryQuery) WithActionData(opts ...func(*ActionDataQuery)) *ActionSummaryQuery {
	query := (&ActionDataClient{config: asq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	asq.withActionData = query
	return asq
}

// WithRunnerCount tells the query-builder to eager-load the nodes that are connected to
// the "runner_count" edge. The optional arguments are used to configure the query builder of the edge.
func (asq *ActionSummaryQuery) WithRunnerCount(opts ...func(*RunnerCountQuery)) *ActionSummaryQuery {
	query := (&RunnerCountClient{config: asq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	asq.withRunnerCount = query
	return asq
}

// WithActionCacheStatistics tells the query-builder to eager-load the nodes that are connected to
// the "action_cache_statistics" edge. The optional arguments are used to configure the query builder of the edge.
func (asq *ActionSummaryQuery) WithActionCacheStatistics(opts ...func(*ActionCacheStatisticsQuery)) *ActionSummaryQuery {
	query := (&ActionCacheStatisticsClient{config: asq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	asq.withActionCacheStatistics = query
	return asq
}

// 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 {
//		ActionsCreated int64 `json:"actions_created,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ActionSummary.Query().
//		GroupBy(actionsummary.FieldActionsCreated).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (asq *ActionSummaryQuery) GroupBy(field string, fields ...string) *ActionSummaryGroupBy {
	asq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ActionSummaryGroupBy{build: asq}
	grbuild.flds = &asq.ctx.Fields
	grbuild.label = actionsummary.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 {
//		ActionsCreated int64 `json:"actions_created,omitempty"`
//	}
//
//	client.ActionSummary.Query().
//		Select(actionsummary.FieldActionsCreated).
//		Scan(ctx, &v)
func (asq *ActionSummaryQuery) Select(fields ...string) *ActionSummarySelect {
	asq.ctx.Fields = append(asq.ctx.Fields, fields...)
	sbuild := &ActionSummarySelect{ActionSummaryQuery: asq}
	sbuild.label = actionsummary.Label
	sbuild.flds, sbuild.scan = &asq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ActionSummarySelect configured with the given aggregations.
func (asq *ActionSummaryQuery) Aggregate(fns ...AggregateFunc) *ActionSummarySelect {
	return asq.Select().Aggregate(fns...)
}

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

func (asq *ActionSummaryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ActionSummary, error) {
	var (
		nodes       = []*ActionSummary{}
		withFKs     = asq.withFKs
		_spec       = asq.querySpec()
		loadedTypes = [4]bool{
			asq.withMetrics != nil,
			asq.withActionData != nil,
			asq.withRunnerCount != nil,
			asq.withActionCacheStatistics != nil,
		}
	)
	if asq.withMetrics != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, actionsummary.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ActionSummary).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ActionSummary{config: asq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(asq.modifiers) > 0 {
		_spec.Modifiers = asq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, asq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := asq.withMetrics; query != nil {
		if err := asq.loadMetrics(ctx, query, nodes, nil,
			func(n *ActionSummary, e *Metrics) { n.Edges.Metrics = e }); err != nil {
			return nil, err
		}
	}
	if query := asq.withActionData; query != nil {
		if err := asq.loadActionData(ctx, query, nodes,
			func(n *ActionSummary) { n.Edges.ActionData = []*ActionData{} },
			func(n *ActionSummary, e *ActionData) { n.Edges.ActionData = append(n.Edges.ActionData, e) }); err != nil {
			return nil, err
		}
	}
	if query := asq.withRunnerCount; query != nil {
		if err := asq.loadRunnerCount(ctx, query, nodes,
			func(n *ActionSummary) { n.Edges.RunnerCount = []*RunnerCount{} },
			func(n *ActionSummary, e *RunnerCount) { n.Edges.RunnerCount = append(n.Edges.RunnerCount, e) }); err != nil {
			return nil, err
		}
	}
	if query := asq.withActionCacheStatistics; query != nil {
		if err := asq.loadActionCacheStatistics(ctx, query, nodes, nil,
			func(n *ActionSummary, e *ActionCacheStatistics) { n.Edges.ActionCacheStatistics = e }); err != nil {
			return nil, err
		}
	}
	for name, query := range asq.withNamedActionData {
		if err := asq.loadActionData(ctx, query, nodes,
			func(n *ActionSummary) { n.appendNamedActionData(name) },
			func(n *ActionSummary, e *ActionData) { n.appendNamedActionData(name, e) }); err != nil {
			return nil, err
		}
	}
	for name, query := range asq.withNamedRunnerCount {
		if err := asq.loadRunnerCount(ctx, query, nodes,
			func(n *ActionSummary) { n.appendNamedRunnerCount(name) },
			func(n *ActionSummary, e *RunnerCount) { n.appendNamedRunnerCount(name, e) }); err != nil {
			return nil, err
		}
	}
	for i := range asq.loadTotal {
		if err := asq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (asq *ActionSummaryQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*ActionSummary, init func(*ActionSummary), assign func(*ActionSummary, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ActionSummary)
	for i := range nodes {
		if nodes[i].metrics_action_summary == nil {
			continue
		}
		fk := *nodes[i].metrics_action_summary
		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_action_summary" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (asq *ActionSummaryQuery) loadActionData(ctx context.Context, query *ActionDataQuery, nodes []*ActionSummary, init func(*ActionSummary), assign func(*ActionSummary, *ActionData)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ActionSummary)
	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.ActionData(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(actionsummary.ActionDataColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.action_summary_action_data
		if fk == nil {
			return fmt.Errorf(`foreign-key "action_summary_action_data" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "action_summary_action_data" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (asq *ActionSummaryQuery) loadRunnerCount(ctx context.Context, query *RunnerCountQuery, nodes []*ActionSummary, init func(*ActionSummary), assign func(*ActionSummary, *RunnerCount)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ActionSummary)
	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.RunnerCount(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(actionsummary.RunnerCountColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.action_summary_runner_count
		if fk == nil {
			return fmt.Errorf(`foreign-key "action_summary_runner_count" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "action_summary_runner_count" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (asq *ActionSummaryQuery) loadActionCacheStatistics(ctx context.Context, query *ActionCacheStatisticsQuery, nodes []*ActionSummary, init func(*ActionSummary), assign func(*ActionSummary, *ActionCacheStatistics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ActionSummary)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.ActionCacheStatistics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(actionsummary.ActionCacheStatisticsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.action_summary_action_cache_statistics
		if fk == nil {
			return fmt.Errorf(`foreign-key "action_summary_action_cache_statistics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "action_summary_action_cache_statistics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// WithNamedActionData tells the query-builder to eager-load the nodes that are connected to the "action_data"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (asq *ActionSummaryQuery) WithNamedActionData(name string, opts ...func(*ActionDataQuery)) *ActionSummaryQuery {
	query := (&ActionDataClient{config: asq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if asq.withNamedActionData == nil {
		asq.withNamedActionData = make(map[string]*ActionDataQuery)
	}
	asq.withNamedActionData[name] = query
	return asq
}

// WithNamedRunnerCount tells the query-builder to eager-load the nodes that are connected to the "runner_count"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (asq *ActionSummaryQuery) WithNamedRunnerCount(name string, opts ...func(*RunnerCountQuery)) *ActionSummaryQuery {
	query := (&RunnerCountClient{config: asq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if asq.withNamedRunnerCount == nil {
		asq.withNamedRunnerCount = make(map[string]*RunnerCountQuery)
	}
	asq.withNamedRunnerCount[name] = query
	return asq
}

// ActionSummaryGroupBy is the group-by builder for ActionSummary entities.
type ActionSummaryGroupBy struct {
	selector
	build *ActionSummaryQuery
}

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

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

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

// ActionSummarySelect is the builder for selecting fields of ActionSummary entities.
type ActionSummarySelect struct {
	*ActionSummaryQuery
	selector
}

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

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

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