// 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/depositaddress"
	"github.com/lightsparkdev/spark/so/ent/predicate"
	"github.com/lightsparkdev/spark/so/ent/signingkeyshare"
	"github.com/lightsparkdev/spark/so/ent/tree"
	"github.com/lightsparkdev/spark/so/ent/utxo"
	"github.com/lightsparkdev/spark/so/ent/utxoswap"
)

// DepositAddressQuery is the builder for querying DepositAddress entities.
type DepositAddressQuery struct {
	config
	ctx                 *QueryContext
	order               []depositaddress.OrderOption
	inters              []Interceptor
	predicates          []predicate.DepositAddress
	withSigningKeyshare *SigningKeyshareQuery
	withUtxo            *UtxoQuery
	withUtxoswaps       *UtxoSwapQuery
	withTree            *TreeQuery
	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 DepositAddressQuery builder.
func (daq *DepositAddressQuery) Where(ps ...predicate.DepositAddress) *DepositAddressQuery {
	daq.predicates = append(daq.predicates, ps...)
	return daq
}

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

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

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

// Order specifies how the records should be ordered.
func (daq *DepositAddressQuery) Order(o ...depositaddress.OrderOption) *DepositAddressQuery {
	daq.order = append(daq.order, o...)
	return daq
}

// QuerySigningKeyshare chains the current query on the "signing_keyshare" edge.
func (daq *DepositAddressQuery) QuerySigningKeyshare() *SigningKeyshareQuery {
	query := (&SigningKeyshareClient{config: daq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := daq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := daq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(depositaddress.Table, depositaddress.FieldID, selector),
			sqlgraph.To(signingkeyshare.Table, signingkeyshare.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, depositaddress.SigningKeyshareTable, depositaddress.SigningKeyshareColumn),
		)
		fromU = sqlgraph.SetNeighbors(daq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryUtxo chains the current query on the "utxo" edge.
func (daq *DepositAddressQuery) QueryUtxo() *UtxoQuery {
	query := (&UtxoClient{config: daq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := daq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := daq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(depositaddress.Table, depositaddress.FieldID, selector),
			sqlgraph.To(utxo.Table, utxo.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, depositaddress.UtxoTable, depositaddress.UtxoColumn),
		)
		fromU = sqlgraph.SetNeighbors(daq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryUtxoswaps chains the current query on the "utxoswaps" edge.
func (daq *DepositAddressQuery) QueryUtxoswaps() *UtxoSwapQuery {
	query := (&UtxoSwapClient{config: daq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := daq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := daq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(depositaddress.Table, depositaddress.FieldID, selector),
			sqlgraph.To(utxoswap.Table, utxoswap.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, depositaddress.UtxoswapsTable, depositaddress.UtxoswapsColumn),
		)
		fromU = sqlgraph.SetNeighbors(daq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTree chains the current query on the "tree" edge.
func (daq *DepositAddressQuery) QueryTree() *TreeQuery {
	query := (&TreeClient{config: daq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := daq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := daq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(depositaddress.Table, depositaddress.FieldID, selector),
			sqlgraph.To(tree.Table, tree.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, depositaddress.TreeTable, depositaddress.TreeColumn),
		)
		fromU = sqlgraph.SetNeighbors(daq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithSigningKeyshare tells the query-builder to eager-load the nodes that are connected to
// the "signing_keyshare" edge. The optional arguments are used to configure the query builder of the edge.
func (daq *DepositAddressQuery) WithSigningKeyshare(opts ...func(*SigningKeyshareQuery)) *DepositAddressQuery {
	query := (&SigningKeyshareClient{config: daq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	daq.withSigningKeyshare = query
	return daq
}

// WithUtxo tells the query-builder to eager-load the nodes that are connected to
// the "utxo" edge. The optional arguments are used to configure the query builder of the edge.
func (daq *DepositAddressQuery) WithUtxo(opts ...func(*UtxoQuery)) *DepositAddressQuery {
	query := (&UtxoClient{config: daq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	daq.withUtxo = query
	return daq
}

// WithUtxoswaps tells the query-builder to eager-load the nodes that are connected to
// the "utxoswaps" edge. The optional arguments are used to configure the query builder of the edge.
func (daq *DepositAddressQuery) WithUtxoswaps(opts ...func(*UtxoSwapQuery)) *DepositAddressQuery {
	query := (&UtxoSwapClient{config: daq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	daq.withUtxoswaps = query
	return daq
}

// WithTree tells the query-builder to eager-load the nodes that are connected to
// the "tree" edge. The optional arguments are used to configure the query builder of the edge.
func (daq *DepositAddressQuery) WithTree(opts ...func(*TreeQuery)) *DepositAddressQuery {
	query := (&TreeClient{config: daq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	daq.withTree = query
	return daq
}

// 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.DepositAddress.Query().
//		GroupBy(depositaddress.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (daq *DepositAddressQuery) GroupBy(field string, fields ...string) *DepositAddressGroupBy {
	daq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DepositAddressGroupBy{build: daq}
	grbuild.flds = &daq.ctx.Fields
	grbuild.label = depositaddress.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.DepositAddress.Query().
//		Select(depositaddress.FieldCreateTime).
//		Scan(ctx, &v)
func (daq *DepositAddressQuery) Select(fields ...string) *DepositAddressSelect {
	daq.ctx.Fields = append(daq.ctx.Fields, fields...)
	sbuild := &DepositAddressSelect{DepositAddressQuery: daq}
	sbuild.label = depositaddress.Label
	sbuild.flds, sbuild.scan = &daq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DepositAddressSelect configured with the given aggregations.
func (daq *DepositAddressQuery) Aggregate(fns ...AggregateFunc) *DepositAddressSelect {
	return daq.Select().Aggregate(fns...)
}

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

func (daq *DepositAddressQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DepositAddress, error) {
	var (
		nodes       = []*DepositAddress{}
		withFKs     = daq.withFKs
		_spec       = daq.querySpec()
		loadedTypes = [4]bool{
			daq.withSigningKeyshare != nil,
			daq.withUtxo != nil,
			daq.withUtxoswaps != nil,
			daq.withTree != nil,
		}
	)
	if daq.withSigningKeyshare != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, depositaddress.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*DepositAddress).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &DepositAddress{config: daq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(daq.modifiers) > 0 {
		_spec.Modifiers = daq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, daq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := daq.withSigningKeyshare; query != nil {
		if err := daq.loadSigningKeyshare(ctx, query, nodes, nil,
			func(n *DepositAddress, e *SigningKeyshare) { n.Edges.SigningKeyshare = e }); err != nil {
			return nil, err
		}
	}
	if query := daq.withUtxo; query != nil {
		if err := daq.loadUtxo(ctx, query, nodes,
			func(n *DepositAddress) { n.Edges.Utxo = []*Utxo{} },
			func(n *DepositAddress, e *Utxo) { n.Edges.Utxo = append(n.Edges.Utxo, e) }); err != nil {
			return nil, err
		}
	}
	if query := daq.withUtxoswaps; query != nil {
		if err := daq.loadUtxoswaps(ctx, query, nodes,
			func(n *DepositAddress) { n.Edges.Utxoswaps = []*UtxoSwap{} },
			func(n *DepositAddress, e *UtxoSwap) { n.Edges.Utxoswaps = append(n.Edges.Utxoswaps, e) }); err != nil {
			return nil, err
		}
	}
	if query := daq.withTree; query != nil {
		if err := daq.loadTree(ctx, query, nodes, nil,
			func(n *DepositAddress, e *Tree) { n.Edges.Tree = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (daq *DepositAddressQuery) loadSigningKeyshare(ctx context.Context, query *SigningKeyshareQuery, nodes []*DepositAddress, init func(*DepositAddress), assign func(*DepositAddress, *SigningKeyshare)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*DepositAddress)
	for i := range nodes {
		if nodes[i].deposit_address_signing_keyshare == nil {
			continue
		}
		fk := *nodes[i].deposit_address_signing_keyshare
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(signingkeyshare.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 "deposit_address_signing_keyshare" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (daq *DepositAddressQuery) loadUtxo(ctx context.Context, query *UtxoQuery, nodes []*DepositAddress, init func(*DepositAddress), assign func(*DepositAddress, *Utxo)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*DepositAddress)
	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.Utxo(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(depositaddress.UtxoColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.deposit_address_utxo
		if fk == nil {
			return fmt.Errorf(`foreign-key "deposit_address_utxo" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "deposit_address_utxo" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (daq *DepositAddressQuery) loadUtxoswaps(ctx context.Context, query *UtxoSwapQuery, nodes []*DepositAddress, init func(*DepositAddress), assign func(*DepositAddress, *UtxoSwap)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*DepositAddress)
	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.UtxoSwap(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(depositaddress.UtxoswapsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.deposit_address_utxoswaps
		if fk == nil {
			return fmt.Errorf(`foreign-key "deposit_address_utxoswaps" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "deposit_address_utxoswaps" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (daq *DepositAddressQuery) loadTree(ctx context.Context, query *TreeQuery, nodes []*DepositAddress, init func(*DepositAddress), assign func(*DepositAddress, *Tree)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*DepositAddress)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.Tree(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(depositaddress.TreeColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.deposit_address_tree
		if fk == nil {
			return fmt.Errorf(`foreign-key "deposit_address_tree" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "deposit_address_tree" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

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

// DepositAddressGroupBy is the group-by builder for DepositAddress entities.
type DepositAddressGroupBy struct {
	selector
	build *DepositAddressQuery
}

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

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

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

// DepositAddressSelect is the builder for selecting fields of DepositAddress entities.
type DepositAddressSelect struct {
	*DepositAddressQuery
	selector
}

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

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

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