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

// TreeNodeQuery is the builder for querying TreeNode entities.
type TreeNodeQuery struct {
	config
	ctx                 *QueryContext
	order               []treenode.OrderOption
	inters              []Interceptor
	predicates          []predicate.TreeNode
	withTree            *TreeQuery
	withParent          *TreeNodeQuery
	withSigningKeyshare *SigningKeyshareQuery
	withChildren        *TreeNodeQuery
	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 TreeNodeQuery builder.
func (tnq *TreeNodeQuery) Where(ps ...predicate.TreeNode) *TreeNodeQuery {
	tnq.predicates = append(tnq.predicates, ps...)
	return tnq
}

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

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

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

// Order specifies how the records should be ordered.
func (tnq *TreeNodeQuery) Order(o ...treenode.OrderOption) *TreeNodeQuery {
	tnq.order = append(tnq.order, o...)
	return tnq
}

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

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

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

// QueryChildren chains the current query on the "children" edge.
func (tnq *TreeNodeQuery) QueryChildren() *TreeNodeQuery {
	query := (&TreeNodeClient{config: tnq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := tnq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := tnq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(treenode.Table, treenode.FieldID, selector),
			sqlgraph.To(treenode.Table, treenode.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, true, treenode.ChildrenTable, treenode.ChildrenColumn),
		)
		fromU = sqlgraph.SetNeighbors(tnq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 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 (tnq *TreeNodeQuery) WithTree(opts ...func(*TreeQuery)) *TreeNodeQuery {
	query := (&TreeClient{config: tnq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	tnq.withTree = query
	return tnq
}

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

// 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 (tnq *TreeNodeQuery) WithSigningKeyshare(opts ...func(*SigningKeyshareQuery)) *TreeNodeQuery {
	query := (&SigningKeyshareClient{config: tnq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	tnq.withSigningKeyshare = query
	return tnq
}

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

// 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.TreeNode.Query().
//		GroupBy(treenode.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (tnq *TreeNodeQuery) GroupBy(field string, fields ...string) *TreeNodeGroupBy {
	tnq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &TreeNodeGroupBy{build: tnq}
	grbuild.flds = &tnq.ctx.Fields
	grbuild.label = treenode.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.TreeNode.Query().
//		Select(treenode.FieldCreateTime).
//		Scan(ctx, &v)
func (tnq *TreeNodeQuery) Select(fields ...string) *TreeNodeSelect {
	tnq.ctx.Fields = append(tnq.ctx.Fields, fields...)
	sbuild := &TreeNodeSelect{TreeNodeQuery: tnq}
	sbuild.label = treenode.Label
	sbuild.flds, sbuild.scan = &tnq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a TreeNodeSelect configured with the given aggregations.
func (tnq *TreeNodeQuery) Aggregate(fns ...AggregateFunc) *TreeNodeSelect {
	return tnq.Select().Aggregate(fns...)
}

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

func (tnq *TreeNodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TreeNode, error) {
	var (
		nodes       = []*TreeNode{}
		withFKs     = tnq.withFKs
		_spec       = tnq.querySpec()
		loadedTypes = [4]bool{
			tnq.withTree != nil,
			tnq.withParent != nil,
			tnq.withSigningKeyshare != nil,
			tnq.withChildren != nil,
		}
	)
	if tnq.withTree != nil || tnq.withParent != nil || tnq.withSigningKeyshare != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, treenode.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*TreeNode).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &TreeNode{config: tnq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(tnq.modifiers) > 0 {
		_spec.Modifiers = tnq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, tnq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := tnq.withTree; query != nil {
		if err := tnq.loadTree(ctx, query, nodes, nil,
			func(n *TreeNode, e *Tree) { n.Edges.Tree = e }); err != nil {
			return nil, err
		}
	}
	if query := tnq.withParent; query != nil {
		if err := tnq.loadParent(ctx, query, nodes, nil,
			func(n *TreeNode, e *TreeNode) { n.Edges.Parent = e }); err != nil {
			return nil, err
		}
	}
	if query := tnq.withSigningKeyshare; query != nil {
		if err := tnq.loadSigningKeyshare(ctx, query, nodes, nil,
			func(n *TreeNode, e *SigningKeyshare) { n.Edges.SigningKeyshare = e }); err != nil {
			return nil, err
		}
	}
	if query := tnq.withChildren; query != nil {
		if err := tnq.loadChildren(ctx, query, nodes,
			func(n *TreeNode) { n.Edges.Children = []*TreeNode{} },
			func(n *TreeNode, e *TreeNode) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (tnq *TreeNodeQuery) loadTree(ctx context.Context, query *TreeQuery, nodes []*TreeNode, init func(*TreeNode), assign func(*TreeNode, *Tree)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TreeNode)
	for i := range nodes {
		if nodes[i].tree_node_tree == nil {
			continue
		}
		fk := *nodes[i].tree_node_tree
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tree.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 "tree_node_tree" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (tnq *TreeNodeQuery) loadParent(ctx context.Context, query *TreeNodeQuery, nodes []*TreeNode, init func(*TreeNode), assign func(*TreeNode, *TreeNode)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TreeNode)
	for i := range nodes {
		if nodes[i].tree_node_parent == nil {
			continue
		}
		fk := *nodes[i].tree_node_parent
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(treenode.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "tree_node_parent" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (tnq *TreeNodeQuery) loadSigningKeyshare(ctx context.Context, query *SigningKeyshareQuery, nodes []*TreeNode, init func(*TreeNode), assign func(*TreeNode, *SigningKeyshare)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TreeNode)
	for i := range nodes {
		if nodes[i].tree_node_signing_keyshare == nil {
			continue
		}
		fk := *nodes[i].tree_node_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 "tree_node_signing_keyshare" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (tnq *TreeNodeQuery) loadChildren(ctx context.Context, query *TreeNodeQuery, nodes []*TreeNode, init func(*TreeNode), assign func(*TreeNode, *TreeNode)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*TreeNode)
	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.TreeNode(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(treenode.ChildrenColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.tree_node_parent
		if fk == nil {
			return fmt.Errorf(`foreign-key "tree_node_parent" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "tree_node_parent" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

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

// TreeNodeGroupBy is the group-by builder for TreeNode entities.
type TreeNodeGroupBy struct {
	selector
	build *TreeNodeQuery
}

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

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

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

// TreeNodeSelect is the builder for selecting fields of TreeNode entities.
type TreeNodeSelect struct {
	*TreeNodeQuery
	selector
}

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

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

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