Skip to main content

polyglot_sql/
traversal.rs

1//! Tree traversal utilities for SQL expression ASTs.
2//!
3//! This module provides read-only traversal, search, and transformation utilities
4//! for the [`Expression`] tree produced by the parser. Because Rust's ownership
5//! model does not allow parent pointers inside the AST, parent information is
6//! tracked externally via [`TreeContext`] (built on demand).
7//!
8//! # Traversal
9//!
10//! Two iterator types are provided:
11//! - [`DfsIter`] -- depth-first (pre-order) traversal using a stack. Visits a node
12//!   before its children. Good for top-down analysis and early termination.
13//! - [`BfsIter`] -- breadth-first (level-order) traversal using a queue. Visits all
14//!   nodes at depth N before any node at depth N+1. Good for level-aware analysis.
15//!
16//! Both are available through the [`ExpressionWalk`] trait methods [`dfs`](ExpressionWalk::dfs)
17//! and [`bfs`](ExpressionWalk::bfs).
18//!
19//! # Searching
20//!
21//! The [`ExpressionWalk`] trait also provides convenience methods for finding expressions:
22//! [`find`](ExpressionWalk::find), [`find_all`](ExpressionWalk::find_all),
23//! [`contains`](ExpressionWalk::contains), and [`count`](ExpressionWalk::count).
24//! Common predicates are available as free functions: [`is_column`], [`is_literal`],
25//! [`is_function`], [`is_aggregate`], [`is_window_function`], [`is_subquery`], and
26//! [`is_select`].
27//!
28//! # Transformation
29//!
30//! The [`transform`] and [`transform_map`] functions perform bottom-up (post-order)
31//! tree rewrites, delegating to [`transform_recursive`](crate::dialects::transform_recursive).
32//! The [`ExpressionWalk::transform_owned`] method provides the same capability as
33//! an owned method on `Expression`.
34//!
35//! Based on traversal patterns from `sqlglot/expressions.py`.
36
37use crate::expressions::Expression;
38use std::collections::{HashMap, VecDeque};
39
40/// Unique identifier for expression nodes during traversal
41pub type NodeId = usize;
42
43/// Information about a node's parent relationship
44#[derive(Debug, Clone)]
45pub struct ParentInfo {
46    /// The NodeId of the parent (None for root)
47    pub parent_id: Option<NodeId>,
48    /// Which argument/field in the parent this node occupies
49    pub arg_key: String,
50    /// Index if the node is part of a list (e.g., expressions in SELECT)
51    pub index: Option<usize>,
52}
53
54/// External parent-tracking context for an expression tree.
55///
56/// Since Rust's ownership model does not allow intrusive parent pointers in the AST,
57/// `TreeContext` provides an on-demand side-table that maps each node (identified by
58/// a [`NodeId`]) to its [`ParentInfo`] (parent node, field name, and list index).
59///
60/// Build a context from any expression root with [`TreeContext::build`], then query
61/// parent relationships with [`get`](TreeContext::get), ancestry chains with
62/// [`ancestors_of`](TreeContext::ancestors_of), or tree depth with
63/// [`depth_of`](TreeContext::depth_of).
64///
65/// This is useful when analysis requires upward navigation (e.g., determining whether
66/// a column reference appears inside a WHERE clause or a JOIN condition).
67#[derive(Debug, Default)]
68pub struct TreeContext {
69    /// Map from NodeId to parent information
70    nodes: HashMap<NodeId, ParentInfo>,
71    /// Counter for generating NodeIds
72    next_id: NodeId,
73    /// Stack for tracking current path during traversal
74    path: Vec<(NodeId, String, Option<usize>)>,
75}
76
77impl TreeContext {
78    /// Create a new empty tree context
79    pub fn new() -> Self {
80        Self::default()
81    }
82
83    /// Build context from an expression tree
84    pub fn build(root: &Expression) -> Self {
85        let mut ctx = Self::new();
86        ctx.visit_expr(root);
87        ctx
88    }
89
90    /// Visit an expression and record parent information
91    fn visit_expr(&mut self, expr: &Expression) -> NodeId {
92        let id = self.next_id;
93        self.next_id += 1;
94
95        // Record parent info based on current path
96        let parent_info = if let Some((parent_id, arg_key, index)) = self.path.last() {
97            ParentInfo {
98                parent_id: Some(*parent_id),
99                arg_key: arg_key.clone(),
100                index: *index,
101            }
102        } else {
103            ParentInfo {
104                parent_id: None,
105                arg_key: String::new(),
106                index: None,
107            }
108        };
109        self.nodes.insert(id, parent_info);
110
111        // Visit children
112        for (key, child) in iter_children(expr) {
113            self.path.push((id, key.to_string(), None));
114            self.visit_expr(child);
115            self.path.pop();
116        }
117
118        // Visit children in lists
119        for (key, children) in iter_children_lists(expr) {
120            for (idx, child) in children.iter().enumerate() {
121                self.path.push((id, key.to_string(), Some(idx)));
122                self.visit_expr(child);
123                self.path.pop();
124            }
125        }
126
127        id
128    }
129
130    /// Get parent info for a node
131    pub fn get(&self, id: NodeId) -> Option<&ParentInfo> {
132        self.nodes.get(&id)
133    }
134
135    /// Get the depth of a node (0 for root)
136    pub fn depth_of(&self, id: NodeId) -> usize {
137        let mut depth = 0;
138        let mut current = id;
139        while let Some(info) = self.nodes.get(&current) {
140            if let Some(parent_id) = info.parent_id {
141                depth += 1;
142                current = parent_id;
143            } else {
144                break;
145            }
146        }
147        depth
148    }
149
150    /// Get ancestors of a node (parent, grandparent, etc.)
151    pub fn ancestors_of(&self, id: NodeId) -> Vec<NodeId> {
152        let mut ancestors = Vec::new();
153        let mut current = id;
154        while let Some(info) = self.nodes.get(&current) {
155            if let Some(parent_id) = info.parent_id {
156                ancestors.push(parent_id);
157                current = parent_id;
158            } else {
159                break;
160            }
161        }
162        ancestors
163    }
164}
165
166/// Iterate over single-child fields of an expression
167///
168/// Returns an iterator of (field_name, &Expression) pairs.
169fn iter_children(expr: &Expression) -> Vec<(&'static str, &Expression)> {
170    let mut children = Vec::new();
171
172    match expr {
173        Expression::Alias(a) => {
174            children.push(("this", &a.this));
175        }
176        Expression::Cast(c) => {
177            children.push(("this", &c.this));
178        }
179        Expression::Not(u) | Expression::Neg(u) | Expression::BitwiseNot(u) => {
180            children.push(("this", &u.this));
181        }
182        Expression::Paren(p) => {
183            children.push(("this", &p.this));
184        }
185        Expression::IsNull(i) => {
186            children.push(("this", &i.this));
187        }
188        Expression::Exists(e) => {
189            children.push(("this", &e.this));
190        }
191        Expression::Subquery(s) => {
192            children.push(("this", &s.this));
193        }
194        Expression::Where(w) => {
195            children.push(("this", &w.this));
196        }
197        Expression::Having(h) => {
198            children.push(("this", &h.this));
199        }
200        Expression::Qualify(q) => {
201            children.push(("this", &q.this));
202        }
203        Expression::And(op)
204        | Expression::Or(op)
205        | Expression::Add(op)
206        | Expression::Sub(op)
207        | Expression::Mul(op)
208        | Expression::Div(op)
209        | Expression::Mod(op)
210        | Expression::Eq(op)
211        | Expression::Neq(op)
212        | Expression::Lt(op)
213        | Expression::Lte(op)
214        | Expression::Gt(op)
215        | Expression::Gte(op)
216        | Expression::BitwiseAnd(op)
217        | Expression::BitwiseOr(op)
218        | Expression::BitwiseXor(op)
219        | Expression::Concat(op) => {
220            children.push(("left", &op.left));
221            children.push(("right", &op.right));
222        }
223        Expression::Like(op) | Expression::ILike(op) => {
224            children.push(("left", &op.left));
225            children.push(("right", &op.right));
226        }
227        Expression::Between(b) => {
228            children.push(("this", &b.this));
229            children.push(("low", &b.low));
230            children.push(("high", &b.high));
231        }
232        Expression::In(i) => {
233            children.push(("this", &i.this));
234        }
235        Expression::Case(c) => {
236            if let Some(ref operand) = &c.operand {
237                children.push(("operand", operand));
238            }
239        }
240        Expression::WindowFunction(wf) => {
241            children.push(("this", &wf.this));
242        }
243        Expression::Union(u) => {
244            children.push(("left", &u.left));
245            children.push(("right", &u.right));
246        }
247        Expression::Intersect(i) => {
248            children.push(("left", &i.left));
249            children.push(("right", &i.right));
250        }
251        Expression::Except(e) => {
252            children.push(("left", &e.left));
253            children.push(("right", &e.right));
254        }
255        Expression::Ordered(o) => {
256            children.push(("this", &o.this));
257        }
258        Expression::Interval(i) => {
259            if let Some(ref this) = i.this {
260                children.push(("this", this));
261            }
262        }
263        _ => {}
264    }
265
266    children
267}
268
269/// Iterate over list-child fields of an expression
270///
271/// Returns an iterator of (field_name, &[Expression]) pairs.
272fn iter_children_lists(expr: &Expression) -> Vec<(&'static str, &[Expression])> {
273    let mut lists = Vec::new();
274
275    match expr {
276        Expression::Select(s) => {
277            lists.push(("expressions", s.expressions.as_slice()));
278            // Note: FROM, JOINs, etc. are stored differently
279        }
280        Expression::Function(f) => {
281            lists.push(("args", f.args.as_slice()));
282        }
283        Expression::AggregateFunction(f) => {
284            lists.push(("args", f.args.as_slice()));
285        }
286        Expression::From(f) => {
287            lists.push(("expressions", f.expressions.as_slice()));
288        }
289        Expression::GroupBy(g) => {
290            lists.push(("expressions", g.expressions.as_slice()));
291        }
292        // OrderBy.expressions is Vec<Ordered>, not Vec<Expression>
293        // We handle Ordered items via iter_children
294        Expression::In(i) => {
295            lists.push(("expressions", i.expressions.as_slice()));
296        }
297        Expression::Array(a) => {
298            lists.push(("expressions", a.expressions.as_slice()));
299        }
300        Expression::Tuple(t) => {
301            lists.push(("expressions", t.expressions.as_slice()));
302        }
303        // Values.expressions is Vec<Tuple>, handle specially
304        Expression::Coalesce(c) => {
305            lists.push(("expressions", c.expressions.as_slice()));
306        }
307        Expression::Greatest(g) | Expression::Least(g) => {
308            lists.push(("expressions", g.expressions.as_slice()));
309        }
310        _ => {}
311    }
312
313    lists
314}
315
316/// Pre-order depth-first iterator over an expression tree.
317///
318/// Visits each node before its children, using a stack-based approach. This means
319/// the root is yielded first, followed by the entire left subtree (recursively),
320/// then the right subtree. For a binary expression `a + b`, the iteration order
321/// is: `Add`, `a`, `b`.
322///
323/// Created via [`ExpressionWalk::dfs`] or [`DfsIter::new`].
324pub struct DfsIter<'a> {
325    stack: Vec<&'a Expression>,
326}
327
328impl<'a> DfsIter<'a> {
329    /// Create a new DFS iterator starting from the given expression
330    pub fn new(root: &'a Expression) -> Self {
331        Self { stack: vec![root] }
332    }
333}
334
335impl<'a> Iterator for DfsIter<'a> {
336    type Item = &'a Expression;
337
338    fn next(&mut self) -> Option<Self::Item> {
339        let expr = self.stack.pop()?;
340
341        // Add children in reverse order so they come out in forward order
342        let children: Vec<_> = iter_children(expr).into_iter().map(|(_, e)| e).collect();
343        for child in children.into_iter().rev() {
344            self.stack.push(child);
345        }
346
347        let lists: Vec<_> = iter_children_lists(expr)
348            .into_iter()
349            .flat_map(|(_, es)| es.iter())
350            .collect();
351        for child in lists.into_iter().rev() {
352            self.stack.push(child);
353        }
354
355        Some(expr)
356    }
357}
358
359/// Level-order breadth-first iterator over an expression tree.
360///
361/// Visits all nodes at depth N before any node at depth N+1, using a queue-based
362/// approach. For a tree `(a + b) = c`, the iteration order is: `Eq` (depth 0),
363/// `Add`, `c` (depth 1), `a`, `b` (depth 2).
364///
365/// Created via [`ExpressionWalk::bfs`] or [`BfsIter::new`].
366pub struct BfsIter<'a> {
367    queue: VecDeque<&'a Expression>,
368}
369
370impl<'a> BfsIter<'a> {
371    /// Create a new BFS iterator starting from the given expression
372    pub fn new(root: &'a Expression) -> Self {
373        let mut queue = VecDeque::new();
374        queue.push_back(root);
375        Self { queue }
376    }
377}
378
379impl<'a> Iterator for BfsIter<'a> {
380    type Item = &'a Expression;
381
382    fn next(&mut self) -> Option<Self::Item> {
383        let expr = self.queue.pop_front()?;
384
385        // Add children to queue
386        for (_, child) in iter_children(expr) {
387            self.queue.push_back(child);
388        }
389
390        for (_, children) in iter_children_lists(expr) {
391            for child in children {
392                self.queue.push_back(child);
393            }
394        }
395
396        Some(expr)
397    }
398}
399
400/// Extension trait that adds traversal and search methods to [`Expression`].
401///
402/// This trait is implemented for `Expression` and provides a fluent API for
403/// iterating, searching, measuring, and transforming expression trees without
404/// needing to import the iterator types directly.
405pub trait ExpressionWalk {
406    /// Returns a depth-first (pre-order) iterator over this expression and all descendants.
407    ///
408    /// The root node is yielded first, then its children are visited recursively
409    /// from left to right.
410    fn dfs(&self) -> DfsIter<'_>;
411
412    /// Returns a breadth-first (level-order) iterator over this expression and all descendants.
413    ///
414    /// All nodes at depth N are yielded before any node at depth N+1.
415    fn bfs(&self) -> BfsIter<'_>;
416
417    /// Finds the first expression matching `predicate` in depth-first order.
418    ///
419    /// Returns `None` if no descendant (including this node) matches.
420    fn find<F>(&self, predicate: F) -> Option<&Expression>
421    where
422        F: Fn(&Expression) -> bool;
423
424    /// Collects all expressions matching `predicate` in depth-first order.
425    ///
426    /// Returns an empty vector if no descendants match.
427    fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
428    where
429        F: Fn(&Expression) -> bool;
430
431    /// Returns `true` if this node or any descendant matches `predicate`.
432    fn contains<F>(&self, predicate: F) -> bool
433    where
434        F: Fn(&Expression) -> bool;
435
436    /// Counts how many nodes (including this one) match `predicate`.
437    fn count<F>(&self, predicate: F) -> usize
438    where
439        F: Fn(&Expression) -> bool;
440
441    /// Returns direct child expressions of this node.
442    ///
443    /// Collects all single-child fields and list-child fields into a flat vector
444    /// of references. Leaf nodes return an empty vector.
445    fn children(&self) -> Vec<&Expression>;
446
447    /// Returns the maximum depth of the expression tree rooted at this node.
448    ///
449    /// A leaf node has depth 0, a node whose deepest child is a leaf has depth 1, etc.
450    fn tree_depth(&self) -> usize;
451
452    /// Transforms this expression tree bottom-up using the given function (owned variant).
453    ///
454    /// Children are transformed first, then `fun` is called on the resulting node.
455    /// Return `Ok(None)` from `fun` to replace a node with `NULL`.
456    /// Return `Ok(Some(expr))` to substitute the node with `expr`.
457    fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
458    where
459        F: Fn(Expression) -> crate::Result<Option<Expression>>,
460        Self: Sized;
461}
462
463impl ExpressionWalk for Expression {
464    fn dfs(&self) -> DfsIter<'_> {
465        DfsIter::new(self)
466    }
467
468    fn bfs(&self) -> BfsIter<'_> {
469        BfsIter::new(self)
470    }
471
472    fn find<F>(&self, predicate: F) -> Option<&Expression>
473    where
474        F: Fn(&Expression) -> bool,
475    {
476        self.dfs().find(|e| predicate(e))
477    }
478
479    fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
480    where
481        F: Fn(&Expression) -> bool,
482    {
483        self.dfs().filter(|e| predicate(e)).collect()
484    }
485
486    fn contains<F>(&self, predicate: F) -> bool
487    where
488        F: Fn(&Expression) -> bool,
489    {
490        self.dfs().any(|e| predicate(e))
491    }
492
493    fn count<F>(&self, predicate: F) -> usize
494    where
495        F: Fn(&Expression) -> bool,
496    {
497        self.dfs().filter(|e| predicate(e)).count()
498    }
499
500    fn children(&self) -> Vec<&Expression> {
501        let mut result: Vec<&Expression> = Vec::new();
502        for (_, child) in iter_children(self) {
503            result.push(child);
504        }
505        for (_, children_list) in iter_children_lists(self) {
506            for child in children_list {
507                result.push(child);
508            }
509        }
510        result
511    }
512
513    fn tree_depth(&self) -> usize {
514        let mut max_depth = 0;
515
516        for (_, child) in iter_children(self) {
517            let child_depth = child.tree_depth();
518            if child_depth + 1 > max_depth {
519                max_depth = child_depth + 1;
520            }
521        }
522
523        for (_, children) in iter_children_lists(self) {
524            for child in children {
525                let child_depth = child.tree_depth();
526                if child_depth + 1 > max_depth {
527                    max_depth = child_depth + 1;
528                }
529            }
530        }
531
532        max_depth
533    }
534
535    fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
536    where
537        F: Fn(Expression) -> crate::Result<Option<Expression>>,
538    {
539        transform(self, &fun)
540    }
541}
542
543/// Transforms an expression tree bottom-up, with optional node removal.
544///
545/// Recursively transforms all children first, then applies `fun` to the resulting node.
546/// If `fun` returns `Ok(None)`, the node is replaced with an `Expression::Null`.
547/// If `fun` returns `Ok(Some(expr))`, the node is replaced with `expr`.
548///
549/// This is the primary transformation entry point when callers need the ability to
550/// "delete" nodes by returning `None`.
551///
552/// # Example
553///
554/// ```rust,ignore
555/// use polyglot_sql::traversal::transform;
556///
557/// // Remove all Paren wrapper nodes from a tree
558/// let result = transform(expr, &|e| match e {
559///     Expression::Paren(p) => Ok(Some(p.this)),
560///     other => Ok(Some(other)),
561/// })?;
562/// ```
563pub fn transform<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
564where
565    F: Fn(Expression) -> crate::Result<Option<Expression>>,
566{
567    crate::dialects::transform_recursive(expr, &|e| match fun(e)? {
568        Some(transformed) => Ok(transformed),
569        None => Ok(Expression::Null(crate::expressions::Null)),
570    })
571}
572
573/// Transforms an expression tree bottom-up without node removal.
574///
575/// Like [`transform`], but `fun` returns an `Expression` directly rather than
576/// `Option<Expression>`, so nodes cannot be deleted. This is a convenience wrapper
577/// for the common case where every node is mapped to exactly one output node.
578///
579/// # Example
580///
581/// ```rust,ignore
582/// use polyglot_sql::traversal::transform_map;
583///
584/// // Uppercase all column names in a tree
585/// let result = transform_map(expr, &|e| match e {
586///     Expression::Column(mut c) => {
587///         c.name.name = c.name.name.to_uppercase();
588///         Ok(Expression::Column(c))
589///     }
590///     other => Ok(other),
591/// })?;
592/// ```
593pub fn transform_map<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
594where
595    F: Fn(Expression) -> crate::Result<Expression>,
596{
597    crate::dialects::transform_recursive(expr, fun)
598}
599
600// ---------------------------------------------------------------------------
601// Common expression predicates
602// ---------------------------------------------------------------------------
603// These free functions are intended for use with the search methods on
604// `ExpressionWalk` (e.g., `expr.find(is_column)`, `expr.contains(is_aggregate)`).
605
606/// Returns `true` if `expr` is a column reference ([`Expression::Column`]).
607pub fn is_column(expr: &Expression) -> bool {
608    matches!(expr, Expression::Column(_))
609}
610
611/// Returns `true` if `expr` is a literal value (number, string, boolean, or NULL).
612pub fn is_literal(expr: &Expression) -> bool {
613    matches!(
614        expr,
615        Expression::Literal(_) | Expression::Boolean(_) | Expression::Null(_)
616    )
617}
618
619/// Returns `true` if `expr` is a function call (regular or aggregate).
620pub fn is_function(expr: &Expression) -> bool {
621    matches!(
622        expr,
623        Expression::Function(_) | Expression::AggregateFunction(_)
624    )
625}
626
627/// Returns `true` if `expr` is a subquery ([`Expression::Subquery`]).
628pub fn is_subquery(expr: &Expression) -> bool {
629    matches!(expr, Expression::Subquery(_))
630}
631
632/// Returns `true` if `expr` is a SELECT statement ([`Expression::Select`]).
633pub fn is_select(expr: &Expression) -> bool {
634    matches!(expr, Expression::Select(_))
635}
636
637/// Returns `true` if `expr` is an aggregate function ([`Expression::AggregateFunction`]).
638pub fn is_aggregate(expr: &Expression) -> bool {
639    matches!(expr, Expression::AggregateFunction(_))
640}
641
642/// Returns `true` if `expr` is a window function ([`Expression::WindowFunction`]).
643pub fn is_window_function(expr: &Expression) -> bool {
644    matches!(expr, Expression::WindowFunction(_))
645}
646
647/// Collects all column references ([`Expression::Column`]) from the expression tree.
648///
649/// Performs a depth-first search and returns references to every column node found.
650pub fn get_columns(expr: &Expression) -> Vec<&Expression> {
651    expr.find_all(is_column)
652}
653
654/// Collects all table references ([`Expression::Table`]) from the expression tree.
655///
656/// Performs a depth-first search and returns references to every table node found.
657pub fn get_tables(expr: &Expression) -> Vec<&Expression> {
658    expr.find_all(|e| matches!(e, Expression::Table(_)))
659}
660
661/// Returns `true` if the expression tree contains any aggregate function calls.
662pub fn contains_aggregate(expr: &Expression) -> bool {
663    expr.contains(is_aggregate)
664}
665
666/// Returns `true` if the expression tree contains any window function calls.
667pub fn contains_window_function(expr: &Expression) -> bool {
668    expr.contains(is_window_function)
669}
670
671/// Returns `true` if the expression tree contains any subquery nodes.
672pub fn contains_subquery(expr: &Expression) -> bool {
673    expr.contains(is_subquery)
674}
675
676/// Find the parent of `target` within the tree rooted at `root`.
677///
678/// Uses pointer identity ([`std::ptr::eq`]) — `target` must be a reference
679/// obtained from the same tree (e.g., via [`ExpressionWalk::find`] or DFS iteration).
680///
681/// Returns `None` if `target` is the root itself or is not found in the tree.
682pub fn find_parent<'a>(root: &'a Expression, target: &Expression) -> Option<&'a Expression> {
683    fn search<'a>(node: &'a Expression, target: *const Expression) -> Option<&'a Expression> {
684        for (_, child) in iter_children(node) {
685            if std::ptr::eq(child, target) {
686                return Some(node);
687            }
688            if let Some(found) = search(child, target) {
689                return Some(found);
690            }
691        }
692        for (_, children_list) in iter_children_lists(node) {
693            for child in children_list {
694                if std::ptr::eq(child, target) {
695                    return Some(node);
696                }
697                if let Some(found) = search(child, target) {
698                    return Some(found);
699                }
700            }
701        }
702        None
703    }
704
705    search(root, target as *const Expression)
706}
707
708/// Find the first ancestor of `target` matching `predicate`, walking from
709/// parent toward root.
710///
711/// Uses pointer identity for target lookup. Returns `None` if no ancestor
712/// matches or `target` is not found in the tree.
713pub fn find_ancestor<'a, F>(
714    root: &'a Expression,
715    target: &Expression,
716    predicate: F,
717) -> Option<&'a Expression>
718where
719    F: Fn(&Expression) -> bool,
720{
721    // Build path from root to target
722    fn build_path<'a>(
723        node: &'a Expression,
724        target: *const Expression,
725        path: &mut Vec<&'a Expression>,
726    ) -> bool {
727        if std::ptr::eq(node, target) {
728            return true;
729        }
730        path.push(node);
731        for (_, child) in iter_children(node) {
732            if build_path(child, target, path) {
733                return true;
734            }
735        }
736        for (_, children_list) in iter_children_lists(node) {
737            for child in children_list {
738                if build_path(child, target, path) {
739                    return true;
740                }
741            }
742        }
743        path.pop();
744        false
745    }
746
747    let mut path = Vec::new();
748    if !build_path(root, target as *const Expression, &mut path) {
749        return None;
750    }
751
752    // Walk path in reverse (parent first, then grandparent, etc.)
753    for ancestor in path.iter().rev() {
754        if predicate(ancestor) {
755            return Some(ancestor);
756        }
757    }
758    None
759}
760
761#[cfg(test)]
762mod tests {
763    use super::*;
764    use crate::expressions::{BinaryOp, Column, Identifier, Literal};
765
766    fn make_column(name: &str) -> Expression {
767        Expression::Column(Column {
768            name: Identifier {
769                name: name.to_string(),
770                quoted: false,
771                trailing_comments: vec![],
772            },
773            table: None,
774            join_mark: false,
775            trailing_comments: vec![],
776        })
777    }
778
779    fn make_literal(value: i64) -> Expression {
780        Expression::Literal(Literal::Number(value.to_string()))
781    }
782
783    #[test]
784    fn test_dfs_simple() {
785        let left = make_column("a");
786        let right = make_literal(1);
787        let expr = Expression::Eq(Box::new(BinaryOp {
788            left,
789            right,
790            left_comments: vec![],
791            operator_comments: vec![],
792            trailing_comments: vec![],
793        }));
794
795        let nodes: Vec<_> = expr.dfs().collect();
796        assert_eq!(nodes.len(), 3); // Eq, Column, Literal
797        assert!(matches!(nodes[0], Expression::Eq(_)));
798        assert!(matches!(nodes[1], Expression::Column(_)));
799        assert!(matches!(nodes[2], Expression::Literal(_)));
800    }
801
802    #[test]
803    fn test_find() {
804        let left = make_column("a");
805        let right = make_literal(1);
806        let expr = Expression::Eq(Box::new(BinaryOp {
807            left,
808            right,
809            left_comments: vec![],
810            operator_comments: vec![],
811            trailing_comments: vec![],
812        }));
813
814        let column = expr.find(is_column);
815        assert!(column.is_some());
816        assert!(matches!(column.unwrap(), Expression::Column(_)));
817
818        let literal = expr.find(is_literal);
819        assert!(literal.is_some());
820        assert!(matches!(literal.unwrap(), Expression::Literal(_)));
821    }
822
823    #[test]
824    fn test_find_all() {
825        let col1 = make_column("a");
826        let col2 = make_column("b");
827        let expr = Expression::And(Box::new(BinaryOp {
828            left: col1,
829            right: col2,
830            left_comments: vec![],
831            operator_comments: vec![],
832            trailing_comments: vec![],
833        }));
834
835        let columns = expr.find_all(is_column);
836        assert_eq!(columns.len(), 2);
837    }
838
839    #[test]
840    fn test_contains() {
841        let col = make_column("a");
842        let lit = make_literal(1);
843        let expr = Expression::Eq(Box::new(BinaryOp {
844            left: col,
845            right: lit,
846            left_comments: vec![],
847            operator_comments: vec![],
848            trailing_comments: vec![],
849        }));
850
851        assert!(expr.contains(is_column));
852        assert!(expr.contains(is_literal));
853        assert!(!expr.contains(is_subquery));
854    }
855
856    #[test]
857    fn test_count() {
858        let col1 = make_column("a");
859        let col2 = make_column("b");
860        let lit = make_literal(1);
861
862        let inner = Expression::Add(Box::new(BinaryOp {
863            left: col2,
864            right: lit,
865            left_comments: vec![],
866            operator_comments: vec![],
867            trailing_comments: vec![],
868        }));
869
870        let expr = Expression::Eq(Box::new(BinaryOp {
871            left: col1,
872            right: inner,
873            left_comments: vec![],
874            operator_comments: vec![],
875            trailing_comments: vec![],
876        }));
877
878        assert_eq!(expr.count(is_column), 2);
879        assert_eq!(expr.count(is_literal), 1);
880    }
881
882    #[test]
883    fn test_tree_depth() {
884        // Single node
885        let lit = make_literal(1);
886        assert_eq!(lit.tree_depth(), 0);
887
888        // One level
889        let col = make_column("a");
890        let expr = Expression::Eq(Box::new(BinaryOp {
891            left: col,
892            right: lit.clone(),
893            left_comments: vec![],
894            operator_comments: vec![],
895            trailing_comments: vec![],
896        }));
897        assert_eq!(expr.tree_depth(), 1);
898
899        // Two levels
900        let inner = Expression::Add(Box::new(BinaryOp {
901            left: make_column("b"),
902            right: lit,
903            left_comments: vec![],
904            operator_comments: vec![],
905            trailing_comments: vec![],
906        }));
907        let outer = Expression::Eq(Box::new(BinaryOp {
908            left: make_column("a"),
909            right: inner,
910            left_comments: vec![],
911            operator_comments: vec![],
912            trailing_comments: vec![],
913        }));
914        assert_eq!(outer.tree_depth(), 2);
915    }
916
917    #[test]
918    fn test_tree_context() {
919        let col = make_column("a");
920        let lit = make_literal(1);
921        let expr = Expression::Eq(Box::new(BinaryOp {
922            left: col,
923            right: lit,
924            left_comments: vec![],
925            operator_comments: vec![],
926            trailing_comments: vec![],
927        }));
928
929        let ctx = TreeContext::build(&expr);
930
931        // Root has no parent
932        let root_info = ctx.get(0).unwrap();
933        assert!(root_info.parent_id.is_none());
934
935        // Children have root as parent
936        let left_info = ctx.get(1).unwrap();
937        assert_eq!(left_info.parent_id, Some(0));
938        assert_eq!(left_info.arg_key, "left");
939
940        let right_info = ctx.get(2).unwrap();
941        assert_eq!(right_info.parent_id, Some(0));
942        assert_eq!(right_info.arg_key, "right");
943    }
944
945    // -- Step 8: transform / transform_map tests --
946
947    #[test]
948    fn test_transform_rename_columns() {
949        let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
950        let expr = ast[0].clone();
951        let result = super::transform_map(expr, &|e| {
952            if let Expression::Column(ref c) = e {
953                if c.name.name == "a" {
954                    return Ok(Expression::Column(Column {
955                        name: Identifier::new("alpha"),
956                        table: c.table.clone(),
957                        join_mark: false,
958                        trailing_comments: vec![],
959                    }));
960                }
961            }
962            Ok(e)
963        })
964        .unwrap();
965        let sql = crate::generator::Generator::sql(&result).unwrap();
966        assert!(sql.contains("alpha"), "Expected 'alpha' in: {}", sql);
967        assert!(sql.contains("b"), "Expected 'b' in: {}", sql);
968    }
969
970    #[test]
971    fn test_transform_noop() {
972        let ast = crate::parser::Parser::parse_sql("SELECT 1 + 2").unwrap();
973        let expr = ast[0].clone();
974        let result = super::transform_map(expr.clone(), &|e| Ok(e)).unwrap();
975        let sql1 = crate::generator::Generator::sql(&expr).unwrap();
976        let sql2 = crate::generator::Generator::sql(&result).unwrap();
977        assert_eq!(sql1, sql2);
978    }
979
980    #[test]
981    fn test_transform_nested() {
982        let ast = crate::parser::Parser::parse_sql("SELECT a + b FROM t").unwrap();
983        let expr = ast[0].clone();
984        let result = super::transform_map(expr, &|e| {
985            if let Expression::Column(ref c) = e {
986                return Ok(Expression::Literal(Literal::Number(
987                    if c.name.name == "a" { "1" } else { "2" }.to_string(),
988                )));
989            }
990            Ok(e)
991        })
992        .unwrap();
993        let sql = crate::generator::Generator::sql(&result).unwrap();
994        assert_eq!(sql, "SELECT 1 + 2 FROM t");
995    }
996
997    #[test]
998    fn test_transform_error() {
999        let ast = crate::parser::Parser::parse_sql("SELECT a FROM t").unwrap();
1000        let expr = ast[0].clone();
1001        let result = super::transform_map(expr, &|e| {
1002            if let Expression::Column(ref c) = e {
1003                if c.name.name == "a" {
1004                    return Err(crate::error::Error::Parse("test error".to_string()));
1005                }
1006            }
1007            Ok(e)
1008        });
1009        assert!(result.is_err());
1010    }
1011
1012    #[test]
1013    fn test_transform_owned_trait() {
1014        let ast = crate::parser::Parser::parse_sql("SELECT x FROM t").unwrap();
1015        let expr = ast[0].clone();
1016        let result = expr.transform_owned(|e| Ok(Some(e))).unwrap();
1017        let sql = crate::generator::Generator::sql(&result).unwrap();
1018        assert_eq!(sql, "SELECT x FROM t");
1019    }
1020
1021    // -- children() tests --
1022
1023    #[test]
1024    fn test_children_leaf() {
1025        let lit = make_literal(1);
1026        assert_eq!(lit.children().len(), 0);
1027    }
1028
1029    #[test]
1030    fn test_children_binary_op() {
1031        let left = make_column("a");
1032        let right = make_literal(1);
1033        let expr = Expression::Eq(Box::new(BinaryOp {
1034            left,
1035            right,
1036            left_comments: vec![],
1037            operator_comments: vec![],
1038            trailing_comments: vec![],
1039        }));
1040        let children = expr.children();
1041        assert_eq!(children.len(), 2);
1042        assert!(matches!(children[0], Expression::Column(_)));
1043        assert!(matches!(children[1], Expression::Literal(_)));
1044    }
1045
1046    #[test]
1047    fn test_children_select() {
1048        let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1049        let expr = &ast[0];
1050        let children = expr.children();
1051        // Should include select list items (a, b)
1052        assert!(children.len() >= 2);
1053    }
1054
1055    // -- find_parent() tests --
1056
1057    #[test]
1058    fn test_find_parent_binary() {
1059        let left = make_column("a");
1060        let right = make_literal(1);
1061        let expr = Expression::Eq(Box::new(BinaryOp {
1062            left,
1063            right,
1064            left_comments: vec![],
1065            operator_comments: vec![],
1066            trailing_comments: vec![],
1067        }));
1068
1069        // Find the column child and get its parent
1070        let col = expr.find(is_column).unwrap();
1071        let parent = super::find_parent(&expr, col);
1072        assert!(parent.is_some());
1073        assert!(matches!(parent.unwrap(), Expression::Eq(_)));
1074    }
1075
1076    #[test]
1077    fn test_find_parent_root_has_none() {
1078        let lit = make_literal(1);
1079        let parent = super::find_parent(&lit, &lit);
1080        assert!(parent.is_none());
1081    }
1082
1083    // -- find_ancestor() tests --
1084
1085    #[test]
1086    fn test_find_ancestor_select() {
1087        let ast = crate::parser::Parser::parse_sql("SELECT a FROM t WHERE a > 1").unwrap();
1088        let expr = &ast[0];
1089
1090        // Find a column inside the WHERE clause
1091        let where_col = expr.dfs().find(|e| {
1092            if let Expression::Column(c) = e {
1093                c.name.name == "a"
1094            } else {
1095                false
1096            }
1097        });
1098        assert!(where_col.is_some());
1099
1100        // Find Select ancestor of that column
1101        let ancestor = super::find_ancestor(expr, where_col.unwrap(), is_select);
1102        assert!(ancestor.is_some());
1103        assert!(matches!(ancestor.unwrap(), Expression::Select(_)));
1104    }
1105
1106    #[test]
1107    fn test_find_ancestor_no_match() {
1108        let left = make_column("a");
1109        let right = make_literal(1);
1110        let expr = Expression::Eq(Box::new(BinaryOp {
1111            left,
1112            right,
1113            left_comments: vec![],
1114            operator_comments: vec![],
1115            trailing_comments: vec![],
1116        }));
1117
1118        let col = expr.find(is_column).unwrap();
1119        let ancestor = super::find_ancestor(&expr, col, is_select);
1120        assert!(ancestor.is_none());
1121    }
1122
1123    #[test]
1124    fn test_ancestors() {
1125        let col = make_column("a");
1126        let lit = make_literal(1);
1127        let inner = Expression::Add(Box::new(BinaryOp {
1128            left: col,
1129            right: lit,
1130            left_comments: vec![],
1131            operator_comments: vec![],
1132            trailing_comments: vec![],
1133        }));
1134        let outer = Expression::Eq(Box::new(BinaryOp {
1135            left: make_column("b"),
1136            right: inner,
1137            left_comments: vec![],
1138            operator_comments: vec![],
1139            trailing_comments: vec![],
1140        }));
1141
1142        let ctx = TreeContext::build(&outer);
1143
1144        // The inner Add's left child (column "a") should have ancestors
1145        // Node 0: Eq
1146        // Node 1: Column "b" (left of Eq)
1147        // Node 2: Add (right of Eq)
1148        // Node 3: Column "a" (left of Add)
1149        // Node 4: Literal (right of Add)
1150
1151        let ancestors = ctx.ancestors_of(3);
1152        assert_eq!(ancestors, vec![2, 0]); // Add, then Eq
1153    }
1154}