Skip to main content

no_mistakes_postgres_sql/
bound_expr.rs

1use crate::erased_visit_fn::visit_expressions_mut;
2use sqlparser::ast::{BinaryOperator, Expr, ObjectNamePart, Value};
3use std::ops::ControlFlow;
4
5pub fn conjuncts_of(expr: &Expr, out: &mut Vec<Expr>) {
6    match expr {
7        Expr::Nested(inner) => conjuncts_of(inner, out),
8        Expr::BinaryOp {
9            left,
10            op: BinaryOperator::And,
11            right,
12        } => {
13            conjuncts_of(left, out);
14            conjuncts_of(right, out);
15        }
16        other => out.push(unnest(other)),
17    }
18}
19
20pub fn unnest(expr: &Expr) -> Expr {
21    match expr {
22        Expr::Nested(inner) => unnest(inner),
23        other => other.clone(),
24    }
25}
26
27pub fn canonical_bound_expr(expr: &Expr) -> Expr {
28    let mut normalized = unnest(expr);
29    let _: ControlFlow<()> = visit_expressions_mut(&mut normalized, |expr| {
30        if let Expr::Nested(inner) = expr {
31            // The post-order visitor has already canonicalized the nested operand.
32            let inner = std::mem::replace(inner, Box::new(Expr::Value(Value::Null.into())));
33            *expr = *inner;
34            return ControlFlow::Continue(());
35        }
36        match expr {
37            Expr::Identifier(ident) => {
38                ident.value = crate::idents::ident_key(ident);
39                ident.quote_style = ident
40                    .value
41                    .bytes()
42                    .any(|byte| byte.is_ascii_uppercase())
43                    .then_some('"');
44            }
45            Expr::Function(function) => {
46                for part in &mut function.name.0 {
47                    match part {
48                        ObjectNamePart::Identifier(ident) if ident.quote_style.is_none() => {
49                            ident.value.make_ascii_lowercase();
50                        }
51                        _ => {}
52                    }
53                }
54            }
55            _ => {}
56        }
57        ControlFlow::Continue(())
58    });
59    normalized
60}