1use crate::expressions::Expression;
38use std::collections::{HashMap, VecDeque};
39
40pub type NodeId = usize;
42
43#[derive(Debug, Clone)]
45pub struct ParentInfo {
46 pub parent_id: Option<NodeId>,
48 pub arg_key: String,
50 pub index: Option<usize>,
52}
53
54#[derive(Debug, Default)]
68pub struct TreeContext {
69 nodes: HashMap<NodeId, ParentInfo>,
71 next_id: NodeId,
73 path: Vec<(NodeId, String, Option<usize>)>,
75}
76
77impl TreeContext {
78 pub fn new() -> Self {
80 Self::default()
81 }
82
83 pub fn build(root: &Expression) -> Self {
85 let mut ctx = Self::new();
86 ctx.visit_expr(root);
87 ctx
88 }
89
90 fn visit_expr(&mut self, expr: &Expression) -> NodeId {
92 let id = self.next_id;
93 self.next_id += 1;
94
95 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 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 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 pub fn get(&self, id: NodeId) -> Option<&ParentInfo> {
132 self.nodes.get(&id)
133 }
134
135 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(¤t) {
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 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(¤t) {
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
166fn 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::Ordered(o) => {
687 children.push(("this", &o.this));
688 }
689 Expression::Interval(i) => {
690 if let Some(ref this) = i.this {
691 children.push(("this", this));
692 }
693 }
694 _ => {}
695 }
696
697 children
698}
699
700fn iter_children_lists(expr: &Expression) -> Vec<(&'static str, &[Expression])> {
704 let mut lists = Vec::new();
705
706 match expr {
707 Expression::Select(s) => lists.push(("expressions", s.expressions.as_slice())),
708 Expression::Function(f) => {
709 lists.push(("args", f.args.as_slice()));
710 }
711 Expression::AggregateFunction(f) => {
712 lists.push(("args", f.args.as_slice()));
713 }
714 Expression::From(f) => {
715 lists.push(("expressions", f.expressions.as_slice()));
716 }
717 Expression::GroupBy(g) => {
718 lists.push(("expressions", g.expressions.as_slice()));
719 }
720 Expression::In(i) => {
723 lists.push(("expressions", i.expressions.as_slice()));
724 }
725 Expression::Array(a) => {
726 lists.push(("expressions", a.expressions.as_slice()));
727 }
728 Expression::Tuple(t) => {
729 lists.push(("expressions", t.expressions.as_slice()));
730 }
731 Expression::Coalesce(c) => {
733 lists.push(("expressions", c.expressions.as_slice()));
734 }
735 Expression::Greatest(g) | Expression::Least(g) => {
736 lists.push(("expressions", g.expressions.as_slice()));
737 }
738 _ => {}
739 }
740
741 lists
742}
743
744pub struct DfsIter<'a> {
753 stack: Vec<&'a Expression>,
754}
755
756impl<'a> DfsIter<'a> {
757 pub fn new(root: &'a Expression) -> Self {
759 Self { stack: vec![root] }
760 }
761}
762
763impl<'a> Iterator for DfsIter<'a> {
764 type Item = &'a Expression;
765
766 fn next(&mut self) -> Option<Self::Item> {
767 let expr = self.stack.pop()?;
768
769 let children: Vec<_> = iter_children(expr).into_iter().map(|(_, e)| e).collect();
771 for child in children.into_iter().rev() {
772 self.stack.push(child);
773 }
774
775 let lists: Vec<_> = iter_children_lists(expr)
776 .into_iter()
777 .flat_map(|(_, es)| es.iter())
778 .collect();
779 for child in lists.into_iter().rev() {
780 self.stack.push(child);
781 }
782
783 Some(expr)
784 }
785}
786
787pub struct BfsIter<'a> {
795 queue: VecDeque<&'a Expression>,
796}
797
798impl<'a> BfsIter<'a> {
799 pub fn new(root: &'a Expression) -> Self {
801 let mut queue = VecDeque::new();
802 queue.push_back(root);
803 Self { queue }
804 }
805}
806
807impl<'a> Iterator for BfsIter<'a> {
808 type Item = &'a Expression;
809
810 fn next(&mut self) -> Option<Self::Item> {
811 let expr = self.queue.pop_front()?;
812
813 for (_, child) in iter_children(expr) {
815 self.queue.push_back(child);
816 }
817
818 for (_, children) in iter_children_lists(expr) {
819 for child in children {
820 self.queue.push_back(child);
821 }
822 }
823
824 Some(expr)
825 }
826}
827
828pub trait ExpressionWalk {
834 fn dfs(&self) -> DfsIter<'_>;
839
840 fn bfs(&self) -> BfsIter<'_>;
844
845 fn find<F>(&self, predicate: F) -> Option<&Expression>
849 where
850 F: Fn(&Expression) -> bool;
851
852 fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
856 where
857 F: Fn(&Expression) -> bool;
858
859 fn contains<F>(&self, predicate: F) -> bool
861 where
862 F: Fn(&Expression) -> bool;
863
864 fn count<F>(&self, predicate: F) -> usize
866 where
867 F: Fn(&Expression) -> bool;
868
869 fn children(&self) -> Vec<&Expression>;
874
875 fn tree_depth(&self) -> usize;
879
880 fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
886 where
887 F: Fn(Expression) -> crate::Result<Option<Expression>>,
888 Self: Sized;
889}
890
891impl ExpressionWalk for Expression {
892 fn dfs(&self) -> DfsIter<'_> {
893 DfsIter::new(self)
894 }
895
896 fn bfs(&self) -> BfsIter<'_> {
897 BfsIter::new(self)
898 }
899
900 fn find<F>(&self, predicate: F) -> Option<&Expression>
901 where
902 F: Fn(&Expression) -> bool,
903 {
904 self.dfs().find(|e| predicate(e))
905 }
906
907 fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
908 where
909 F: Fn(&Expression) -> bool,
910 {
911 self.dfs().filter(|e| predicate(e)).collect()
912 }
913
914 fn contains<F>(&self, predicate: F) -> bool
915 where
916 F: Fn(&Expression) -> bool,
917 {
918 self.dfs().any(|e| predicate(e))
919 }
920
921 fn count<F>(&self, predicate: F) -> usize
922 where
923 F: Fn(&Expression) -> bool,
924 {
925 self.dfs().filter(|e| predicate(e)).count()
926 }
927
928 fn children(&self) -> Vec<&Expression> {
929 let mut result: Vec<&Expression> = Vec::new();
930 for (_, child) in iter_children(self) {
931 result.push(child);
932 }
933 for (_, children_list) in iter_children_lists(self) {
934 for child in children_list {
935 result.push(child);
936 }
937 }
938 result
939 }
940
941 fn tree_depth(&self) -> usize {
942 let mut max_depth = 0;
943
944 for (_, child) in iter_children(self) {
945 let child_depth = child.tree_depth();
946 if child_depth + 1 > max_depth {
947 max_depth = child_depth + 1;
948 }
949 }
950
951 for (_, children) in iter_children_lists(self) {
952 for child in children {
953 let child_depth = child.tree_depth();
954 if child_depth + 1 > max_depth {
955 max_depth = child_depth + 1;
956 }
957 }
958 }
959
960 max_depth
961 }
962
963 fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
964 where
965 F: Fn(Expression) -> crate::Result<Option<Expression>>,
966 {
967 transform(self, &fun)
968 }
969}
970
971pub fn transform<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
992where
993 F: Fn(Expression) -> crate::Result<Option<Expression>>,
994{
995 crate::dialects::transform_recursive(expr, &|e| match fun(e)? {
996 Some(transformed) => Ok(transformed),
997 None => Ok(Expression::Null(crate::expressions::Null)),
998 })
999}
1000
1001pub fn transform_map<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
1022where
1023 F: Fn(Expression) -> crate::Result<Expression>,
1024{
1025 crate::dialects::transform_recursive(expr, fun)
1026}
1027
1028pub fn is_column(expr: &Expression) -> bool {
1036 matches!(expr, Expression::Column(_))
1037}
1038
1039pub fn is_literal(expr: &Expression) -> bool {
1041 matches!(
1042 expr,
1043 Expression::Literal(_) | Expression::Boolean(_) | Expression::Null(_)
1044 )
1045}
1046
1047pub fn is_function(expr: &Expression) -> bool {
1049 matches!(
1050 expr,
1051 Expression::Function(_) | Expression::AggregateFunction(_)
1052 )
1053}
1054
1055pub fn is_subquery(expr: &Expression) -> bool {
1057 matches!(expr, Expression::Subquery(_))
1058}
1059
1060pub fn is_select(expr: &Expression) -> bool {
1062 matches!(expr, Expression::Select(_))
1063}
1064
1065pub fn is_aggregate(expr: &Expression) -> bool {
1067 matches!(expr, Expression::AggregateFunction(_))
1068}
1069
1070pub fn is_window_function(expr: &Expression) -> bool {
1072 matches!(expr, Expression::WindowFunction(_))
1073}
1074
1075pub fn get_columns(expr: &Expression) -> Vec<&Expression> {
1079 expr.find_all(is_column)
1080}
1081
1082pub fn get_tables(expr: &Expression) -> Vec<&Expression> {
1086 expr.find_all(|e| matches!(e, Expression::Table(_)))
1087}
1088
1089fn unwrap_merge_table(expr: &Expression) -> Option<&Expression> {
1093 match expr {
1094 Expression::Table(_) => Some(expr),
1095 Expression::Alias(alias) => match &alias.this {
1096 Expression::Table(_) => Some(&alias.this),
1097 _ => None,
1098 },
1099 _ => None,
1100 }
1101}
1102
1103pub fn get_merge_target(expr: &Expression) -> Option<&Expression> {
1108 match expr {
1109 Expression::Merge(m) => unwrap_merge_table(&m.this),
1110 _ => None,
1111 }
1112}
1113
1114pub fn get_merge_source(expr: &Expression) -> Option<&Expression> {
1120 match expr {
1121 Expression::Merge(m) => unwrap_merge_table(&m.using),
1122 _ => None,
1123 }
1124}
1125
1126pub fn contains_aggregate(expr: &Expression) -> bool {
1128 expr.contains(is_aggregate)
1129}
1130
1131pub fn contains_window_function(expr: &Expression) -> bool {
1133 expr.contains(is_window_function)
1134}
1135
1136pub fn contains_subquery(expr: &Expression) -> bool {
1138 expr.contains(is_subquery)
1139}
1140
1141macro_rules! is_type {
1147 ($name:ident, $($variant:pat),+ $(,)?) => {
1148 pub fn $name(expr: &Expression) -> bool {
1150 matches!(expr, $($variant)|+)
1151 }
1152 };
1153}
1154
1155is_type!(is_insert, Expression::Insert(_));
1157is_type!(is_update, Expression::Update(_));
1158is_type!(is_delete, Expression::Delete(_));
1159is_type!(is_merge, Expression::Merge(_));
1160is_type!(is_union, Expression::Union(_));
1161is_type!(is_intersect, Expression::Intersect(_));
1162is_type!(is_except, Expression::Except(_));
1163
1164is_type!(is_boolean, Expression::Boolean(_));
1166is_type!(is_null_literal, Expression::Null(_));
1167is_type!(is_star, Expression::Star(_));
1168is_type!(is_identifier, Expression::Identifier(_));
1169is_type!(is_table, Expression::Table(_));
1170
1171is_type!(is_eq, Expression::Eq(_));
1173is_type!(is_neq, Expression::Neq(_));
1174is_type!(is_lt, Expression::Lt(_));
1175is_type!(is_lte, Expression::Lte(_));
1176is_type!(is_gt, Expression::Gt(_));
1177is_type!(is_gte, Expression::Gte(_));
1178is_type!(is_like, Expression::Like(_));
1179is_type!(is_ilike, Expression::ILike(_));
1180
1181is_type!(is_add, Expression::Add(_));
1183is_type!(is_sub, Expression::Sub(_));
1184is_type!(is_mul, Expression::Mul(_));
1185is_type!(is_div, Expression::Div(_));
1186is_type!(is_mod, Expression::Mod(_));
1187is_type!(is_concat, Expression::Concat(_));
1188
1189is_type!(is_and, Expression::And(_));
1191is_type!(is_or, Expression::Or(_));
1192is_type!(is_not, Expression::Not(_));
1193
1194is_type!(is_in, Expression::In(_));
1196is_type!(is_between, Expression::Between(_));
1197is_type!(is_is_null, Expression::IsNull(_));
1198is_type!(is_exists, Expression::Exists(_));
1199
1200is_type!(is_count, Expression::Count(_));
1202is_type!(is_sum, Expression::Sum(_));
1203is_type!(is_avg, Expression::Avg(_));
1204is_type!(is_min_func, Expression::Min(_));
1205is_type!(is_max_func, Expression::Max(_));
1206is_type!(is_coalesce, Expression::Coalesce(_));
1207is_type!(is_null_if, Expression::NullIf(_));
1208is_type!(is_cast, Expression::Cast(_));
1209is_type!(is_try_cast, Expression::TryCast(_));
1210is_type!(is_safe_cast, Expression::SafeCast(_));
1211is_type!(is_case, Expression::Case(_));
1212
1213is_type!(is_from, Expression::From(_));
1215is_type!(is_join, Expression::Join(_));
1216is_type!(is_where, Expression::Where(_));
1217is_type!(is_group_by, Expression::GroupBy(_));
1218is_type!(is_having, Expression::Having(_));
1219is_type!(is_order_by, Expression::OrderBy(_));
1220is_type!(is_limit, Expression::Limit(_));
1221is_type!(is_offset, Expression::Offset(_));
1222is_type!(is_with, Expression::With(_));
1223is_type!(is_cte, Expression::Cte(_));
1224is_type!(is_alias, Expression::Alias(_));
1225is_type!(is_paren, Expression::Paren(_));
1226is_type!(is_ordered, Expression::Ordered(_));
1227
1228is_type!(is_create_table, Expression::CreateTable(_));
1230is_type!(is_drop_table, Expression::DropTable(_));
1231is_type!(is_alter_table, Expression::AlterTable(_));
1232is_type!(is_create_index, Expression::CreateIndex(_));
1233is_type!(is_drop_index, Expression::DropIndex(_));
1234is_type!(is_create_view, Expression::CreateView(_));
1235is_type!(is_drop_view, Expression::DropView(_));
1236
1237pub fn is_query(expr: &Expression) -> bool {
1243 matches!(
1244 expr,
1245 Expression::Select(_)
1246 | Expression::Insert(_)
1247 | Expression::Update(_)
1248 | Expression::Delete(_)
1249 | Expression::Merge(_)
1250 )
1251}
1252
1253pub fn is_set_operation(expr: &Expression) -> bool {
1255 matches!(
1256 expr,
1257 Expression::Union(_) | Expression::Intersect(_) | Expression::Except(_)
1258 )
1259}
1260
1261pub fn is_comparison(expr: &Expression) -> bool {
1263 matches!(
1264 expr,
1265 Expression::Eq(_)
1266 | Expression::Neq(_)
1267 | Expression::Lt(_)
1268 | Expression::Lte(_)
1269 | Expression::Gt(_)
1270 | Expression::Gte(_)
1271 | Expression::Like(_)
1272 | Expression::ILike(_)
1273 )
1274}
1275
1276pub fn is_arithmetic(expr: &Expression) -> bool {
1278 matches!(
1279 expr,
1280 Expression::Add(_)
1281 | Expression::Sub(_)
1282 | Expression::Mul(_)
1283 | Expression::Div(_)
1284 | Expression::Mod(_)
1285 )
1286}
1287
1288pub fn is_logical(expr: &Expression) -> bool {
1290 matches!(
1291 expr,
1292 Expression::And(_) | Expression::Or(_) | Expression::Not(_)
1293 )
1294}
1295
1296pub fn is_ddl(expr: &Expression) -> bool {
1298 matches!(
1299 expr,
1300 Expression::CreateTable(_)
1301 | Expression::DropTable(_)
1302 | Expression::AlterTable(_)
1303 | Expression::CreateIndex(_)
1304 | Expression::DropIndex(_)
1305 | Expression::CreateView(_)
1306 | Expression::DropView(_)
1307 | Expression::AlterView(_)
1308 | Expression::CreateSchema(_)
1309 | Expression::DropSchema(_)
1310 | Expression::CreateDatabase(_)
1311 | Expression::DropDatabase(_)
1312 | Expression::CreateFunction(_)
1313 | Expression::DropFunction(_)
1314 | Expression::CreateProcedure(_)
1315 | Expression::DropProcedure(_)
1316 | Expression::CreateSequence(_)
1317 | Expression::DropSequence(_)
1318 | Expression::AlterSequence(_)
1319 | Expression::CreateTrigger(_)
1320 | Expression::DropTrigger(_)
1321 | Expression::CreateType(_)
1322 | Expression::DropType(_)
1323 )
1324}
1325
1326pub fn find_parent<'a>(root: &'a Expression, target: &Expression) -> Option<&'a Expression> {
1333 fn search<'a>(node: &'a Expression, target: *const Expression) -> Option<&'a Expression> {
1334 for (_, child) in iter_children(node) {
1335 if std::ptr::eq(child, target) {
1336 return Some(node);
1337 }
1338 if let Some(found) = search(child, target) {
1339 return Some(found);
1340 }
1341 }
1342 for (_, children_list) in iter_children_lists(node) {
1343 for child in children_list {
1344 if std::ptr::eq(child, target) {
1345 return Some(node);
1346 }
1347 if let Some(found) = search(child, target) {
1348 return Some(found);
1349 }
1350 }
1351 }
1352 None
1353 }
1354
1355 search(root, target as *const Expression)
1356}
1357
1358pub fn find_ancestor<'a, F>(
1364 root: &'a Expression,
1365 target: &Expression,
1366 predicate: F,
1367) -> Option<&'a Expression>
1368where
1369 F: Fn(&Expression) -> bool,
1370{
1371 fn build_path<'a>(
1373 node: &'a Expression,
1374 target: *const Expression,
1375 path: &mut Vec<&'a Expression>,
1376 ) -> bool {
1377 if std::ptr::eq(node, target) {
1378 return true;
1379 }
1380 path.push(node);
1381 for (_, child) in iter_children(node) {
1382 if build_path(child, target, path) {
1383 return true;
1384 }
1385 }
1386 for (_, children_list) in iter_children_lists(node) {
1387 for child in children_list {
1388 if build_path(child, target, path) {
1389 return true;
1390 }
1391 }
1392 }
1393 path.pop();
1394 false
1395 }
1396
1397 let mut path = Vec::new();
1398 if !build_path(root, target as *const Expression, &mut path) {
1399 return None;
1400 }
1401
1402 for ancestor in path.iter().rev() {
1404 if predicate(ancestor) {
1405 return Some(ancestor);
1406 }
1407 }
1408 None
1409}
1410
1411#[cfg(test)]
1412mod tests {
1413 use super::*;
1414 use crate::expressions::{BinaryOp, Column, Identifier, Literal};
1415
1416 fn make_column(name: &str) -> Expression {
1417 Expression::Column(Column {
1418 name: Identifier {
1419 name: name.to_string(),
1420 quoted: false,
1421 trailing_comments: vec![],
1422 span: None,
1423 },
1424 table: None,
1425 join_mark: false,
1426 trailing_comments: vec![],
1427 span: None,
1428 inferred_type: None,
1429 })
1430 }
1431
1432 fn make_literal(value: i64) -> Expression {
1433 Expression::Literal(Literal::Number(value.to_string()))
1434 }
1435
1436 #[test]
1437 fn test_dfs_simple() {
1438 let left = make_column("a");
1439 let right = make_literal(1);
1440 let expr = Expression::Eq(Box::new(BinaryOp {
1441 left,
1442 right,
1443 left_comments: vec![],
1444 operator_comments: vec![],
1445 trailing_comments: vec![],
1446 inferred_type: None,
1447 }));
1448
1449 let nodes: Vec<_> = expr.dfs().collect();
1450 assert_eq!(nodes.len(), 3); assert!(matches!(nodes[0], Expression::Eq(_)));
1452 assert!(matches!(nodes[1], Expression::Column(_)));
1453 assert!(matches!(nodes[2], Expression::Literal(_)));
1454 }
1455
1456 #[test]
1457 fn test_find() {
1458 let left = make_column("a");
1459 let right = make_literal(1);
1460 let expr = Expression::Eq(Box::new(BinaryOp {
1461 left,
1462 right,
1463 left_comments: vec![],
1464 operator_comments: vec![],
1465 trailing_comments: vec![],
1466 inferred_type: None,
1467 }));
1468
1469 let column = expr.find(is_column);
1470 assert!(column.is_some());
1471 assert!(matches!(column.unwrap(), Expression::Column(_)));
1472
1473 let literal = expr.find(is_literal);
1474 assert!(literal.is_some());
1475 assert!(matches!(literal.unwrap(), Expression::Literal(_)));
1476 }
1477
1478 #[test]
1479 fn test_find_all() {
1480 let col1 = make_column("a");
1481 let col2 = make_column("b");
1482 let expr = Expression::And(Box::new(BinaryOp {
1483 left: col1,
1484 right: col2,
1485 left_comments: vec![],
1486 operator_comments: vec![],
1487 trailing_comments: vec![],
1488 inferred_type: None,
1489 }));
1490
1491 let columns = expr.find_all(is_column);
1492 assert_eq!(columns.len(), 2);
1493 }
1494
1495 #[test]
1496 fn test_contains() {
1497 let col = make_column("a");
1498 let lit = make_literal(1);
1499 let expr = Expression::Eq(Box::new(BinaryOp {
1500 left: col,
1501 right: lit,
1502 left_comments: vec![],
1503 operator_comments: vec![],
1504 trailing_comments: vec![],
1505 inferred_type: None,
1506 }));
1507
1508 assert!(expr.contains(is_column));
1509 assert!(expr.contains(is_literal));
1510 assert!(!expr.contains(is_subquery));
1511 }
1512
1513 #[test]
1514 fn test_count() {
1515 let col1 = make_column("a");
1516 let col2 = make_column("b");
1517 let lit = make_literal(1);
1518
1519 let inner = Expression::Add(Box::new(BinaryOp {
1520 left: col2,
1521 right: lit,
1522 left_comments: vec![],
1523 operator_comments: vec![],
1524 trailing_comments: vec![],
1525 inferred_type: None,
1526 }));
1527
1528 let expr = Expression::Eq(Box::new(BinaryOp {
1529 left: col1,
1530 right: inner,
1531 left_comments: vec![],
1532 operator_comments: vec![],
1533 trailing_comments: vec![],
1534 inferred_type: None,
1535 }));
1536
1537 assert_eq!(expr.count(is_column), 2);
1538 assert_eq!(expr.count(is_literal), 1);
1539 }
1540
1541 #[test]
1542 fn test_tree_depth() {
1543 let lit = make_literal(1);
1545 assert_eq!(lit.tree_depth(), 0);
1546
1547 let col = make_column("a");
1549 let expr = Expression::Eq(Box::new(BinaryOp {
1550 left: col,
1551 right: lit.clone(),
1552 left_comments: vec![],
1553 operator_comments: vec![],
1554 trailing_comments: vec![],
1555 inferred_type: None,
1556 }));
1557 assert_eq!(expr.tree_depth(), 1);
1558
1559 let inner = Expression::Add(Box::new(BinaryOp {
1561 left: make_column("b"),
1562 right: lit,
1563 left_comments: vec![],
1564 operator_comments: vec![],
1565 trailing_comments: vec![],
1566 inferred_type: None,
1567 }));
1568 let outer = Expression::Eq(Box::new(BinaryOp {
1569 left: make_column("a"),
1570 right: inner,
1571 left_comments: vec![],
1572 operator_comments: vec![],
1573 trailing_comments: vec![],
1574 inferred_type: None,
1575 }));
1576 assert_eq!(outer.tree_depth(), 2);
1577 }
1578
1579 #[test]
1580 fn test_tree_context() {
1581 let col = make_column("a");
1582 let lit = make_literal(1);
1583 let expr = Expression::Eq(Box::new(BinaryOp {
1584 left: col,
1585 right: lit,
1586 left_comments: vec![],
1587 operator_comments: vec![],
1588 trailing_comments: vec![],
1589 inferred_type: None,
1590 }));
1591
1592 let ctx = TreeContext::build(&expr);
1593
1594 let root_info = ctx.get(0).unwrap();
1596 assert!(root_info.parent_id.is_none());
1597
1598 let left_info = ctx.get(1).unwrap();
1600 assert_eq!(left_info.parent_id, Some(0));
1601 assert_eq!(left_info.arg_key, "left");
1602
1603 let right_info = ctx.get(2).unwrap();
1604 assert_eq!(right_info.parent_id, Some(0));
1605 assert_eq!(right_info.arg_key, "right");
1606 }
1607
1608 #[test]
1611 fn test_transform_rename_columns() {
1612 let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1613 let expr = ast[0].clone();
1614 let result = super::transform_map(expr, &|e| {
1615 if let Expression::Column(ref c) = e {
1616 if c.name.name == "a" {
1617 return Ok(Expression::Column(Column {
1618 name: Identifier::new("alpha"),
1619 table: c.table.clone(),
1620 join_mark: false,
1621 trailing_comments: vec![],
1622 span: None,
1623 inferred_type: None,
1624 }));
1625 }
1626 }
1627 Ok(e)
1628 })
1629 .unwrap();
1630 let sql = crate::generator::Generator::sql(&result).unwrap();
1631 assert!(sql.contains("alpha"), "Expected 'alpha' in: {}", sql);
1632 assert!(sql.contains("b"), "Expected 'b' in: {}", sql);
1633 }
1634
1635 #[test]
1636 fn test_transform_noop() {
1637 let ast = crate::parser::Parser::parse_sql("SELECT 1 + 2").unwrap();
1638 let expr = ast[0].clone();
1639 let result = super::transform_map(expr.clone(), &|e| Ok(e)).unwrap();
1640 let sql1 = crate::generator::Generator::sql(&expr).unwrap();
1641 let sql2 = crate::generator::Generator::sql(&result).unwrap();
1642 assert_eq!(sql1, sql2);
1643 }
1644
1645 #[test]
1646 fn test_transform_nested() {
1647 let ast = crate::parser::Parser::parse_sql("SELECT a + b FROM t").unwrap();
1648 let expr = ast[0].clone();
1649 let result = super::transform_map(expr, &|e| {
1650 if let Expression::Column(ref c) = e {
1651 return Ok(Expression::Literal(Literal::Number(
1652 if c.name.name == "a" { "1" } else { "2" }.to_string(),
1653 )));
1654 }
1655 Ok(e)
1656 })
1657 .unwrap();
1658 let sql = crate::generator::Generator::sql(&result).unwrap();
1659 assert_eq!(sql, "SELECT 1 + 2 FROM t");
1660 }
1661
1662 #[test]
1663 fn test_transform_error() {
1664 let ast = crate::parser::Parser::parse_sql("SELECT a FROM t").unwrap();
1665 let expr = ast[0].clone();
1666 let result = super::transform_map(expr, &|e| {
1667 if let Expression::Column(ref c) = e {
1668 if c.name.name == "a" {
1669 return Err(crate::error::Error::parse("test error", 0, 0, 0, 0));
1670 }
1671 }
1672 Ok(e)
1673 });
1674 assert!(result.is_err());
1675 }
1676
1677 #[test]
1678 fn test_transform_owned_trait() {
1679 let ast = crate::parser::Parser::parse_sql("SELECT x FROM t").unwrap();
1680 let expr = ast[0].clone();
1681 let result = expr.transform_owned(|e| Ok(Some(e))).unwrap();
1682 let sql = crate::generator::Generator::sql(&result).unwrap();
1683 assert_eq!(sql, "SELECT x FROM t");
1684 }
1685
1686 #[test]
1689 fn test_children_leaf() {
1690 let lit = make_literal(1);
1691 assert_eq!(lit.children().len(), 0);
1692 }
1693
1694 #[test]
1695 fn test_children_binary_op() {
1696 let left = make_column("a");
1697 let right = make_literal(1);
1698 let expr = Expression::Eq(Box::new(BinaryOp {
1699 left,
1700 right,
1701 left_comments: vec![],
1702 operator_comments: vec![],
1703 trailing_comments: vec![],
1704 inferred_type: None,
1705 }));
1706 let children = expr.children();
1707 assert_eq!(children.len(), 2);
1708 assert!(matches!(children[0], Expression::Column(_)));
1709 assert!(matches!(children[1], Expression::Literal(_)));
1710 }
1711
1712 #[test]
1713 fn test_children_select() {
1714 let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1715 let expr = &ast[0];
1716 let children = expr.children();
1717 assert!(children.len() >= 2);
1719 }
1720
1721 #[test]
1722 fn test_children_select_includes_from_and_join_sources() {
1723 let ast = crate::parser::Parser::parse_sql(
1724 "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id",
1725 )
1726 .unwrap();
1727 let expr = &ast[0];
1728 let children = expr.children();
1729
1730 let table_names: Vec<&str> = children
1731 .iter()
1732 .filter_map(|e| match e {
1733 Expression::Table(t) => Some(t.name.name.as_str()),
1734 _ => None,
1735 })
1736 .collect();
1737
1738 assert!(table_names.contains(&"users"));
1739 assert!(table_names.contains(&"orders"));
1740 }
1741
1742 #[test]
1743 fn test_get_tables_includes_insert_query_sources() {
1744 let ast = crate::parser::Parser::parse_sql(
1745 "INSERT INTO dst (id) SELECT s.id FROM src s JOIN dim d ON s.id = d.id",
1746 )
1747 .unwrap();
1748 let expr = &ast[0];
1749 let tables = get_tables(expr);
1750 let names: Vec<&str> = tables
1751 .iter()
1752 .filter_map(|e| match e {
1753 Expression::Table(t) => Some(t.name.name.as_str()),
1754 _ => None,
1755 })
1756 .collect();
1757
1758 assert!(names.contains(&"src"));
1759 assert!(names.contains(&"dim"));
1760 }
1761
1762 #[test]
1765 fn test_find_parent_binary() {
1766 let left = make_column("a");
1767 let right = make_literal(1);
1768 let expr = Expression::Eq(Box::new(BinaryOp {
1769 left,
1770 right,
1771 left_comments: vec![],
1772 operator_comments: vec![],
1773 trailing_comments: vec![],
1774 inferred_type: None,
1775 }));
1776
1777 let col = expr.find(is_column).unwrap();
1779 let parent = super::find_parent(&expr, col);
1780 assert!(parent.is_some());
1781 assert!(matches!(parent.unwrap(), Expression::Eq(_)));
1782 }
1783
1784 #[test]
1785 fn test_find_parent_root_has_none() {
1786 let lit = make_literal(1);
1787 let parent = super::find_parent(&lit, &lit);
1788 assert!(parent.is_none());
1789 }
1790
1791 #[test]
1794 fn test_find_ancestor_select() {
1795 let ast = crate::parser::Parser::parse_sql("SELECT a FROM t WHERE a > 1").unwrap();
1796 let expr = &ast[0];
1797
1798 let where_col = expr.dfs().find(|e| {
1800 if let Expression::Column(c) = e {
1801 c.name.name == "a"
1802 } else {
1803 false
1804 }
1805 });
1806 assert!(where_col.is_some());
1807
1808 let ancestor = super::find_ancestor(expr, where_col.unwrap(), is_select);
1810 assert!(ancestor.is_some());
1811 assert!(matches!(ancestor.unwrap(), Expression::Select(_)));
1812 }
1813
1814 #[test]
1815 fn test_find_ancestor_no_match() {
1816 let left = make_column("a");
1817 let right = make_literal(1);
1818 let expr = Expression::Eq(Box::new(BinaryOp {
1819 left,
1820 right,
1821 left_comments: vec![],
1822 operator_comments: vec![],
1823 trailing_comments: vec![],
1824 inferred_type: None,
1825 }));
1826
1827 let col = expr.find(is_column).unwrap();
1828 let ancestor = super::find_ancestor(&expr, col, is_select);
1829 assert!(ancestor.is_none());
1830 }
1831
1832 #[test]
1833 fn test_ancestors() {
1834 let col = make_column("a");
1835 let lit = make_literal(1);
1836 let inner = Expression::Add(Box::new(BinaryOp {
1837 left: col,
1838 right: lit,
1839 left_comments: vec![],
1840 operator_comments: vec![],
1841 trailing_comments: vec![],
1842 inferred_type: None,
1843 }));
1844 let outer = Expression::Eq(Box::new(BinaryOp {
1845 left: make_column("b"),
1846 right: inner,
1847 left_comments: vec![],
1848 operator_comments: vec![],
1849 trailing_comments: vec![],
1850 inferred_type: None,
1851 }));
1852
1853 let ctx = TreeContext::build(&outer);
1854
1855 let ancestors = ctx.ancestors_of(3);
1863 assert_eq!(ancestors, vec![2, 0]); }
1865
1866 #[test]
1867 fn test_get_merge_target_and_source() {
1868 let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1869
1870 let sql = "MERGE INTO orders o USING customers c ON o.customer_id = c.id WHEN MATCHED THEN UPDATE SET amount = amount + 100";
1872 let exprs = dialect.parse(sql).unwrap();
1873 let expr = &exprs[0];
1874
1875 assert!(is_merge(expr));
1876 assert!(is_query(expr));
1877
1878 let target = get_merge_target(expr).expect("should find target table");
1879 assert!(matches!(target, Expression::Table(_)));
1880 if let Expression::Table(t) = target {
1881 assert_eq!(t.name.name, "orders");
1882 }
1883
1884 let source = get_merge_source(expr).expect("should find source table");
1885 assert!(matches!(source, Expression::Table(_)));
1886 if let Expression::Table(t) = source {
1887 assert_eq!(t.name.name, "customers");
1888 }
1889 }
1890
1891 #[test]
1892 fn test_get_merge_source_subquery_returns_none() {
1893 let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1894
1895 let sql = "MERGE INTO orders o USING (SELECT * FROM customers) c ON o.customer_id = c.id WHEN MATCHED THEN DELETE";
1897 let exprs = dialect.parse(sql).unwrap();
1898 let expr = &exprs[0];
1899
1900 assert!(get_merge_target(expr).is_some());
1901 assert!(get_merge_source(expr).is_none());
1902 }
1903
1904 #[test]
1905 fn test_get_merge_on_non_merge_returns_none() {
1906 let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1907 let exprs = dialect.parse("SELECT 1").unwrap();
1908 assert!(get_merge_target(&exprs[0]).is_none());
1909 assert!(get_merge_source(&exprs[0]).is_none());
1910 }
1911
1912 #[test]
1913 fn test_get_tables_finds_tables_inside_in_subquery() {
1914 let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1915 let sql = "SELECT id, name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE amount > 1000)";
1916 let exprs = dialect.parse(sql).unwrap();
1917 let tables = get_tables(&exprs[0]);
1918 let names: Vec<&str> = tables
1919 .iter()
1920 .filter_map(|e| {
1921 if let Expression::Table(t) = e {
1922 Some(t.name.name.as_str())
1923 } else {
1924 None
1925 }
1926 })
1927 .collect();
1928 assert!(names.contains(&"customers"), "should find outer table");
1929 assert!(names.contains(&"orders"), "should find subquery table");
1930 }
1931
1932 #[test]
1933 fn test_get_tables_finds_tables_inside_exists_subquery() {
1934 let dialect = crate::Dialect::get(crate::dialects::DialectType::Generic);
1935 let sql = "SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)";
1936 let exprs = dialect.parse(sql).unwrap();
1937 let tables = get_tables(&exprs[0]);
1938 let names: Vec<&str> = tables
1939 .iter()
1940 .filter_map(|e| {
1941 if let Expression::Table(t) = e {
1942 Some(t.name.name.as_str())
1943 } else {
1944 None
1945 }
1946 })
1947 .collect();
1948 assert!(names.contains(&"customers"), "should find outer table");
1949 assert!(names.contains(&"orders"), "should find EXISTS subquery table");
1950 }
1951
1952 #[test]
1953 fn test_get_tables_finds_tables_in_correlated_subquery() {
1954 let dialect = crate::Dialect::get(crate::dialects::DialectType::TSQL);
1955 let sql = "SELECT id, name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE amount > 1000)";
1956 let exprs = dialect.parse(sql).unwrap();
1957 let tables = get_tables(&exprs[0]);
1958 let names: Vec<&str> = tables
1959 .iter()
1960 .filter_map(|e| {
1961 if let Expression::Table(t) = e {
1962 Some(t.name.name.as_str())
1963 } else {
1964 None
1965 }
1966 })
1967 .collect();
1968 assert!(names.contains(&"customers"), "TSQL: should find outer table");
1969 assert!(names.contains(&"orders"), "TSQL: should find subquery table");
1970 }
1971}