// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lightsparkdev/spark/so/ent/predicate"
	"github.com/lightsparkdev/spark/so/ent/preimagerequest"
	"github.com/lightsparkdev/spark/so/ent/treenode"
	"github.com/lightsparkdev/spark/so/ent/usersignedtransaction"
)

// UserSignedTransactionQuery is the builder for querying UserSignedTransaction entities.
type UserSignedTransactionQuery struct {
	config
	ctx                 *QueryContext
	order               []usersignedtransaction.OrderOption
	inters              []Interceptor
	predicates          []predicate.UserSignedTransaction
	withTreeNode        *TreeNodeQuery
	withPreimageRequest *PreimageRequestQuery
	withFKs             bool
	modifiers           []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the UserSignedTransactionQuery builder.
func (ustq *UserSignedTransactionQuery) Where(ps ...predicate.UserSignedTransaction) *UserSignedTransactionQuery {
	ustq.predicates = append(ustq.predicates, ps...)
	return ustq
}

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

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

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

// Order specifies how the records should be ordered.
func (ustq *UserSignedTransactionQuery) Order(o ...usersignedtransaction.OrderOption) *UserSignedTransactionQuery {
	ustq.order = append(ustq.order, o...)
	return ustq
}

// QueryTreeNode chains the current query on the "tree_node" edge.
func (ustq *UserSignedTransactionQuery) QueryTreeNode() *TreeNodeQuery {
	query := (&TreeNodeClient{config: ustq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ustq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ustq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(usersignedtransaction.Table, usersignedtransaction.FieldID, selector),
			sqlgraph.To(treenode.Table, treenode.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, usersignedtransaction.TreeNodeTable, usersignedtransaction.TreeNodeColumn),
		)
		fromU = sqlgraph.SetNeighbors(ustq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPreimageRequest chains the current query on the "preimage_request" edge.
func (ustq *UserSignedTransactionQuery) QueryPreimageRequest() *PreimageRequestQuery {
	query := (&PreimageRequestClient{config: ustq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ustq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ustq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(usersignedtransaction.Table, usersignedtransaction.FieldID, selector),
			sqlgraph.To(preimagerequest.Table, preimagerequest.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, usersignedtransaction.PreimageRequestTable, usersignedtransaction.PreimageRequestColumn),
		)
		fromU = sqlgraph.SetNeighbors(ustq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of UserSignedTransaction IDs.
func (ustq *UserSignedTransactionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if ustq.ctx.Unique == nil && ustq.path != nil {
		ustq.Unique(true)
	}
	ctx = setContextOp(ctx, ustq.ctx, ent.OpQueryIDs)
	if err = ustq.Select(usersignedtransaction.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithTreeNode tells the query-builder to eager-load the nodes that are connected to
// the "tree_node" edge. The optional arguments are used to configure the query builder of the edge.
func (ustq *UserSignedTransactionQuery) WithTreeNode(opts ...func(*TreeNodeQuery)) *UserSignedTransactionQuery {
	query := (&TreeNodeClient{config: ustq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ustq.withTreeNode = query
	return ustq
}

// WithPreimageRequest tells the query-builder to eager-load the nodes that are connected to
// the "preimage_request" edge. The optional arguments are used to configure the query builder of the edge.
func (ustq *UserSignedTransactionQuery) WithPreimageRequest(opts ...func(*PreimageRequestQuery)) *UserSignedTransactionQuery {
	query := (&PreimageRequestClient{config: ustq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ustq.withPreimageRequest = query
	return ustq
}

// 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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.UserSignedTransaction.Query().
//		GroupBy(usersignedtransaction.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ustq *UserSignedTransactionQuery) GroupBy(field string, fields ...string) *UserSignedTransactionGroupBy {
	ustq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &UserSignedTransactionGroupBy{build: ustq}
	grbuild.flds = &ustq.ctx.Fields
	grbuild.label = usersignedtransaction.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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//	}
//
//	client.UserSignedTransaction.Query().
//		Select(usersignedtransaction.FieldCreateTime).
//		Scan(ctx, &v)
func (ustq *UserSignedTransactionQuery) Select(fields ...string) *UserSignedTransactionSelect {
	ustq.ctx.Fields = append(ustq.ctx.Fields, fields...)
	sbuild := &UserSignedTransactionSelect{UserSignedTransactionQuery: ustq}
	sbuild.label = usersignedtransaction.Label
	sbuild.flds, sbuild.scan = &ustq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a UserSignedTransactionSelect configured with the given aggregations.
func (ustq *UserSignedTransactionQuery) Aggregate(fns ...AggregateFunc) *UserSignedTransactionSelect {
	return ustq.Select().Aggregate(fns...)
}

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

func (ustq *UserSignedTransactionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserSignedTransaction, error) {
	var (
		nodes       = []*UserSignedTransaction{}
		withFKs     = ustq.withFKs
		_spec       = ustq.querySpec()
		loadedTypes = [2]bool{
			ustq.withTreeNode != nil,
			ustq.withPreimageRequest != nil,
		}
	)
	if ustq.withTreeNode != nil || ustq.withPreimageRequest != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, usersignedtransaction.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*UserSignedTransaction).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &UserSignedTransaction{config: ustq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(ustq.modifiers) > 0 {
		_spec.Modifiers = ustq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ustq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ustq.withTreeNode; query != nil {
		if err := ustq.loadTreeNode(ctx, query, nodes, nil,
			func(n *UserSignedTransaction, e *TreeNode) { n.Edges.TreeNode = e }); err != nil {
			return nil, err
		}
	}
	if query := ustq.withPreimageRequest; query != nil {
		if err := ustq.loadPreimageRequest(ctx, query, nodes, nil,
			func(n *UserSignedTransaction, e *PreimageRequest) { n.Edges.PreimageRequest = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ustq *UserSignedTransactionQuery) loadTreeNode(ctx context.Context, query *TreeNodeQuery, nodes []*UserSignedTransaction, init func(*UserSignedTransaction), assign func(*UserSignedTransaction, *TreeNode)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*UserSignedTransaction)
	for i := range nodes {
		if nodes[i].user_signed_transaction_tree_node == nil {
			continue
		}
		fk := *nodes[i].user_signed_transaction_tree_node
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(treenode.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 "user_signed_transaction_tree_node" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ustq *UserSignedTransactionQuery) loadPreimageRequest(ctx context.Context, query *PreimageRequestQuery, nodes []*UserSignedTransaction, init func(*UserSignedTransaction), assign func(*UserSignedTransaction, *PreimageRequest)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*UserSignedTransaction)
	for i := range nodes {
		if nodes[i].user_signed_transaction_preimage_request == nil {
			continue
		}
		fk := *nodes[i].user_signed_transaction_preimage_request
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(preimagerequest.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 "user_signed_transaction_preimage_request" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (ustq *UserSignedTransactionQuery) ForUpdate(opts ...sql.LockOption) *UserSignedTransactionQuery {
	if ustq.driver.Dialect() == dialect.Postgres {
		ustq.Unique(false)
	}
	ustq.modifiers = append(ustq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return ustq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (ustq *UserSignedTransactionQuery) ForShare(opts ...sql.LockOption) *UserSignedTransactionQuery {
	if ustq.driver.Dialect() == dialect.Postgres {
		ustq.Unique(false)
	}
	ustq.modifiers = append(ustq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return ustq
}

// UserSignedTransactionGroupBy is the group-by builder for UserSignedTransaction entities.
type UserSignedTransactionGroupBy struct {
	selector
	build *UserSignedTransactionQuery
}

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

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

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

// UserSignedTransactionSelect is the builder for selecting fields of UserSignedTransaction entities.
type UserSignedTransactionSelect struct {
	*UserSignedTransactionQuery
	selector
}

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

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

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