1use std::collections::BTreeSet;
20
21use itertools::Itertools;
22use mz_expr::visit::Visit;
23use mz_expr::{BinaryFunc, MirRelationExpr, MirScalarExpr, VariadicFunc};
24use mz_repr::{ReprColumnType, Row, SqlColumnType};
25
26use crate::analysis::{DerivedBuilder, ReprRelationType};
27use crate::{Transform, TransformCtx, TransformError};
28
29#[derive(Debug)]
32pub struct CaseLiteralTransform;
33
34impl Transform for CaseLiteralTransform {
35 fn name(&self) -> &'static str {
36 "CaseLiteralTransform"
37 }
38
39 #[mz_ore::instrument(
40 target = "optimizer",
41 level = "debug",
42 fields(path.segment = "case_literal")
43 )]
44 fn actually_perform_transform(
45 &self,
46 relation: &mut MirRelationExpr,
47 ctx: &mut TransformCtx,
48 ) -> Result<(), TransformError> {
49 let mut builder = DerivedBuilder::new(ctx.features);
51 builder.require(ReprRelationType);
52 let derived = builder.visit(&*relation);
53
54 let mut todo = vec![(&mut *relation, derived.as_view())];
55 while let Some((expr, view)) = todo.pop() {
56 match expr {
57 MirRelationExpr::Map { scalars, .. } => {
58 let output_type: &Vec<ReprColumnType> = view
60 .value::<ReprRelationType>()
61 .expect("ReprRelationType required")
62 .as_ref()
63 .unwrap();
64 let input_arity = output_type.len() - scalars.len();
65 for (index, scalar) in scalars.iter_mut().enumerate() {
66 Self::rewrite_scalar(scalar, &output_type[..input_arity + index])?;
67 }
68 }
69 MirRelationExpr::Filter { predicates, .. } => {
70 let input_type: &Vec<ReprColumnType> = view
71 .last_child()
72 .value::<ReprRelationType>()
73 .expect("ReprRelationType required")
74 .as_ref()
75 .unwrap();
76 for predicate in predicates.iter_mut() {
77 Self::rewrite_scalar(predicate, input_type)?;
78 }
79 }
80 MirRelationExpr::Reduce { aggregates, .. } => {
81 let input_type: &Vec<ReprColumnType> = view
82 .last_child()
83 .value::<ReprRelationType>()
84 .expect("ReprRelationType required")
85 .as_ref()
86 .unwrap();
87 for agg in aggregates.iter_mut() {
88 Self::rewrite_scalar(&mut agg.expr, input_type)?;
89 }
90 }
91 MirRelationExpr::FlatMap { exprs, .. } => {
92 let input_type: &Vec<ReprColumnType> = view
93 .last_child()
94 .value::<ReprRelationType>()
95 .expect("ReprRelationType required")
96 .as_ref()
97 .unwrap();
98 for e in exprs.iter_mut() {
99 Self::rewrite_scalar(e, input_type)?;
100 }
101 }
102 MirRelationExpr::Join { equivalences, .. } => {
103 let mut children: Vec<_> = view.children_rev().collect::<Vec<_>>();
104 children.reverse();
105 let input_types: Vec<ReprColumnType> = children
106 .iter()
107 .flat_map(|c| {
108 c.value::<ReprRelationType>()
109 .expect("ReprRelationType required")
110 .as_ref()
111 .unwrap()
112 .iter()
113 .cloned()
114 })
115 .collect();
116 for class in equivalences.iter_mut() {
117 for expr in class.iter_mut() {
118 Self::rewrite_scalar(expr, &input_types)?;
119 }
120 }
121 }
122 MirRelationExpr::TopK { limit, .. } => {
123 let input_type: &Vec<ReprColumnType> = view
124 .last_child()
125 .value::<ReprRelationType>()
126 .expect("ReprRelationType required")
127 .as_ref()
128 .unwrap();
129 if let Some(limit) = limit {
130 Self::rewrite_scalar(limit, input_type)?;
131 }
132 }
133 _ => {}
134 }
135 todo.extend(expr.children_mut().rev().zip_eq(view.children_rev()));
136 }
137
138 mz_repr::explain::trace_plan(&*relation);
139 Ok(())
140 }
141}
142
143impl CaseLiteralTransform {
144 fn rewrite_scalar(
147 expr: &mut MirScalarExpr,
148 column_types: &[ReprColumnType],
149 ) -> Result<(), TransformError> {
150 expr.try_visit_mut_post(&mut |node: &mut MirScalarExpr| {
151 try_fold_into_case_literal(node, column_types);
152 try_create_case_literal(node, column_types);
153 Ok(())
154 })
155 }
156}
157
158fn try_fold_into_case_literal(expr: &mut MirScalarExpr, column_types: &[ReprColumnType]) {
166 let MirScalarExpr::If { cond, then, els } = expr else {
167 return;
168 };
169 let Some((common_candidate, literal_row)) = peek_eq_literal(cond) else {
170 return;
171 };
172 let MirScalarExpr::CallVariadic {
173 func: VariadicFunc::CaseLiteral(cl),
174 exprs,
175 } = els.as_mut()
176 else {
177 return;
178 };
179
180 if exprs[0] != *common_candidate {
182 return;
183 }
184
185 let return_type = ReprColumnType::from(&cl.return_type)
188 .union(&then.typ(column_types))
189 .expect("incompatible branch types");
190 cl.return_type = SqlColumnType::from_repr(&return_type);
191
192 if let Some(existing_idx) = cl.get(literal_row) {
193 exprs[existing_idx] = then.take();
195 } else {
196 let new_idx = exprs.len() - 1;
198 exprs.insert(new_idx, then.take());
199 cl.insert(literal_row.clone(), new_idx);
200 }
201
202 *expr = els.take();
204}
205
206fn try_create_case_literal(expr: &mut MirScalarExpr, column_types: &[ReprColumnType]) {
209 if !has_at_least_two_arms(expr) {
210 return;
211 }
212
213 let chain = expr.take();
215 let (collected_cases, common, els) = collect_if_chain_arms(chain);
216
217 let common = common.expect("common expr must be set when arm_count >= 2");
218
219 let mut return_type: Option<ReprColumnType> = None;
221 for (_, result) in &collected_cases {
222 let t = result.typ(column_types);
223 return_type = Some(match return_type {
224 None => t,
225 Some(prev) => prev.union(&t).expect("incompatible branch types"),
226 });
227 }
228 let els_type = els.typ(column_types);
229 let return_type = match return_type {
230 Some(prev) => prev.union(&els_type).expect("incompatible else type"),
231 None => els_type,
232 };
233 let sql_return_type = SqlColumnType::from_repr(&return_type);
234
235 let mut exprs = Vec::with_capacity(collected_cases.len() + 2);
237 exprs.push(common);
238 let mut cl = mz_expr::func::CaseLiteral {
239 lookup: Vec::with_capacity(collected_cases.len()),
240 return_type: sql_return_type,
241 };
242 for (row, result_expr) in collected_cases {
243 let idx = exprs.len();
244 cl.insert(row, idx);
245 exprs.push(result_expr);
246 }
247 exprs.push(els);
248
249 *expr = MirScalarExpr::CallVariadic {
250 func: VariadicFunc::CaseLiteral(cl),
251 exprs,
252 };
253}
254
255fn has_at_least_two_arms(expr: &MirScalarExpr) -> bool {
258 let mut count = 0;
259 let mut common_candidate: Option<&MirScalarExpr> = None;
260 let mut current = expr;
261
262 loop {
263 match current {
264 MirScalarExpr::If { cond, then: _, els } => {
265 if let Some((expr_side, _literal_row)) = peek_eq_literal(cond) {
266 match common_candidate {
267 None => {
268 common_candidate = Some(expr_side);
269 }
270 Some(existing) => {
271 if existing != expr_side {
272 break;
273 }
274 }
275 }
276 count += 1;
277 if count >= 2 {
278 return true;
279 }
280 current = els;
281 } else {
282 break;
283 }
284 }
285 _ => break,
286 }
287 }
288
289 false
290}
291
292fn peek_eq_literal(cond: &MirScalarExpr) -> Option<(&MirScalarExpr, &Row)> {
296 let MirScalarExpr::CallBinary {
297 func: BinaryFunc::Eq(_),
298 expr1,
299 expr2,
300 } = cond
301 else {
302 return None;
303 };
304
305 if let Some(row) = expr1.as_literal_non_null_row() {
306 if !expr2.is_literal() {
307 return Some((expr2.as_ref(), row));
308 }
309 }
310 if let Some(row) = expr2.as_literal_non_null_row() {
311 if !expr1.is_literal() {
312 return Some((expr1.as_ref(), row));
313 }
314 }
315 None
316}
317
318fn collect_if_chain_arms(
323 chain: MirScalarExpr,
324) -> (
325 Vec<(Row, MirScalarExpr)>,
326 Option<MirScalarExpr>,
327 MirScalarExpr,
328) {
329 let mut cases = Vec::new();
330 let mut seen = BTreeSet::new();
331 let mut common_candidate: Option<MirScalarExpr> = None;
332 let mut remaining = chain;
333
334 loop {
335 match remaining {
336 MirScalarExpr::If { cond, then, els } => {
337 if let Some((expr_side, literal_row)) = peek_eq_literal(&cond) {
338 match &common_candidate {
339 None => {
340 common_candidate = Some(expr_side.clone());
341 }
342 Some(existing) => {
343 if existing != expr_side {
344 remaining = MirScalarExpr::If { cond, then, els };
345 break;
346 }
347 }
348 }
349
350 if seen.insert(literal_row.clone()) {
352 cases.push((literal_row.clone(), *then));
353 }
354
355 remaining = *els;
356 } else {
357 remaining = MirScalarExpr::If { cond, then, els };
358 break;
359 }
360 }
361 _ => break,
362 }
363 }
364
365 (cases, common_candidate, remaining)
366}
367
368#[cfg(test)]
369mod tests {
370 use mz_expr::func::Eq;
371 use mz_expr::{Eval, MirRelationExpr, MirScalarExpr, VariadicFunc};
372 use mz_repr::{Datum, ReprColumnType, ReprRelationType, ReprScalarType};
373
374 use super::*;
375
376 fn lit_i64(v: i64) -> MirScalarExpr {
378 MirScalarExpr::literal_ok(Datum::Int64(v), ReprScalarType::Int64)
379 }
380
381 fn wrap_in_map(scalar: MirScalarExpr) -> MirRelationExpr {
383 MirRelationExpr::Map {
384 input: Box::new(MirRelationExpr::constant(
385 vec![vec![Datum::Int64(0)]],
386 ReprRelationType::new(vec![ReprColumnType {
387 scalar_type: ReprScalarType::Int64,
388 nullable: false,
389 }]),
390 )),
391 scalars: vec![scalar],
392 }
393 }
394
395 fn apply_transform(scalar: MirScalarExpr) -> MirScalarExpr {
397 let mut relation = wrap_in_map(scalar);
398 let mut features = mz_repr::optimize::OptimizerFeatures::default();
399 features.enable_case_literal_transform = true;
400 let typecheck_ctx = crate::typecheck::empty_typechecking_context();
401 let mut df_meta = crate::dataflow::DataflowMetainfo::default();
402 let mut transform_ctx =
403 crate::TransformCtx::local(&features, &typecheck_ctx, &mut df_meta, None, None);
404 crate::Transform::transform(&CaseLiteralTransform, &mut relation, &mut transform_ctx)
405 .unwrap();
406 match relation {
407 MirRelationExpr::Map { scalars, .. } => scalars.into_iter().next().unwrap(),
408 other => panic!("expected Map, got {other:?}"),
409 }
410 }
411
412 fn assert_case_literal(expr: &MirScalarExpr, expected_cases: usize) {
414 match expr {
415 MirScalarExpr::CallVariadic {
416 func: VariadicFunc::CaseLiteral(cl),
417 ..
418 } => {
419 assert_eq!(
420 cl.lookup.len(),
421 expected_cases,
422 "expected {expected_cases} cases, got {}",
423 cl.lookup.len()
424 );
425 }
426 other => panic!("expected CaseLiteral, got {other:?}"),
427 }
428 }
429
430 fn build_2_arm_chain() -> MirScalarExpr {
432 MirScalarExpr::column(0)
433 .call_binary(lit_i64(1), Eq)
434 .if_then_else(
435 lit_i64(10),
436 MirScalarExpr::column(0)
437 .call_binary(lit_i64(2), Eq)
438 .if_then_else(lit_i64(20), lit_i64(0)),
439 )
440 }
441
442 #[mz_ore::test]
443 #[cfg_attr(miri, ignore)] fn test_null_literal_skipped() {
445 let null_lit = MirScalarExpr::literal(Ok(Datum::Null), ReprScalarType::Int64);
449 let expr = MirScalarExpr::column(0)
450 .call_binary(null_lit, Eq)
451 .if_then_else(
452 lit_i64(10),
453 MirScalarExpr::column(0)
454 .call_binary(lit_i64(2), Eq)
455 .if_then_else(
456 lit_i64(20),
457 MirScalarExpr::column(0)
458 .call_binary(lit_i64(3), Eq)
459 .if_then_else(lit_i64(30), lit_i64(0)),
460 ),
461 );
462 let result = apply_transform(expr);
463 match &result {
471 MirScalarExpr::If { els, .. } => {
472 assert_case_literal(els, 2);
473 }
474 other => panic!("expected If with CaseLiteral in els, got {other:?}"),
475 }
476 }
477
478 #[mz_ore::test]
479 #[cfg_attr(miri, ignore)] fn test_64_arm_chain() {
481 let n: usize = 64;
483 let mut expr = lit_i64(-1);
484 for i in (0..n).rev() {
485 let i = i64::try_from(i).expect("arm index fits in i64");
486 expr = MirScalarExpr::column(0)
487 .call_binary(lit_i64(i), Eq)
488 .if_then_else(lit_i64(100 * i), expr);
489 }
490 let result = apply_transform(expr);
491 assert_case_literal(&result, n);
492
493 let arena = mz_repr::RowArena::new();
495 assert_eq!(
496 result.eval(&[Datum::Int64(0)], &arena).unwrap(),
497 Datum::Int64(0)
498 );
499 assert_eq!(
500 result.eval(&[Datum::Int64(32)], &arena).unwrap(),
501 Datum::Int64(3200)
502 );
503 assert_eq!(
504 result.eval(&[Datum::Int64(63)], &arena).unwrap(),
505 Datum::Int64(6300)
506 );
507 assert_eq!(
508 result.eval(&[Datum::Int64(999)], &arena).unwrap(),
509 Datum::Int64(-1)
510 );
511 }
512
513 #[mz_ore::test]
514 #[cfg_attr(miri, ignore)] fn test_eval_basic() {
516 let expr = build_2_arm_chain();
518 let result = apply_transform(expr);
519
520 let arena = mz_repr::RowArena::new();
521
522 let out = result.eval(&[Datum::Int64(1)], &arena).unwrap();
524 assert_eq!(out, Datum::Int64(10));
525
526 let out = result.eval(&[Datum::Int64(2)], &arena).unwrap();
528 assert_eq!(out, Datum::Int64(20));
529
530 let out = result.eval(&[Datum::Int64(99)], &arena).unwrap();
532 assert_eq!(out, Datum::Int64(0));
533
534 let out = result.eval(&[Datum::Null], &arena).unwrap();
536 assert_eq!(out, Datum::Int64(0));
537 }
538
539 #[mz_ore::test]
540 #[cfg_attr(miri, ignore)] fn test_string_literals() {
542 fn lit_str(s: &str) -> MirScalarExpr {
545 MirScalarExpr::literal_ok(Datum::String(s), ReprScalarType::String)
546 }
547 fn wrap_in_string_map(scalar: MirScalarExpr) -> MirRelationExpr {
548 MirRelationExpr::Map {
549 input: Box::new(MirRelationExpr::constant(
550 vec![vec![Datum::String("x")]],
551 ReprRelationType::new(vec![ReprColumnType {
552 scalar_type: ReprScalarType::String,
553 nullable: false,
554 }]),
555 )),
556 scalars: vec![scalar],
557 }
558 }
559 let expr = MirScalarExpr::column(0)
560 .call_binary(lit_str("a"), Eq)
561 .if_then_else(
562 lit_i64(1),
563 MirScalarExpr::column(0)
564 .call_binary(lit_str("b"), Eq)
565 .if_then_else(lit_i64(2), lit_i64(0)),
566 );
567 let mut relation = wrap_in_string_map(expr);
568 let mut features = mz_repr::optimize::OptimizerFeatures::default();
569 features.enable_case_literal_transform = true;
570 let typecheck_ctx = crate::typecheck::empty_typechecking_context();
571 let mut df_meta = crate::dataflow::DataflowMetainfo::default();
572 let mut transform_ctx =
573 crate::TransformCtx::local(&features, &typecheck_ctx, &mut df_meta, None, None);
574 crate::Transform::transform(&CaseLiteralTransform, &mut relation, &mut transform_ctx)
575 .unwrap();
576 let result = match relation {
577 MirRelationExpr::Map { scalars, .. } => scalars.into_iter().next().unwrap(),
578 other => panic!("expected Map, got {other:?}"),
579 };
580 assert_case_literal(&result, 2);
581
582 let arena = mz_repr::RowArena::new();
583 assert_eq!(
584 result.eval(&[Datum::String("a")], &arena).unwrap(),
585 Datum::Int64(1)
586 );
587 assert_eq!(
588 result.eval(&[Datum::String("b")], &arena).unwrap(),
589 Datum::Int64(2)
590 );
591 assert_eq!(
592 result.eval(&[Datum::String("z")], &arena).unwrap(),
593 Datum::Int64(0)
594 );
595 }
596}