// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"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/paymentintent"
	"github.com/lightsparkdev/spark/so/ent/predicate"
	"github.com/lightsparkdev/spark/so/ent/sparkinvoice"
	"github.com/lightsparkdev/spark/so/ent/tokencreate"
	"github.com/lightsparkdev/spark/so/ent/tokenmint"
	"github.com/lightsparkdev/spark/so/ent/tokenoutput"
	"github.com/lightsparkdev/spark/so/ent/tokentransaction"
	"github.com/lightsparkdev/spark/so/ent/tokentransactionpeersignature"
)

// TokenTransactionQuery is the builder for querying TokenTransaction entities.
type TokenTransactionQuery struct {
	config
	ctx                *QueryContext
	order              []tokentransaction.OrderOption
	inters             []Interceptor
	predicates         []predicate.TokenTransaction
	withSpentOutput    *TokenOutputQuery
	withSpentOutputV2  *TokenOutputQuery
	withCreatedOutput  *TokenOutputQuery
	withMint           *TokenMintQuery
	withCreate         *TokenCreateQuery
	withPaymentIntent  *PaymentIntentQuery
	withPeerSignatures *TokenTransactionPeerSignatureQuery
	withSparkInvoice   *SparkInvoiceQuery
	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 TokenTransactionQuery builder.
func (ttq *TokenTransactionQuery) Where(ps ...predicate.TokenTransaction) *TokenTransactionQuery {
	ttq.predicates = append(ttq.predicates, ps...)
	return ttq
}

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

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

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

// Order specifies how the records should be ordered.
func (ttq *TokenTransactionQuery) Order(o ...tokentransaction.OrderOption) *TokenTransactionQuery {
	ttq.order = append(ttq.order, o...)
	return ttq
}

// QuerySpentOutput chains the current query on the "spent_output" edge.
func (ttq *TokenTransactionQuery) QuerySpentOutput() *TokenOutputQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokenoutput.Table, tokenoutput.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, true, tokentransaction.SpentOutputTable, tokentransaction.SpentOutputColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QuerySpentOutputV2 chains the current query on the "spent_output_v2" edge.
func (ttq *TokenTransactionQuery) QuerySpentOutputV2() *TokenOutputQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokenoutput.Table, tokenoutput.FieldID),
			sqlgraph.Edge(sqlgraph.M2M, true, tokentransaction.SpentOutputV2Table, tokentransaction.SpentOutputV2PrimaryKey...),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryCreatedOutput chains the current query on the "created_output" edge.
