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

// MemoryMetricsQuery is the builder for querying MemoryMetrics entities.
type MemoryMetricsQuery struct {
	config
	ctx                     *QueryContext
	order                   []memorymetrics.OrderOption
	inters                  []Interceptor
	predicates              []predicate.MemoryMetrics
	withMetrics             *MetricsQuery
	withGarbageMetrics      *GarbageMetricsQuery
	withFKs                 bool
	modifiers               []func(*sql.Selector)
	loadTotal               []func(context.Context, []*MemoryMetrics) error
	withNamedGarbageMetrics map[string]*GarbageMetricsQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the MemoryMetricsQuery builder.
func (mmq *MemoryMetricsQuery) Where(ps ...predicate.MemoryMetrics) *MemoryMetricsQuery {
	mmq.predicates = append(mmq.predicates, ps...)
	return mmq
}

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

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

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

// Order specifies how the records should be ordered.
func (mmq *MemoryMetricsQuery) Order(o ...memorymetrics.OrderOption) *MemoryMetricsQuery {
	mmq.order = append(mmq.order, o...)
	return mmq
}

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

// QueryGarbageMetrics chains the current query on the "garbage_metrics" edge.
func (mmq *MemoryMetricsQuery) QueryGarbageMetrics() *GarbageMetricsQuery {
	query := (&GarbageMetricsClient{config: mmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(memorymetrics.Table, memorymetrics.FieldID, selector),
			sqlgraph.To(garbagemetrics.Table, garbagemetrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, memorymetrics.GarbageMetricsTable, memorymetrics.GarbageMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithGarbageMetrics tells the query-builder to eager-load the nodes that are connected to
// the "garbage_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (mmq *MemoryMetricsQuery) WithGarbageMetrics(opts ...func(*GarbageMetricsQuery)) *MemoryMetricsQuery {
	query := (&GarbageMetricsClient{config: mmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mmq.withGarbageMetrics = query
	return mmq
}

// 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 {
//		PeakPostGcHeapSize int64 `json:"peak_post_gc_heap_size,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.MemoryMetrics.Query().
//		GroupBy(memorymetrics.FieldPeakPostGcHeapSize).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (mmq *MemoryMetricsQuery) GroupBy(field string, fields ...string) *MemoryMetricsGroupBy {
	mmq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &MemoryMetricsGroupBy{build: mmq}
	grbuild.flds = &mmq.ctx.Fields
	grbuild.label = memorymetrics.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 {
//		PeakPostGcHeapSize int64 `json:"peak_post_gc_heap_size,omitempty"`
//	}
//
//	client.MemoryMetrics.Query().
//		Select(memorymetrics.FieldPeakPostGcHeapSize).
//		Scan(ctx, &v)
func (mmq *MemoryMetricsQuery) Select(fields ...string) *MemoryMetricsSelect {
	mmq.ctx.Fields = append(mmq.ctx.Fields, fields...)
	sbuild := &MemoryMetricsSelect{MemoryMetricsQuery: mmq}
	sbuild.label = memorymetrics.Label
	sbuild.flds, sbuild.scan = &mmq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a MemoryMetricsSelect configured with the given aggregations.
func (mmq *MemoryMetricsQuery) Aggregate(fns ...AggregateFunc) *MemoryMetricsSelect {
	return mmq.Select().Aggregate(fns...)
}

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

func (mmq *MemoryMetricsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*MemoryMetrics, error) {
	var (
		nodes       = []*MemoryMetrics{}
		withFKs     = mmq.withFKs
		_spec       = mmq.querySpec()
		loadedTypes = [2]bool{
			mmq.withMetrics != nil,
			mmq.withGarbageMetrics != nil,
		}
	)
	if mmq.withMetrics != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, memorymetrics.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*MemoryMetrics).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &MemoryMetrics{config: mmq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(mmq.modifiers) > 0 {
		_spec.Modifiers = mmq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, mmq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := mmq.withMetrics; query != nil {
		if err := mmq.loadMetrics(ctx, query, nodes, nil,
			func(n *MemoryMetrics, e *Metrics) { n.Edges.Metrics = e }); err != nil {
			return nil, err
		}
	}
	if query := mmq.withGarbageMetrics; query != nil {
		if err := mmq.loadGarbageMetrics(ctx, query, nodes,
			func(n *MemoryMetrics) { n.Edges.GarbageMetrics = []*GarbageMetrics{} },
			func(n *MemoryMetrics, e *GarbageMetrics) { n.Edges.GarbageMetrics = append(n.Edges.GarbageMetrics, e) }); err != nil {
			return nil, err
		}
	}
	for name, query := range mmq.withNamedGarbageMetrics {
		if err := mmq.loadGarbageMetrics(ctx, query, nodes,
			func(n *MemoryMetrics) { n.appendNamedGarbageMetrics(name) },
			func(n *MemoryMetrics, e *GarbageMetrics) { n.appendNamedGarbageMetrics(name, e) }); err != nil {
			return nil, err
		}
	}
	for i := range mmq.loadTotal {
		if err := mmq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (mmq *MemoryMetricsQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*MemoryMetrics, init func(*MemoryMetrics), assign func(*MemoryMetrics, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*MemoryMetrics)
	for i := range nodes {
		if nodes[i].metrics_memory_metrics == nil {
			continue
		}
		fk := *nodes[i].metrics_memory_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_memory_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (mmq *MemoryMetricsQuery) loadGarbageMetrics(ctx context.Context, query *GarbageMetricsQuery, nodes []*MemoryMetrics, init func(*MemoryMetrics), assign func(*MemoryMetrics, *GarbageMetrics)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*MemoryMetrics)
	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.GarbageMetrics(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(memorymetrics.GarbageMetricsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.memory_metrics_garbage_metrics
		if fk == nil {
			return fmt.Errorf(`foreign-key "memory_metrics_garbage_metrics" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "memory_metrics_garbage_metrics" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// WithNamedGarbageMetrics tells the query-builder to eager-load the nodes that are connected to the "garbage_metrics"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (mmq *MemoryMetricsQuery) WithNamedGarbageMetrics(name string, opts ...func(*GarbageMetricsQuery)) *MemoryMetricsQuery {
	query := (&GarbageMetricsClient{config: mmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if mmq.withNamedGarbageMetrics == nil {
		mmq.withNamedGarbageMetrics = make(map[string]*GarbageMetricsQuery)
	}
	mmq.withNamedGarbageMetrics[name] = query
	return mmq
}

// MemoryMetricsGroupBy is the group-by builder for MemoryMetrics entities.
type MemoryMetricsGroupBy struct {
	selector
	build *MemoryMetricsQuery
}

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

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

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

// MemoryMetricsSelect is the builder for selecting fields of MemoryMetrics entities.
type MemoryMetricsSelect struct {
	*MemoryMetricsQuery
	selector
}

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

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

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