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::Alias(a) => {
174 children.push(("this", &a.this));
175 }
176 Expression::Cast(c) => {
177 children.push(("this", &c.this));
178 }
179 Expression::Not(u) | Expression::Neg(u) | Expression::BitwiseNot(u) => {
180 children.push(("this", &u.this));
181 }
182 Expression::Paren(p) => {
183 children.push(("this", &p.this));
184 }
185 Expression::IsNull(i) => {
186 children.push(("this", &i.this));
187 }
188 Expression::Exists(e) => {
189 children.push(("this", &e.this));
190 }
191 Expression::Subquery(s) => {
192 children.push(("this", &s.this));
193 }
194 Expression::Where(w) => {
195 children.push(("this", &w.this));
196 }
197 Expression::Having(h) => {
198 children.push(("this", &h.this));
199 }
200 Expression::Qualify(q) => {
201 children.push(("this", &q.this));
202 }
203 Expression::And(op)
204 | Expression::Or(op)
205 | Expression::Add(op)
206 | Expression::Sub(op)
207 | Expression::Mul(op)
208 | Expression::Div(op)
209 | Expression::Mod(op)
210 | Expression::Eq(op)
211 | Expression::Neq(op)
212 | Expression::Lt(op)
213 | Expression::Lte(op)
214 | Expression::Gt(op)
215 | Expression::Gte(op)
216 | Expression::BitwiseAnd(op)
217 | Expression::BitwiseOr(op)
218 | Expression::BitwiseXor(op)
219 | Expression::Concat(op) => {
220 children.push(("left", &op.left));
221 children.push(("right", &op.right));
222 }
223 Expression::Like(op) | Expression::ILike(op) => {
224 children.push(("left", &op.left));
225 children.push(("right", &op.right));
226 }
227 Expression::Between(b) => {
228 children.push(("this", &b.this));
229 children.push(("low", &b.low));
230 children.push(("high", &b.high));
231 }
232 Expression::In(i) => {
233 children.push(("this", &i.this));
234 }
235 Expression::Case(c) => {
236 if let Some(ref operand) = &c.operand {
237 children.push(("operand", operand));
238 }
239 }
240 Expression::WindowFunction(wf) => {
241 children.push(("this", &wf.this));
242 }
243 Expression::Union(u) => {
244 children.push(("left", &u.left));
245 children.push(("right", &u.right));
246 }
247 Expression::Intersect(i) => {
248 children.push(("left", &i.left));
249 children.push(("right", &i.right));
250 }
251 Expression::Except(e) => {
252 children.push(("left", &e.left));
253 children.push(("right", &e.right));
254 }
255 Expression::Ordered(o) => {
256 children.push(("this", &o.this));
257 }
258 Expression::Interval(i) => {
259 if let Some(ref this) = i.this {
260 children.push(("this", this));
261 }
262 }
263 _ => {}
264 }
265
266 children
267}
268
269fn iter_children_lists(expr: &Expression) -> Vec<(&'static str, &[Expression])> {
273 let mut lists = Vec::new();
274
275 match expr {
276 Expression::Select(s) => {
277 lists.push(("expressions", s.expressions.as_slice()));
278 }
280 Expression::Function(f) => {
281 lists.push(("args", f.args.as_slice()));
282 }
283 Expression::AggregateFunction(f) => {
284 lists.push(("args", f.args.as_slice()));
285 }
286 Expression::From(f) => {
287 lists.push(("expressions", f.expressions.as_slice()));
288 }
289 Expression::GroupBy(g) => {
290 lists.push(("expressions", g.expressions.as_slice()));
291 }
292 Expression::In(i) => {
295 lists.push(("expressions", i.expressions.as_slice()));
296 }
297 Expression::Array(a) => {
298 lists.push(("expressions", a.expressions.as_slice()));
299 }
300 Expression::Tuple(t) => {
301 lists.push(("expressions", t.expressions.as_slice()));
302 }
303 Expression::Coalesce(c) => {
305 lists.push(("expressions", c.expressions.as_slice()));
306 }
307 Expression::Greatest(g) | Expression::Least(g) => {
308 lists.push(("expressions", g.expressions.as_slice()));
309 }
310 _ => {}
311 }
312
313 lists
314}
315
316pub struct DfsIter<'a> {
325 stack: Vec<&'a Expression>,
326}
327
328impl<'a> DfsIter<'a> {
329 pub fn new(root: &'a Expression) -> Self {
331 Self { stack: vec![root] }
332 }
333}
334
335impl<'a> Iterator for DfsIter<'a> {
336 type Item = &'a Expression;
337
338 fn next(&mut self) -> Option<Self::Item> {
339 let expr = self.stack.pop()?;
340
341 let children: Vec<_> = iter_children(expr).into_iter().map(|(_, e)| e).collect();
343 for child in children.into_iter().rev() {
344 self.stack.push(child);
345 }
346
347 let lists: Vec<_> = iter_children_lists(expr)
348 .into_iter()
349 .flat_map(|(_, es)| es.iter())
350 .collect();
351 for child in lists.into_iter().rev() {
352 self.stack.push(child);
353 }
354
355 Some(expr)
356 }
357}
358
359pub struct BfsIter<'a> {
367 queue: VecDeque<&'a Expression>,
368}
369
370impl<'a> BfsIter<'a> {
371 pub fn new(root: &'a Expression) -> Self {
373 let mut queue = VecDeque::new();
374 queue.push_back(root);
375 Self { queue }
376 }
377}
378
379impl<'a> Iterator for BfsIter<'a> {
380 type Item = &'a Expression;
381
382 fn next(&mut self) -> Option<Self::Item> {
383 let expr = self.queue.pop_front()?;
384
385 for (_, child) in iter_children(expr) {
387 self.queue.push_back(child);
388 }
389
390 for (_, children) in iter_children_lists(expr) {
391 for child in children {
392 self.queue.push_back(child);
393 }
394 }
395
396 Some(expr)
397 }
398}
399
400pub trait ExpressionWalk {
406 fn dfs(&self) -> DfsIter<'_>;
411
412 fn bfs(&self) -> BfsIter<'_>;
416
417 fn find<F>(&self, predicate: F) -> Option<&Expression>
421 where
422 F: Fn(&Expression) -> bool;
423
424 fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
428 where
429 F: Fn(&Expression) -> bool;
430
431 fn contains<F>(&self, predicate: F) -> bool
433 where
434 F: Fn(&Expression) -> bool;
435
436 fn count<F>(&self, predicate: F) -> usize
438 where
439 F: Fn(&Expression) -> bool;
440
441 fn children(&self) -> Vec<&Expression>;
446
447 fn tree_depth(&self) -> usize;
451
452 fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
458 where
459 F: Fn(Expression) -> crate::Result<Option<Expression>>,
460 Self: Sized;
461}
462
463impl ExpressionWalk for Expression {
464 fn dfs(&self) -> DfsIter<'_> {
465 DfsIter::new(self)
466 }
467
468 fn bfs(&self) -> BfsIter<'_> {
469 BfsIter::new(self)
470 }
471
472 fn find<F>(&self, predicate: F) -> Option<&Expression>
473 where
474 F: Fn(&Expression) -> bool,
475 {
476 self.dfs().find(|e| predicate(e))
477 }
478
479 fn find_all<F>(&self, predicate: F) -> Vec<&Expression>
480 where
481 F: Fn(&Expression) -> bool,
482 {
483 self.dfs().filter(|e| predicate(e)).collect()
484 }
485
486 fn contains<F>(&self, predicate: F) -> bool
487 where
488 F: Fn(&Expression) -> bool,
489 {
490 self.dfs().any(|e| predicate(e))
491 }
492
493 fn count<F>(&self, predicate: F) -> usize
494 where
495 F: Fn(&Expression) -> bool,
496 {
497 self.dfs().filter(|e| predicate(e)).count()
498 }
499
500 fn children(&self) -> Vec<&Expression> {
501 let mut result: Vec<&Expression> = Vec::new();
502 for (_, child) in iter_children(self) {
503 result.push(child);
504 }
505 for (_, children_list) in iter_children_lists(self) {
506 for child in children_list {
507 result.push(child);
508 }
509 }
510 result
511 }
512
513 fn tree_depth(&self) -> usize {
514 let mut max_depth = 0;
515
516 for (_, child) in iter_children(self) {
517 let child_depth = child.tree_depth();
518 if child_depth + 1 > max_depth {
519 max_depth = child_depth + 1;
520 }
521 }
522
523 for (_, children) in iter_children_lists(self) {
524 for child in children {
525 let child_depth = child.tree_depth();
526 if child_depth + 1 > max_depth {
527 max_depth = child_depth + 1;
528 }
529 }
530 }
531
532 max_depth
533 }
534
535 fn transform_owned<F>(self, fun: F) -> crate::Result<Expression>
536 where
537 F: Fn(Expression) -> crate::Result<Option<Expression>>,
538 {
539 transform(self, &fun)
540 }
541}
542
543pub fn transform<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
564where
565 F: Fn(Expression) -> crate::Result<Option<Expression>>,
566{
567 crate::dialects::transform_recursive(expr, &|e| match fun(e)? {
568 Some(transformed) => Ok(transformed),
569 None => Ok(Expression::Null(crate::expressions::Null)),
570 })
571}
572
573pub fn transform_map<F>(expr: Expression, fun: &F) -> crate::Result<Expression>
594where
595 F: Fn(Expression) -> crate::Result<Expression>,
596{
597 crate::dialects::transform_recursive(expr, fun)
598}
599
600pub fn is_column(expr: &Expression) -> bool {
608 matches!(expr, Expression::Column(_))
609}
610
611pub fn is_literal(expr: &Expression) -> bool {
613 matches!(
614 expr,
615 Expression::Literal(_) | Expression::Boolean(_) | Expression::Null(_)
616 )
617}
618
619pub fn is_function(expr: &Expression) -> bool {
621 matches!(
622 expr,
623 Expression::Function(_) | Expression::AggregateFunction(_)
624 )
625}
626
627pub fn is_subquery(expr: &Expression) -> bool {
629 matches!(expr, Expression::Subquery(_))
630}
631
632pub fn is_select(expr: &Expression) -> bool {
634 matches!(expr, Expression::Select(_))
635}
636
637pub fn is_aggregate(expr: &Expression) -> bool {
639 matches!(expr, Expression::AggregateFunction(_))
640}
641
642pub fn is_window_function(expr: &Expression) -> bool {
644 matches!(expr, Expression::WindowFunction(_))
645}
646
647pub fn get_columns(expr: &Expression) -> Vec<&Expression> {
651 expr.find_all(is_column)
652}
653
654pub fn get_tables(expr: &Expression) -> Vec<&Expression> {
658 expr.find_all(|e| matches!(e, Expression::Table(_)))
659}
660
661pub fn contains_aggregate(expr: &Expression) -> bool {
663 expr.contains(is_aggregate)
664}
665
666pub fn contains_window_function(expr: &Expression) -> bool {
668 expr.contains(is_window_function)
669}
670
671pub fn contains_subquery(expr: &Expression) -> bool {
673 expr.contains(is_subquery)
674}
675
676macro_rules! is_type {
682 ($name:ident, $($variant:pat),+ $(,)?) => {
683 pub fn $name(expr: &Expression) -> bool {
685 matches!(expr, $($variant)|+)
686 }
687 };
688}
689
690is_type!(is_insert, Expression::Insert(_));
692is_type!(is_update, Expression::Update(_));
693is_type!(is_delete, Expression::Delete(_));
694is_type!(is_union, Expression::Union(_));
695is_type!(is_intersect, Expression::Intersect(_));
696is_type!(is_except, Expression::Except(_));
697
698is_type!(is_boolean, Expression::Boolean(_));
700is_type!(is_null_literal, Expression::Null(_));
701is_type!(is_star, Expression::Star(_));
702is_type!(is_identifier, Expression::Identifier(_));
703is_type!(is_table, Expression::Table(_));
704
705is_type!(is_eq, Expression::Eq(_));
707is_type!(is_neq, Expression::Neq(_));
708is_type!(is_lt, Expression::Lt(_));
709is_type!(is_lte, Expression::Lte(_));
710is_type!(is_gt, Expression::Gt(_));
711is_type!(is_gte, Expression::Gte(_));
712is_type!(is_like, Expression::Like(_));
713is_type!(is_ilike, Expression::ILike(_));
714
715is_type!(is_add, Expression::Add(_));
717is_type!(is_sub, Expression::Sub(_));
718is_type!(is_mul, Expression::Mul(_));
719is_type!(is_div, Expression::Div(_));
720is_type!(is_mod, Expression::Mod(_));
721is_type!(is_concat, Expression::Concat(_));
722
723is_type!(is_and, Expression::And(_));
725is_type!(is_or, Expression::Or(_));
726is_type!(is_not, Expression::Not(_));
727
728is_type!(is_in, Expression::In(_));
730is_type!(is_between, Expression::Between(_));
731is_type!(is_is_null, Expression::IsNull(_));
732is_type!(is_exists, Expression::Exists(_));
733
734is_type!(is_count, Expression::Count(_));
736is_type!(is_sum, Expression::Sum(_));
737is_type!(is_avg, Expression::Avg(_));
738is_type!(is_min_func, Expression::Min(_));
739is_type!(is_max_func, Expression::Max(_));
740is_type!(is_coalesce, Expression::Coalesce(_));
741is_type!(is_null_if, Expression::NullIf(_));
742is_type!(is_cast, Expression::Cast(_));
743is_type!(is_try_cast, Expression::TryCast(_));
744is_type!(is_safe_cast, Expression::SafeCast(_));
745is_type!(is_case, Expression::Case(_));
746
747is_type!(is_from, Expression::From(_));
749is_type!(is_join, Expression::Join(_));
750is_type!(is_where, Expression::Where(_));
751is_type!(is_group_by, Expression::GroupBy(_));
752is_type!(is_having, Expression::Having(_));
753is_type!(is_order_by, Expression::OrderBy(_));
754is_type!(is_limit, Expression::Limit(_));
755is_type!(is_offset, Expression::Offset(_));
756is_type!(is_with, Expression::With(_));
757is_type!(is_cte, Expression::Cte(_));
758is_type!(is_alias, Expression::Alias(_));
759is_type!(is_paren, Expression::Paren(_));
760is_type!(is_ordered, Expression::Ordered(_));
761
762is_type!(is_create_table, Expression::CreateTable(_));
764is_type!(is_drop_table, Expression::DropTable(_));
765is_type!(is_alter_table, Expression::AlterTable(_));
766is_type!(is_create_index, Expression::CreateIndex(_));
767is_type!(is_drop_index, Expression::DropIndex(_));
768is_type!(is_create_view, Expression::CreateView(_));
769is_type!(is_drop_view, Expression::DropView(_));
770
771pub fn is_query(expr: &Expression) -> bool {
777 matches!(
778 expr,
779 Expression::Select(_) | Expression::Insert(_) | Expression::Update(_) | Expression::Delete(_)
780 )
781}
782
783pub fn is_set_operation(expr: &Expression) -> bool {
785 matches!(
786 expr,
787 Expression::Union(_) | Expression::Intersect(_) | Expression::Except(_)
788 )
789}
790
791pub fn is_comparison(expr: &Expression) -> bool {
793 matches!(
794 expr,
795 Expression::Eq(_)
796 | Expression::Neq(_)
797 | Expression::Lt(_)
798 | Expression::Lte(_)
799 | Expression::Gt(_)
800 | Expression::Gte(_)
801 | Expression::Like(_)
802 | Expression::ILike(_)
803 )
804}
805
806pub fn is_arithmetic(expr: &Expression) -> bool {
808 matches!(
809 expr,
810 Expression::Add(_)
811 | Expression::Sub(_)
812 | Expression::Mul(_)
813 | Expression::Div(_)
814 | Expression::Mod(_)
815 )
816}
817
818pub fn is_logical(expr: &Expression) -> bool {
820 matches!(
821 expr,
822 Expression::And(_) | Expression::Or(_) | Expression::Not(_)
823 )
824}
825
826pub fn is_ddl(expr: &Expression) -> bool {
828 matches!(
829 expr,
830 Expression::CreateTable(_)
831 | Expression::DropTable(_)
832 | Expression::AlterTable(_)
833 | Expression::CreateIndex(_)
834 | Expression::DropIndex(_)
835 | Expression::CreateView(_)
836 | Expression::DropView(_)
837 | Expression::AlterView(_)
838 | Expression::CreateSchema(_)
839 | Expression::DropSchema(_)
840 | Expression::CreateDatabase(_)
841 | Expression::DropDatabase(_)
842 | Expression::CreateFunction(_)
843 | Expression::DropFunction(_)
844 | Expression::CreateProcedure(_)
845 | Expression::DropProcedure(_)
846 | Expression::CreateSequence(_)
847 | Expression::DropSequence(_)
848 | Expression::AlterSequence(_)
849 | Expression::CreateTrigger(_)
850 | Expression::DropTrigger(_)
851 | Expression::CreateType(_)
852 | Expression::DropType(_)
853 )
854}
855
856pub fn find_parent<'a>(root: &'a Expression, target: &Expression) -> Option<&'a Expression> {
863 fn search<'a>(node: &'a Expression, target: *const Expression) -> Option<&'a Expression> {
864 for (_, child) in iter_children(node) {
865 if std::ptr::eq(child, target) {
866 return Some(node);
867 }
868 if let Some(found) = search(child, target) {
869 return Some(found);
870 }
871 }
872 for (_, children_list) in iter_children_lists(node) {
873 for child in children_list {
874 if std::ptr::eq(child, target) {
875 return Some(node);
876 }
877 if let Some(found) = search(child, target) {
878 return Some(found);
879 }
880 }
881 }
882 None
883 }
884
885 search(root, target as *const Expression)
886}
887
888pub fn find_ancestor<'a, F>(
894 root: &'a Expression,
895 target: &Expression,
896 predicate: F,
897) -> Option<&'a Expression>
898where
899 F: Fn(&Expression) -> bool,
900{
901 fn build_path<'a>(
903 node: &'a Expression,
904 target: *const Expression,
905 path: &mut Vec<&'a Expression>,
906 ) -> bool {
907 if std::ptr::eq(node, target) {
908 return true;
909 }
910 path.push(node);
911 for (_, child) in iter_children(node) {
912 if build_path(child, target, path) {
913 return true;
914 }
915 }
916 for (_, children_list) in iter_children_lists(node) {
917 for child in children_list {
918 if build_path(child, target, path) {
919 return true;
920 }
921 }
922 }
923 path.pop();
924 false
925 }
926
927 let mut path = Vec::new();
928 if !build_path(root, target as *const Expression, &mut path) {
929 return None;
930 }
931
932 for ancestor in path.iter().rev() {
934 if predicate(ancestor) {
935 return Some(ancestor);
936 }
937 }
938 None
939}
940
941#[cfg(test)]
942mod tests {
943 use super::*;
944 use crate::expressions::{BinaryOp, Column, Identifier, Literal};
945
946 fn make_column(name: &str) -> Expression {
947 Expression::Column(Column {
948 name: Identifier {
949 name: name.to_string(),
950 quoted: false,
951 trailing_comments: vec![],
952 },
953 table: None,
954 join_mark: false,
955 trailing_comments: vec![],
956 })
957 }
958
959 fn make_literal(value: i64) -> Expression {
960 Expression::Literal(Literal::Number(value.to_string()))
961 }
962
963 #[test]
964 fn test_dfs_simple() {
965 let left = make_column("a");
966 let right = make_literal(1);
967 let expr = Expression::Eq(Box::new(BinaryOp {
968 left,
969 right,
970 left_comments: vec![],
971 operator_comments: vec![],
972 trailing_comments: vec![],
973 }));
974
975 let nodes: Vec<_> = expr.dfs().collect();
976 assert_eq!(nodes.len(), 3); assert!(matches!(nodes[0], Expression::Eq(_)));
978 assert!(matches!(nodes[1], Expression::Column(_)));
979 assert!(matches!(nodes[2], Expression::Literal(_)));
980 }
981
982 #[test]
983 fn test_find() {
984 let left = make_column("a");
985 let right = make_literal(1);
986 let expr = Expression::Eq(Box::new(BinaryOp {
987 left,
988 right,
989 left_comments: vec![],
990 operator_comments: vec![],
991 trailing_comments: vec![],
992 }));
993
994 let column = expr.find(is_column);
995 assert!(column.is_some());
996 assert!(matches!(column.unwrap(), Expression::Column(_)));
997
998 let literal = expr.find(is_literal);
999 assert!(literal.is_some());
1000 assert!(matches!(literal.unwrap(), Expression::Literal(_)));
1001 }
1002
1003 #[test]
1004 fn test_find_all() {
1005 let col1 = make_column("a");
1006 let col2 = make_column("b");
1007 let expr = Expression::And(Box::new(BinaryOp {
1008 left: col1,
1009 right: col2,
1010 left_comments: vec![],
1011 operator_comments: vec![],
1012 trailing_comments: vec![],
1013 }));
1014
1015 let columns = expr.find_all(is_column);
1016 assert_eq!(columns.len(), 2);
1017 }
1018
1019 #[test]
1020 fn test_contains() {
1021 let col = make_column("a");
1022 let lit = make_literal(1);
1023 let expr = Expression::Eq(Box::new(BinaryOp {
1024 left: col,
1025 right: lit,
1026 left_comments: vec![],
1027 operator_comments: vec![],
1028 trailing_comments: vec![],
1029 }));
1030
1031 assert!(expr.contains(is_column));
1032 assert!(expr.contains(is_literal));
1033 assert!(!expr.contains(is_subquery));
1034 }
1035
1036 #[test]
1037 fn test_count() {
1038 let col1 = make_column("a");
1039 let col2 = make_column("b");
1040 let lit = make_literal(1);
1041
1042 let inner = Expression::Add(Box::new(BinaryOp {
1043 left: col2,
1044 right: lit,
1045 left_comments: vec![],
1046 operator_comments: vec![],
1047 trailing_comments: vec![],
1048 }));
1049
1050 let expr = Expression::Eq(Box::new(BinaryOp {
1051 left: col1,
1052 right: inner,
1053 left_comments: vec![],
1054 operator_comments: vec![],
1055 trailing_comments: vec![],
1056 }));
1057
1058 assert_eq!(expr.count(is_column), 2);
1059 assert_eq!(expr.count(is_literal), 1);
1060 }
1061
1062 #[test]
1063 fn test_tree_depth() {
1064 let lit = make_literal(1);
1066 assert_eq!(lit.tree_depth(), 0);
1067
1068 let col = make_column("a");
1070 let expr = Expression::Eq(Box::new(BinaryOp {
1071 left: col,
1072 right: lit.clone(),
1073 left_comments: vec![],
1074 operator_comments: vec![],
1075 trailing_comments: vec![],
1076 }));
1077 assert_eq!(expr.tree_depth(), 1);
1078
1079 let inner = Expression::Add(Box::new(BinaryOp {
1081 left: make_column("b"),
1082 right: lit,
1083 left_comments: vec![],
1084 operator_comments: vec![],
1085 trailing_comments: vec![],
1086 }));
1087 let outer = Expression::Eq(Box::new(BinaryOp {
1088 left: make_column("a"),
1089 right: inner,
1090 left_comments: vec![],
1091 operator_comments: vec![],
1092 trailing_comments: vec![],
1093 }));
1094 assert_eq!(outer.tree_depth(), 2);
1095 }
1096
1097 #[test]
1098 fn test_tree_context() {
1099 let col = make_column("a");
1100 let lit = make_literal(1);
1101 let expr = Expression::Eq(Box::new(BinaryOp {
1102 left: col,
1103 right: lit,
1104 left_comments: vec![],
1105 operator_comments: vec![],
1106 trailing_comments: vec![],
1107 }));
1108
1109 let ctx = TreeContext::build(&expr);
1110
1111 let root_info = ctx.get(0).unwrap();
1113 assert!(root_info.parent_id.is_none());
1114
1115 let left_info = ctx.get(1).unwrap();
1117 assert_eq!(left_info.parent_id, Some(0));
1118 assert_eq!(left_info.arg_key, "left");
1119
1120 let right_info = ctx.get(2).unwrap();
1121 assert_eq!(right_info.parent_id, Some(0));
1122 assert_eq!(right_info.arg_key, "right");
1123 }
1124
1125 #[test]
1128 fn test_transform_rename_columns() {
1129 let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1130 let expr = ast[0].clone();
1131 let result = super::transform_map(expr, &|e| {
1132 if let Expression::Column(ref c) = e {
1133 if c.name.name == "a" {
1134 return Ok(Expression::Column(Column {
1135 name: Identifier::new("alpha"),
1136 table: c.table.clone(),
1137 join_mark: false,
1138 trailing_comments: vec![],
1139 }));
1140 }
1141 }
1142 Ok(e)
1143 })
1144 .unwrap();
1145 let sql = crate::generator::Generator::sql(&result).unwrap();
1146 assert!(sql.contains("alpha"), "Expected 'alpha' in: {}", sql);
1147 assert!(sql.contains("b"), "Expected 'b' in: {}", sql);
1148 }
1149
1150 #[test]
1151 fn test_transform_noop() {
1152 let ast = crate::parser::Parser::parse_sql("SELECT 1 + 2").unwrap();
1153 let expr = ast[0].clone();
1154 let result = super::transform_map(expr.clone(), &|e| Ok(e)).unwrap();
1155 let sql1 = crate::generator::Generator::sql(&expr).unwrap();
1156 let sql2 = crate::generator::Generator::sql(&result).unwrap();
1157 assert_eq!(sql1, sql2);
1158 }
1159
1160 #[test]
1161 fn test_transform_nested() {
1162 let ast = crate::parser::Parser::parse_sql("SELECT a + b FROM t").unwrap();
1163 let expr = ast[0].clone();
1164 let result = super::transform_map(expr, &|e| {
1165 if let Expression::Column(ref c) = e {
1166 return Ok(Expression::Literal(Literal::Number(
1167 if c.name.name == "a" { "1" } else { "2" }.to_string(),
1168 )));
1169 }
1170 Ok(e)
1171 })
1172 .unwrap();
1173 let sql = crate::generator::Generator::sql(&result).unwrap();
1174 assert_eq!(sql, "SELECT 1 + 2 FROM t");
1175 }
1176
1177 #[test]
1178 fn test_transform_error() {
1179 let ast = crate::parser::Parser::parse_sql("SELECT a FROM t").unwrap();
1180 let expr = ast[0].clone();
1181 let result = super::transform_map(expr, &|e| {
1182 if let Expression::Column(ref c) = e {
1183 if c.name.name == "a" {
1184 return Err(crate::error::Error::Parse("test error".to_string()));
1185 }
1186 }
1187 Ok(e)
1188 });
1189 assert!(result.is_err());
1190 }
1191
1192 #[test]
1193 fn test_transform_owned_trait() {
1194 let ast = crate::parser::Parser::parse_sql("SELECT x FROM t").unwrap();
1195 let expr = ast[0].clone();
1196 let result = expr.transform_owned(|e| Ok(Some(e))).unwrap();
1197 let sql = crate::generator::Generator::sql(&result).unwrap();
1198 assert_eq!(sql, "SELECT x FROM t");
1199 }
1200
1201 #[test]
1204 fn test_children_leaf() {
1205 let lit = make_literal(1);
1206 assert_eq!(lit.children().len(), 0);
1207 }
1208
1209 #[test]
1210 fn test_children_binary_op() {
1211 let left = make_column("a");
1212 let right = make_literal(1);
1213 let expr = Expression::Eq(Box::new(BinaryOp {
1214 left,
1215 right,
1216 left_comments: vec![],
1217 operator_comments: vec![],
1218 trailing_comments: vec![],
1219 }));
1220 let children = expr.children();
1221 assert_eq!(children.len(), 2);
1222 assert!(matches!(children[0], Expression::Column(_)));
1223 assert!(matches!(children[1], Expression::Literal(_)));
1224 }
1225
1226 #[test]
1227 fn test_children_select() {
1228 let ast = crate::parser::Parser::parse_sql("SELECT a, b FROM t").unwrap();
1229 let expr = &ast[0];
1230 let children = expr.children();
1231 assert!(children.len() >= 2);
1233 }
1234
1235 #[test]
1238 fn test_find_parent_binary() {
1239 let left = make_column("a");
1240 let right = make_literal(1);
1241 let expr = Expression::Eq(Box::new(BinaryOp {
1242 left,
1243 right,
1244 left_comments: vec![],
1245 operator_comments: vec![],
1246 trailing_comments: vec![],
1247 }));
1248
1249 let col = expr.find(is_column).unwrap();
1251 let parent = super::find_parent(&expr, col);
1252 assert!(parent.is_some());
1253 assert!(matches!(parent.unwrap(), Expression::Eq(_)));
1254 }
1255
1256 #[test]
1257 fn test_find_parent_root_has_none() {
1258 let lit = make_literal(1);
1259 let parent = super::find_parent(&lit, &lit);
1260 assert!(parent.is_none());
1261 }
1262
1263 #[test]
1266 fn test_find_ancestor_select() {
1267 let ast = crate::parser::Parser::parse_sql("SELECT a FROM t WHERE a > 1").unwrap();
1268 let expr = &ast[0];
1269
1270 let where_col = expr.dfs().find(|e| {
1272 if let Expression::Column(c) = e {
1273 c.name.name == "a"
1274 } else {
1275 false
1276 }
1277 });
1278 assert!(where_col.is_some());
1279
1280 let ancestor = super::find_ancestor(expr, where_col.unwrap(), is_select);
1282 assert!(ancestor.is_some());
1283 assert!(matches!(ancestor.unwrap(), Expression::Select(_)));
1284 }
1285
1286 #[test]
1287 fn test_find_ancestor_no_match() {
1288 let left = make_column("a");
1289 let right = make_literal(1);
1290 let expr = Expression::Eq(Box::new(BinaryOp {
1291 left,
1292 right,
1293 left_comments: vec![],
1294 operator_comments: vec![],
1295 trailing_comments: vec![],
1296 }));
1297
1298 let col = expr.find(is_column).unwrap();
1299 let ancestor = super::find_ancestor(&expr, col, is_select);
1300 assert!(ancestor.is_none());
1301 }
1302
1303 #[test]
1304 fn test_ancestors() {
1305 let col = make_column("a");
1306 let lit = make_literal(1);
1307 let inner = Expression::Add(Box::new(BinaryOp {
1308 left: col,
1309 right: lit,
1310 left_comments: vec![],
1311 operator_comments: vec![],
1312 trailing_comments: vec![],
1313 }));
1314 let outer = Expression::Eq(Box::new(BinaryOp {
1315 left: make_column("b"),
1316 right: inner,
1317 left_comments: vec![],
1318 operator_comments: vec![],
1319 trailing_comments: vec![],
1320 }));
1321
1322 let ctx = TreeContext::build(&outer);
1323
1324 let ancestors = ctx.ancestors_of(3);
1332 assert_eq!(ancestors, vec![2, 0]); }
1334}