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

// ArtifactMetricsQuery is the builder for querying ArtifactMetrics entities.
type ArtifactMetricsQuery struct {
	config
	ctx                                *QueryContext
	order                              []artifactmetrics.OrderOption
	inters                             []Interceptor
	predicates                         []predicate.ArtifactMetrics
	withMetrics                        *MetricsQuery
	withSourceArtifactsRead            *FilesMetricQuery
	withOutputArtifactsSeen            *FilesMetricQuery
	withOutputArtifactsFromActionCache *FilesMetricQuery
	withTopLevelArtifacts              *FilesMetricQuery
	withFKs                            bool
	modifiers                          []func(*sql.Selector)
	loadTotal                          []func(context.Context, []*ArtifactMetrics) error
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the ArtifactMetricsQuery builder.
func (amq *ArtifactMetricsQuery) Where(ps ...predicate.ArtifactMetrics) *ArtifactMetricsQuery {
	amq.predicates = append(amq.predicates, ps...)
	return amq
}

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

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

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

// Order specifies how the records should be ordered.
func (amq *ArtifactMetricsQuery) Order(o ...artifactmetrics.OrderOption) *ArtifactMetricsQuery {
	amq.order = append(amq.order, o...)
	return amq
}

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

// QuerySourceArtifactsRead chains the current query on the "source_artifacts_read" edge.
func (amq *ArtifactMetricsQuery) QuerySourceArtifactsRead() *FilesMetricQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := amq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := amq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(artifactmetrics.Table, artifactmetrics.FieldID, selector),
			sqlgraph.To(filesmetric.Table, filesmetric.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, artifactmetrics.SourceArtifactsReadTable, artifactmetrics.SourceArtifactsReadColumn),
		)
		fromU = sqlgraph.SetNeighbors(amq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryOutputArtifactsSeen chains the current query on the "output_artifacts_seen" edge.
func (amq *ArtifactMetricsQuery) QueryOutputArtifactsSeen() *FilesMetricQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := amq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := amq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(artifactmetrics.Table, artifactmetrics.FieldID, selector),
			sqlgraph.To(filesmetric.Table, filesmetric.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, artifactmetrics.OutputArtifactsSeenTable, artifactmetrics.OutputArtifactsSeenColumn),
		)
		fromU = sqlgraph.SetNeighbors(amq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryOutputArtifactsFromActionCache chains the current query on the "output_artifacts_from_action_cache" edge.
func (amq *ArtifactMetricsQuery) QueryOutputArtifactsFromActionCache() *FilesMetricQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := amq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := amq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(artifactmetrics.Table, artifactmetrics.FieldID, selector),
			sqlgraph.To(filesmetric.Table, filesmetric.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, artifactmetrics.OutputArtifactsFromActionCacheTable, artifactmetrics.OutputArtifactsFromActionCacheColumn),
		)
		fromU = sqlgraph.SetNeighbors(amq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTopLevelArtifacts chains the current query on the "top_level_artifacts" edge.
func (amq *ArtifactMetricsQuery) QueryTopLevelArtifacts() *FilesMetricQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := amq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := amq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(artifactmetrics.Table, artifactmetrics.FieldID, selector),
			sqlgraph.To(filesmetric.Table, filesmetric.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, artifactmetrics.TopLevelArtifactsTable, artifactmetrics.TopLevelArtifactsColumn),
		)
		fromU = sqlgraph.SetNeighbors(amq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithSourceArtifactsRead tells the query-builder to eager-load the nodes that are connected to
// the "source_artifacts_read" edge. The optional arguments are used to configure the query builder of the edge.
func (amq *ArtifactMetricsQuery) WithSourceArtifactsRead(opts ...func(*FilesMetricQuery)) *ArtifactMetricsQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	amq.withSourceArtifactsRead = query
	return amq
}

// WithOutputArtifactsSeen tells the query-builder to eager-load the nodes that are connected to
// the "output_artifacts_seen" edge. The optional arguments are used to configure the query builder of the edge.
func (amq *ArtifactMetricsQuery) WithOutputArtifactsSeen(opts ...func(*FilesMetricQuery)) *ArtifactMetricsQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	amq.withOutputArtifactsSeen = query
	return amq
}

// WithOutputArtifactsFromActionCache tells the query-builder to eager-load the nodes that are connected to
// the "output_artifacts_from_action_cache" edge. The optional arguments are used to configure the query builder of the edge.
func (amq *ArtifactMetricsQuery) WithOutputArtifactsFromActionCache(opts ...func(*FilesMetricQuery)) *ArtifactMetricsQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	amq.withOutputArtifactsFromActionCache = query
	return amq
}

