sql_cli/query_plan/
expression_lifter.rs

1use crate::query_plan::{QueryPlan, WorkUnit, WorkUnitExpression, WorkUnitType};
2use crate::sql::parser::ast::{
3    CTEType, ColumnRef, SelectItem, SelectStatement, SqlExpression, WhereClause, CTE,
4};
5use std::collections::HashSet;
6
7/// Expression lifter that identifies and lifts non-supported WHERE expressions to CTEs
8pub struct ExpressionLifter {
9    /// Counter for generating unique CTE names
10    cte_counter: usize,
11
12    /// Set of function names that need to be lifted
13    liftable_functions: HashSet<String>,
14}
15
16impl ExpressionLifter {
17    /// Create a new expression lifter
18    pub fn new() -> Self {
19        let mut liftable_functions = HashSet::new();
20
21        // Add window functions that need lifting
22        liftable_functions.insert("ROW_NUMBER".to_string());
23        liftable_functions.insert("RANK".to_string());
24        liftable_functions.insert("DENSE_RANK".to_string());
25        liftable_functions.insert("LAG".to_string());
26        liftable_functions.insert("LEAD".to_string());
27        liftable_functions.insert("FIRST_VALUE".to_string());
28        liftable_functions.insert("LAST_VALUE".to_string());
29        liftable_functions.insert("NTH_VALUE".to_string());
30
31        // Add aggregate functions that might need lifting in certain contexts
32        liftable_functions.insert("PERCENTILE_CONT".to_string());
33        liftable_functions.insert("PERCENTILE_DISC".to_string());
34
35        ExpressionLifter {
36            cte_counter: 0,
37            liftable_functions,
38        }
39    }
40
41    /// Generate a unique CTE name
42    fn next_cte_name(&mut self) -> String {
43        self.cte_counter += 1;
44        format!("__lifted_{}", self.cte_counter)
45    }
46
47    /// Check if an expression needs to be lifted
48    pub fn needs_lifting(&self, expr: &SqlExpression) -> bool {
49        match expr {
50            SqlExpression::WindowFunction { .. } => true,
51
52            SqlExpression::FunctionCall { name, .. } => {
53                self.liftable_functions.contains(&name.to_uppercase())
54            }
55
56            SqlExpression::BinaryOp { left, right, .. } => {
57                self.needs_lifting(left) || self.needs_lifting(right)
58            }
59
60            SqlExpression::Not { expr } => self.needs_lifting(expr),
61
62            SqlExpression::InList { expr, values } => {
63                self.needs_lifting(expr) || values.iter().any(|v| self.needs_lifting(v))
64            }
65
66            SqlExpression::NotInList { expr, values } => {
67                self.needs_lifting(expr) || values.iter().any(|v| self.needs_lifting(v))
68            }
69
70            SqlExpression::Between { expr, lower, upper } => {
71                self.needs_lifting(expr) || self.needs_lifting(lower) || self.needs_lifting(upper)
72            }
73
74            SqlExpression::CaseExpression {
75                when_branches,
76                else_branch,
77            } => {
78                when_branches.iter().any(|branch| {
79                    self.needs_lifting(&branch.condition) || self.needs_lifting(&branch.result)
80                }) || else_branch
81                    .as_ref()
82                    .map_or(false, |e| self.needs_lifting(e))
83            }
84
85            SqlExpression::SimpleCaseExpression {
86                expr,
87                when_branches,
88                else_branch,
89            } => {
90                self.needs_lifting(expr)
91                    || when_branches.iter().any(|branch| {
92                        self.needs_lifting(&branch.value) || self.needs_lifting(&branch.result)
93                    })
94                    || else_branch
95                        .as_ref()
96                        .map_or(false, |e| self.needs_lifting(e))
97            }
98
99            _ => false,
100        }
101    }
102
103    /// Analyze WHERE clause and identify expressions to lift
104    pub fn analyze_where_clause(&mut self, where_clause: &WhereClause) -> Vec<LiftableExpression> {
105        let mut liftable = Vec::new();
106
107        // Analyze each condition in the WHERE clause
108        for condition in &where_clause.conditions {
109            if self.needs_lifting(&condition.expr) {
110                liftable.push(LiftableExpression {
111                    expression: condition.expr.clone(),
112                    suggested_name: self.next_cte_name(),
113                    dependencies: Vec::new(), // TODO: Analyze dependencies
114                });
115            }
116        }
117
118        liftable
119    }
120
121    /// Lift expressions from a SELECT statement
122    pub fn lift_expressions(&mut self, stmt: &mut SelectStatement) -> Vec<CTE> {
123        let mut lifted_ctes = Vec::new();
124
125        // First, check for column alias dependencies (e.g., using alias in PARTITION BY)
126        let alias_deps = self.analyze_column_alias_dependencies(stmt);
127        if !alias_deps.is_empty() {
128            let cte = self.lift_column_aliases(stmt, &alias_deps);
129            lifted_ctes.push(cte);
130        }
131
132        // Check WHERE clause for liftable expressions
133        if let Some(ref where_clause) = stmt.where_clause {
134            let liftable = self.analyze_where_clause(where_clause);
135
136            for lift_expr in liftable {
137                // Create a CTE that includes the lifted expression as a computed column
138                let cte_select = SelectStatement {
139                    distinct: false,
140                    columns: vec!["*".to_string()],
141                    select_items: vec![
142                        SelectItem::Star,
143                        SelectItem::Expression {
144                            expr: lift_expr.expression.clone(),
145                            alias: "lifted_value".to_string(),
146                        },
147                    ],
148                    from_table: stmt.from_table.clone(),
149                    from_subquery: stmt.from_subquery.clone(),
150                    from_function: stmt.from_function.clone(),
151                    from_alias: stmt.from_alias.clone(),
152                    joins: stmt.joins.clone(),
153                    where_clause: None, // Move simpler parts of WHERE here if possible
154                    order_by: None,
155                    group_by: None,
156                    having: None,
157                    limit: None,
158                    offset: None,
159                    ctes: Vec::new(),
160                    into_table: None,
161                    set_operations: Vec::new(),
162                };
163
164                let cte = CTE {
165                    name: lift_expr.suggested_name.clone(),
166                    column_list: None,
167                    cte_type: CTEType::Standard(cte_select),
168                };
169
170                lifted_ctes.push(cte);
171
172                // Update the main query to reference the CTE
173                stmt.from_table = Some(lift_expr.suggested_name);
174
175                // Replace the complex WHERE expression with a simple column reference
176                use crate::sql::parser::ast::Condition;
177                stmt.where_clause = Some(WhereClause {
178                    conditions: vec![Condition {
179                        expr: SqlExpression::Column(ColumnRef::unquoted(
180                            "lifted_value".to_string(),
181                        )),
182                        connector: None,
183                    }],
184                });
185            }
186        }
187
188        // Add lifted CTEs to the statement
189        stmt.ctes.extend(lifted_ctes.clone());
190
191        lifted_ctes
192    }
193
194    /// Analyze column alias dependencies (e.g., alias used in PARTITION BY)
195    fn analyze_column_alias_dependencies(
196        &self,
197        stmt: &SelectStatement,
198    ) -> Vec<(String, SqlExpression)> {
199        let mut dependencies = Vec::new();
200
201        // Extract all aliases defined in SELECT
202        let mut aliases = std::collections::HashMap::new();
203        for item in &stmt.select_items {
204            if let SelectItem::Expression { expr, alias } = item {
205                aliases.insert(alias.clone(), expr.clone());
206                tracing::debug!("Found alias: {} -> {:?}", alias, expr);
207            }
208        }
209
210        // Check if any aliases are used in window functions
211        for item in &stmt.select_items {
212            if let SelectItem::Expression { expr, .. } = item {
213                if let SqlExpression::WindowFunction { window_spec, .. } = expr {
214                    // Check PARTITION BY
215                    for col in &window_spec.partition_by {
216                        tracing::debug!("Checking PARTITION BY column: {}", col);
217                        if aliases.contains_key(col) {
218                            tracing::debug!(
219                                "Found dependency: {} depends on {:?}",
220                                col,
221                                aliases[col]
222                            );
223                            dependencies.push((col.clone(), aliases[col].clone()));
224                        }
225                    }
226
227                    // Check ORDER BY
228                    for order_col in &window_spec.order_by {
229                        let col = &order_col.column;
230                        if aliases.contains_key(col) {
231                            dependencies.push((col.clone(), aliases[col].clone()));
232                        }
233                    }
234                }
235            }
236        }
237
238        // Remove duplicates
239        dependencies.sort_by(|a, b| a.0.cmp(&b.0));
240        dependencies.dedup_by(|a, b| a.0 == b.0);
241
242        dependencies
243    }
244
245    /// Lift column aliases to a CTE when they're used in the same SELECT
246    fn lift_column_aliases(
247        &mut self,
248        stmt: &mut SelectStatement,
249        deps: &[(String, SqlExpression)],
250    ) -> CTE {
251        let cte_name = self.next_cte_name();
252
253        // Build CTE that computes the aliased columns
254        let mut cte_select_items = vec![SelectItem::Star];
255        for (alias, expr) in deps {
256            cte_select_items.push(SelectItem::Expression {
257                expr: expr.clone(),
258                alias: alias.clone(),
259            });
260        }
261
262        let cte_select = SelectStatement {
263            distinct: false,
264            columns: vec!["*".to_string()],
265            select_items: cte_select_items,
266            from_table: stmt.from_table.clone(),
267            from_subquery: stmt.from_subquery.clone(),
268            from_function: stmt.from_function.clone(),
269            from_alias: stmt.from_alias.clone(),
270            joins: stmt.joins.clone(),
271            where_clause: stmt.where_clause.clone(),
272            order_by: None,
273            group_by: None,
274            having: None,
275            limit: None,
276            offset: None,
277            ctes: Vec::new(),
278            into_table: None,
279            set_operations: Vec::new(),
280        };
281
282        // Update the main query to use simple column references
283        let mut new_select_items = Vec::new();
284        for item in &stmt.select_items {
285            match item {
286                SelectItem::Expression { expr: _, alias }
287                    if deps.iter().any(|(a, _)| a == alias) =>
288                {
289                    // Replace with simple column reference
290                    new_select_items.push(SelectItem::Column(ColumnRef::unquoted(alias.clone())));
291                }
292                _ => {
293                    new_select_items.push(item.clone());
294                }
295            }
296        }
297
298        stmt.select_items = new_select_items;
299        stmt.from_table = Some(cte_name.clone());
300        stmt.from_subquery = None;
301        stmt.where_clause = None; // Already in the CTE
302
303        CTE {
304            name: cte_name,
305            column_list: None,
306            cte_type: CTEType::Standard(cte_select),
307        }
308    }
309
310    /// Create work units for lifted expressions
311    pub fn create_work_units_for_lifted(
312        &mut self,
313        lifted_ctes: &[CTE],
314        plan: &mut QueryPlan,
315    ) -> Vec<String> {
316        let mut cte_ids = Vec::new();
317
318        for cte in lifted_ctes {
319            let unit_id = format!("cte_{}", cte.name);
320
321            let work_unit = WorkUnit {
322                id: unit_id.clone(),
323                work_type: WorkUnitType::CTE,
324                expression: match &cte.cte_type {
325                    CTEType::Standard(select) => WorkUnitExpression::Select(select.clone()),
326                    CTEType::Web(_) => WorkUnitExpression::Custom("WEB CTE".to_string()),
327                },
328                dependencies: Vec::new(), // CTEs typically don't depend on each other initially
329                parallelizable: true,     // CTEs can often be computed in parallel
330                cost_estimate: None,
331            };
332
333            plan.add_unit(work_unit);
334            cte_ids.push(unit_id);
335        }
336
337        cte_ids
338    }
339}
340
341/// Represents an expression that can be lifted to a CTE
342#[derive(Debug)]
343pub struct LiftableExpression {
344    /// The expression to lift
345    pub expression: SqlExpression,
346
347    /// Suggested name for the CTE
348    pub suggested_name: String,
349
350    /// Dependencies on other CTEs or tables
351    pub dependencies: Vec<String>,
352}
353
354/// Analyze dependencies between expressions
355pub fn analyze_dependencies(expr: &SqlExpression) -> HashSet<String> {
356    let mut deps = HashSet::new();
357
358    match expr {
359        SqlExpression::Column(col) => {
360            deps.insert(col.name.clone());
361        }
362
363        SqlExpression::FunctionCall { args, .. } => {
364            for arg in args {
365                deps.extend(analyze_dependencies(arg));
366            }
367        }
368
369        SqlExpression::WindowFunction {
370            args, window_spec, ..
371        } => {
372            for arg in args {
373                deps.extend(analyze_dependencies(arg));
374            }
375
376            // Add partition and order columns as dependencies
377            for col in &window_spec.partition_by {
378                deps.insert(col.clone());
379            }
380
381            for order_col in &window_spec.order_by {
382                deps.insert(order_col.column.clone());
383            }
384        }
385
386        SqlExpression::BinaryOp { left, right, .. } => {
387            deps.extend(analyze_dependencies(left));
388            deps.extend(analyze_dependencies(right));
389        }
390
391        SqlExpression::CaseExpression {
392            when_branches,
393            else_branch,
394        } => {
395            for branch in when_branches {
396                deps.extend(analyze_dependencies(&branch.condition));
397                deps.extend(analyze_dependencies(&branch.result));
398            }
399
400            if let Some(else_expr) = else_branch {
401                deps.extend(analyze_dependencies(else_expr));
402            }
403        }
404
405        SqlExpression::SimpleCaseExpression {
406            expr,
407            when_branches,
408            else_branch,
409        } => {
410            deps.extend(analyze_dependencies(expr));
411
412            for branch in when_branches {
413                deps.extend(analyze_dependencies(&branch.value));
414                deps.extend(analyze_dependencies(&branch.result));
415            }
416
417            if let Some(else_expr) = else_branch {
418                deps.extend(analyze_dependencies(else_expr));
419            }
420        }
421
422        _ => {}
423    }
424
425    deps
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn test_needs_lifting_window_function() {
434        let lifter = ExpressionLifter::new();
435
436        let window_expr = SqlExpression::WindowFunction {
437            name: "ROW_NUMBER".to_string(),
438            args: vec![],
439            window_spec: crate::sql::parser::ast::WindowSpec {
440                partition_by: vec![],
441                order_by: vec![],
442                frame: None,
443            },
444        };
445
446        assert!(lifter.needs_lifting(&window_expr));
447    }
448
449    #[test]
450    fn test_needs_lifting_simple_expression() {
451        let lifter = ExpressionLifter::new();
452
453        let simple_expr = SqlExpression::BinaryOp {
454            left: Box::new(SqlExpression::Column(ColumnRef::unquoted(
455                "col1".to_string(),
456            ))),
457            op: "=".to_string(),
458            right: Box::new(SqlExpression::NumberLiteral("42".to_string())),
459        };
460
461        assert!(!lifter.needs_lifting(&simple_expr));
462    }
463
464    #[test]
465    fn test_analyze_dependencies() {
466        let expr = SqlExpression::BinaryOp {
467            left: Box::new(SqlExpression::Column(ColumnRef::unquoted(
468                "col1".to_string(),
469            ))),
470            op: "+".to_string(),
471            right: Box::new(SqlExpression::Column(ColumnRef::unquoted(
472                "col2".to_string(),
473            ))),
474        };
475
476        let deps = analyze_dependencies(&expr);
477        assert!(deps.contains("col1"));
478        assert!(deps.contains("col2"));
479        assert_eq!(deps.len(), 2);
480    }
481}