// 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/predicate"
	"github.com/lightsparkdev/spark/so/ent/preimagerequest"
	"github.com/lightsparkdev/spark/so/ent/preimageshare"
	"github.com/lightsparkdev/spark/so/ent/transfer"
	"github.com/lightsparkdev/spark/so/ent/usersignedtransaction"
)

// PreimageRequestQuery is the builder for querying PreimageRequest entities.
type PreimageRequestQuery struct {
	config
	ctx                *QueryContext
	order              []preimagerequest.OrderOption
	inters             []Interceptor
	predicates         []predicate.PreimageRequest
	withTransactions   *UserSignedTransactionQuery
	withPreimageShares *PreimageShareQuery
	withTransfers      *TransferQuery
	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 PreimageRequestQuery builder.
func (prq *PreimageRequestQuery) Where(ps ...predicate.PreimageRequest) *PreimageRequestQuery {
	prq.predicates = append(prq.predicates, ps...)
	return prq
}

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

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

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

// Order specifies how the records should be ordered.
func (prq *PreimageRequestQuery) Order(o ...preimagerequest.OrderOption) *PreimageRequestQuery {
	prq.order = append(prq.order, o...)
	return prq
}

// QueryTransactions chains the current query on the "transactions" edge.
func (prq *PreimageRequestQuery) QueryTransactions() *UserSignedTransactionQuery {
	query := (&UserSignedTransactionClient{config: prq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := prq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := prq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(preimagerequest.Table, preimagerequest.FieldID, selector),
			sqlgraph.To(usersignedtransaction.Table, usersignedtransaction.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, true, preimagerequest.TransactionsTable, preimagerequest.TransactionsColumn),
		)
		fromU = sqlgraph.SetNeighbors(prq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPreimageShares chains the current query on the "preimage_shares" edge.
func (prq *PreimageRequestQuery) QueryPreimageShares() *PreimageShareQuery {
	query := (&PreimageShareClient{config: prq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := prq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := prq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(preimagerequest.Table, preimagerequest.FieldID, selector),
			sqlgraph.To(preimageshare.Table, preimageshare.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, preimagerequest.PreimageSharesTable, preimagerequest.PreimageSharesColumn),
		)
		fromU = sqlgraph.SetNeighbors(prq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTransfers chains the current query on the "transfers" edge.
func (prq *PreimageRequestQuery) QueryTransfers() *TransferQuery {
	query := (&TransferClient{config: prq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := prq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := prq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(preimagerequest.Table, preimagerequest.FieldID, selector),
			sqlgraph.To(transfer.Table, transfer.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, preimagerequest.TransfersTable, preimagerequest.TransfersColumn),
		)
		fromU = sqlgraph.SetNeighbors(prq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithPreimageShares tells the query-builder to eager-load the nodes that are connected to
// the "preimage_shares" edge. The optional arguments are used to configure the query builder of the edge.
func (prq *PreimageRequestQuery) WithPreimageShares(opts ...func(*PreimageShareQuery)) *PreimageRequestQuery {
	query := (&PreimageShareClient{config: prq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	prq.withPreimageShares = query
	return prq
}

// WithTransfers tells the query-builder to eager-load the nodes that are connected to
// the "transfers" edge. The optional arguments are used to configure the query builder of the edge.
func (prq *PreimageRequestQuery) WithTransfers(opts ...func(*TransferQuery)) *PreimageRequestQuery {
	query := (&TransferClient{config: prq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	prq.withTransfers = query
	return prq
}

// 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.PreimageRequest.Query().
//		GroupBy(preimagerequest.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (prq *PreimageRequestQuery) GroupBy(field string, fields ...string) *PreimageRequestGroupBy {
	prq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &PreimageRequestGroupBy{build: prq}
	grbuild.flds = &prq.ctx.Fields
	grbuild.label = preimagerequest.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.PreimageRequest.Query().
//		Select(preimagerequest.FieldCreateTime).
//		Scan(ctx, &v)
func (prq *PreimageRequestQuery) Select(fields ...string) *PreimageRequestSelect {
	prq.ctx.Fields = append(prq.ctx.Fields, fields...)
	sbuild := &PreimageRequestSelect{PreimageRequestQuery: prq}
	sbuild.label = preimagerequest.Label
	sbuild.flds, sbuild.scan = &prq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a PreimageRequestSelect configured with the given aggregations.
func (prq *PreimageRequestQuery) Aggregate(fns ...AggregateFunc) *PreimageRequestSelect {
	return prq.Select().Aggregate(fns...)
}

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

func (prq *PreimageRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PreimageRequest, error) {
	var (
		nodes       = []*PreimageRequest{}
		withFKs     = prq.withFKs
		_spec       = prq.querySpec()
		loadedTypes = [3]bool{
			prq.withTransactions != nil,
			prq.withPreimageShares != nil,
			prq.withTransfers != nil,
		}
	)
	if prq.withTransfers != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, preimagerequest.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*PreimageRequest).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &PreimageRequest{config: prq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(prq.modifiers) > 0 {
		_spec.Modifiers = prq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, prq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := prq.withTransactions; query != nil {
		if err := prq.loadTransactions(ctx, query, nodes,
			func(n *PreimageRequest) { n.Edges.Transactions = []*UserSignedTransaction{} },
			func(n *PreimageRequest, e *UserSignedTransaction) {
				n.Edges.Transactions = append(n.Edges.Transactions, e)
			}); err != nil {
			return nil, err
		}
	}
	if query := prq.withPreimageShares; query != nil {
		if err := prq.loadPreimageShares(ctx, query, nodes, nil,
			func(n *PreimageRequest, e *PreimageShare) { n.Edges.PreimageShares = e }); err != nil {
			return nil, err
		}
	}
	if query := prq.withTransfers; query != nil {
		if err := prq.loadTransfers(ctx, query, nodes, nil,
			func(n *PreimageRequest, e *Transfer) { n.Edges.Transfers = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (prq *PreimageRequestQuery) loadTransactions(ctx context.Context, query *UserSignedTransactionQuery, nodes []*PreimageRequest, init func(*PreimageRequest), assign func(*PreimageRequest, *UserSignedTransaction)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*PreimageRequest)
	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.UserSignedTransaction(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(preimagerequest.TransactionsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.user_signed_transaction_preimage_request
		if fk == nil {
			return fmt.Errorf(`foreign-key "user_signed_transaction_preimage_request" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "user_signed_transaction_preimage_request" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (prq *PreimageRequestQuery) loadPreimageShares(ctx context.Context, query *PreimageShareQuery, nodes []*PreimageRequest, init func(*PreimageRequest), assign func(*PreimageRequest, *PreimageShare)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*PreimageRequest)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.PreimageShare(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(preimagerequest.PreimageSharesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.preimage_request_preimage_shares
		if fk == nil {
			return fmt.Errorf(`foreign-key "preimage_request_preimage_shares" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "preimage_request_preimage_shares" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (prq *PreimageRequestQuery) loadTransfers(ctx context.Context, query *TransferQuery, nodes []*PreimageRequest, init func(*PreimageRequest), assign func(*PreimageRequest, *Transfer)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*PreimageRequest)
	for i := range nodes {
		if nodes[i].preimage_request_transfers == nil {
			continue
		}
		fk := *nodes[i].preimage_request_transfers
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(transfer.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 "preimage_request_transfers" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

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

// PreimageRequestGroupBy is the group-by builder for PreimageRequest entities.
type PreimageRequestGroupBy struct {
	selector
	build *PreimageRequestQuery
}

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

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

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

// PreimageRequestSelect is the builder for selecting fields of PreimageRequest entities.
type PreimageRequestSelect struct {
	*PreimageRequestQuery
	selector
}

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

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

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