// WithTopLevelArtifacts tells the query-builder to eager-load the nodes that are connected to
// the "top_level_artifacts" edge. The optional arguments are used to configure the query builder of the edge.
func (amq *ArtifactMetricsQuery) WithTopLevelArtifacts(opts ...func(*FilesMetricQuery)) *ArtifactMetricsQuery {
	query := (&FilesMetricClient{config: amq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	amq.withTopLevelArtifacts = query
	return amq
}

// 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 (amq *ArtifactMetricsQuery) GroupBy(field string, fields ...string) *ArtifactMetricsGroupBy {
	amq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ArtifactMetricsGroupBy{build: amq}
	grbuild.flds = &amq.ctx.Fields
	grbuild.label = artifactmetrics.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 (amq *ArtifactMetricsQuery) Select(fields ...string) *ArtifactMetricsSelect {
	amq.ctx.Fields = append(amq.ctx.Fields, fields...)
	sbuild := &ArtifactMetricsSelect{ArtifactMetricsQuery: amq}
	sbuild.label = artifactmetrics.Label
	sbuild.flds, sbuild.scan = &amq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ArtifactMetricsSelect configured with the given aggregations.
func (amq *ArtifactMetricsQuery) Aggregate(fns ...AggregateFunc) *ArtifactMetricsSelect {
	return amq.Select().Aggregate(fns...)
}

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

func (amq *ArtifactMetricsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ArtifactMetrics, error) {
	var (
		nodes       = []*ArtifactMetrics{}
		withFKs     = amq.withFKs
		_spec       = amq.querySpec()
		loadedTypes = [5]bool{
			amq.withMetrics != nil,
			amq.withSourceArtifactsRead != nil,
			amq.withOutputArtifactsSeen != nil,
			amq.withOutputArtifactsFromActionCache != nil,
			amq.withTopLevelArtifacts != nil,
		}
	)
	if amq.withMetrics != nil || amq.withSourceArtifactsRead != nil || amq.withOutputArtifactsSeen != nil || amq.withOutputArtifactsFromActionCache != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, artifactmetrics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ArtifactMetrics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ArtifactMetrics{config: amq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(amq.modifiers) > 0 {
		_spec.Modifiers = amq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, amq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := amq.withMetrics; query != nil {
		if err := amq.loadMetrics(ctx, query, nodes, nil,
			func(n *ArtifactMetrics, e *Metrics) { n.Edges.Metrics = e }); err != nil {
			return nil, err
		}
	}
	if query := amq.withSourceArtifactsRead; query != nil {
		if err := amq.loadSourceArtifactsRead(ctx, query, nodes, nil,
			func(n *ArtifactMetrics, e *FilesMetric) { n.Edges.SourceArtifactsRead = e }); err != nil {
			return nil, err
		}
	}
	if query := amq.withOutputArtifactsSeen; query != nil {
		if err := amq.loadOutputArtifactsSeen(ctx, query, nodes, nil,
			func(n *ArtifactMetrics, e *FilesMetric) { n.Edges.OutputArtifactsSeen = e }); err != nil {
			return nil, err
		}
	}
	if query := amq.withOutputArtifactsFromActionCache; query != nil {
		if err := amq.loadOutputArtifactsFromActionCache(ctx, query, nodes, nil,
			func(n *ArtifactMetrics, e *FilesMetric) { n.Edges.OutputArtifactsFromActionCache = e }); err != nil {
			return nil, err
		}
	}
	if query := amq.withTopLevelArtifacts; query != nil {
		if err := amq.loadTopLevelArtifacts(ctx, query, nodes, nil,
			func(n *ArtifactMetrics, e *FilesMetric) { n.Edges.TopLevelArtifacts = e }); err != nil {
			return nil, err
		}
	}
	for i := range amq.loadTotal {
		if err := amq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (amq *ArtifactMetricsQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*ArtifactMetrics, init func(*ArtifactMetrics), assign func(*ArtifactMetrics, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ArtifactMetrics)
	for i := range nodes {
		if nodes[i].metrics_artifact_metrics == nil {
			continue
		}
		fk := *nodes[i].metrics_artifact_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_artifact_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (amq *ArtifactMetricsQuery) loadSourceArtifactsRead(ctx context.Context, query *FilesMetricQuery, nodes []*ArtifactMetrics, init func(*ArtifactMetrics), assign func(*ArtifactMetrics, *FilesMetric)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ArtifactMetrics)
	for i := range nodes {
		if nodes[i].artifact_metrics_source_artifacts_read == nil {
			continue
		}
		fk := *nodes[i].artifact_metrics_source_artifacts_read
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(filesmetric.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 "artifact_metrics_source_artifacts_read" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (amq *ArtifactMetricsQuery) loadOutputArtifactsSeen(ctx context.Context, query *FilesMetricQuery, nodes []*ArtifactMetrics, init func(*ArtifactMetrics), assign func(*ArtifactMetrics, *FilesMetric)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ArtifactMetrics)
	for i := range nodes {
		if nodes[i].artifact_metrics_output_artifacts_seen == nil {
			continue
		}
		fk := *nodes[i].artifact_metrics_output_artifacts_seen
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(filesmetric.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 "artifact_metrics_output_artifacts_seen" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (amq *ArtifactMetricsQuery) loadOutputArtifactsFromActionCache(ctx context.Context, query *FilesMetricQuery, nodes []*ArtifactMetrics, init func(*ArtifactMetrics), assign func(*ArtifactMetrics, *FilesMetric)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ArtifactMetrics)
	for i := range nodes {
		if nodes[i].artifact_metrics_output_artifacts_from_action_cache == nil {
			continue
		}
		fk := *nodes[i].artifact_metrics_output_artifacts_from_action_cache
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(filesmetric.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 "artifact_metrics_output_artifacts_from_action_cache" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (amq *ArtifactMetricsQuery) loadTopLevelArtifacts(ctx context.Context, query *FilesMetricQuery, nodes []*ArtifactMetrics, init func(*ArtifactMetrics), assign func(*ArtifactMetrics, *FilesMetric)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*ArtifactMetrics)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.FilesMetric(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(artifactmetrics.TopLevelArtifactsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.artifact_metrics_top_level_artifacts
		if fk == nil {
			return fmt.Errorf(`foreign-key "artifact_metrics_top_level_artifacts" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "artifact_metrics_top_level_artifacts" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// ArtifactMetricsGroupBy is the group-by builder for ArtifactMetrics entities.
type ArtifactMetricsGroupBy struct {
	selector
	build *ArtifactMetricsQuery
}

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

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

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

// ArtifactMetricsSelect is the builder for selecting fields of ArtifactMetrics entities.
type ArtifactMetricsSelect struct {
	*ArtifactMetricsQuery
	selector
}

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

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

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