// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"wechat-api/ent/messagerecords"
	"wechat-api/ent/predicate"
	"wechat-api/ent/sopnode"
	"wechat-api/ent/sopstage"
	"wechat-api/ent/soptask"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// SopStageQuery is the builder for querying SopStage entities.
type SopStageQuery struct {
	config
	ctx               *QueryContext
	order             []sopstage.OrderOption
	inters            []Interceptor
	predicates        []predicate.SopStage
	withSopTask       *SopTaskQuery
	withStageNodes    *SopNodeQuery
	withStageMessages *MessageRecordsQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the SopStageQuery builder.
func (ssq *SopStageQuery) Where(ps ...predicate.SopStage) *SopStageQuery {
	ssq.predicates = append(ssq.predicates, ps...)
	return ssq
}

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

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

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

// Order specifies how the records should be ordered.
func (ssq *SopStageQuery) Order(o ...sopstage.OrderOption) *SopStageQuery {
	ssq.order = append(ssq.order, o...)
	return ssq
}

// QuerySopTask chains the current query on the "sop_task" edge.
func (ssq *SopStageQuery) QuerySopTask() *SopTaskQuery {
	query := (&SopTaskClient{config: ssq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ssq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ssq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sopstage.Table, sopstage.FieldID, selector),
			sqlgraph.To(soptask.Table, soptask.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, sopstage.SopTaskTable, sopstage.SopTaskColumn),
		)
		fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryStageNodes chains the current query on the "stage_nodes" edge.
func (ssq *SopStageQuery) QueryStageNodes() *SopNodeQuery {
	query := (&SopNodeClient{config: ssq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ssq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ssq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sopstage.Table, sopstage.FieldID, selector),
			sqlgraph.To(sopnode.Table, sopnode.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, sopstage.StageNodesTable, sopstage.StageNodesColumn),
		)
		fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryStageMessages chains the current query on the "stage_messages" edge.
func (ssq *SopStageQuery) QueryStageMessages() *MessageRecordsQuery {
	query := (&MessageRecordsClient{config: ssq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ssq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ssq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sopstage.Table, sopstage.FieldID, selector),
			sqlgraph.To(messagerecords.Table, messagerecords.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, sopstage.StageMessagesTable, sopstage.StageMessagesColumn),
		)
		fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first SopStage ID from the query.
// Returns a *NotFoundError when no SopStage ID was found.
func (ssq *SopStageQuery) FirstID(ctx context.Context) (id uint64, err error) {
	var ids []uint64
	if ids, err = ssq.Limit(1).IDs(setContextOp(ctx, ssq.ctx, "FirstID")); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{sopstage.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of SopStages.
func (ssq *SopStageQuery) All(ctx context.Context) ([]*SopStage, error) {
	ctx = setContextOp(ctx, ssq.ctx, "All")
	if err := ssq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*SopStage, *SopStageQuery]()
	return withInterceptors[[]*SopStage](ctx, ssq, qr, ssq.inters)
}

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

// IDs executes the query and returns a list of SopStage IDs.
func (ssq *SopStageQuery) IDs(ctx context.Context) (ids []uint64, err error) {
	if ssq.ctx.Unique == nil && ssq.path != nil {
		ssq.Unique(true)
	}
	ctx = setContextOp(ctx, ssq.ctx, "IDs")
	if err = ssq.Select(sopstage.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithSopTask tells the query-builder to eager-load the nodes that are connected to
// the "sop_task" edge. The optional arguments are used to configure the query builder of the edge.
func (ssq *SopStageQuery) WithSopTask(opts ...func(*SopTaskQuery)) *SopStageQuery {
	query := (&SopTaskClient{config: ssq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ssq.withSopTask = query
	return ssq
}

// WithStageNodes tells the query-builder to eager-load the nodes that are connected to
// the "stage_nodes" edge. The optional arguments are used to configure the query builder of the edge.
func (ssq *SopStageQuery) WithStageNodes(opts ...func(*SopNodeQuery)) *SopStageQuery {
	query := (&SopNodeClient{config: ssq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ssq.withStageNodes = query
	return ssq
}

// WithStageMessages tells the query-builder to eager-load the nodes that are connected to
// the "stage_messages" edge. The optional arguments are used to configure the query builder of the edge.
func (ssq *SopStageQuery) WithStageMessages(opts ...func(*MessageRecordsQuery)) *SopStageQuery {
	query := (&MessageRecordsClient{config: ssq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ssq.withStageMessages = query
	return ssq
}

// 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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.SopStage.Query().
//		GroupBy(sopstage.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ssq *SopStageQuery) GroupBy(field string, fields ...string) *SopStageGroupBy {
	ssq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &SopStageGroupBy{build: ssq}
	grbuild.flds = &ssq.ctx.Fields
	grbuild.label = sopstage.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.SopStage.Query().
//		Select(sopstage.FieldCreatedAt).
//		Scan(ctx, &v)
func (ssq *SopStageQuery) Select(fields ...string) *SopStageSelect {
	ssq.ctx.Fields = append(ssq.ctx.Fields, fields...)
	sbuild := &SopStageSelect{SopStageQuery: ssq}
	sbuild.label = sopstage.Label
	sbuild.flds, sbuild.scan = &ssq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a SopStageSelect configured with the given aggregations.
func (ssq *SopStageQuery) Aggregate(fns ...AggregateFunc) *SopStageSelect {
	return ssq.Select().Aggregate(fns...)
}

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

func (ssq *SopStageQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SopStage, error) {
	var (
		nodes       = []*SopStage{}
		_spec       = ssq.querySpec()
		loadedTypes = [3]bool{
			ssq.withSopTask != nil,
			ssq.withStageNodes != nil,
			ssq.withStageMessages != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*SopStage).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &SopStage{config: ssq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ssq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ssq.withSopTask; query != nil {
		if err := ssq.loadSopTask(ctx, query, nodes, nil,
			func(n *SopStage, e *SopTask) { n.Edges.SopTask = e }); err != nil {
			return nil, err
		}
	}
	if query := ssq.withStageNodes; query != nil {
		if err := ssq.loadStageNodes(ctx, query, nodes,
			func(n *SopStage) { n.Edges.StageNodes = []*SopNode{} },
			func(n *SopStage, e *SopNode) { n.Edges.StageNodes = append(n.Edges.StageNodes, e) }); err != nil {
			return nil, err
		}
	}
	if query := ssq.withStageMessages; query != nil {
		if err := ssq.loadStageMessages(ctx, query, nodes,
			func(n *SopStage) { n.Edges.StageMessages = []*MessageRecords{} },
			func(n *SopStage, e *MessageRecords) { n.Edges.StageMessages = append(n.Edges.StageMessages, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ssq *SopStageQuery) loadSopTask(ctx context.Context, query *SopTaskQuery, nodes []*SopStage, init func(*SopStage), assign func(*SopStage, *SopTask)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*SopStage)
	for i := range nodes {
		fk := nodes[i].TaskID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(soptask.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 "task_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ssq *SopStageQuery) loadStageNodes(ctx context.Context, query *SopNodeQuery, nodes []*SopStage, init func(*SopStage), assign func(*SopStage, *SopNode)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uint64]*SopStage)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(sopnode.FieldStageID)
	}
	query.Where(predicate.SopNode(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(sopstage.StageNodesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.StageID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "stage_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (ssq *SopStageQuery) loadStageMessages(ctx context.Context, query *MessageRecordsQuery, nodes []*SopStage, init func(*SopStage), assign func(*SopStage, *MessageRecords)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uint64]*SopStage)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(messagerecords.FieldSourceID)
	}
	query.Where(predicate.MessageRecords(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(sopstage.StageMessagesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.SourceID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "source_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// SopStageGroupBy is the group-by builder for SopStage entities.
type SopStageGroupBy struct {
	selector
	build *SopStageQuery
}

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

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

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

// SopStageSelect is the builder for selecting fields of SopStage entities.
type SopStageSelect struct {
	*SopStageQuery
	selector
}

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

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

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