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