// 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/namedsetoffiles"
	"github.com/buildbarn/bb-portal/ent/gen/ent/outputgroup"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
	"github.com/buildbarn/bb-portal/ent/gen/ent/targetcomplete"
	"github.com/buildbarn/bb-portal/ent/gen/ent/testfile"
)

// OutputGroupQuery is the builder for querying OutputGroup entities.
type OutputGroupQuery struct {
	config
	ctx                  *QueryContext
	order                []outputgroup.OrderOption
	inters               []Interceptor
	predicates           []predicate.OutputGroup
	withTargetComplete   *TargetCompleteQuery
	withInlineFiles      *TestFileQuery
	withFileSets         *NamedSetOfFilesQuery
	withFKs              bool
	modifiers            []func(*sql.Selector)
	loadTotal            []func(context.Context, []*OutputGroup) error
	withNamedInlineFiles map[string]*TestFileQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the OutputGroupQuery builder.
func (ogq *OutputGroupQuery) Where(ps ...predicate.OutputGroup) *OutputGroupQuery {
	ogq.predicates = append(ogq.predicates, ps...)
	return ogq
}

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

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

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

// Order specifies how the records should be ordered.
func (ogq *OutputGroupQuery) Order(o ...outputgroup.OrderOption) *OutputGroupQuery {
	ogq.order = append(ogq.order, o...)
	return ogq
}

// QueryTargetComplete chains the current query on the "target_complete" edge.
func (ogq *OutputGroupQuery) QueryTargetComplete() *TargetCompleteQuery {
	query := (&TargetCompleteClient{config: ogq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ogq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ogq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(outputgroup.Table, outputgroup.FieldID, selector),
			sqlgraph.To(targetcomplete.Table, targetcomplete.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, outputgroup.TargetCompleteTable, outputgroup.TargetCompleteColumn),
		)
		fromU = sqlgraph.SetNeighbors(ogq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryInlineFiles chains the current query on the "inline_files" edge.
func (ogq *OutputGroupQuery) QueryInlineFiles() *TestFileQuery {
	query := (&TestFileClient{config: ogq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ogq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ogq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(outputgroup.Table, outputgroup.FieldID, selector),
			sqlgraph.To(testfile.Table, testfile.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, outputgroup.InlineFilesTable, outputgroup.InlineFilesColumn),
		)
		fromU = sqlgraph.SetNeighbors(ogq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryFileSets chains the current query on the "file_sets" edge.
func (ogq *OutputGroupQuery) QueryFileSets() *NamedSetOfFilesQuery {
	query := (&NamedSetOfFilesClient{config: ogq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ogq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ogq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(outputgroup.Table, outputgroup.FieldID, selector),
			sqlgraph.To(namedsetoffiles.Table, namedsetoffiles.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, outputgroup.FileSetsTable, outputgroup.FileSetsColumn),
		)
		fromU = sqlgraph.SetNeighbors(ogq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithTargetComplete tells the query-builder to eager-load the nodes that are connected to
// the "target_complete" edge. The optional arguments are used to configure the query builder of the edge.
func (ogq *OutputGroupQuery) WithTargetComplete(opts ...func(*TargetCompleteQuery)) *OutputGroupQuery {
	query := (&TargetCompleteClient{config: ogq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ogq.withTargetComplete = query
	return ogq
}

// WithInlineFiles tells the query-builder to eager-load the nodes that are connected to
// the "inline_files" edge. The optional arguments are used to configure the query builder of the edge.
func (ogq *OutputGroupQuery) WithInlineFiles(opts ...func(*TestFileQuery)) *OutputGroupQuery {
	query := (&TestFileClient{config: ogq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ogq.withInlineFiles = query
	return ogq
}

// WithFileSets tells the query-builder to eager-load the nodes that are connected to
// the "file_sets" edge. The optional arguments are used to configure the query builder of the edge.
func (ogq *OutputGroupQuery) WithFileSets(opts ...func(*NamedSetOfFilesQuery)) *OutputGroupQuery {
	query := (&NamedSetOfFilesClient{config: ogq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ogq.withFileSets = query
	return ogq
}

// 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 {
//		Name string `json:"name,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.OutputGroup.Query().
//		GroupBy(outputgroup.FieldName).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ogq *OutputGroupQuery) GroupBy(field string, fields ...string) *OutputGroupGroupBy {
	ogq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &OutputGroupGroupBy{build: ogq}
	grbuild.flds = &ogq.ctx.Fields
	grbuild.label = outputgroup.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 {
//		Name string `json:"name,omitempty"`
//	}
//
//	client.OutputGroup.Query().
//		Select(outputgroup.FieldName).
//		Scan(ctx, &v)
func (ogq *OutputGroupQuery) Select(fields ...string) *OutputGroupSelect {
	ogq.ctx.Fields = append(ogq.ctx.Fields, fields...)
	sbuild := &OutputGroupSelect{OutputGroupQuery: ogq}
	sbuild.label = outputgroup.Label
	sbuild.flds, sbuild.scan = &ogq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a OutputGroupSelect configured with the given aggregations.
func (ogq *OutputGroupQuery) Aggregate(fns ...AggregateFunc) *OutputGroupSelect {
	return ogq.Select().Aggregate(fns...)
}

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

func (ogq *OutputGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OutputGroup, error) {
	var (
		nodes       = []*OutputGroup{}
		withFKs     = ogq.withFKs
		_spec       = ogq.querySpec()
		loadedTypes = [3]bool{
			ogq.withTargetComplete != nil,
			ogq.withInlineFiles != nil,
			ogq.withFileSets != nil,
		}
	)
	if ogq.withTargetComplete != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, outputgroup.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*OutputGroup).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &OutputGroup{config: ogq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(ogq.modifiers) > 0 {
		_spec.Modifiers = ogq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ogq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ogq.withTargetComplete; query != nil {
		if err := ogq.loadTargetComplete(ctx, query, nodes, nil,
			func(n *OutputGroup, e *TargetComplete) { n.Edges.TargetComplete = e }); err != nil {
			return nil, err
		}
	}
	if query := ogq.withInlineFiles; query != nil {
		if err := ogq.loadInlineFiles(ctx, query, nodes,
			func(n *OutputGroup) { n.Edges.InlineFiles = []*TestFile{} },
			func(n *OutputGroup, e *TestFile) { n.Edges.InlineFiles = append(n.Edges.InlineFiles, e) }); err != nil {
			return nil, err
		}
	}
	if query := ogq.withFileSets; query != nil {
		if err := ogq.loadFileSets(ctx, query, nodes, nil,
			func(n *OutputGroup, e *NamedSetOfFiles) { n.Edges.FileSets = e }); err != nil {
			return nil, err
		}
	}
	for name, query := range ogq.withNamedInlineFiles {
		if err := ogq.loadInlineFiles(ctx, query, nodes,
			func(n *OutputGroup) { n.appendNamedInlineFiles(name) },
			func(n *OutputGroup, e *TestFile) { n.appendNamedInlineFiles(name, e) }); err != nil {
			return nil, err
		}
	}
	for i := range ogq.loadTotal {
		if err := ogq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ogq *OutputGroupQuery) loadTargetComplete(ctx context.Context, query *TargetCompleteQuery, nodes []*OutputGroup, init func(*OutputGroup), assign func(*OutputGroup, *TargetComplete)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*OutputGroup)
	for i := range nodes {
		if nodes[i].target_complete_output_group == nil {
			continue
		}
		fk := *nodes[i].target_complete_output_group
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(targetcomplete.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 "target_complete_output_group" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ogq *OutputGroupQuery) loadInlineFiles(ctx context.Context, query *TestFileQuery, nodes []*OutputGroup, init func(*OutputGroup), assign func(*OutputGroup, *TestFile)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*OutputGroup)
	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.TestFile(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(outputgroup.InlineFilesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.output_group_inline_files
		if fk == nil {
			return fmt.Errorf(`foreign-key "output_group_inline_files" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "output_group_inline_files" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (ogq *OutputGroupQuery) loadFileSets(ctx context.Context, query *NamedSetOfFilesQuery, nodes []*OutputGroup, init func(*OutputGroup), assign func(*OutputGroup, *NamedSetOfFiles)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*OutputGroup)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.NamedSetOfFiles(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(outputgroup.FileSetsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.output_group_file_sets
		if fk == nil {
			return fmt.Errorf(`foreign-key "output_group_file_sets" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "output_group_file_sets" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// WithNamedInlineFiles tells the query-builder to eager-load the nodes that are connected to the "inline_files"
// edge with the given name. The optional arguments are used to configure the query builder of the edge.
func (ogq *OutputGroupQuery) WithNamedInlineFiles(name string, opts ...func(*TestFileQuery)) *OutputGroupQuery {
	query := (&TestFileClient{config: ogq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	if ogq.withNamedInlineFiles == nil {
		ogq.withNamedInlineFiles = make(map[string]*TestFileQuery)
	}
	ogq.withNamedInlineFiles[name] = query
	return ogq
}

// OutputGroupGroupBy is the group-by builder for OutputGroup entities.
type OutputGroupGroupBy struct {
	selector
	build *OutputGroupQuery
}

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

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

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

// OutputGroupSelect is the builder for selecting fields of OutputGroup entities.
type OutputGroupSelect struct {
	*OutputGroupQuery
	selector
}

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

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

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