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
7pub struct ExpressionLifter {
9 cte_counter: usize,
11
12 liftable_functions: HashSet<String>,
14}
15
16impl ExpressionLifter {
17 pub fn new() -> Self {
19 let mut liftable_functions = HashSet::new();
20
21 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 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 fn next_cte_name(&mut self) -> String {
43 self.cte_counter += 1;
44 format!("__lifted_{}", self.cte_counter)
45 }
46
47 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 pub fn analyze_where_clause(&mut self, where_clause: &WhereClause) -> Vec<LiftableExpression> {
105 let mut liftable = Vec::new();
106
107 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(), });
115 }
116 }
117
118 liftable
119 }
120
121 pub fn lift_expressions(&mut self, stmt: &mut SelectStatement) -> Vec<CTE> {
123 let mut lifted_ctes = Vec::new();
124
125 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 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 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, order_by: None,
155 group_by: None,
156 having: None,
157 limit: None,
158 offset: None,
159 ctes: Vec::new(),
160 };
161
162 let cte = CTE {
163 name: lift_expr.suggested_name.clone(),
164 column_list: None,
165 cte_type: CTEType::Standard(cte_select),
166 };
167
168 lifted_ctes.push(cte);
169
170 stmt.from_table = Some(lift_expr.suggested_name);
172
173 use crate::sql::parser::ast::Condition;
175 stmt.where_clause = Some(WhereClause {
176 conditions: vec![Condition {
177 expr: SqlExpression::Column(ColumnRef::unquoted(
178 "lifted_value".to_string(),
179 )),
180 connector: None,
181 }],
182 });
183 }
184 }
185
186 stmt.ctes.extend(lifted_ctes.clone());
188
189 lifted_ctes
190 }
191
192 fn analyze_column_alias_dependencies(
194 &self,
195 stmt: &SelectStatement,
196 ) -> Vec<(String, SqlExpression)> {
197 let mut dependencies = Vec::new();
198
199 let mut aliases = std::collections::HashMap::new();
201 for item in &stmt.select_items {
202 if let SelectItem::Expression { expr, alias } = item {
203 aliases.insert(alias.clone(), expr.clone());
204 tracing::debug!("Found alias: {} -> {:?}", alias, expr);
205 }
206 }
207
208 for item in &stmt.select_items {
210 if let SelectItem::Expression { expr, .. } = item {
211 if let SqlExpression::WindowFunction { window_spec, .. } = expr {
212 for col in &window_spec.partition_by {
214 tracing::debug!("Checking PARTITION BY column: {}", col);
215 if aliases.contains_key(col) {
216 tracing::debug!(
217 "Found dependency: {} depends on {:?}",
218 col,
219 aliases[col]
220 );
221 dependencies.push((col.clone(), aliases[col].clone()));
222 }
223 }
224
225 for order_col in &window_spec.order_by {
227 let col = &order_col.column;
228 if aliases.contains_key(col) {
229 dependencies.push((col.clone(), aliases[col].clone()));
230 }
231 }
232 }
233 }
234 }
235
236 dependencies.sort_by(|a, b| a.0.cmp(&b.0));
238 dependencies.dedup_by(|a, b| a.0 == b.0);
239
240 dependencies
241 }
242
243 fn lift_column_aliases(
245 &mut self,
246 stmt: &mut SelectStatement,
247 deps: &[(String, SqlExpression)],
248 ) -> CTE {
249 let cte_name = self.next_cte_name();
250
251 let mut cte_select_items = vec![SelectItem::Star];
253 for (alias, expr) in deps {
254 cte_select_items.push(SelectItem::Expression {
255 expr: expr.clone(),
256 alias: alias.clone(),
257 });
258 }
259
260 let cte_select = SelectStatement {
261 distinct: false,
262 columns: vec!["*".to_string()],
263 select_items: cte_select_items,
264 from_table: stmt.from_table.clone(),
265 from_subquery: stmt.from_subquery.clone(),
266 from_function: stmt.from_function.clone(),
267 from_alias: stmt.from_alias.clone(),
268 joins: stmt.joins.clone(),
269 where_clause: stmt.where_clause.clone(),
270 order_by: None,
271 group_by: None,
272 having: None,
273 limit: None,
274 offset: None,
275 ctes: Vec::new(),
276 };
277
278 let mut new_select_items = Vec::new();
280 for item in &stmt.select_items {
281 match item {
282 SelectItem::Expression { expr: _, alias }
283 if deps.iter().any(|(a, _)| a == alias) =>
284 {
285 new_select_items.push(SelectItem::Column(ColumnRef::unquoted(alias.clone())));
287 }
288 _ => {
289 new_select_items.push(item.clone());
290 }
291 }
292 }
293
294 stmt.select_items = new_select_items;
295 stmt.from_table = Some(cte_name.clone());
296 stmt.from_subquery = None;
297 stmt.where_clause = None; CTE {
300 name: cte_name,
301 column_list: None,
302 cte_type: CTEType::Standard(cte_select),
303 }
304 }
305
306 pub fn create_work_units_for_lifted(
308 &mut self,
309 lifted_ctes: &[CTE],
310 plan: &mut QueryPlan,
311 ) -> Vec<String> {
312 let mut cte_ids = Vec::new();
313
314 for cte in lifted_ctes {
315 let unit_id = format!("cte_{}", cte.name);
316
317 let work_unit = WorkUnit {
318 id: unit_id.clone(),
319 work_type: WorkUnitType::CTE,
320 expression: match &cte.cte_type {
321 CTEType::Standard(select) => WorkUnitExpression::Select(select.clone()),
322 CTEType::Web(_) => WorkUnitExpression::Custom("WEB CTE".to_string()),
323 },
324 dependencies: Vec::new(), parallelizable: true, cost_estimate: None,
327 };
328
329 plan.add_unit(work_unit);
330 cte_ids.push(unit_id);
331 }
332
333 cte_ids
334 }
335}
336
337#[derive(Debug)]
339pub struct LiftableExpression {
340 pub expression: SqlExpression,
342
343 pub suggested_name: String,
345
346 pub dependencies: Vec<String>,
348}
349
350pub fn analyze_dependencies(expr: &SqlExpression) -> HashSet<String> {
352 let mut deps = HashSet::new();
353
354 match expr {
355 SqlExpression::Column(col) => {
356 deps.insert(col.name.clone());
357 }
358
359 SqlExpression::FunctionCall { args, .. } => {
360 for arg in args {
361 deps.extend(analyze_dependencies(arg));
362 }
363 }
364
365 SqlExpression::WindowFunction {
366 args, window_spec, ..
367 } => {
368 for arg in args {
369 deps.extend(analyze_dependencies(arg));
370 }
371
372 for col in &window_spec.partition_by {
374 deps.insert(col.clone());
375 }
376
377 for order_col in &window_spec.order_by {
378 deps.insert(order_col.column.clone());
379 }
380 }
381
382 SqlExpression::BinaryOp { left, right, .. } => {
383 deps.extend(analyze_dependencies(left));
384 deps.extend(analyze_dependencies(right));
385 }
386
387 SqlExpression::CaseExpression {
388 when_branches,
389 else_branch,
390 } => {
391 for branch in when_branches {
392 deps.extend(analyze_dependencies(&branch.condition));
393 deps.extend(analyze_dependencies(&branch.result));
394 }
395
396 if let Some(else_expr) = else_branch {
397 deps.extend(analyze_dependencies(else_expr));
398 }
399 }
400
401 SqlExpression::SimpleCaseExpression {
402 expr,
403 when_branches,
404 else_branch,
405 } => {
406 deps.extend(analyze_dependencies(expr));
407
408 for branch in when_branches {
409 deps.extend(analyze_dependencies(&branch.value));
410 deps.extend(analyze_dependencies(&branch.result));
411 }
412
413 if let Some(else_expr) = else_branch {
414 deps.extend(analyze_dependencies(else_expr));
415 }
416 }
417
418 _ => {}
419 }
420
421 deps
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 #[test]
429 fn test_needs_lifting_window_function() {
430 let lifter = ExpressionLifter::new();
431
432 let window_expr = SqlExpression::WindowFunction {
433 name: "ROW_NUMBER".to_string(),
434 args: vec![],
435 window_spec: crate::sql::parser::ast::WindowSpec {
436 partition_by: vec![],
437 order_by: vec![],
438 frame: None,
439 },
440 };
441
442 assert!(lifter.needs_lifting(&window_expr));
443 }
444
445 #[test]
446 fn test_needs_lifting_simple_expression() {
447 let lifter = ExpressionLifter::new();
448
449 let simple_expr = SqlExpression::BinaryOp {
450 left: Box::new(SqlExpression::Column(ColumnRef::unquoted(
451 "col1".to_string(),
452 ))),
453 op: "=".to_string(),
454 right: Box::new(SqlExpression::NumberLiteral("42".to_string())),
455 };
456
457 assert!(!lifter.needs_lifting(&simple_expr));
458 }
459
460 #[test]
461 fn test_analyze_dependencies() {
462 let expr = SqlExpression::BinaryOp {
463 left: Box::new(SqlExpression::Column(ColumnRef::unquoted(
464 "col1".to_string(),
465 ))),
466 op: "+".to_string(),
467 right: Box::new(SqlExpression::Column(ColumnRef::unquoted(
468 "col2".to_string(),
469 ))),
470 };
471
472 let deps = analyze_dependencies(&expr);
473 assert!(deps.contains("col1"));
474 assert!(deps.contains("col2"));
475 assert_eq!(deps.len(), 2);
476 }
477}