Skip to main content

mz_transform/
case_literal.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Rewrites chains of `If(Eq(expr, literal), result, If(...))` into
11//! `CallVariadic { func: CaseLiteral { lookup, return_type }, exprs }` for
12//! O(log n) evaluation via `BTreeMap` lookup.
13//!
14//! Uses the `ReprRelationType` analysis to obtain column types in O(n),
15//! avoiding repeated `input.typ()` calls. Each scalar is then visited
16//! bottom-up so inner CaseLiterals are created first, then outer If nodes
17//! fold into them.
18
19use 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/// Rewrites If-chains matching a single expression against literals
30/// into a `CaseLiteral` variadic function with `BTreeMap` lookup.
31#[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        // Pre-compute column types for all nodes in a single pass.
50        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                    // Use the output type (includes scalars' types).
59                    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    /// Rewrites a scalar expression tree bottom-up, replacing If-chains of
145    /// `If(Eq(common_candidate, literal), result, ...)` with `CaseLiteral`.
146    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
158/// Fold rule: if node is `If(Eq(x, lit), res, CallVariadic(CaseLiteral{..}, [x, ...]))`
159/// where the CaseLiteral's input (`exprs[0]`) structurally equals `x`, insert (or
160/// overwrite) `res` into the existing CaseLiteral.
161///
162/// Because we traverse bottom-up, the current If is an *earlier* arm than anything
163/// already in the CaseLiteral. For duplicates, the outer/earlier arm wins per SQL
164/// CASE semantics, so we overwrite the existing entry.
165fn 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    // Check that the CaseLiteral's input matches the If's common expression.
181    if exprs[0] != *common_candidate {
182        return;
183    }
184
185    // Widen `return_type` to the type of the replaced If, else a nullable `then` would leave the
186    // CaseLiteral typed as non-nullable.
187    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        // Duplicate literal: overwrite with the earlier arm's result (this If).
194        exprs[existing_idx] = then.take();
195    } else {
196        // New literal: insert before the fallback (last position).
197        let new_idx = exprs.len() - 1;
198        exprs.insert(new_idx, then.take());
199        cl.insert(literal_row.clone(), new_idx);
200    }
201
202    // Replace the If with the CaseLiteral.
203    *expr = els.take();
204}
205
206/// Chain-walk rule: if node is an If-chain with >= 2 consecutive arms matching
207/// `Eq(same_expr, literal)`, create a new CaseLiteral.
208fn try_create_case_literal(expr: &mut MirScalarExpr, column_types: &[ReprColumnType]) {
209    if !has_at_least_two_arms(expr) {
210        return;
211    }
212
213    // Take the expression and dismantle it.
214    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    // Compute the return type as the union of all branch types and els type.
220    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    // Build the exprs vector: [input, result1, result2, ..., els]
236    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
255/// Returns `true` if the If-chain has at least 2 arms matching `Eq(same_expr, literal)`.
256/// Bails early once 2 are found to avoid unnecessary traversal.
257fn 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
292/// Inspects an `Eq(expr, literal)` condition and returns references to the
293/// non-literal expression and the literal `Row`.
294/// Returns `(non_literal_expr_ref, literal_row_ref)`.
295fn 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
318/// Walks an If-chain and collects `(literal_row, result_expr)` pairs.
319///
320/// The input `chain` is consumed and dismantled.
321/// Returns `(cases, common_candidate, els)`.
322fn 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                    // First occurrence of each literal wins (SQL CASE semantics).
351                    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    /// Helper: build an i64 literal.
377    fn lit_i64(v: i64) -> MirScalarExpr {
378        MirScalarExpr::literal_ok(Datum::Int64(v), ReprScalarType::Int64)
379    }
380
381    /// Wrap a scalar expression in a `Map` over a constant to allow applying the transform.
382    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    /// Apply the CaseLiteralTransform to a relation and return the first scalar from the Map.
396    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    /// Verify that the result is a CaseLiteral with the expected number of cases.
413    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    // Build a CASE-like If-chain: CASE #0 WHEN 1 THEN 10 WHEN 2 THEN 20 ELSE 0 END
431    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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
444    fn test_null_literal_skipped() {
445        // If(Eq(#0, NULL::int64), 10, If(Eq(#0, 2), 20, If(Eq(#0, 3), 30, 0)))
446        // The NULL arm breaks the chain at the top level because
447        // peek_eq_literal skips NULL literals, so arm1 doesn't match.
448        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        // The NULL arm breaks the chain at the top level. The inner 2 arms
464        // (comparing #0 to 2 and 3) should still be converted.
465        // With bottom-up, the inner chain becomes a CaseLiteral first.
466        // Then the outer If(Eq(#0, NULL), 10, CaseLiteral) has a CaseLiteral
467        // in els, but the cond is Eq(#0, NULL) which is not a valid literal
468        // (NULL is skipped), so the fold rule doesn't fire.
469        // Result: If(Eq(#0, NULL), 10, CaseLiteral(...))
470        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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
480    fn test_64_arm_chain() {
481        // Build a 64-arm If-chain and verify it converts to a single CaseLiteral.
482        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        // Spot-check evaluation.
494        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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
515    fn test_eval_basic() {
516        // Verify that evaluating the CaseLiteral produces correct results.
517        let expr = build_2_arm_chain();
518        let result = apply_transform(expr);
519
520        let arena = mz_repr::RowArena::new();
521
522        // Input = 1 → output should be 10
523        let out = result.eval(&[Datum::Int64(1)], &arena).unwrap();
524        assert_eq!(out, Datum::Int64(10));
525
526        // Input = 2 → output should be 20
527        let out = result.eval(&[Datum::Int64(2)], &arena).unwrap();
528        assert_eq!(out, Datum::Int64(20));
529
530        // Input = 99 → output should be 0 (els)
531        let out = result.eval(&[Datum::Int64(99)], &arena).unwrap();
532        assert_eq!(out, Datum::Int64(0));
533
534        // Input = NULL → output should be 0 (els, since NULL = x is falsy)
535        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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
541    fn test_string_literals() {
542        // CASE #0 WHEN 'a' THEN 1 WHEN 'b' THEN 2 ELSE 0 END
543        // Verify that non-i64 literal types also work.
544        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}