Skip to main content

sqlglot_rust/optimizer/
mod.rs

1//! Query optimization passes.
2//!
3//! Inspired by Python sqlglot's optimizer module. Currently implements:
4//! - Constant folding (e.g., `1 + 2` → `3`)
5//! - Boolean simplification (e.g., `TRUE AND x` → `x`)
6//! - Dead predicate elimination (e.g., `WHERE TRUE`)
7//! - Subquery unnesting / decorrelation (EXISTS, IN → JOINs)
8//! - Predicate pushdown (WHERE → derived tables / JOIN ON)
9//! - Column qualification (qualify_columns — resolve `*`, add table qualifiers)
10//! - Type annotation (annotate_types — infer SQL types for all AST nodes)
11//! - Column lineage (lineage — trace data flow from source to output columns)
12//!
13//! Future optimizations:
14//! - Join reordering
15//! - Column pruning
16
17pub mod annotate_types;
18pub mod lineage;
19pub mod pushdown_predicates;
20pub mod qualify_columns;
21pub mod scope_analysis;
22pub mod unnest_subqueries;
23
24use crate::ast::*;
25use crate::errors::Result;
26
27/// Optimize a SQL statement by applying transformation passes.
28pub fn optimize(statement: Statement) -> Result<Statement> {
29    let mut stmt = statement;
30    stmt = fold_constants(stmt);
31    stmt = simplify_booleans(stmt);
32    stmt = unnest_subqueries::unnest_subqueries(stmt);
33    stmt = pushdown_predicates::pushdown_predicates(stmt);
34    Ok(stmt)
35}
36
37/// Fold constant expressions (e.g., `1 + 2` → `3`).
38fn fold_constants(statement: Statement) -> Statement {
39    match statement {
40        Statement::Select(mut sel) => {
41            if let Some(wh) = sel.where_clause {
42                sel.where_clause = Some(fold_expr(wh));
43            }
44            if let Some(having) = sel.having {
45                sel.having = Some(fold_expr(having));
46            }
47            for item in &mut sel.columns {
48                if let SelectItem::Expr { expr, .. } = item {
49                    *expr = fold_expr(expr.clone());
50                }
51            }
52            Statement::Select(sel)
53        }
54        other => other,
55    }
56}
57
58fn fold_expr(expr: Expr) -> Expr {
59    match expr {
60        Expr::BinaryOp { left, op, right } => {
61            let left = fold_expr(*left);
62            let right = fold_expr(*right);
63
64            // Try numeric folding
65            if let (Expr::Number(l), Expr::Number(r)) = (&left, &right) {
66                if let (Ok(lv), Ok(rv)) = (l.parse::<f64>(), r.parse::<f64>()) {
67                    let result = match op {
68                        BinaryOperator::Plus => Some(lv + rv),
69                        BinaryOperator::Minus => Some(lv - rv),
70                        BinaryOperator::Multiply => Some(lv * rv),
71                        BinaryOperator::Divide if rv != 0.0 => Some(lv / rv),
72                        BinaryOperator::Modulo if rv != 0.0 => Some(lv % rv),
73                        _ => None,
74                    };
75                    if let Some(val) = result {
76                        // Emit integer if it's a whole number
77                        if val.fract() == 0.0 && val.abs() < i64::MAX as f64 {
78                            return Expr::Number(format!("{}", val as i64));
79                        }
80                        return Expr::Number(format!("{val}"));
81                    }
82
83                    // Try boolean folding for comparison
84                    let cmp = match op {
85                        BinaryOperator::Eq => Some(lv == rv),
86                        BinaryOperator::Neq => Some(lv != rv),
87                        BinaryOperator::Lt => Some(lv < rv),
88                        BinaryOperator::Gt => Some(lv > rv),
89                        BinaryOperator::LtEq => Some(lv <= rv),
90                        BinaryOperator::GtEq => Some(lv >= rv),
91                        _ => None,
92                    };
93                    if let Some(val) = cmp {
94                        return Expr::Boolean(val);
95                    }
96                }
97            }
98
99            // String concatenation folding
100            if matches!(op, BinaryOperator::Concat) {
101                if let (Expr::StringLiteral(l), Expr::StringLiteral(r)) = (&left, &right) {
102                    return Expr::StringLiteral(format!("{l}{r}"));
103                }
104            }
105
106            Expr::BinaryOp {
107                left: Box::new(left),
108                op,
109                right: Box::new(right),
110            }
111        }
112        Expr::UnaryOp {
113            op: UnaryOperator::Minus,
114            expr,
115        } => {
116            let inner = fold_expr(*expr);
117            if let Expr::Number(ref n) = inner {
118                if let Ok(v) = n.parse::<f64>() {
119                    let neg = -v;
120                    if neg.fract() == 0.0 && neg.abs() < i64::MAX as f64 {
121                        return Expr::Number(format!("{}", neg as i64));
122                    }
123                    return Expr::Number(format!("{neg}"));
124                }
125            }
126            Expr::UnaryOp {
127                op: UnaryOperator::Minus,
128                expr: Box::new(inner),
129            }
130        }
131        Expr::Nested(inner) => {
132            let folded = fold_expr(*inner);
133            if folded.is_literal() {
134                folded
135            } else {
136                Expr::Nested(Box::new(folded))
137            }
138        }
139        other => other,
140    }
141}
142
143/// Simplify boolean expressions.
144fn simplify_booleans(statement: Statement) -> Statement {
145    match statement {
146        Statement::Select(mut sel) => {
147            // Simplify boolean expressions in SELECT columns
148            for item in &mut sel.columns {
149                if let SelectItem::Expr { expr, .. } = item {
150                    *expr = simplify_bool_expr(expr.clone());
151                }
152            }
153            if let Some(wh) = sel.where_clause {
154                let simplified = simplify_bool_expr(wh);
155                // WHERE TRUE → no WHERE clause
156                if simplified == Expr::Boolean(true) {
157                    sel.where_clause = None;
158                } else {
159                    sel.where_clause = Some(simplified);
160                }
161            }
162            if let Some(having) = sel.having {
163                let simplified = simplify_bool_expr(having);
164                if simplified == Expr::Boolean(true) {
165                    sel.having = None;
166                } else {
167                    sel.having = Some(simplified);
168                }
169            }
170            Statement::Select(sel)
171        }
172        other => other,
173    }
174}
175
176fn simplify_bool_expr(expr: Expr) -> Expr {
177    match expr {
178        Expr::BinaryOp {
179            left,
180            op: BinaryOperator::And,
181            right,
182        } => {
183            let left = simplify_bool_expr(*left);
184            let right = simplify_bool_expr(*right);
185            match (&left, &right) {
186                (Expr::Boolean(true), _) => right,
187                (_, Expr::Boolean(true)) => left,
188                (Expr::Boolean(false), _) | (_, Expr::Boolean(false)) => Expr::Boolean(false),
189                _ => Expr::BinaryOp {
190                    left: Box::new(left),
191                    op: BinaryOperator::And,
192                    right: Box::new(right),
193                },
194            }
195        }
196        Expr::BinaryOp {
197            left,
198            op: BinaryOperator::Or,
199            right,
200        } => {
201            let left = simplify_bool_expr(*left);
202            let right = simplify_bool_expr(*right);
203            match (&left, &right) {
204                (Expr::Boolean(true), _) | (_, Expr::Boolean(true)) => Expr::Boolean(true),
205                (Expr::Boolean(false), _) => right,
206                (_, Expr::Boolean(false)) => left,
207                _ => Expr::BinaryOp {
208                    left: Box::new(left),
209                    op: BinaryOperator::Or,
210                    right: Box::new(right),
211                },
212            }
213        }
214        Expr::UnaryOp {
215            op: UnaryOperator::Not,
216            expr,
217        } => {
218            let inner = simplify_bool_expr(*expr);
219            match inner {
220                Expr::Boolean(b) => Expr::Boolean(!b),
221                Expr::UnaryOp {
222                    op: UnaryOperator::Not,
223                    expr: inner2,
224                } => *inner2,
225                other => Expr::UnaryOp {
226                    op: UnaryOperator::Not,
227                    expr: Box::new(other),
228                },
229            }
230        }
231        Expr::Nested(inner) => {
232            let simplified = simplify_bool_expr(*inner);
233            if simplified.is_literal() {
234                simplified
235            } else {
236                Expr::Nested(Box::new(simplified))
237            }
238        }
239        other => other,
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::parser::Parser;
247
248    fn optimize_sql(sql: &str) -> Statement {
249        let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
250        optimize(stmt).unwrap()
251    }
252
253    #[test]
254    fn test_constant_folding() {
255        let stmt = optimize_sql("SELECT 1 + 2 FROM t");
256        if let Statement::Select(sel) = stmt {
257            if let SelectItem::Expr { expr, .. } = &sel.columns[0] {
258                assert_eq!(*expr, Expr::Number("3".to_string()));
259            }
260        }
261    }
262
263    #[test]
264    fn test_boolean_simplification_where_true() {
265        let stmt = optimize_sql("SELECT x FROM t WHERE TRUE");
266        if let Statement::Select(sel) = stmt {
267            assert!(sel.where_clause.is_none());
268        }
269    }
270
271    #[test]
272    fn test_boolean_simplification_and_true() {
273        let stmt = optimize_sql("SELECT x FROM t WHERE TRUE AND x > 1");
274        if let Statement::Select(sel) = stmt {
275            // Should simplify to just x > 1
276            assert!(sel.where_clause.is_some());
277            assert!(!matches!(
278                &sel.where_clause,
279                Some(Expr::BinaryOp {
280                    op: BinaryOperator::And,
281                    ..
282                })
283            ));
284        }
285    }
286
287    #[test]
288    fn test_double_negation() {
289        let stmt = optimize_sql("SELECT x FROM t WHERE NOT NOT x > 1");
290        if let Statement::Select(sel) = stmt {
291            // Should simplify to x > 1 (no NOT)
292            assert!(sel.where_clause.is_some());
293        }
294    }
295}