func (ttq *TokenTransactionQuery) QueryCreatedOutput() *TokenOutputQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokenoutput.Table, tokenoutput.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, true, tokentransaction.CreatedOutputTable, tokentransaction.CreatedOutputColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryMint chains the current query on the "mint" edge.
func (ttq *TokenTransactionQuery) QueryMint() *TokenMintQuery {
	query := (&TokenMintClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokenmint.Table, tokenmint.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokentransaction.MintTable, tokentransaction.MintColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryCreate chains the current query on the "create" edge.
func (ttq *TokenTransactionQuery) QueryCreate() *TokenCreateQuery {
	query := (&TokenCreateClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokencreate.Table, tokencreate.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokentransaction.CreateTable, tokentransaction.CreateColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPaymentIntent chains the current query on the "payment_intent" edge.
func (ttq *TokenTransactionQuery) QueryPaymentIntent() *PaymentIntentQuery {
	query := (&PaymentIntentClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(paymentintent.Table, paymentintent.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokentransaction.PaymentIntentTable, tokentransaction.PaymentIntentColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPeerSignatures chains the current query on the "peer_signatures" edge.
func (ttq *TokenTransactionQuery) QueryPeerSignatures() *TokenTransactionPeerSignatureQuery {
	query := (&TokenTransactionPeerSignatureClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(tokentransactionpeersignature.Table, tokentransactionpeersignature.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, tokentransaction.PeerSignaturesTable, tokentransaction.PeerSignaturesColumn),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QuerySparkInvoice chains the current query on the "spark_invoice" edge.
func (ttq *TokenTransactionQuery) QuerySparkInvoice() *SparkInvoiceQuery {
	query := (&SparkInvoiceClient{config: ttq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ttq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ttq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokentransaction.Table, tokentransaction.FieldID, selector),
			sqlgraph.To(sparkinvoice.Table, sparkinvoice.FieldID),
			sqlgraph.Edge(sqlgraph.M2M, false, tokentransaction.SparkInvoiceTable, tokentransaction.SparkInvoicePrimaryKey...),
		)
		fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the TokenTransactionQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (ttq *TokenTransactionQuery) Clone() *TokenTransactionQuery {
	if ttq == nil {
		return nil
	}
	return &TokenTransactionQuery{
		config:             ttq.config,
		ctx:                ttq.ctx.Clone(),
		order:              append([]tokentransaction.OrderOption{}, ttq.order...),
		inters:             append([]Interceptor{}, ttq.inters...),
		predicates:         append([]predicate.TokenTransaction{}, ttq.predicates...),
		withSpentOutput:    ttq.withSpentOutput.Clone(),
		withSpentOutputV2:  ttq.withSpentOutputV2.Clone(),
		withCreatedOutput:  ttq.withCreatedOutput.Clone(),
		withMint:           ttq.withMint.Clone(),
		withCreate:         ttq.withCreate.Clone(),
		withPaymentIntent:  ttq.withPaymentIntent.Clone(),
		withPeerSignatures: ttq.withPeerSignatures.Clone(),
		withSparkInvoice:   ttq.withSparkInvoice.Clone(),
		// clone intermediate query.
		sql:  ttq.sql.Clone(),
		path: ttq.path,
	}
}

// WithSpentOutput tells the query-builder to eager-load the nodes that are connected to
// the "spent_output" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithSpentOutput(opts ...func(*TokenOutputQuery)) *TokenTransactionQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withSpentOutput = query
	return ttq
}

// WithSpentOutputV2 tells the query-builder to eager-load the nodes that are connected to
// the "spent_output_v2" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithSpentOutputV2(opts ...func(*TokenOutputQuery)) *TokenTransactionQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withSpentOutputV2 = query
	return ttq
}

// WithCreatedOutput tells the query-builder to eager-load the nodes that are connected to
// the "created_output" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithCreatedOutput(opts ...func(*TokenOutputQuery)) *TokenTransactionQuery {
	query := (&TokenOutputClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withCreatedOutput = query
	return ttq
}

// WithMint tells the query-builder to eager-load the nodes that are connected to
// the "mint" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithMint(opts ...func(*TokenMintQuery)) *TokenTransactionQuery {
	query := (&TokenMintClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withMint = query
	return ttq
}

// WithCreate tells the query-builder to eager-load the nodes that are connected to
// the "create" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithCreate(opts ...func(*TokenCreateQuery)) *TokenTransactionQuery {
	query := (&TokenCreateClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withCreate = query
	return ttq
}

// WithPaymentIntent tells the query-builder to eager-load the nodes that are connected to
// the "payment_intent" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithPaymentIntent(opts ...func(*PaymentIntentQuery)) *TokenTransactionQuery {
	query := (&PaymentIntentClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withPaymentIntent = query
	return ttq
}

// WithPeerSignatures tells the query-builder to eager-load the nodes that are connected to
// the "peer_signatures" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithPeerSignatures(opts ...func(*TokenTransactionPeerSignatureQuery)) *TokenTransactionQuery {
	query := (&TokenTransactionPeerSignatureClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withPeerSignatures = query
	return ttq
}

// WithSparkInvoice tells the query-builder to eager-load the nodes that are connected to
// the "spark_invoice" edge. The optional arguments are used to configure the query builder of the edge.
func (ttq *TokenTransactionQuery) WithSparkInvoice(opts ...func(*SparkInvoiceQuery)) *TokenTransactionQuery {
	query := (&SparkInvoiceClient{config: ttq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ttq.withSparkInvoice = query
	return ttq
}

// 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.TokenTransaction.Query().
//		GroupBy(tokentransaction.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ttq *TokenTransactionQuery) GroupBy(field string, fields ...string) *TokenTransactionGroupBy {
	ttq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &TokenTransactionGroupBy{build: ttq}
	grbuild.flds = &ttq.ctx.Fields
	grbuild.label = tokentransaction.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.TokenTransaction.Query().
//		Select(tokentransaction.FieldCreateTime).
//		Scan(ctx, &v)
func (ttq *TokenTransactionQuery) Select(fields ...string) *TokenTransactionSelect {
	ttq.ctx.Fields = append(ttq.ctx.Fields, fields...)
	sbuild := &TokenTransactionSelect{TokenTransactionQuery: ttq}
	sbuild.label = tokentransaction.Label
	sbuild.flds, sbuild.scan = &ttq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a TokenTransactionSelect configured with the given aggregations.
func (ttq *TokenTransactionQuery) Aggregate(fns ...AggregateFunc) *TokenTransactionSelect {
	return ttq.Select().Aggregate(fns...)
}

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

func (ttq *TokenTransactionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TokenTransaction, error) {
	var (
		nodes       = []*TokenTransaction{}
		withFKs     = ttq.withFKs
		_spec       = ttq.querySpec()
		loadedTypes = [8]bool{
			ttq.withSpentOutput != nil,
			ttq.withSpentOutputV2 != nil,
			ttq.withCreatedOutput != nil,
			ttq.withMint != nil,
			ttq.withCreate != nil,
			ttq.withPaymentIntent != nil,
			ttq.withPeerSignatures != nil,
			ttq.withSparkInvoice != nil,
		}
	)
	if ttq.withMint != nil || ttq.withCreate != nil || ttq.withPaymentIntent != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, tokentransaction.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*TokenTransaction).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &TokenTransaction{config: ttq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(ttq.modifiers) > 0 {
		_spec.Modifiers = ttq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ttq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ttq.withSpentOutput; query != nil {
		if err := ttq.loadSpentOutput(ctx, query, nodes,
			func(n *TokenTransaction) { n.Edges.SpentOutput = []*TokenOutput{} },
			func(n *TokenTransaction, e *TokenOutput) { n.Edges.SpentOutput = append(n.Edges.SpentOutput, e) }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withSpentOutputV2; query != nil {
		if err := ttq.loadSpentOutputV2(ctx, query, nodes,
			func(n *TokenTransaction) { n.Edges.SpentOutputV2 = []*TokenOutput{} },
			func(n *TokenTransaction, e *TokenOutput) { n.Edges.SpentOutputV2 = append(n.Edges.SpentOutputV2, e) }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withCreatedOutput; query != nil {
		if err := ttq.loadCreatedOutput(ctx, query, nodes,
			func(n *TokenTransaction) { n.Edges.CreatedOutput = []*TokenOutput{} },
			func(n *TokenTransaction, e *TokenOutput) { n.Edges.CreatedOutput = append(n.Edges.CreatedOutput, e) }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withMint; query != nil {
		if err := ttq.loadMint(ctx, query, nodes, nil,
			func(n *TokenTransaction, e *TokenMint) { n.Edges.Mint = e }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withCreate; query != nil {
		if err := ttq.loadCreate(ctx, query, nodes, nil,
			func(n *TokenTransaction, e *TokenCreate) { n.Edges.Create = e }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withPaymentIntent; query != nil {
		if err := ttq.loadPaymentIntent(ctx, query, nodes, nil,
			func(n *TokenTransaction, e *PaymentIntent) { n.Edges.PaymentIntent = e }); err != nil {
			return nil, err
		}
	}
	if query := ttq.withPeerSignatures; query != nil {
		if err := ttq.loadPeerSignatures(ctx, query, nodes,
			func(n *TokenTransaction) { n.Edges.PeerSignatures = []*TokenTransactionPeerSignature{} },
			func(n *TokenTransaction, e *TokenTransactionPeerSignature) {
				n.Edges.PeerSignatures = append(n.Edges.PeerSignatures, e)
			}); err != nil {
			return nil, err
		}
	}
	if query := ttq.withSparkInvoice; query != nil {
		if err := ttq.loadSparkInvoice(ctx, query, nodes,
			func(n *TokenTransaction) { n.Edges.SparkInvoice = []*SparkInvoice{} },
			func(n *TokenTransaction, e *SparkInvoice) { n.Edges.SparkInvoice = append(n.Edges.SparkInvoice, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ttq *TokenTransactionQuery) loadSpentOutput(ctx context.Context, query *TokenOutputQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenOutput)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*TokenTransaction)
	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.TokenOutput(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(tokentransaction.SpentOutputColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.token_output_output_spent_token_transaction
		if fk == nil {
			return fmt.Errorf(`foreign-key "token_output_output_spent_token_transaction" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "token_output_output_spent_token_transaction" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadSpentOutputV2(ctx context.Context, query *TokenOutputQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenOutput)) error {
	edgeIDs := make([]driver.Value, len(nodes))
	byID := make(map[uuid.UUID]*TokenTransaction)
	nids := make(map[uuid.UUID]map[*TokenTransaction]struct{})
	for i, node := range nodes {
		edgeIDs[i] = node.ID
		byID[node.ID] = node
		if init != nil {
			init(node)
		}
	}
	query.Where(func(s *sql.Selector) {
		joinT := sql.Table(tokentransaction.SpentOutputV2Table)
		s.Join(joinT).On(s.C(tokenoutput.FieldID), joinT.C(tokentransaction.SpentOutputV2PrimaryKey[0]))
		s.Where(sql.InValues(joinT.C(tokentransaction.SpentOutputV2PrimaryKey[1]), edgeIDs...))
		columns := s.SelectedColumns()
		s.Select(joinT.C(tokentransaction.SpentOutputV2PrimaryKey[1]))
		s.AppendSelect(columns...)
		s.SetDistinct(false)
	})
	if err := query.prepareQuery(ctx); err != nil {
		return err
	}
	qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
		return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
			assign := spec.Assign
			values := spec.ScanValues
			spec.ScanValues = func(columns []string) ([]any, error) {
				values, err := values(columns[1:])
				if err != nil {
					return nil, err
				}
				return append([]any{new(uuid.UUID)}, values...), nil
			}
			spec.Assign = func(columns []string, values []any) error {
				outValue := *values[0].(*uuid.UUID)
				inValue := *values[1].(*uuid.UUID)
				if nids[inValue] == nil {
					nids[inValue] = map[*TokenTransaction]struct{}{byID[outValue]: {}}
					return assign(columns[1:], values[1:])
				}
				nids[inValue][byID[outValue]] = struct{}{}
				return nil
			}
		})
	})
	neighbors, err := withInterceptors[[]*TokenOutput](ctx, query, qr, query.inters)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected "spent_output_v2" node returned %v`, n.ID)
		}
		for kn := range nodes {
			assign(kn, n)
		}
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadCreatedOutput(ctx context.Context, query *TokenOutputQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenOutput)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*TokenTransaction)
	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.TokenOutput(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(tokentransaction.CreatedOutputColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.token_output_output_created_token_transaction
		if fk == nil {
			return fmt.Errorf(`foreign-key "token_output_output_created_token_transaction" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "token_output_output_created_token_transaction" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadMint(ctx context.Context, query *TokenMintQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenMint)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenTransaction)
	for i := range nodes {
		if nodes[i].token_transaction_mint == nil {
			continue
		}
		fk := *nodes[i].token_transaction_mint
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tokenmint.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 "token_transaction_mint" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadCreate(ctx context.Context, query *TokenCreateQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenCreate)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenTransaction)
	for i := range nodes {
		if nodes[i].token_transaction_create == nil {
			continue
		}
		fk := *nodes[i].token_transaction_create
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tokencreate.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 "token_transaction_create" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadPaymentIntent(ctx context.Context, query *PaymentIntentQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *PaymentIntent)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenTransaction)
	for i := range nodes {
		if nodes[i].token_transaction_payment_intent == nil {
			continue
		}
		fk := *nodes[i].token_transaction_payment_intent
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(paymentintent.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 "token_transaction_payment_intent" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadPeerSignatures(ctx context.Context, query *TokenTransactionPeerSignatureQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *TokenTransactionPeerSignature)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*TokenTransaction)
	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.TokenTransactionPeerSignature(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(tokentransaction.PeerSignaturesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.token_transaction_peer_signatures
		if fk == nil {
			return fmt.Errorf(`foreign-key "token_transaction_peer_signatures" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "token_transaction_peer_signatures" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (ttq *TokenTransactionQuery) loadSparkInvoice(ctx context.Context, query *SparkInvoiceQuery, nodes []*TokenTransaction, init func(*TokenTransaction), assign func(*TokenTransaction, *SparkInvoice)) error {
	edgeIDs := make([]driver.Value, len(nodes))
	byID := make(map[uuid.UUID]*TokenTransaction)
	nids := make(map[uuid.UUID]map[*TokenTransaction]struct{})
	for i, node := range nodes {
		edgeIDs[i] = node.ID
		byID[node.ID] = node
		if init != nil {
			init(node)
		}
	}
	query.Where(func(s *sql.Selector) {
		joinT := sql.Table(tokentransaction.SparkInvoiceTable)
		s.Join(joinT).On(s.C(sparkinvoice.FieldID), joinT.C(tokentransaction.SparkInvoicePrimaryKey[1]))
		s.Where(sql.InValues(joinT.C(tokentransaction.SparkInvoicePrimaryKey[0]), edgeIDs...))
		columns := s.SelectedColumns()
		s.Select(joinT.C(tokentransaction.SparkInvoicePrimaryKey[0]))
		s.AppendSelect(columns...)
		s.SetDistinct(false)
	})
	if err := query.prepareQuery(ctx); err != nil {
		return err
	}
	qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
		return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
			assign := spec.Assign
			values := spec.ScanValues
			spec.ScanValues = func(columns []string) ([]any, error) {
				values, err := values(columns[1:])
				if err != nil {
					return nil, err
				}
				return append([]any{new(uuid.UUID)}, values...), nil
			}
			spec.Assign = func(columns []string, values []any) error {
				outValue := *values[0].(*uuid.UUID)
				inValue := *values[1].(*uuid.UUID)
				if nids[inValue] == nil {
					nids[inValue] = map[*TokenTransaction]struct{}{byID[outValue]: {}}
					return assign(columns[1:], values[1:])
				}
				nids[inValue][byID[outValue]] = struct{}{}
				return nil
			}
		})
	})
	neighbors, err := withInterceptors[[]*SparkInvoice](ctx, query, qr, query.inters)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected "spark_invoice" node returned %v`, n.ID)
		}
		for kn := range nodes {
			assign(kn, n)
		}
	}
	return nil
}

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

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

func (ttq *TokenTransactionQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(ttq.driver.Dialect())
	t1 := builder.Table(tokentransaction.Table)
	columns := ttq.ctx.Fields
	if len(columns) == 0 {
		columns = tokentransaction.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if ttq.sql != nil {
		selector = ttq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if ttq.ctx.Unique != nil && *ttq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range ttq.modifiers {
		m(selector)
	}
	for _, p := range ttq.predicates {
		p(selector)
	}
	for _, p := range ttq.order {
		p(selector)
	}
	if offset := ttq.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 := ttq.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 (ttq *TokenTransactionQuery) ForUpdate(opts ...sql.LockOption) *TokenTransactionQuery {
	if ttq.driver.Dialect() == dialect.Postgres {
		ttq.Unique(false)
	}
	ttq.modifiers = append(ttq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return ttq
}

// 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 (ttq *TokenTransactionQuery) ForShare(opts ...sql.LockOption) *TokenTransactionQuery {
	if ttq.driver.Dialect() == dialect.Postgres {
		ttq.Unique(false)
	}
	ttq.modifiers = append(ttq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return ttq
}

// TokenTransactionGroupBy is the group-by builder for TokenTransaction entities.
type TokenTransactionGroupBy struct {
	selector
	build *TokenTransactionQuery
}

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

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

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

// TokenTransactionSelect is the builder for selecting fields of TokenTransaction entities.
type TokenTransactionSelect struct {
	*TokenTransactionQuery
	selector
}

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

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

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