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, TableRef};
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::Select(s) => {
174            if let Some(from) = &s.from {
175                for source in &from.expressions {
176                    children.push(("from", source));
177                }
178            }
179            for join in &s.joins {
180                children.push(("join_this", &join.this));
181                if let Some(on) = &join.on {
182                    children.push(("join_on", on));
183                }
184                if let Some(match_condition) = &join.match_condition {
185                    children.push(("join_match_condition", match_condition));
186                }
187                for pivot in &join.pivots {
188                    children.push(("join_pivot", pivot));
189                }
190            }
191            for lateral_view in &s.lateral_views {
192                children.push(("lateral_view", &lateral_view.this));
193            }
194            if let Some(prewhere) = &s.prewhere {
195                children.push(("prewhere", prewhere));
196            }
197            if let Some(where_clause) = &s.where_clause {
198                children.push(("where", &where_clause.this));
199            }
200            if let Some(group_by) = &s.group_by {
201                for e in &group_by.expressions {
202                    children.push(("group_by", e));
203                }
204            }
205            if let Some(having) = &s.having {
206                children.push(("having", &having.this));
207            }
208            if let Some(qualify) = &s.qualify {
209                children.push(("qualify", &qualify.this));
210            }
211            if let Some(order_by) = &s.order_by {
212                for ordered in &order_by.expressions {
213                    children.push(("order_by", &ordered.this));
214                }
215            }
216            if let Some(distribute_by) = &s.distribute_by {
217                for e in &distribute_by.expressions {
218                    children.push(("distribute_by", e));
219                }
220            }
221            if let Some(cluster_by) = &s.cluster_by {
222                for ordered in &cluster_by.expressions {
223                    children.push(("cluster_by", &ordered.this));
224                }
225            }
226            if let Some(sort_by) = &s.sort_by {
227                for ordered in &sort_by.expressions {
228                    children.push(("sort_by", &ordered.this));
229                }
230            }
231            if let Some(limit) = &s.limit {
232                children.push(("limit", &limit.this));
233            }
234            if let Some(offset) = &s.offset {
235                children.push(("offset", &offset.this));
236            }
237            if let Some(limit_by) = &s.limit_by {
238                for e in limit_by {
239                    children.push(("limit_by", e));
240                }
241            }
242            if let Some(fetch) = &s.fetch {
243                if let Some(count) = &fetch.count {
244                    children.push(("fetch", count));
245                }
246            }
247            if let Some(top) = &s.top {
248                children.push(("top", &top.this));
249            }
250            if let Some(with) = &s.with {
251                for cte in &with.ctes {
252                    children.push(("with_cte", &cte.this));
253                }
254                if let Some(search) = &with.search {
255                    children.push(("with_search", search));
256                }
257            }
258            if let Some(sample) = &s.sample {
259                children.push(("sample_size", &sample.size));
260                if let Some(seed) = &sample.seed {
261                    children.push(("sample_seed", seed));
262                }
263                if let Some(offset) = &sample.offset {
264                    children.push(("sample_offset", offset));
265                }
266                if let Some(bucket_numerator) = &sample.bucket_numerator {
267                    children.push(("sample_bucket_numerator", bucket_numerator));
268                }
269                if let Some(bucket_denominator) = &sample.bucket_denominator {
270                    children.push(("sample_bucket_denominator", bucket_denominator));
271                }
272                if let Some(bucket_field) = &sample.bucket_field {
273                    children.push(("sample_bucket_field", bucket_field));
274                }
275            }
276            if let Some(connect) = &s.connect {
277                if let Some(start) = &connect.start {
278                    children.push(("connect_start", start));
279                }
280                children.push(("connect", &connect.connect));
281            }
282            if let Some(into) = &s.into {
283                children.push(("into", &into.this));
284            }
285            for lock in &s.locks {
286                for e in &lock.expressions {
287                    children.push(("lock_expression", e));
288                }
289                if let Some(wait) = &lock.wait {
290                    children.push(("lock_wait", wait));
291                }
292                if let Some(key) = &lock.key {
293                    children.push(("lock_key", key));
294                }
295                if let Some(update) = &lock.update {
296                    children.push(("lock_update", update));
297                }
298            }
299            for e in &s.for_xml {
300                children.push(("for_xml", e));
301            }
302        }
303        Expression::With(with) => {
304            for cte in &with.ctes {
305                children.push(("cte", &cte.this));
306            }
307            if let Some(search) = &with.search {
308                children.push(("search", search));
309            }
310        }
311        Expression::Cte(cte) => {
312            children.push(("this", &cte.this));
313        }
314        Expression::Insert(insert) => {
315            if let Some(query) = &insert.query {
316                children.push(("query", query));
317            }
318            if let Some(with) = &insert.with {
319                for cte in &with.ctes {
320                    children.push(("with_cte", &cte.this));
321                }
322                if let Some(search) = &with.search {
323                    children.push(("with_search", search));
324                }
325            }
326            if let Some(on_conflict) = &insert.on_conflict {
327                children.push(("on_conflict", on_conflict));
328            }
329            if let Some(replace_where) = &insert.replace_where {
330                children.push(("replace_where", replace_where));
331            }
332            if let Some(source) = &insert.source {
333                children.push(("source", source));
334            }
335            if let Some(function_target) = &insert.function_target {
336                children.push(("function_target", function_target));
337            }
338            if let Some(partition_by) = &insert.partition_by {
339                children.push(("partition_by", partition_by));
340            }
341            if let Some(output) = &insert.output {
342                for column in &output.columns {
343                    children.push(("output_column", column));
344                }
345                if let Some(into_table) = &output.into_table {
346                    children.push(("output_into_table", into_table));
347                }
348            }
349            for row in &insert.values {
350                for value in row {
351                    children.push(("value", value));
352                }
353            }
354            for (_, value) in &insert.partition {
355                if let Some(value) = value {
356                    children.push(("partition_value", value));
357                }
358            }
359            for returning in &insert.returning {
360                children.push(("returning", returning));
361            }
362            for setting in &insert.settings {
363                children.push(("setting", setting));
364            }
365        }
366        Expression::Update(update) => {
367            if let Some(from_clause) = &update.from_clause {
368                for source in &from_clause.expressions {
369                    children.push(("from", source));
370                }
371            }
372            for join in &update.table_joins {
373                children.push(("table_join_this", &join.this));
374                if let Some(on) = &join.on {
375                    children.push(("table_join_on", on));
376                }
377            }
378            for join in &update.from_joins {
379                children.push(("from_join_this", &join.this));
380                if let Some(on) = &join.on {
381                    children.push(("from_join_on", on));
382                }
383            }
384            for (_, value) in &update.set {
385                children.push(("set_value", value));
386            }
387            if let Some(where_clause) = &update.where_clause {
388                children.push(("where", &where_clause.this));
389            }
390            if let Some(output) = &update.output {
391                for column in &output.columns {
392                    children.push(("output_column", column));
393                }
394                if let Some(into_table) = &output.into_table {
395                    children.push(("output_into_table", into_table));
396                }
397            }
398            if let Some(with) = &update.with {
399                for cte in &with.ctes {
400                    children.push(("with_cte", &cte.this));
401                }
402                if let Some(search) = &with.search {
403                    children.push(("with_search", search));
404                }
405            }
406            if let Some(limit) = &update.limit {
407                children.push(("limit", limit));
408            }
409            if let Some(order_by) = &update.order_by {
410                for ordered in &order_by.expressions {
411                    children.push(("order_by", &ordered.this));
412                }
413            }
414            for returning in &update.returning {
415                children.push(("returning", returning));
416            }
417        }
418        Expression::Delete(delete) => {
419            if let Some(with) = &delete.with {
420                for cte in &with.ctes {
421                    children.push(("with_cte", &cte.this));
422                }
423                if let Some(search) = &with.search {
424                    children.push(("with_search", search));
425                }
426            }
427            if let Some(where_clause) = &delete.where_clause {
428                children.push(("where", &where_clause.this));
429            }
430            if let Some(output) = &delete.output {
431                for column in &output.columns {
432                    children.push(("output_column", column));
433                }
434                if let Some(into_table) = &output.into_table {
435                    children.push(("output_into_table", into_table));
436                }
437            }
438            if let Some(limit) = &delete.limit {
439                children.push(("limit", limit));
440            }
441            if let Some(order_by) = &delete.order_by {
442                for ordered in &order_by.expressions {
443                    children.push(("order_by", &ordered.this));
444                }
445            }
446            for returning in &delete.returning {
447                children.push(("returning", returning));
448            }
449            for join in &delete.joins {
450                children.push(("join_this", &join.this));
451                if let Some(on) = &join.on {
452                    children.push(("join_on", on));
453                }
454            }
455        }
456        Expression::Join(join) => {
457            children.push(("this", &join.this));
458            if let Some(on) = &join.on {
459                children.push(("on", on));
460            }
461            if let Some(match_condition) = &join.match_condition {
462                children.push(("match_condition", match_condition));
463            }
464            for pivot in &join.pivots {
465                children.push(("pivot", pivot));
466            }
467        }
468        Expression::Alias(a) => {
469            children.push(("this", &a.this));
470        }
471        Expression::Cast(c) => {
472            children.push(("this", &c.this));
473        }
474        Expression::Not(u) | Expression::Neg(u) | Expression::BitwiseNot(u) => {
475            children.push(("this", &u.this));
476        }
477        Expression::Paren(p) => {
478            children.push(("this", &p.this));
479        }
480        Expression::IsNull(i) => {
481            children.push(("this", &i.this));
482        }
483        Expression::Exists(e) => {
484            children.push(("this", &e.this));
485        }
486        Expression::Subquery(s) => {
487            children.push(("this", &s.this));
488        }
489        Expression::Where(w) => {
490            children.push(("this", &w.this));
491        }
492        Expression::Having(h) => {
493            children.push(("this", &h.this));
494        }
495        Expression::Qualify(q) => {
496            children.push(("this", &q.this));
497        }
498        Expression::And(op)
499        | Expression::Or(op)
500        | Expression::Add(op)
501        | Expression::Sub(op)
502        | Expression::Mul(op)
503        | Expression::Div(op)
504        | Expression::Mod(op)
505        | Expression::Eq(op)
506        | Expression::Neq(op)
507        | Expression::Lt(op)
508        | Expression::Lte(op)
509        | Expression::Gt(op)
510        | Expression::Gte(op)
511        | Expression::BitwiseAnd(op)
512        | Expression::BitwiseOr(op)
513        | Expression::BitwiseXor(op)
514        | Expression::Concat(op) => {
515            children.push(("left", &op.left));
516            children.push(("right", &op.right));
517        }
518        Expression::Like(op) | Expression::ILike(op) => {
519            children.push(("left", &op.left));
520            children.push(("right", &op.right));
521        }
522        Expression::Between(b) => {
523            children.push(("this", &b.this));
524            children.push(("low", &b.low));
525            children.push(("high", &b.high));
526        }
527        Expression::In(i) => {
528            children.push(("this", &i.this));
529            if let Some(ref query) = i.query {
530                children.push(("query", query));
531            }
532            if let Some(ref unnest) = i.unnest {
533                children.push(("unnest", unnest));
534            }
535        }
536        Expression::Case(c) => {
537            if let Some(ref operand) = &c.operand {
538                children.push(("operand", operand));
539            }
540        }
541        Expression::WindowFunction(wf) => {
542            children.push(("this", &wf.this));
543        }
544        Expression::Union(u) => {
545            children.push(("left", &u.left));
546            children.push(("right", &u.right));
547            if let Some(with) = &u.with {
548                for cte in &with.ctes {
549                    children.push(("with_cte", &cte.this));
550                }
551                if let Some(search) = &with.search {
552                    children.push(("with_search", search));
553                }
554            }
555            if let Some(order_by) = &u.order_by {
556                for ordered in &order_by.expressions {
557                    children.push(("order_by", &ordered.this));
558                }
559            }
560            if let Some(limit) = &u.limit {
561                children.push(("limit", limit));
562            }
563            if let Some(offset) = &u.offset {
564                children.push(("offset", offset));
565            }
566            if let Some(distribute_by) = &u.distribute_by {
567                for e in &distribute_by.expressions {
568                    children.push(("distribute_by", e));
569                }
570            }
571            if let Some(sort_by) = &u.sort_by {
572                for ordered in &sort_by.expressions {
573                    children.push(("sort_by", &ordered.this));
574                }
575            }
576            if let Some(cluster_by) = &u.cluster_by {
577                for ordered in &cluster_by.expressions {
578                    children.push(("cluster_by", &ordered.this));
579                }
580            }
581            for e in &u.on_columns {
582                children.push(("on_column", e));
583            }
584        }
585        Expression::Intersect(i) => {
586            children.push(("left", &i.left));
587            children.push(("right", &i.right));
588            if let Some(with) = &i.with {
589                for cte in &with.ctes {
590                    children.push(("with_cte", &cte.this));
591                }
592                if let Some(search) = &with.search {
593                    children.push(("with_search", search));
594                }
595            }
596            if let Some(order_by) = &i.order_by {
597                for ordered in &order_by.expressions {
598                    children.push(("order_by", &ordered.this));
599                }
600            }
601            if let Some(limit) = &i.limit {
602                children.push(("limit", limit));
603            }
604            if let Some(offset) = &i.offset {
605                children.push(("offset", offset));
606            }
607            if let Some(distribute_by) = &i.distribute_by {
608                for e in &distribute_by.expressions {
609                    children.push(("distribute_by", e));
610                }
611            }
612            if let Some(sort_by) = &i.sort_by {
613                for ordered in &sort_by.expressions {
614                    children.push(("sort_by", &ordered.this));
615                }
616            }
617            if let Some(cluster_by) = &i.cluster_by {
618                for ordered in &cluster_by.expressions {
619                    children.push(("cluster_by", &ordered.this));
620                }
621            }
622            for e in &i.on_columns {
623                children.push(("on_column", e));
624            }
625        }
626        Expression::Except(e) => {
627            children.push(("left", &e.left));
628            children.push(("right", &e.right));
629            if let Some(with) = &e.with {
630                for cte in &with.ctes {
631                    children.push(("with_cte", &cte.this));
632                }
633                if let Some(search) = &with.search {
634                    children.push(("with_search", search));
635                }
636            }
637            if let Some(order_by) = &e.order_by {
638                for ordered in &order_by.expressions {
639                    children.push(("order_by", &ordered.this));
640                }
641            }
642            if let Some(limit) = &e.limit {
643                children.push(("limit", limit));
644            }
645            if let Some(offset) = &e.offset {
646                children.push(("offset", offset));
647            }
648            if let Some(distribute_by) = &e.distribute_by {
649                for expr in &distribute_by.expressions {
650                    children.push(("distribute_by", expr));
651                }
652            }
653            if let Some(sort_by) = &e.sort_by {
654                for ordered in &sort_by.expressions {
655                    children.push(("sort_by", &ordered.this));
656                }
657            }
658            if let Some(cluster_by) = &e.cluster_by {
659                for ordered in &cluster_by.expressions {
660                    children.push(("cluster_by", &ordered.this));
661                }
662            }
663            for expr in &e.on_columns {
664                children.push(("on_column", expr));
665            }
666        }
667        Expression::Merge(merge) => {
668            children.push(("this", &merge.this));
669            children.push(("using", &merge.using));
670            if let Some(on) = &merge.on {
671                children.push(("on", on));
672            }
673            if let Some(using_cond) = &merge.using_cond {
674                children.push(("using_cond", using_cond));
675            }
676            if let Some(whens) = &merge.whens {
677                children.push(("whens", whens));
678            }
679            if let Some(with_) = &merge.with_ {
680                children.push(("with_", with_));
681            }
682            if let Some(returning) = &merge.returning {
683                children.push(("returning", returning));
684            }
685        }
686        Expression::Any(q) | Expression::All(q) => {
687            children.push(("this", &q.this));
688            children.push(("subquery", &q.subquery));
689        }
690        Expression::Ordered(o) => {
691            children.push(("this", &o.this));
692        }
693        Expression::Interval(i) => {
694            if let Some(ref this) = i.this {
695                children.push(("this", this));
696            }
697        }
698        Expression::Describe(d) => {
699            children.push(("target", &d.target));
700        }
701        Expression::CreateTask(ct) => {
702            children.push(("body", &ct.body));
703        }
704        Expression::Analyze(a) => {
705            if let Some(this) = &a.this {
706                children.push(("this", this));
707            }
708            if let Some(expr) = &a.expression {
709                children.push(("expression", expr));
710            }
711        }
712        _ => {}
713    }
714
715    children
716}
717
718/// Iterate over list-child fields of an expression
719///
720/// Returns an iterator of (field_name, &[Expression]) pairs.
721fn iter_children_lists(expr: &Expression) -> Vec<(&'static str, &[Expression])> {
722    let mut lists = Vec::new();
723
724    match expr {
725        Expression::Select(s) => lists.push(("expressions", s.expressions.as_slice())),
726        Expression::Function(f) => {
727            lists.push(("args", f.args.as_slice()));
728        }
729        Expression::AggregateFunction(f) => {
730            lists.push(("args", f.args.as_slice()));
731        }
732        Expression::From(f) => {
733            lists.push(("expressions", f.expressions.as_slice()));
734        }
735        Expression::GroupBy(g) => {
736            lists.push(("expressions", g.expressions.as_slice()));
737        }
738        // OrderBy.expressions is Vec<Ordered>, not Vec<Expression>
739        // We handle Ordered items via iter_children
740        Expression::In(i) => {
741            lists.push(("expressions", i.expressions.as_slice()));
742        }
743        Expression::Array(a) => {
744            lists.push(("expressions", a.expressions.as_slice()));
745        }
746        Expression::Tuple(t) => {
747            lists.push(("expressions", t.expressions.as_slice()));
748        }
749        Expression::TryCatch(try_catch) => {
750            lists.push(("try_body", try_catch.try_body.as_slice()));
751            if let Some(catch_body) = &try_catch.catch_body {
752                lists.push(("catch_body", catch_body.as_slice()));
753            }
754        }
755        // Values.expressions is Vec<Tuple>, handle specially
756        Expression::Coalesce(c) => {
757            lists.push(("expressions", c.expressions.as_slice()));
758        }
759        Expression::Greatest(g) | Expression::Least(g) => {
760            lists.push(("expressions", g.expressions.as_slice()));
761        }
762        _ => {}
763    }
764
765    lists
766}
767
768/// Pre-order depth-first iterator over an expression tree.
769///
770/// Visits each node before its children, using a stack-based approach. This means
771/// the root is yielded first, followed by the entire left subtree (recursively),
772/// then the right subtree. For a binary expression `a + b`, the iteration order
773/// is: `Add`, `a`, `b`.
774///
775/// Created via [`ExpressionWalk::dfs`] or [`DfsIter::new`].
776pub struct DfsIter<'a> {
777    stack: Vec<&'a Expression>,
778}
779
780impl<'a> DfsIter<'a> {
781    /// Create a new DFS iterator starting from the given expression
782    pub fn new(root: &'a Expression) -> Self {
783        Self { stack: vec![root] }
784    }
785}
786
787impl<'a> Iterator for DfsIter<'a> {
788    type Item = &'a Expression;
789
790    fn next(&mut self) -> Option<Self::Item> {
791        let expr = self.stack.pop()?;
792
793        // Add children in reverse order so they come out in forward order
794        let children: Vec<_> = iter_children(expr).into_iter().map(|(_, e)| e).collect();
795        for child in children.into_iter().rev() {
796            self.stack.push(child);
797        }
798
799        let lists: Vec<_> = iter_children_lists(expr)
800            .into_iter()
801            .flat_map(|(_, es)| es.iter())
802            .collect();
803        for child in lists.into_iter().rev() {
804            self.stack.push(child);
805        }
806
807        Some(expr)
808    }
809}
810
811/// Level-order breadth-first iterator over an expression tree.
812///
813/// Visits all nodes at depth N before any node at depth N+1, using a queue-based
814/// approach. For a tree `(a + b) = c`, the iteration order is: `Eq` (depth 0),
815/// `Add`, `c` (depth 1), `a`, `b` (depth 2).
816///
817/// Created via [`ExpressionWalk::bfs`] or [`BfsIter::new`].
818pub struct BfsIter<'a> {
819    queue: VecDeque<&'a Expression>,
820}
821
822impl<'a> BfsIter<'a> {
823    /// Create a new BFS iterator starting from the given expression
824    pub fn new(root: &'a Expression) -> Self {
825        let mut queue = VecDeque::new();
826        queue.push_back(root);
827        Self { queue }
828    }
829}
830
831impl<'a> Iterator for BfsIter<'a> {
832    type Item = &'a Expression;
833
834    fn next(&mut self) -> Option<Self::Item> {
835        let expr = self.queue.pop_front()?;
836
837        // Add children to queue
838        for (_, child) in iter_children(expr) {
839            self.queue.push_back(child);
840        }
841
842        for (_, children) in iter_children_lists(expr) {
843            for child in children {
844                self.queue.push_back(child);
845            }
846        }
847
848        Some(expr)
849    }
850}
851
852/// Extension trait that adds traversal and search methods to [`Expression`].
853///
854/// This trait is implemented for `Expression` and provides a fluent API for
855/// iterating, searching, measuring, and transforming expression trees without
856/// needing to import the iterator types directly.
857pub trait ExpressionWalk {
858    /// Returns a depth-first (pre-order) iterator over this expression and all descendants.
859    ///
860    /// The root node is yielded first, then its children are visited recursively
861    /// from left to right.
862    fn dfs(&self) -> DfsIter<'_>;
863
864    /// Returns a breadth-first (level-order) iterator over this expression and all descendants.
865    ///
866    /// All nodes at depth N are yielded before any node at depth N+1.
867    fn bfs(&self) -> BfsIter<'_>;
868
869    /// Finds the first expression matching `predicate` in depth-first order.
870    ///
871    /// Returns `None` if no descendant (including this node) matches.
872    fn find<F>(&self, predicate: F) -> Option<&Expression>
873    where
874        F: Fn(&Expression) -> bool;
875
876    /// Collects all expressions matching `predicate` in depth-first order.
877    ///
878    /// Returns an empty vector if no descendants match.
879    fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
880    where
881        F: Fn(&Expression) -> bool;
882
883    /// Returns `true` if this node or any descendant matches `predicate`.
884    fn contains<F>(&self, predicate: F) -> bool
885    where
886        F: Fn(&Expression) -> bool;
887
888    /// Counts how many nodes (including this one) match `predicate`.
889    fn count<F>(&self, predicate: F) -> usize
890    where
891        F: Fn(&Expression) -> bool;
892
893    /// Returns direct child expressions of this node.
894    ///
895    /// Collects all single-child fields and list-child fields into a flat vector
896    /// of references. Leaf nodes return an empty vector.
897    fn children(&self) -> Vec<&Expression>;
898
899    /// Returns the maximum depth of the expression tree rooted at this node.
900    ///
901    /// A leaf node has depth 0, a node whose deepest child is a leaf has depth 1, etc.
902    fn tree_depth(&self) -> usize;
903
904    /// Transforms this expression tree bottom-up using the given function (owned variant).
905    ///
906    /// Children are transformed first, then `fun` is called on the resulting node.
907    /// Return `Ok(None)` from `fun` to replace a node with `NULL`.
908    /// Return `Ok(Some(expr))` to substitute the node with `expr`.
909    fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
910    where
911        F: Fn(Expression) -> crate::Result<Option<Expression>>,
912        Self: Sized;
913}
914
915impl ExpressionWalk for Expression {
916    fn dfs(&self) -> DfsIter<'_> {
917        DfsIter::new(self)
918    }
919
920    fn bfs(&self) -> BfsIter<'_> {
921        BfsIter::new(self)
922    }
923
924    fn find<F>(&self, predicate: F) -> Option<&Expression>
925    where
926        F: Fn(&Expression) -> bool,
927    {
928        self.dfs().find(|e| predicate(e))
929    }
930
931    fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
932    where
933        F: Fn(&Expression) -> bool,
934    {
935        self.dfs().filter(|e| predicate(e)).collect()
936    }
937
938    fn contains<F>(&self, predicate: F) -> bool
939    where
940        F: Fn(&Expression) -> bool,
941    {
942        self.dfs().any(|e| predicate(e))
943    }
944
945    fn count<F>(&self, predicate: F) -> usize
946    where
947        F: Fn(&Expression) -> bool,
948    {
949        self.dfs().filter(|e| predicate(e)).count()
950    }
951
952    fn children(&self) -> Vec<&Expression> {
953        let mut result: Vec<&Expression> = Vec::new();
954        for (_, child) in iter_children(self) {
955            result.push(child);
956        }
957        for (_, children_list) in iter_children_lists(self) {
958            for child in children_list {
959                result.push(child);
960            }
961        }
962        result
963    }
964
965    fn tree_depth(&self) -> usize {
966        let mut max_depth = 0;
967
968        for (_, child) in iter_children(self) {
969            let child_depth = child.tree_depth();
970            if child_depth + 1 > max_depth {
971                max_depth = child_depth + 1;
972            }
973        }
974
975        for (_, children) in iter_children_lists(self) {
976            for child in children {
977                let child_depth = child.tree_depth();
978                if child_depth + 1 > max_depth {
979                    max_depth = child_depth + 1;
980                }
981            }
982        }
983
984        max_depth
985    }
986
987    fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
988    where
989        F: Fn(Expression) -> crate::Result<Option<Expression>>,
990    {
991        transform(self, &fun)
992    }
993}
994
995/// Transforms an expression tree bottom-up, with optional node removal.
996///
997/// Recursively transforms all children first, then applies `fun` to the resulting node.
998/// If `fun` returns `Ok(None)`, the node is replaced with an `Expression::Null`.
999/// If `fun` returns `Ok(Some(expr))`, the node is replaced with `expr`.
1000///
1001/// This is the primary transformation entry point when callers need the ability to
1002/// "delete" nodes by returning `None`.
1003///
1004/// # Example
1005///
1006/// ```rust,ignore
1007/// use polyglot_sql::traversal::transform;
1008///
1009/// // Remove all Paren wrapper nodes from a tree
1010/// let result = transform(expr, &|e| match e {
1011///     Expression::Paren(p) => Ok(Some(p.this)),
1012///     other => Ok(Some(other)),
1013/// })?;
1014/// ```
1015pub fn transform<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
1016where
1017    F: Fn(Expression) -> crate::Result<Option<Expression>>,
1018{
1019    crate::dialects::transform_recursive(expr, &|e| match fun(e)? {
1020        Some(transformed) => Ok(transformed),
1021        None => Ok(Expression::Null(crate::expressions::Null)),
1022    })
1023}
1024
1025/// Transforms an expression tree bottom-up without node removal.
1026///
1027/// Like [`transform`], but `fun` returns an `Expression` directly rather than
1028/// `Option<Expression>`, so nodes cannot be deleted. This is a convenience wrapper
1029/// for the common case where every node is mapped to exactly one output node.
1030///
1031/// # Example
1032///
1033/// ```rust,ignore
1034/// use polyglot_sql::traversal::transform_map;
1035///
1036/// // Uppercase all column names in a tree
1037/// let result = transform_map(expr, &|e| match e {
1038///     Expression::Column(mut c) => {
1039///         c.name.name = c.name.name.to_uppercase();
1040///         Ok(Expression::Column(c))
1041///     }
1042///     other => Ok(other),
1043/// })?;
1044/// ```
1045pub fn transform_map<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
1046where
1047    F: Fn(Expression) -> crate::Result<Expression>,
1048{
1049    crate::dialects::transform_recursive(expr, fun)
1050}
1051
1052// ---------------------------------------------------------------------------
1053// Common expression predicates
1054// ---------------------------------------------------------------------------
1055// These free functions are intended for use with the search methods on
1056// `ExpressionWalk` (e.g., `expr.find(is_column)`, `expr.contains(is_aggregate)`).
1057
1058/// Returns `true` if `expr` is a column reference ([`Expression::Column`]).
1059pub fn is_column(expr: &Expression) -> bool {
1060    matches!(expr, Expression::Column(_))
1061}
1062
1063/// Returns `true` if `expr` is a literal value (number, string, boolean, or NULL).
1064pub fn is_literal(expr: &Expression) -> bool {
1065    matches!(
1066        expr,
1067        Expression::Literal(_) | Expression::Boolean(_) | Expression::Null(_)
1068    )
1069}
1070
1071/// Returns `true` if `expr` is a function call (regular or aggregate).
1072pub fn is_function(expr: &Expression) -> bool {
1073    matches!(
1074        expr,
1075        Expression::Function(_) | Expression::AggregateFunction(_)
1076    )
1077}
1078
1079/// Returns `true` if `expr` is a subquery ([`Expression::Subquery`]).
1080pub fn is_subquery(expr: &Expression) -> bool {
1081    matches!(expr, Expression::Subquery(_))
1082}
1083
1084/// Returns `true` if `expr` is a SELECT statement ([`Expression::Select`]).
1085pub fn is_select(expr: &Expression) -> bool {
1086    matches!(expr, Expression::Select(_))
1087}
1088
1089/// Returns `true` if `expr` is an aggregate function ([`Expression::AggregateFunction`]).
1090pub fn is_aggregate(expr: &Expression) -> bool {
1091    matches!(expr, Expression::AggregateFunction(_))
1092}
1093
1094/// Returns `true` if `expr` is a window function ([`Expression::WindowFunction`]).
1095pub fn is_window_function(expr: &Expression) -> bool {
1096    matches!(expr, Expression::WindowFunction(_))
1097}
1098
1099/// Collects all column references ([`Expression::Column`]) from the expression tree.
1100///
1101/// Performs a depth-first search and returns references to every column node found.
1102pub fn get_columns(expr: &Expression) -> Vec<&Expression> {
1103    expr.find_all(is_column)
1104}
1105
1106/// Collects all table references ([`Expression::Table`]) from the expression tree.
1107///
1108/// Performs a depth-first search and returns references to every table node found.
1109///
1110/// Note: DML target tables (`Insert.table`, `Update.table`, `Delete.table`) are
1111/// stored as `TableRef` struct fields, not as `Expression::Table` nodes, so they
1112/// are not reachable via tree traversal. Use [`get_all_tables`] to include those.
1113pub fn get_tables(expr: &Expression) -> Vec<&Expression> {
1114    expr.find_all(|e| matches!(e, Expression::Table(_)))
1115}
1116
1117/// Collects **all** referenced tables from the expression tree, including DML
1118/// target tables that are stored as `TableRef` struct fields and are therefore
1119/// not reachable through normal tree traversal.
1120///
1121/// Returns owned `Expression::Table` values. This is the comprehensive version
1122/// of [`get_tables`] — use it when you need to discover every table referenced
1123/// in a statement, including inside CTE bodies containing INSERT/UPDATE/DELETE.
1124pub fn get_all_tables(expr: &Expression) -> Vec<Expression> {
1125    use std::collections::HashSet;
1126
1127    let mut seen = HashSet::new();
1128    let mut result = Vec::new();
1129
1130    // First: collect all Expression::Table nodes found via DFS.
1131    for node in expr.dfs() {
1132        if let Expression::Table(t) = node {
1133            let qname = table_ref_qualified_name(t);
1134            if seen.insert(qname) {
1135                result.push(node.clone());
1136            }
1137        }
1138
1139        // Also extract DML target TableRef fields not reachable via iter_children.
1140        let refs: Vec<&TableRef> = match node {
1141            Expression::Insert(ins) => vec![&ins.table],
1142            Expression::Update(upd) => {
1143                let mut v = vec![&upd.table];
1144                v.extend(upd.extra_tables.iter());
1145                v
1146            }
1147            Expression::Delete(del) => {
1148                let mut v = vec![&del.table];
1149                v.extend(del.using.iter());
1150                v
1151            }
1152            _ => continue,
1153        };
1154        for tref in refs {
1155            if tref.name.name.is_empty() {
1156                continue;
1157            }
1158            let qname = table_ref_qualified_name(tref);
1159            if seen.insert(qname) {
1160                result.push(Expression::Table(Box::new(tref.clone())));
1161            }
1162        }
1163    }
1164
1165    result
1166}
1167
1168/// Build a qualified name string from a TableRef for deduplication purposes.
1169fn table_ref_qualified_name(t: &TableRef) -> String {
1170    let mut name = String::new();
1171    if let Some(ref cat) = t.catalog {
1172        name.push_str(&cat.name);
1173        name.push('.');
1174    }
1175    if let Some(ref schema) = t.schema {
1176        name.push_str(&schema.name);
1177        name.push('.');
1178    }
1179    name.push_str(&t.name.name);
1180    name
1181}
1182
1183/// Extracts the underlying [`Expression::Table`] from a MERGE field that may
1184/// be a bare `Table`, an `Alias` wrapping a `Table`, or an `Identifier`.
1185/// Returns `None` if the expression doesn't contain a recognisable table.
1186fn unwrap_merge_table(expr: &Expression) -> Option<&Expression> {
1187    match expr {
1188        Expression::Table(_) => Some(expr),
1189        Expression::Alias(alias) => match &alias.this {
1190            Expression::Table(_) => Some(&alias.this),
1191            _ => None,
1192        },
1193        _ => None,
1194    }
1195}
1196
1197/// Returns the target table of a MERGE statement (the `Merge.this` field),
1198/// unwrapping any alias wrapper to yield the underlying [`Expression::Table`].
1199///
1200/// Returns `None` if `expr` is not a `Merge` or the target isn't a recognisable table.
1201pub fn get_merge_target(expr: &Expression) -> Option<&Expression> {
1202    match expr {
1203        Expression::Merge(m) => unwrap_merge_table(&m.this),
1204        _ => None,
1205    }
1206}
1207
1208/// Returns the source table of a MERGE statement (the `Merge.using` field),
1209/// unwrapping any alias wrapper to yield the underlying [`Expression::Table`].
1210///
1211/// Returns `None` if `expr` is not a `Merge`, the source isn't a recognisable
1212/// table (e.g. it's a subquery), or the source is otherwise unresolvable.
1213pub fn get_merge_source(expr: &Expression) -> Option<&Expression> {
1214    match expr {
1215        Expression::Merge(m) => unwrap_merge_table(&m.using),
1216        _ => None,
1217    }
1218}
1219
1220/// Returns `true` if the expression tree contains any aggregate function calls.
1221pub fn contains_aggregate(expr: &Expression) -> bool {
1222    expr.contains(is_aggregate)
1223}
1224
1225/// Returns `true` if the expression tree contains any window function calls.
1226pub fn contains_window_function(expr: &Expression) -> bool {
1227    expr.contains(is_window_function)
1228}
1229
1230/// Returns `true` if the expression tree contains any subquery nodes.
1231pub fn contains_subquery(expr: &Expression) -> bool {
1232    expr.contains(is_subquery)
1233}
1234
1235// ---------------------------------------------------------------------------
1236// Extended type predicates
1237// ---------------------------------------------------------------------------
1238
1239/// Macro for generating simple type-predicate functions.
1240macro_rules! is_type {
1241    ($name:ident, $($variant:pat),+ $(,)?) => {
1242        /// Returns `true` if `expr` matches the expected AST variant(s).
1243        pub fn $name(expr: &Expression) -> bool {
1244            matches!(expr, $($variant)|+)
1245        }
1246    };
1247}
1248
1249// Query
1250is_type!(is_insert, Expression::Insert(_));
1251is_type!(is_update, Expression::Update(_));
1252is_type!(is_delete, Expression::Delete(_));
1253is_type!(is_merge, Expression::Merge(_));
1254is_type!(is_union, Expression::Union(_));
1255is_type!(is_intersect, Expression::Intersect(_));
1256is_type!(is_except, Expression::Except(_));
1257
1258// Identifiers & literals
1259is_type!(is_boolean, Expression::Boolean(_));
1260is_type!(is_null_literal, Expression::Null(_));
1261is_type!(is_star, Expression::Star(_));
1262is_type!(is_identifier, Expression::Identifier(_));
1263is_type!(is_table, Expression::Table(_));
1264
1265// Comparison
1266is_type!(is_eq, Expression::Eq(_));
1267is_type!(is_neq, Expression::Neq(_));
1268is_type!(is_lt, Expression::Lt(_));
1269is_type!(is_lte, Expression::Lte(_));
1270is_type!(is_gt, Expression::Gt(_));
1271is_type!(is_gte, Expression::Gte(_));
1272is_type!(is_like, Expression::Like(_));
1273is_type!(is_ilike, Expression::ILike(_));
1274
1275// Arithmetic
1276is_type!(is_add, Expression::Add(_));
1277is_type!(is_sub, Expression::Sub(_));
1278is_type!(is_mul, Expression::Mul(_));
1279is_type!(is_div, Expression::Div(_));
1280is_type!(is_mod, Expression::Mod(_));
1281is_type!(is_concat, Expression::Concat(_));
1282
1283// Logical
1284is_type!(is_and, Expression::And(_));
1285is_type!(is_or, Expression::Or(_));
1286is_type!(is_not, Expression::Not(_));
1287
1288// Predicates
1289is_type!(is_in, Expression::In(_));
1290is_type!(is_between, Expression::Between(_));
1291is_type!(is_is_null, Expression::IsNull(_));
1292is_type!(is_exists, Expression::Exists(_));
1293
1294// Functions
1295is_type!(is_count, Expression::Count(_));
1296is_type!(is_sum, Expression::Sum(_));
1297is_type!(is_avg, Expression::Avg(_));
1298is_type!(is_min_func, Expression::Min(_));
1299is_type!(is_max_func, Expression::Max(_));
1300is_type!(is_coalesce, Expression::Coalesce(_));
1301is_type!(is_null_if, Expression::NullIf(_));
1302is_type!(is_cast, Expression::Cast(_));
1303is_type!(is_try_cast, Expression::TryCast(_));
1304is_type!(is_safe_cast, Expression::SafeCast(_));
1305is_type!(is_case, Expression::Case(_));
1306
1307// Clauses
1308is_type!(is_from, Expression::From(_));
1309is_type!(is_join, Expression::Join(_));
1310is_type!(is_where, Expression::Where(_));
1311is_type!(is_group_by, Expression::GroupBy(_));
1312is_type!(is_having, Expression::Having(_));
1313is_type!(is_order_by, Expression::OrderBy(_));
1314is_type!(is_limit, Expression::Limit(_));
1315is_type!(is_offset, Expression::Offset(_));
1316is_type!(is_with, Expression::With(_));
1317is_type!(is_cte, Expression::Cte(_));
1318is_type!(is_alias, Expression::Alias(_));
1319is_type!(is_paren, Expression::Paren(_));
1320is_type!(is_ordered, Expression::Ordered(_));
1321
1322// DDL
1323is_type!(is_create_table, Expression::CreateTable(_));
1324is_type!(is_drop_table, Expression::DropTable(_));
1325is_type!(is_alter_table, Expression::AlterTable(_));
1326is_type!(is_create_index, Expression::CreateIndex(_));
1327is_type!(is_drop_index, Expression::DropIndex(_));
1328is_type!(is_create_view, Expression::CreateView(_));
1329is_type!(is_drop_view, Expression::DropView(_));
1330
1331// ---------------------------------------------------------------------------
1332// Composite predicates
1333// ---------------------------------------------------------------------------
1334
1335/// Returns `true` if `expr` is a query statement (SELECT, INSERT, UPDATE, DELETE, or MERGE).
1336pub fn is_query(expr: &Expression) -> bool {
1337    matches!(
1338        expr,
1339        Expression::Select(_)
1340            | Expression::Insert(_)
1341            | Expression::Update(_)
1342            | Expression::Delete(_)
1343            | Expression::Merge(_)
1344    )
1345}
1346
1347/// Returns `true` if `expr` is a set operation (UNION, INTERSECT, or EXCEPT).
1348pub fn is_set_operation(expr: &Expression) -> bool {
1349    matches!(
1350        expr,
1351        Expression::Union(_) | Expression::Intersect(_) | Expression::Except(_)
1352    )
1353}
1354
1355/// Returns `true` if `expr` is a comparison operator.
1356pub fn is_comparison(expr: &Expression) -> bool {
1357    matches!(
1358        expr,
1359        Expression::Eq(_)
1360            | Expression::Neq(_)
1361            | Expression::Lt(_)
1362            | Expression::Lte(_)
1363            | Expression::Gt(_)
1364            | Expression::Gte(_)
1365            | Expression::Like(_)
1366            | Expression::ILike(_)
1367    )
1368}
1369
1370/// Returns `true` if `expr` is an arithmetic operator.
1371pub fn is_arithmetic(expr: &Expression) -> bool {
1372    matches!(
1373        expr,
1374        Expression::Add(_)
1375            | Expression::Sub(_)
1376            | Expression::Mul(_)
1377            | Expression::Div(_)
1378            | Expression::Mod(_)
1379    )
1380}
1381
1382/// Returns `true` if `expr` is a logical operator (AND, OR, NOT).
1383pub fn is_logical(expr: &Expression) -> bool {
1384    matches!(
1385        expr,
1386        Expression::And(_) | Expression::Or(_) | Expression::Not(_)
1387    )
1388}
1389
1390/// Returns `true` if `expr` is a DDL statement.
1391pub fn is_ddl(expr: &Expression) -> bool {
1392    matches!(
1393        expr,
1394        Expression::CreateTable(_)
1395            | Expression::DropTable(_)
1396            | Expression::Undrop(_)
1397            | Expression::AlterTable(_)
1398            | Expression::CreateIndex(_)
1399            | Expression::DropIndex(_)
1400            | Expression::CreateView(_)
1401            | Expression::DropView(_)
1402            | Expression::AlterView(_)
1403            | Expression::CreateSchema(_)
1404            | Expression::DropSchema(_)
1405            | Expression::CreateDatabase(_)
1406            | Expression::DropDatabase(_)
1407            | Expression::CreateFunction(_)
1408            | Expression::DropFunction(_)
1409            | Expression::CreateProcedure(_)
1410            | Expression::DropProcedure(_)
1411            | Expression::CreateSequence(_)
1412            | Expression::CreateSynonym(_)
1413            | Expression::DropSequence(_)
1414            | Expression::AlterSequence(_)
1415            | Expression::CreateTrigger(_)
1416            | Expression::DropTrigger(_)
1417            | Expression::CreateType(_)
1418            | Expression::DropType(_)
1419    )
1420}
1421
1422/// Find the parent of `target` within the tree rooted at `root`.
1423///
1424/// Uses pointer identity ([`std::ptr::eq`]) — `target` must be a reference
1425/// obtained from the same tree (e.g., via [`ExpressionWalk::find`] or DFS iteration).
1426///
1427/// Returns `None` if `target` is the root itself or is not found in the tree.
1428pub fn find_parent<'a>(root: &'a Expression, target: &Expression) -> Option<&'a Expression> {
1429    fn search<'a>(node: &'a Expression, target: *const Expression) -> Option<&'a Expression> {
1430        for (_, child) in iter_children(node) {
1431            if std::ptr::eq(child, target) {
1432                return Some(node);
1433            }
1434            if let Some(found) = search(child, target) {
1435                return Some(found);
1436            }
1437        }
1438        for (_, children_list) in iter_children_lists(node) {
1439            for child in children_list {
1440                if std::ptr::eq(child, target) {
1441                    return Some(node);
1442                }
1443                if let Some(found) = search(child, target) {
1444                    return Some(found);
1445                }
1446            }
1447        }
1448        None
1449    }
1450
1451    search(root, target as *const Expression)
1452}
1453
1454/// Find the first ancestor of `target` matching `predicate`, walking from
1455/// parent toward root.
1456///
1457/// Uses pointer identity for target lookup. Returns `None` if no ancestor
1458/// matches or `target` is not found in the tree.
1459pub fn find_ancestor<'a, F>(
1460    root: &'a Expression,
1461    target: &Expression,
1462    predicate: F,
1463) -> Option<&'a Expression>
1464where
1465    F: Fn(&Expression) -> bool,
1466{
1467    // Build path from root to target
1468    fn build_path<'a>(
1469        node: &'a Expression,
1470        target: *const Expression,
1471        path: &mut Vec<&'a Expression>,
1472    ) -> bool {
1473        if std::ptr::eq(node, target) {
1474            return true;
1475        }
1476        path.push(node);
1477        for (_, child) in iter_children(node) {
1478            if build_path(child, target, path) {
1479                return true;
1480            }
1481        }
1482        for (_, children_list) in iter_children_lists(node) {
1483            for child in children_list {
1484                if build_path(child, target, path) {
1485                    return true;
1486                }
1487            }
1488        }
1489        path.pop();
1490        false
1491    }
1492
1493    let mut path = Vec::new();
1494    if !build_path(root, target as *const Expression, &mut path) {
1495        return None;
1496    }
1497
1498    // Walk path in reverse (parent first, then grandparent, etc.)
1499    for ancestor in path.iter().rev() {
1500        if predicate(ancestor) {
1501            return Some(ancestor);
1502        }
1503    }
1504    None
1505}
1506
1507#[cfg(test)]
1508mod tests {
1509    use super::*;
1510    use crate::expressions::{BinaryOp, Column, Identifier, Literal};
1511
1512    fn make_column(name: &str) -> Expression {
1513        Expression::boxed_column(Column {
1514            name: Identifier {
1515                name: name.to_string(),
1516                quoted: false,
1517                trailing_comments: vec![],
1518                span: None,
1519            },
1520            table: None,
1521            join_mark: false,
1522            trailing_comments: vec![],
1523            span: None,
1524            inferred_type: None,
1525        })
1526    }
1527
1528    fn make_literal(value: i64) -> Expression {
1529        Expression::Literal(Box::new(Literal::Number(value.to_string())))
1530    }
1531
1532    #[test]
1533    fn test_dfs_simple() {
1534        let left = make_column("a");
1535        let right = make_literal(1);
1536        let expr = Expression::Eq(Box::new(BinaryOp {
1537            left,
1538            right,
1539            left_comments: vec![],
1540            operator_comments: vec![],
1541            trailing_comments: vec![],
1542            inferred_type: None,
1543        }));
1544
1545        let nodes: Vec<_> = expr.dfs().collect();
1546        assert_eq!(nodes.len(), 3); // Eq, Column, Literal
1547        assert!(matches!(nodes[0], Expression::Eq(_)));
1548        assert!(matches!(nodes[1], Expression::Column(_)));
1549        assert!(matches!(nodes[2], Expression::Literal(_)));
1550    }
1551
1552    #[test]
1553    fn test_find() {
1554        let left = make_column("a");
1555        let right = make_literal(1);
1556        let expr = Expression::Eq(Box::new(BinaryOp {
1557            left,
1558            right,
1559            left_comments: vec![],
1560            operator_comments: vec![],
1561            trailing_comments: vec![],
1562            inferred_type: None,
1563        }));
1564
1565        let column = expr.find(is_column);
1566        assert!(column.is_some());
1567        assert!(matches!(column.unwrap(), Expression::Column(_)));
1568
1569        let literal = expr.find(is_literal);
1570        assert!(literal.is_some());
1571        assert!(matches!(literal.unwrap(), Expression::Literal(_)));
1572    }
1573
1574    #[test]
1575    fn test_find_all() {
1576        let col1 = make_column("a");
1577        let col2 = make_column("b");
1578        let expr = Expression::And(Box::new(BinaryOp {
1579            left: col1,
1580            right: col2,
1581            left_comments: vec![],
1582            operator_comments: vec![],
1583            trailing_comments: vec![],
1584            inferred_type: None,
1585        }));
1586
1587        let columns = expr.find_all(is_column);
1588        assert_eq!(columns.len(), 2);
1589    }
1590
1591    #[test]
1592    fn test_contains() {
1593        let col = make_column("a");
1594        let lit = make_literal(1);
1595        let expr = Expression::Eq(Box::new(BinaryOp {
1596            left: col,
1597            right: lit,
1598            left_comments: vec![],
1599            operator_comments: vec![],
1600            trailing_comments: vec![],
1601            inferred_type: None,
1602        }));
1603
1604        assert!(expr.contains(is_column));
1605        assert!(expr.contains(is_literal));
1606        assert!(!expr.contains(is_subquery));
1607    }
1608
1609    #[test]
1610    fn test_count() {
1611        let col1 = make_column("a");
1612        let col2 = make_column("b");
1613        let lit = make_literal(1);
1614
1615        let inner = Expression::Add(Box::new(BinaryOp {
1616            left: col2,
1617            right: lit,
1618            left_comments: vec![],
1619            operator_comments: vec![],
1620            trailing_comments: vec![],
1621            inferred_type: None,
1622        }));
1623
1624        let expr = Expression::Eq(Box::new(BinaryOp {
1625            left: col1,
1626            right: inner,
1627            left_comments: vec![],
1628            operator_comments: vec![],
1629            trailing_comments: vec![],
1630            inferred_type: None,
1631        }));
1632
1633        assert_eq!(expr.count(is_column), 2);
1634        assert_eq!(expr.count(is_literal), 1);
1635    }
1636
1637    #[test]
1638    fn test_tree_depth() {
1639        // Single node
1640        let lit = make_literal(1);
1641        assert_eq!(lit.tree_depth(), 0);
1642
1643        // One level
1644        let col = make_column("a");
1645        let expr = Expression::Eq(Box::new(BinaryOp {
1646            left: col,
1647            right: lit.clone(),
1648            left_comments: vec![],
1649            operator_comments: vec![],
1650            trailing_comments: vec![],
1651            inferred_type: None,
1652        }));
1653        assert_eq!(expr.tree_depth(), 1);
1654
1655        // Two levels
1656        let inner = Expression::Add(Box::new(BinaryOp {
1657            left: make_column("b"),
1658            right: lit,
1659            left_comments: vec![],
1660            operator_comments: vec![],
1661            trailing_comments: vec![],
1662            inferred_type: None,
1663        }));
1664        let outer = Expression::Eq(Box::new(BinaryOp {
1665            left: make_column("a"),
1666            right: inner,
1667            left_comments: vec![],
1668            operator_comments: vec![],
1669            trailing_comments: vec![],
1670            inferred_type: None,
1671        }));
1672        assert_eq!(outer.tree_depth(), 2);
1673    }
1674
1675    #[test]
1676    fn test_tree_context() {
1677        let col = make_column("a");
1678        let lit = make_literal(1);
1679        let expr = Expression::Eq(Box::new(BinaryOp {
1680            left: col,
1681            right: lit,
1682            left_comments: vec![],
1683            operator_comments: vec![],
1684            trailing_comments: vec![],
1685            inferred_type: None,
1686        }));
1687
1688        let ctx = TreeContext::build(&expr);
1689
1690        // Root has no parent
1691        let root_info = ctx.get(0).unwrap();
1692        assert!(root_info.parent_id.is_none());
1693
1694        // Children have root as parent
1695        let left_info = ctx.get(1).unwrap();
1696        assert_eq!(left_info.parent_id, Some(0));
1697        assert_eq!(left_info.arg_key, "left");
1698
1699        let right_info = ctx.get(2).unwrap();
1700        assert_eq!(right_info.parent_id, Some(0));
1701        assert_eq!(right_info.arg_key, "right");
1702    }
1703
1704    // -- Step 8: transform / transform_map tests --
1705
1706    #[test]
1707    fn test_transform_rename_columns() {
1708        let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1709        let expr = ast[0].clone();
1710        let result = super::transform_map(expr, &|e| {
1711            if let Expression::Column(ref c) = e {
1712                if c.name.name == "a" {
1713                    return Ok(Expression::boxed_column(Column {
1714                        name: Identifier::new("alpha"),
1715                        table: c.table.clone(),
1716                        join_mark: false,
1717                        trailing_comments: vec![],
1718                        span: None,
1719                        inferred_type: None,
1720                    }));
1721                }
1722            }
1723            Ok(e)
1724        })
1725        .unwrap();
1726        let sql = crate::generator::Generator::sql(&result).unwrap();
1727        assert!(sql.contains("alpha"), "Expected 'alpha' in: {}", sql);
1728        assert!(sql.contains("b"), "Expected 'b' in: {}", sql);
1729    }
1730
1731    #[test]
1732    fn test_transform_noop() {
1733        let ast = crate::parser::Parser::parse_sql("SELECT 1 + 2").unwrap();
1734        let expr = ast[0].clone();
1735        let result = super::transform_map(expr.clone(), &|e| Ok(e)).unwrap();
1736        let sql1 = crate::generator::Generator::sql(&expr).unwrap();
1737        let sql2 = crate::generator::Generator::sql(&result).unwrap();
1738        assert_eq!(sql1, sql2);
1739    }
1740
1741    #[test]
1742    fn test_transform_nested() {
1743        let ast = crate::parser::Parser::parse_sql("SELECT a + b FROM t").unwrap();
1744        let expr = ast[0].clone();
1745        let result = super::transform_map(expr, &|e| {
1746            if let Expression::Column(ref c) = e {
1747                return Ok(Expression::Literal(Box::new(Literal::Number(
1748                    if c.name.name == "a" { "1" } else { "2" }.to_string(),
1749                ))));
1750            }
1751            Ok(e)
1752        })
1753        .unwrap();
1754        let sql = crate::generator::Generator::sql(&result).unwrap();
1755        assert_eq!(sql, "SELECT 1 + 2 FROM t");
1756    }
1757
1758    #[test]
1759    fn test_transform_error() {
1760        let ast = crate::parser::Parser::parse_sql("SELECT a FROM t").unwrap();
1761        let expr = ast[0].clone();
1762        let result = super::transform_map(expr, &|e| {
1763            if let Expression::Column(ref c) = e {
1764                if c.name.name == "a" {
1765                    return Err(crate::error::Error::parse("test error", 0, 0, 0, 0));
1766                }
1767            }
1768            Ok(e)
1769        });
1770        assert!(result.is_err());
1771    }
1772
1773    #[test]
1774    fn test_transform_owned_trait() {
1775        let ast = crate::parser::Parser::parse_sql("SELECT x FROM t").unwrap();
1776        let expr = ast[0].clone();
1777        let result = expr.transform_owned(|e| Ok(Some(e))).unwrap();
1778        let sql = crate::generator::Generator::sql(&result).unwrap();
1779        assert_eq!(sql, "SELECT x FROM t");
1780    }
1781
1782    // -- children() tests --
1783
1784    #[test]
1785    fn test_children_leaf() {
1786        let lit = make_literal(1);
1787        assert_eq!(lit.children().len(), 0);
1788    }
1789
1790    #[test]
1791    fn test_children_binary_op() {
1792        let left = make_column("a");
1793        let right = make_literal(1);
1794        let expr = Expression::Eq(Box::new(BinaryOp {
1795            left,
1796            right,
1797            left_comments: vec![],
1798            operator_comments: vec![],
1799            trailing_comments: vec![],
1800            inferred_type: None,
1801        }));
1802        let children = expr.children();
1803        assert_eq!(children.len(), 2);
1804        assert!(matches!(children[0], Expression::Column(_)));
1805        assert!(matches!(children[1], Expression::Literal(_)));
1806    }
1807
1808    #[test]
1809    fn test_children_select() {
1810        let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1811        let expr = &ast[0];
1812        let children = expr.children();
1813        // Should include select list items (a, b)
1814        assert!(children.len() >= 2);
1815    }
1816
1817    #[test]
1818    fn test_children_select_includes_from_and_join_sources() {
1819        let ast = crate::parser::Parser::parse_sql(
1820            "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id",
1821        )
1822        .unwrap();
1823        let expr = &ast[0];
1824        let children = expr.children();
1825
1826        let table_names: Vec<&str> = children
1827            .iter()
1828            .filter_map(|e| match e {
1829                Expression::Table(t) => Some(t.name.name.as_str()),
1830                _ => None,
1831            })
1832            .collect();
1833
1834        assert!(table_names.contains(&"users"));
1835        assert!(table_names.contains(&"orders"));
1836    }
1837
1838    #[test]
1839    fn test_get_tables_includes_insert_query_sources() {
1840        let ast = crate::parser::Parser::parse_sql(
1841            "INSERT INTO dst (id) SELECT s.id FROM src s JOIN dim d ON s.id = d.id",
1842        )
1843        .unwrap();
1844        let expr = &ast[0];
1845        let tables = get_tables(expr);
1846        let names: Vec<&str> = tables
1847            .iter()
1848            .filter_map(|e| match e {
1849                Expression::Table(t) => Some(t.name.name.as_str()),
1850                _ => None,
1851            })
1852            .collect();
1853
1854        assert!(names.contains(&"src"));
1855        assert!(names.contains(&"dim"));
1856    }
1857
1858    // -- find_parent() tests --
1859
1860    #[test]
1861    fn test_find_parent_binary() {
1862        let left = make_column("a");
1863        let right = make_literal(1);
1864        let expr = Expression::Eq(Box::new(BinaryOp {
1865            left,
1866            right,
1867            left_comments: vec![],
1868            operator_comments: vec![],
1869            trailing_comments: vec![],
1870            inferred_type: None,
1871        }));
1872
1873        // Find the column child and get its parent
1874        let col = expr.find(is_column).unwrap();
1875        let parent = super::find_parent(&expr, col);
1876        assert!(parent.is_some());
1877        assert!(matches!(parent.unwrap(), Expression::Eq(_)));
1878    }
1879
1880    #[test]
1881    fn test_find_parent_root_has_none() {
1882        let lit = make_literal(1);
1883        let parent = super::find_parent(&lit, &lit);
1884        assert!(parent.is_none());
1885    }
1886
1887    // -- find_ancestor() tests --
1888
1889    #[test]
1890    fn test_find_ancestor_select() {
1891        let ast = crate::parser::Parser::parse_sql("SELECT a FROM t WHERE a > 1").unwrap();
1892        let expr = &ast[0];
1893
1894        // Find a column inside the WHERE clause
1895        let where_col = expr.dfs().find(|e| {
1896            if let Expression::Column(c) = e {
1897                c.name.name == "a"
1898            } else {
1899                false
1900            }
1901        });
1902        assert!(where_col.is_some());
1903
1904        // Find Select ancestor of that column
1905        let ancestor = super::find_ancestor(expr, where_col.unwrap(), is_select);
1906        assert!(ancestor.is_some());
1907        assert!(matches!(ancestor.unwrap(), Expression::Select(_)));
1908    }
1909
1910    #[test]
1911    fn test_find_ancestor_no_match() {
1912        let left = make_column("a");
1913        let right = make_literal(1);
1914        let expr = Expression::Eq(Box::new(BinaryOp {
1915            left,
1916            right,
1917            left_comments: vec![],
1918            operator_comments: vec![],
1919            trailing_comments: vec![],
1920            inferred_type: None,
1921        }));
1922
1923        let col = expr.find(is_column).unwrap();
1924        let ancestor = super::find_ancestor(&expr, col, is_select);
1925        assert!(ancestor.is_none());
1926    }
1927
1928    #[test]
1929    fn test_ancestors() {
1930        let col = make_column("a");
1931        let lit = make_literal(1);
1932        let inner = Expression::Add(Box::new(BinaryOp {
1933            left: col,
1934            right: lit,
1935            left_comments: vec![],
1936            operator_comments: vec![],
1937            trailing_comments: vec![],
1938            inferred_type: None,
1939        }));
1940        let outer = Expression::Eq(Box::new(BinaryOp {
1941            left: make_column("b"),
1942            right: inner,
1943            left_comments: vec![],
1944            operator_comments: vec![],
1945            trailing_comments: vec![],
1946            inferred_type: None,
1947        }));
1948
1949        let ctx = TreeContext::build(&outer);
1950
1951        // The inner Add's left child (column "a") should have ancestors
1952        // Node 0: Eq
1953        // Node 1: Column "b" (left of Eq)
1954        // Node 2: Add (right of Eq)
1955        // Node 3: Column "a" (left of Add)
1956        // Node 4: Literal (right of Add)
1957
1958        let ancestors = ctx.ancestors_of(3);
1959        assert_eq!(ancestors, vec![2, 0]); // Add, then Eq
1960    }
1961
1962    #[test]
1963    fn test_get_merge_target_and_source() {
1964        let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1965
1966        // MERGE with aliased target and source tables
1967        let sql = "MERGE INTO orders o USING customers c ON o.customer_id = c.id WHEN MATCHED THEN UPDATE SET amount = amount + 100";
1968        let exprs = dialect.parse(sql).unwrap();
1969        let expr = &exprs[0];
1970
1971        assert!(is_merge(expr));
1972        assert!(is_query(expr));
1973
1974        let target = get_merge_target(expr).expect("should find target table");
1975        assert!(matches!(target, Expression::Table(_)));
1976        if let Expression::Table(t) = target {
1977            assert_eq!(t.name.name, "orders");
1978        }
1979
1980        let source = get_merge_source(expr).expect("should find source table");
1981        assert!(matches!(source, Expression::Table(_)));
1982        if let Expression::Table(t) = source {
1983            assert_eq!(t.name.name, "customers");
1984        }
1985    }
1986
1987    #[test]
1988    fn test_get_merge_source_subquery_returns_none() {
1989        let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1990
1991        // MERGE with subquery source — get_merge_source should return None
1992        let sql = "MERGE INTO orders o USING (SELECT * FROM customers) c ON o.customer_id = c.id WHEN MATCHED THEN DELETE";
1993        let exprs = dialect.parse(sql).unwrap();
1994        let expr = &exprs[0];
1995
1996        assert!(get_merge_target(expr).is_some());
1997        assert!(get_merge_source(expr).is_none());
1998    }
1999
2000    #[test]
2001    fn test_get_merge_on_non_merge_returns_none() {
2002        let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
2003        let exprs = dialect.parse("SELECT 1").unwrap();
2004        assert!(get_merge_target(&exprs[0]).is_none());
2005        assert!(get_merge_source(&exprs[0]).is_none());
2006    }
2007
2008    #[test]
2009    fn test_get_tables_finds_tables_inside_in_subquery() {
2010        let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
2011        let sql = "SELECT id, name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE amount > 1000)";
2012        let exprs = dialect.parse(sql).unwrap();
2013        let tables = get_tables(&exprs[0]);
2014        let names: Vec<&str> = tables
2015            .iter()
2016            .filter_map(|e| {
2017                if let Expression::Table(t) = e {
2018                    Some(t.name.name.as_str())
2019                } else {
2020                    None
2021                }
2022            })
2023            .collect();
2024        assert!(names.contains(&"customers"), "should find outer table");
2025        assert!(names.contains(&"orders"), "should find subquery table");
2026    }
2027
2028    #[test]
2029    fn test_get_tables_finds_tables_inside_exists_subquery() {
2030        let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
2031        let sql = "SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)";
2032        let exprs = dialect.parse(sql).unwrap();
2033        let tables = get_tables(&exprs[0]);
2034        let names: Vec<&str> = tables
2035            .iter()
2036            .filter_map(|e| {
2037                if let Expression::Table(t) = e {
2038                    Some(t.name.name.as_str())
2039                } else {
2040                    None
2041                }
2042            })
2043            .collect();
2044        assert!(names.contains(&"customers"), "should find outer table");
2045        assert!(
2046            names.contains(&"orders"),
2047            "should find EXISTS subquery table"
2048        );
2049    }
2050
2051    #[test]
2052    fn test_get_tables_finds_tables_in_correlated_subquery() {
2053        let dialect = crate::Dialect::get(crate::dialects::DialectType::TSQL);
2054        let sql = "SELECT id, name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE amount > 1000)";
2055        let exprs = dialect.parse(sql).unwrap();
2056        let tables = get_tables(&exprs[0]);
2057        let names: Vec<&str> = tables
2058            .iter()
2059            .filter_map(|e| {
2060                if let Expression::Table(t) = e {
2061                    Some(t.name.name.as_str())
2062                } else {
2063                    None
2064                }
2065            })
2066            .collect();
2067        assert!(
2068            names.contains(&"customers"),
2069            "TSQL: should find outer table"
2070        );
2071        assert!(
2072            names.contains(&"orders"),
2073            "TSQL: should find subquery table"
2074        );
2075    }
2076}