Skip to main content

vortex_functions/
case_when.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! SQL-style CASE WHEN: evaluates `(condition, value)` pairs in order and returns
5//! the value from the first matching condition (first-match-wins). NULL conditions
6//! are treated as false. If no ELSE clause is provided, unmatched rows produce NULL;
7//! otherwise they get the ELSE value.
8//!
9//! Unlike SQL which coerces all branches to a common supertype, all THEN/ELSE
10//! branches must share the same base dtype (ignoring nullability). The result
11//! nullability is the union of all branches (forced nullable if no ELSE).
12//!
13//! The serialized expression format is not part of a Vortex edition and is not
14//! guaranteed to remain compatible across Vortex versions.
15
16use std::fmt;
17use std::fmt::Formatter;
18use std::hash::Hash;
19use std::sync::Arc;
20
21use prost::Message;
22use vortex_array::ArrayRef;
23use vortex_array::ExecutionCtx;
24use vortex_array::IntoArray;
25use vortex_array::arrays::BoolArray;
26use vortex_array::arrays::ConstantArray;
27use vortex_array::arrays::bool::BoolArrayExt;
28use vortex_array::builders::builder_with_capacity_in;
29use vortex_array::builtins::ArrayBuiltins;
30use vortex_array::dtype::DType;
31use vortex_array::optimizer::ArrayOptimizer;
32use vortex_array::proto::expr as pb;
33use vortex_array::scalar::Scalar;
34use vortex_array::scalar_fn::Arity;
35use vortex_array::scalar_fn::ChildName;
36use vortex_array::scalar_fn::EmptyOptions;
37use vortex_array::scalar_fn::ExecutionArgs;
38use vortex_array::scalar_fn::ReduceNode;
39use vortex_array::scalar_fn::ScalarFnId;
40use vortex_array::scalar_fn::ScalarFnRef;
41use vortex_array::scalar_fn::ScalarFnVTable;
42use vortex_array::scalar_fn::ScalarFnVTableExt;
43use vortex_array::scalar_fn::builtin::fill_null::FillNull;
44use vortex_array::scalar_fn::builtin::is_not_null::IsNotNull;
45use vortex_array::scalar_fn::display::ExprDisplay;
46use vortex_buffer::BufferMut;
47use vortex_error::VortexResult;
48use vortex_error::vortex_bail;
49use vortex_error::vortex_ensure;
50use vortex_mask::AllOr;
51use vortex_mask::Mask;
52use vortex_session::VortexSession;
53use vortex_session::registry::CachedId;
54
55use crate::is_null::IsNull;
56use crate::zip::zip_nullability_union;
57
58/// Options for the n-ary CaseWhen expression.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct CaseWhenOptions {
61    /// Number of WHEN/THEN pairs.
62    pub num_when_then_pairs: u32,
63    /// Whether an ELSE clause is present.
64    /// If false, unmatched rows return NULL.
65    pub has_else: bool,
66}
67
68impl CaseWhenOptions {
69    /// Total number of child expressions: 2 per WHEN/THEN pair, plus 1 if ELSE is present.
70    pub fn num_children(&self) -> usize {
71        self.num_when_then_pairs as usize * 2 + usize::from(self.has_else)
72    }
73}
74
75impl fmt::Display for CaseWhenOptions {
76    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77        write!(
78            f,
79            "case_when(pairs={}, else={})",
80            self.num_when_then_pairs, self.has_else
81        )
82    }
83}
84
85/// An n-ary CASE WHEN expression.
86///
87/// Children are in order: `[when_0, then_0, when_1, then_1, ..., else?]`.
88#[derive(Clone)]
89pub struct CaseWhen;
90
91impl ScalarFnVTable for CaseWhen {
92    type Options = CaseWhenOptions;
93
94    fn id(&self) -> ScalarFnId {
95        static ID: CachedId = CachedId::new("vortex.case_when");
96        *ID
97    }
98
99    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
100        vortex_ensure!(
101            options.num_when_then_pairs > 0,
102            "CaseWhen must have at least one WHEN/THEN pair"
103        );
104        let Some(num_children) = options
105            .num_when_then_pairs
106            .checked_mul(2)
107            .and_then(|count| count.checked_add(u32::from(options.has_else)))
108        else {
109            vortex_bail!("CaseWhen has too many children to serialize");
110        };
111        Ok(Some(pb::CaseWhenOpts { num_children }.encode_to_vec()))
112    }
113
114    fn deserialize(
115        &self,
116        metadata: &[u8],
117        _session: &VortexSession,
118    ) -> VortexResult<Self::Options> {
119        let opts = pb::CaseWhenOpts::decode(metadata)?;
120        if opts.num_children < 2 {
121            vortex_bail!(
122                "CaseWhen expects at least 2 children, got {}",
123                opts.num_children
124            );
125        }
126        Ok(CaseWhenOptions {
127            num_when_then_pairs: opts.num_children / 2,
128            has_else: opts.num_children % 2 == 1,
129        })
130    }
131
132    fn arity(&self, options: &Self::Options) -> Arity {
133        Arity::Exact(options.num_children())
134    }
135
136    fn child_name(&self, options: &Self::Options, child_idx: usize) -> ChildName {
137        let num_pair_children = options.num_when_then_pairs as usize * 2;
138        if child_idx < num_pair_children {
139            let pair_idx = child_idx / 2;
140            if child_idx.is_multiple_of(2) {
141                ChildName::from(Arc::from(format!("when_{pair_idx}")))
142            } else {
143                ChildName::from(Arc::from(format!("then_{pair_idx}")))
144            }
145        } else if options.has_else && child_idx == num_pair_children {
146            ChildName::from("else")
147        } else {
148            unreachable!("Invalid child index {} for CaseWhen", child_idx)
149        }
150    }
151
152    fn fmt_sql(
153        &self,
154        options: &Self::Options,
155        expr: &dyn ExprDisplay,
156        f: &mut Formatter<'_>,
157    ) -> fmt::Result {
158        write!(f, "CASE")?;
159        for i in 0..options.num_when_then_pairs as usize {
160            write!(
161                f,
162                " WHEN {} THEN {}",
163                expr.display_child(i * 2),
164                expr.display_child(i * 2 + 1)
165            )?;
166        }
167        if options.has_else {
168            let else_idx = options.num_when_then_pairs as usize * 2;
169            write!(f, " ELSE {}", expr.display_child(else_idx))?;
170        }
171        write!(f, " END")
172    }
173
174    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
175        if options.num_when_then_pairs == 0 {
176            vortex_bail!("CaseWhen must have at least one WHEN/THEN pair");
177        }
178
179        let expected_len = options.num_children();
180        if arg_dtypes.len() != expected_len {
181            vortex_bail!(
182                "CaseWhen expects {expected_len} argument dtypes, got {}",
183                arg_dtypes.len()
184            );
185        }
186
187        // Unlike SQL which coerces all branches to a common supertype, we require
188        // all THEN/ELSE branches to have the same base dtype (ignoring nullability).
189        // The result nullability is the union of all branches, at every nesting level.
190        let first_then = &arg_dtypes[1];
191        let mut result_dtype = first_then.clone();
192
193        for i in 1..options.num_when_then_pairs as usize {
194            let then_i = &arg_dtypes[i * 2 + 1];
195            let Some(union) = zip_nullability_union(&result_dtype, then_i) else {
196                vortex_bail!(
197                    "CaseWhen THEN dtypes must match (ignoring nullability), got {} and {}",
198                    first_then,
199                    then_i
200                );
201            };
202            result_dtype = union;
203        }
204
205        if options.has_else {
206            let else_dtype = &arg_dtypes[options.num_when_then_pairs as usize * 2];
207            let Some(union) = zip_nullability_union(&result_dtype, else_dtype) else {
208                vortex_bail!(
209                    "CaseWhen THEN and ELSE dtypes must match (ignoring nullability), got {} and {}",
210                    first_then,
211                    else_dtype
212                );
213            };
214            result_dtype = union;
215        } else {
216            // No ELSE means unmatched rows are NULL
217            result_dtype = result_dtype.as_nullable();
218        }
219
220        Ok(result_dtype)
221    }
222
223    fn execute(
224        &self,
225        options: &Self::Options,
226        args: &dyn ExecutionArgs,
227        ctx: &mut ExecutionCtx,
228    ) -> VortexResult<ArrayRef> {
229        let row_count = args.row_count();
230        let num_pairs = options.num_when_then_pairs as usize;
231        let dtypes = (0..args.num_inputs())
232            .map(|index| Ok(args.get(index)?.dtype().clone()))
233            .collect::<VortexResult<Vec<_>>>()?;
234        let output_dtype = self.return_dtype(options, &dtypes)?;
235
236        let mut remaining = Mask::new_true(row_count);
237        let mut branches: Vec<(Mask, ArrayRef)> = Vec::with_capacity(num_pairs);
238
239        for i in 0..num_pairs {
240            if remaining.all_false() {
241                break;
242            }
243
244            let condition = args.get(i * 2)?.filter(remaining.clone())?;
245            let cond_bool = condition.execute::<BoolArray>(ctx)?;
246            let cond_mask = cond_bool.to_mask_fill_null_false(ctx);
247            let effective_mask = remaining.intersect_by_rank(&cond_mask);
248
249            if effective_mask.all_false() {
250                continue;
251            }
252
253            let then_value = args.get(i * 2 + 1)?;
254            remaining = remaining.bitand_not(&effective_mask);
255            branches.push((effective_mask, then_value));
256        }
257
258        let else_value: ArrayRef = if options.has_else {
259            args.get(num_pairs * 2)?
260        } else {
261            let then_dtype = args.get(1)?.dtype().as_nullable();
262            ConstantArray::new(Scalar::null(then_dtype), row_count).into_array()
263        };
264
265        if branches.is_empty() {
266            return else_value.cast(output_dtype);
267        }
268
269        // `remaining` now selects the rows that no branch matched.
270        merge_case_branches(&branches, &remaining, &else_value, &output_dtype, ctx)
271    }
272
273    fn simplify<T: ReduceNode>(
274        &self,
275        options: &Self::Options,
276        node: &T,
277    ) -> VortexResult<Option<T>> {
278        // Rewrite the COALESCE-shaped CASE WHEN into `fill_null`, which references `x`
279        // once and lowers to a single fill kernel instead of a `zip`/merge that resolves
280        // `x` twice (once for the `is_null` predicate, once for the value branch).
281        //
282        //   CASE WHEN is_null(x)     THEN c ELSE x END  ==>  fill_null(x, c)
283        //   CASE WHEN is_not_null(x) THEN x ELSE c END  ==>  fill_null(x, c)
284        //
285        // The fill `c` must be a constant: `fill_null`'s kernel reads the fill value via
286        // `as_constant()`, so a non-constant fill would produce an unexecutable node.
287        if options.num_when_then_pairs != 1 || !options.has_else {
288            return Ok(None);
289        }
290
291        let when = node.child(0);
292        let then = node.child(1);
293        let els = node.child(2);
294
295        let when_is = |f: &dyn Fn(&ScalarFnRef) -> bool| when.scalar_fn().is_some_and(f);
296
297        // `is_null(x) ? c : x` — predicate operand and ELSE are the same `x`, fill is THEN.
298        let (x, fill) = if when_is(&|f| f.is::<IsNull>()) && when.child(0).is_same(&els) {
299            (els, then)
300        // `is_not_null(x) ? x : c` — predicate operand and THEN are the same `x`, fill is ELSE.
301        } else if when_is(&|f| f.is::<IsNotNull>()) && when.child(0).is_same(&then) {
302            (then, els)
303        } else {
304            return Ok(None);
305        };
306
307        let Some(scalar) = fill.as_constant() else {
308            return Ok(None);
309        };
310
311        if scalar.is_null() {
312            // Filling the nulls of `x` with NULL is a no-op
313            return Ok(Some(x));
314        }
315
316        let x_dtype = x.node_dtype()?;
317        if !FillNull::supports_dtype(&x_dtype)
318            || x_dtype.as_nullable() != node.node_dtype()?.as_nullable()
319        {
320            return Ok(None);
321        }
322
323        Ok(Some(
324            node.new_node(FillNull.bind(EmptyOptions), &[x, fill])?,
325        ))
326    }
327
328    fn is_strict(&self, _options: &Self::Options) -> bool {
329        // A null in an unselected branch does not force a null output.
330        false
331    }
332
333    fn is_infallible(&self, _options: &Self::Options) -> bool {
334        true
335    }
336}
337
338/// Assemble coarse runs directly; compact fragmented branches before restoring row positions.
339///
340/// `else_mask` selects the rows that no branch matched. Every branch and the ELSE value
341/// are cast to `output_dtype`, the dtype that `return_dtype` reports.
342fn merge_case_branches(
343    branches: &[(Mask, ArrayRef)],
344    else_mask: &Mask,
345    else_value: &ArrayRef,
346    output_dtype: &DType,
347    ctx: &mut ExecutionCtx,
348) -> VortexResult<ArrayRef> {
349    if let Some((_, value)) = branches.iter().find(|(mask, _)| mask.all_true()) {
350        return value.cast(output_dtype.clone());
351    }
352
353    if prefer_runs(branches, else_value.len()) {
354        return merge_runs(branches, else_value, output_dtype, ctx);
355    }
356
357    merge_compact(branches, else_mask, else_value, output_dtype, ctx)
358}
359
360fn prefer_runs(branches: &[(Mask, ArrayRef)], len: usize) -> bool {
361    // A span may add an ELSE run. Coarse runs amortize slicing without the
362    // extra compact-output buffer and gather; isolated branch selections do too.
363    const MIN_ROWS_PER_RUN: usize = 128;
364
365    let mut remaining_spans = branches.len().max(len / (2 * MIN_ROWS_PER_RUN));
366    for (mask, _) in branches {
367        let count = match mask {
368            Mask::AllTrue(_) => 1,
369            Mask::AllFalse(_) => 0,
370            Mask::Values(values) => values.cached_slices().map_or_else(
371                || {
372                    values
373                        .bit_buffer()
374                        .set_slices()
375                        .take(remaining_spans.saturating_add(1))
376                        .count()
377                },
378                |slices| slices.len(),
379            ),
380        };
381
382        if count > remaining_spans {
383            return false;
384        }
385        remaining_spans -= count;
386    }
387
388    true
389}
390
391fn merge_compact(
392    branches: &[(Mask, ArrayRef)],
393    else_mask: &Mask,
394    else_value: &ArrayRef,
395    output_dtype: &DType,
396    ctx: &mut ExecutionCtx,
397) -> VortexResult<ArrayRef> {
398    let len = else_value.len();
399    let mut builder = builder_with_capacity_in(output_dtype, len, ctx.allocator());
400    let mut indices = BufferMut::<u64>::zeroed_in(len, ctx.allocator().clone());
401
402    let else_branch = (!else_mask.all_false()).then_some((else_mask, else_value));
403    let selections = branches
404        .iter()
405        .map(|(mask, value)| (mask, value))
406        .chain(else_branch);
407
408    for (mask, value) in selections {
409        let offset = builder.len();
410        value
411            .filter(mask.clone())?
412            .cast(output_dtype.clone())?
413            .append_to_builder(builder.as_mut(), ctx)?;
414        assign_positions(&mut indices, mask, offset);
415    }
416
417    builder.finish().take(indices.freeze().into_array())
418}
419
420fn merge_runs(
421    branches: &[(Mask, ArrayRef)],
422    else_value: &ArrayRef,
423    output_dtype: &DType,
424    ctx: &mut ExecutionCtx,
425) -> VortexResult<ArrayRef> {
426    let mut spans = Vec::new();
427    for (index, (mask, _)) in branches.iter().enumerate() {
428        if let AllOr::Some(slices) = mask.slices() {
429            spans.extend(slices.iter().map(|&(start, end)| (start, end, index)));
430        }
431    }
432    spans.sort_unstable_by_key(|&(start, ..)| start);
433
434    // Cast once up front: every span below is a slice of these arrays.
435    let values = branches
436        .iter()
437        .map(|(_, value)| value.cast(output_dtype.clone())?.optimize_ctx(ctx))
438        .collect::<VortexResult<Vec<_>>>()?;
439    let else_value = else_value.cast(output_dtype.clone())?.optimize_ctx(ctx)?;
440    let len = else_value.len();
441
442    let mut builder = builder_with_capacity_in(output_dtype, len, ctx.allocator());
443    for (start, end, branch) in spans {
444        if builder.len() < start {
445            else_value
446                .slice(builder.len()..start)?
447                .append_to_builder(builder.as_mut(), ctx)?;
448        }
449
450        values[branch]
451            .slice(start..end)?
452            .append_to_builder(builder.as_mut(), ctx)?;
453    }
454
455    if builder.len() < len {
456        else_value
457            .slice(builder.len()..len)?
458            .append_to_builder(builder.as_mut(), ctx)?;
459    }
460
461    Ok(builder.finish())
462}
463
464fn assign_positions(indices: &mut [u64], mask: &Mask, offset: usize) {
465    match mask.indices() {
466        AllOr::All => {
467            for (position, index) in indices.iter_mut().enumerate() {
468                *index = (offset + position) as u64;
469            }
470        }
471        AllOr::None => {}
472        AllOr::Some(selected) => {
473            for (position, &row) in selected.iter().enumerate() {
474                indices[row] = (offset + position) as u64;
475            }
476        }
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use std::sync::LazyLock;
483
484    use rstest::rstest;
485    use vortex_array::Canonical;
486    use vortex_array::IntoArray;
487    use vortex_array::VortexSessionExecute;
488    use vortex_array::arrays::BoolArray;
489    use vortex_array::arrays::DecimalArray;
490    use vortex_array::arrays::PrimitiveArray;
491    use vortex_array::arrays::ScalarFnArray;
492    use vortex_array::arrays::StructArray;
493    use vortex_array::arrays::VarBinViewArray;
494    use vortex_array::assert_arrays_eq;
495    use vortex_array::dtype::DType;
496    use vortex_array::dtype::DecimalDType;
497    use vortex_array::dtype::Nullability;
498    use vortex_array::dtype::PType;
499    use vortex_array::dtype::StructFields;
500    use vortex_array::scalar::NumericOperator;
501    use vortex_array::scalar::Scalar;
502    use vortex_array::scalar_fn::ScalarFnVTableExt;
503    use vortex_array::scalar_fn::VecExecutionArgs;
504    use vortex_array::scalar_fn::builtin::operators::CompareOperator;
505    use vortex_array::validity::Validity;
506    use vortex_buffer::Buffer;
507    use vortex_buffer::buffer;
508    use vortex_error::VortexExpect as _;
509    use vortex_expr::ArrayExprExt;
510    use vortex_expr::BoundExpression;
511    use vortex_expr::Expression;
512    use vortex_expr::col;
513    use vortex_expr::eq;
514    use vortex_expr::get_item;
515    use vortex_expr::gt;
516    use vortex_expr::is_not_null;
517    use vortex_expr::lit;
518    use vortex_expr::proto::ExprSerializeProtoExt;
519    use vortex_expr::root;
520    use vortex_expr::test_harness;
521    use vortex_session::VortexSession;
522
523    use super::*;
524    use crate::expr::case_when;
525    use crate::expr::case_when_no_else;
526    use crate::expr::is_null;
527    use crate::expr::nested_case_when;
528
529    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
530        let session = VortexSession::empty();
531        vortex_array::initialize(&session);
532        crate::initialize(&session);
533        session
534    });
535
536    #[test]
537    fn compact_and_run_merges_agree_for_nested_and_nullable_values() -> VortexResult<()> {
538        let mut ctx = SESSION.create_execution_ctx();
539        let primitive =
540            PrimitiveArray::from_option_iter([Some(1i64), None, Some(3), Some(4)]).into_array();
541        let fixtures = vec![
542            primitive.clone(),
543            DecimalArray::new(
544                buffer![100i64, -200, 300, 400],
545                DecimalDType::new(15, 2),
546                Validity::from_iter([true, false, true, true]),
547                &mut ctx,
548            )
549            .into_array(),
550            DecimalArray::from_iter([1i128 << 100, -2, 3, 4], DecimalDType::new(38, 0))
551                .into_array(),
552            VarBinViewArray::from_iter(
553                [
554                    Some("long out-of-line value"),
555                    None,
556                    Some("short"),
557                    Some(""),
558                ],
559                DType::Utf8(Nullability::Nullable),
560            )
561            .into_array(),
562            StructArray::try_from_iter([("nested", primitive)])?.into_array(),
563        ];
564        // Each case lists the branch selections in branch order. Rows that no branch
565        // selects come from ELSE.
566        let cases: [&[[bool; 4]]; 5] = [
567            &[[true, false, true, false]],
568            &[[true, true, false, false]],
569            &[[false, true, false, false]],
570            &[[true, false, false, false], [false, false, true, false]],
571            &[[false, false, false, true], [false, true, false, false]],
572        ];
573
574        for value in fixtures {
575            let reorder =
576                |indices: Buffer<u32>, ctx: &mut ExecutionCtx| -> VortexResult<ArrayRef> {
577                    Ok(value
578                        .take(indices.into_array())?
579                        .execute::<Canonical>(ctx)?
580                        .into_array())
581                };
582            let branch_values = [value.clone(), reorder(buffer![1u32, 0, 3, 2], &mut ctx)?];
583            let otherwise = reorder(buffer![3u32, 2, 1, 0], &mut ctx)?;
584
585            for selections in cases {
586                let branches: Vec<_> = selections
587                    .iter()
588                    .zip(&branch_values)
589                    .map(|(selection, value)| (Mask::from_iter(*selection), value.clone()))
590                    .collect();
591                let else_mask = Mask::from_iter(
592                    (0..4).map(|row| !selections.iter().any(|selection| selection[row])),
593                );
594
595                assert_arrays_eq!(
596                    merge_runs(&branches, &otherwise, value.dtype(), &mut ctx)?,
597                    merge_compact(&branches, &else_mask, &otherwise, value.dtype(), &mut ctx)?,
598                    &mut ctx
599                );
600            }
601        }
602
603        Ok(())
604    }
605
606    fn nested_struct(values: [Option<i32>; 4], nullable: bool) -> VortexResult<ArrayRef> {
607        let field = if nullable {
608            PrimitiveArray::from_option_iter(values).into_array()
609        } else {
610            PrimitiveArray::from_iter(values.map(|value| value.vortex_expect("non-null value")))
611                .into_array()
612        };
613
614        Ok(StructArray::try_from_iter([("a", field)])?.into_array())
615    }
616
617    /// THEN and ELSE may differ in nested nullability. The output must keep nested nulls from
618    /// either side, on the run merge, the compact merge and when no branch matches.
619    #[rstest]
620    #[case::compact_nullable_then([true, false, true, false], true)]
621    #[case::compact_nullable_else([true, false, true, false], false)]
622    #[case::runs_nullable_then([true, true, false, false], true)]
623    #[case::runs_nullable_else([true, true, false, false], false)]
624    #[case::no_match_nullable_else([false, false, false, false], false)]
625    fn nested_nullability_is_merged_across_branches(
626        #[case] selection: [bool; 4],
627        #[case] nullable_then: bool,
628    ) -> VortexResult<()> {
629        let nullable = [None, Some(2), None, Some(4)];
630        let non_nullable = [Some(10), Some(20), Some(30), Some(40)];
631        let (then_values, else_values) = if nullable_then {
632            (nullable, non_nullable)
633        } else {
634            (non_nullable, nullable)
635        };
636
637        let array = ScalarFnArray::try_new(
638            CaseWhen.bind(CaseWhenOptions {
639                num_when_then_pairs: 1,
640                has_else: true,
641            }),
642            vec![
643                BoolArray::from_iter(selection).into_array(),
644                nested_struct(then_values, nullable_then)?,
645                nested_struct(else_values, !nullable_then)?,
646            ],
647        )?
648        .into_array();
649
650        let expected = (0..4).map(|row| {
651            if selection[row] {
652                then_values[row]
653            } else {
654                else_values[row]
655            }
656        });
657        let expected = StructArray::try_from_iter([(
658            "a",
659            PrimitiveArray::from_option_iter(expected).into_array(),
660        )])?
661        .into_array();
662
663        let mut ctx = SESSION.create_execution_ctx();
664        assert_arrays_eq!(array, expected, &mut ctx);
665
666        Ok(())
667    }
668
669    #[test]
670    fn test_return_dtype_merges_nested_nullability() -> VortexResult<()> {
671        let field = |nullability| {
672            DType::Struct(
673                StructFields::new(
674                    ["a"].into(),
675                    vec![DType::Primitive(PType::I32, nullability)],
676                ),
677                Nullability::NonNullable,
678            )
679        };
680        let options = CaseWhenOptions {
681            num_when_then_pairs: 1,
682            has_else: true,
683        };
684        let condition = DType::Bool(Nullability::NonNullable);
685
686        for (then_dtype, else_dtype) in [
687            (
688                field(Nullability::Nullable),
689                field(Nullability::NonNullable),
690            ),
691            (
692                field(Nullability::NonNullable),
693                field(Nullability::Nullable),
694            ),
695        ] {
696            assert_eq!(
697                CaseWhen.return_dtype(&options, &[condition.clone(), then_dtype, else_dtype])?,
698                field(Nullability::Nullable)
699            );
700        }
701
702        Ok(())
703    }
704
705    #[test]
706    fn selected_rows_do_not_execute_erroring_branches_or_later_conditions() -> VortexResult<()> {
707        let mut ctx = SESSION.create_execution_ctx();
708        let condition =
709            BoolArray::from_iter([Some(true), Some(false), Some(true), None]).into_array();
710        let division = buffer![20i32, 30, 40, 50]
711            .into_array()
712            .numeric(buffer![2i32, 0, 4, 0].into_array(), NumericOperator::Div)?;
713        assert!(division.clone().execute::<Canonical>(&mut ctx).is_err());
714        let options = CaseWhenOptions {
715            num_when_then_pairs: 1,
716            has_else: true,
717        };
718        let result = CaseWhen.execute(
719            &options,
720            &VecExecutionArgs::new(
721                vec![
722                    condition.clone(),
723                    division.clone(),
724                    ConstantArray::new(7i32, 4).into_array(),
725                ],
726                4,
727            ),
728            &mut ctx,
729        )?;
730        assert_arrays_eq!(result, buffer![10i32, 7, 10, 7].into_array(), &mut ctx);
731
732        let result = CaseWhen.execute(
733            &options,
734            &VecExecutionArgs::new(
735                vec![
736                    condition.clone(),
737                    StructArray::try_from_iter([("value", division.clone())])?.into_array(),
738                    StructArray::try_from_iter([(
739                        "value",
740                        ConstantArray::new(7i32, 4).into_array(),
741                    )])?
742                    .into_array(),
743                ],
744                4,
745            ),
746            &mut ctx,
747        )?;
748        assert_arrays_eq!(
749            result,
750            StructArray::try_from_iter([("value", buffer![10i32, 7, 10, 7].into_array())])?
751                .into_array(),
752            &mut ctx
753        );
754
755        let later_condition = buffer![20i32, 30, 40, 50]
756            .into_array()
757            .numeric(buffer![0i32, 3, 0, 5].into_array(), NumericOperator::Div)?
758            .compare(
759                ConstantArray::new(0i32, 4).into_array(),
760                CompareOperator::Gt,
761            )?;
762        let result = CaseWhen.execute(
763            &CaseWhenOptions {
764                num_when_then_pairs: 2,
765                has_else: true,
766            },
767            &VecExecutionArgs::new(
768                vec![
769                    condition,
770                    ConstantArray::new(2i32, 4).into_array(),
771                    later_condition,
772                    ConstantArray::new(3i32, 4).into_array(),
773                    division,
774                ],
775                4,
776            ),
777            &mut ctx,
778        )?;
779        assert_arrays_eq!(result, buffer![2i32, 3, 2, 3].into_array(), &mut ctx);
780
781        let selected_error = ScalarFnArray::try_new(
782            CaseWhen.bind(options),
783            vec![
784                ConstantArray::new(true, 4).into_array(),
785                buffer![20i32, 30, 40, 50]
786                    .into_array()
787                    .numeric(buffer![2i32, 0, 4, 0].into_array(), NumericOperator::Div)?,
788                ConstantArray::new(7i32, 4).into_array(),
789            ],
790        )?
791        .into_array();
792        assert!(selected_error.execute::<Canonical>(&mut ctx).is_err());
793        Ok(())
794    }
795
796    fn apply_expr(expr: &Expression, array: &ArrayRef) -> ArrayRef {
797        array.clone().apply(expr).unwrap()
798    }
799
800    fn apply_bound_expr(expr: &BoundExpression, array: &ArrayRef) -> ArrayRef {
801        array.clone().apply_bound(expr).unwrap()
802    }
803
804    // ==================== Serialization Tests ====================
805
806    #[rstest]
807    #[case(1, true, 3)]
808    #[case(1, false, 2)]
809    #[case(3, true, 7)]
810    #[case(4, false, 8)]
811    #[case(u32::MAX / 2, true, u32::MAX)]
812    #[case(u32::MAX / 2, false, u32::MAX - 1)]
813    fn test_serialization_roundtrip(
814        #[case] num_when_then_pairs: u32,
815        #[case] has_else: bool,
816        #[case] num_children: u32,
817    ) -> VortexResult<()> {
818        let options = CaseWhenOptions {
819            num_when_then_pairs,
820            has_else,
821        };
822        let serialized = CaseWhen.serialize(&options)?.expect("serializable options");
823        assert_eq!(
824            pb::CaseWhenOpts::decode(serialized.as_slice())?.num_children,
825            num_children
826        );
827        assert_eq!(CaseWhen.deserialize(&serialized, &SESSION)?, options);
828        Ok(())
829    }
830
831    #[rstest]
832    #[case(0, "at least one WHEN/THEN pair")]
833    #[case(u32::MAX / 2 + 1, "too many children")]
834    fn test_serialization_invalid_options(
835        #[case] num_when_then_pairs: u32,
836        #[case] expected_error: &str,
837        #[values(false, true)] has_else: bool,
838    ) {
839        let options = CaseWhenOptions {
840            num_when_then_pairs,
841            has_else,
842        };
843        let error = CaseWhen.serialize(&options).unwrap_err();
844        assert!(error.to_string().contains(expected_error));
845    }
846
847    #[rstest]
848    #[case::missing(&[])]
849    #[case::zero_children(&[0x08, 0])]
850    #[case::one_child(&[0x08, 1])]
851    #[case::truncated(&[0x08, 0x80])]
852    fn test_deserialization_invalid_metadata(#[case] metadata: &[u8]) {
853        assert!(CaseWhen.deserialize(metadata, &SESSION).is_err());
854    }
855
856    #[rstest]
857    fn test_expression_serialization_roundtrip(
858        #[values(1, 3)] num_when_then_pairs: u32,
859        #[values(false, true)] has_else: bool,
860    ) -> VortexResult<()> {
861        let branches = (0..num_when_then_pairs)
862            .map(|value| (eq(col("value"), lit(value)), lit(value)))
863            .collect();
864        let expression = nested_case_when(branches, has_else.then(|| lit(42u32)));
865        let bytes = expression.serialize_proto()?.encode_to_vec();
866        let proto = pb::Expr::decode(bytes.as_slice())?;
867        assert_eq!(proto.id, "vortex.case_when");
868        assert_eq!(Expression::from_proto(&proto, &SESSION)?, expression);
869        Ok(())
870    }
871
872    // ==================== Display Tests ====================
873
874    #[test]
875    fn test_display_with_else() {
876        let expr = case_when(gt(col("value"), lit(0i32)), lit(100i32), lit(0i32));
877        let display = format!("{}", expr);
878        assert!(display.contains("CASE"));
879        assert!(display.contains("WHEN"));
880        assert!(display.contains("THEN"));
881        assert!(display.contains("ELSE"));
882        assert!(display.contains("END"));
883    }
884
885    #[test]
886    fn test_display_no_else() {
887        let expr = case_when_no_else(gt(col("value"), lit(0i32)), lit(100i32));
888        let display = format!("{}", expr);
889        assert!(display.contains("CASE"));
890        assert!(display.contains("WHEN"));
891        assert!(display.contains("THEN"));
892        assert!(!display.contains("ELSE"));
893        assert!(display.contains("END"));
894    }
895
896    #[test]
897    fn test_display_nested_nary() {
898        // CASE WHEN x > 10 THEN 'high' WHEN x > 5 THEN 'medium' ELSE 'low' END
899        let expr = nested_case_when(
900            vec![
901                (gt(col("x"), lit(10i32)), lit("high")),
902                (gt(col("x"), lit(5i32)), lit("medium")),
903            ],
904            Some(lit("low")),
905        );
906        let display = format!("{}", expr);
907        assert_eq!(display.matches("CASE").count(), 1);
908        assert_eq!(display.matches("WHEN").count(), 2);
909        assert_eq!(display.matches("THEN").count(), 2);
910    }
911
912    // ==================== DType Tests ====================
913
914    #[test]
915    fn test_return_dtype_with_else() {
916        let expr = case_when(lit(true), lit(100i32), lit(0i32));
917        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
918        let result_dtype = expr.return_dtype(&input_dtype).unwrap();
919        assert_eq!(
920            result_dtype,
921            DType::Primitive(PType::I32, Nullability::NonNullable)
922        );
923    }
924
925    #[test]
926    fn test_return_dtype_with_nullable_else() {
927        let expr = case_when(
928            lit(true),
929            lit(100i32),
930            lit(Scalar::null(DType::Primitive(
931                PType::I32,
932                Nullability::Nullable,
933            ))),
934        );
935        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
936        let result_dtype = expr.return_dtype(&input_dtype).unwrap();
937        assert_eq!(
938            result_dtype,
939            DType::Primitive(PType::I32, Nullability::Nullable)
940        );
941    }
942
943    #[test]
944    fn test_return_dtype_without_else_is_nullable() {
945        let expr = case_when_no_else(lit(true), lit(100i32));
946        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
947        let result_dtype = expr.return_dtype(&input_dtype).unwrap();
948        assert_eq!(
949            result_dtype,
950            DType::Primitive(PType::I32, Nullability::Nullable)
951        );
952    }
953
954    #[test]
955    fn test_return_dtype_with_struct_input() {
956        let dtype = test_harness::struct_dtype();
957        let expr = case_when(
958            gt(get_item("col1", root()), lit(10u16)),
959            lit(100i32),
960            lit(0i32),
961        );
962        let result_dtype = expr.return_dtype(&dtype).unwrap();
963        assert_eq!(
964            result_dtype,
965            DType::Primitive(PType::I32, Nullability::NonNullable)
966        );
967    }
968
969    #[test]
970    fn test_return_dtype_mismatched_then_else_errors() {
971        let expr = case_when(lit(true), lit(100i32), lit("zero"));
972        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
973        let err = expr.return_dtype(&input_dtype).unwrap_err();
974        assert!(
975            err.to_string()
976                .contains("THEN and ELSE dtypes must match (ignoring nullability)")
977        );
978    }
979
980    // ==================== Arity Tests ====================
981
982    #[test]
983    fn test_arity_with_else() {
984        let options = CaseWhenOptions {
985            num_when_then_pairs: 1,
986            has_else: true,
987        };
988        assert_eq!(CaseWhen.arity(&options), Arity::Exact(3));
989    }
990
991    #[test]
992    fn test_arity_without_else() {
993        let options = CaseWhenOptions {
994            num_when_then_pairs: 1,
995            has_else: false,
996        };
997        assert_eq!(CaseWhen.arity(&options), Arity::Exact(2));
998    }
999
1000    // ==================== Child Name Tests ====================
1001
1002    #[test]
1003    fn test_child_names() {
1004        let options = CaseWhenOptions {
1005            num_when_then_pairs: 1,
1006            has_else: true,
1007        };
1008        assert_eq!(CaseWhen.child_name(&options, 0).to_string(), "when_0");
1009        assert_eq!(CaseWhen.child_name(&options, 1).to_string(), "then_0");
1010        assert_eq!(CaseWhen.child_name(&options, 2).to_string(), "else");
1011    }
1012
1013    // ==================== N-ary Arity Tests ====================
1014
1015    #[test]
1016    fn test_arity_nary_with_else() {
1017        let options = CaseWhenOptions {
1018            num_when_then_pairs: 3,
1019            has_else: true,
1020        };
1021        // 3 pairs * 2 children + 1 else = 7
1022        assert_eq!(CaseWhen.arity(&options), Arity::Exact(7));
1023    }
1024
1025    #[test]
1026    fn test_arity_nary_without_else() {
1027        let options = CaseWhenOptions {
1028            num_when_then_pairs: 3,
1029            has_else: false,
1030        };
1031        // 3 pairs * 2 children = 6
1032        assert_eq!(CaseWhen.arity(&options), Arity::Exact(6));
1033    }
1034
1035    // ==================== N-ary Child Name Tests ====================
1036
1037    #[test]
1038    fn test_child_names_nary() {
1039        let options = CaseWhenOptions {
1040            num_when_then_pairs: 3,
1041            has_else: true,
1042        };
1043        assert_eq!(CaseWhen.child_name(&options, 0).to_string(), "when_0");
1044        assert_eq!(CaseWhen.child_name(&options, 1).to_string(), "then_0");
1045        assert_eq!(CaseWhen.child_name(&options, 2).to_string(), "when_1");
1046        assert_eq!(CaseWhen.child_name(&options, 3).to_string(), "then_1");
1047        assert_eq!(CaseWhen.child_name(&options, 4).to_string(), "when_2");
1048        assert_eq!(CaseWhen.child_name(&options, 5).to_string(), "then_2");
1049        assert_eq!(CaseWhen.child_name(&options, 6).to_string(), "else");
1050    }
1051
1052    // ==================== N-ary DType Tests ====================
1053
1054    #[test]
1055    fn test_return_dtype_nary_mismatched_then_types_errors() {
1056        let expr = nested_case_when(
1057            vec![(lit(true), lit(100i32)), (lit(false), lit("oops"))],
1058            Some(lit(0i32)),
1059        );
1060        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
1061        let err = expr.return_dtype(&input_dtype).unwrap_err();
1062        assert!(err.to_string().contains("THEN dtypes must match"));
1063    }
1064
1065    #[test]
1066    fn test_return_dtype_nary_mixed_nullability() {
1067        // When some THEN branches are nullable and others are not,
1068        // the result should be nullable (union of nullabilities).
1069        let non_null_then = lit(100i32);
1070        let nullable_then = lit(Scalar::null(DType::Primitive(
1071            PType::I32,
1072            Nullability::Nullable,
1073        )));
1074        let expr = nested_case_when(
1075            vec![(lit(true), non_null_then), (lit(false), nullable_then)],
1076            Some(lit(0i32)),
1077        );
1078        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
1079        let result = expr.return_dtype(&input_dtype).unwrap();
1080        assert_eq!(result, DType::Primitive(PType::I32, Nullability::Nullable));
1081    }
1082
1083    #[test]
1084    fn test_return_dtype_nary_no_else_is_nullable() {
1085        let expr = nested_case_when(
1086            vec![(lit(true), lit(10i32)), (lit(false), lit(20i32))],
1087            None,
1088        );
1089        let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
1090        let result = expr.return_dtype(&input_dtype).unwrap();
1091        assert_eq!(result, DType::Primitive(PType::I32, Nullability::Nullable));
1092    }
1093
1094    // ==================== Expression Manipulation Tests ====================
1095
1096    #[test]
1097    fn test_replace_children() {
1098        let expr = case_when(lit(true), lit(1i32), lit(0i32));
1099        let replaced = expr
1100            .with_children([lit(false), lit(2i32), lit(3i32)])
1101            .vortex_expect("operation should succeed in test");
1102        assert_eq!(replaced, case_when(lit(false), lit(2i32), lit(3i32)));
1103    }
1104
1105    // ==================== Evaluate Tests ====================
1106
1107    #[test]
1108    fn test_evaluate_simple_condition() {
1109        let mut ctx = SESSION.create_execution_ctx();
1110        let test_array =
1111            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1112                .unwrap()
1113                .into_array();
1114
1115        let expr = case_when(
1116            gt(get_item("value", root()), lit(2i32)),
1117            lit(100i32),
1118            lit(0i32),
1119        );
1120
1121        let result = apply_expr(&expr, &test_array);
1122        assert_arrays_eq!(
1123            result,
1124            buffer![0i32, 0, 100, 100, 100].into_array(),
1125            &mut ctx
1126        );
1127    }
1128
1129    #[test]
1130    fn test_evaluate_nary_multiple_conditions() {
1131        let mut ctx = SESSION.create_execution_ctx();
1132        // Test n-ary via nested_case_when
1133        let test_array =
1134            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1135                .unwrap()
1136                .into_array();
1137
1138        let expr = nested_case_when(
1139            vec![
1140                (eq(get_item("value", root()), lit(1i32)), lit(10i32)),
1141                (eq(get_item("value", root()), lit(3i32)), lit(30i32)),
1142            ],
1143            Some(lit(0i32)),
1144        );
1145
1146        let result = apply_expr(&expr, &test_array);
1147        assert_arrays_eq!(result, buffer![10i32, 0, 30, 0, 0].into_array(), &mut ctx);
1148    }
1149
1150    #[test]
1151    fn test_evaluate_nary_first_match_wins() {
1152        let mut ctx = SESSION.create_execution_ctx();
1153        let test_array =
1154            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1155                .unwrap()
1156                .into_array();
1157
1158        // Both conditions match for values > 3, but first one wins
1159        let expr = nested_case_when(
1160            vec![
1161                (gt(get_item("value", root()), lit(2i32)), lit(100i32)),
1162                (gt(get_item("value", root()), lit(3i32)), lit(200i32)),
1163            ],
1164            Some(lit(0i32)),
1165        );
1166
1167        let result = apply_expr(&expr, &test_array);
1168        assert_arrays_eq!(
1169            result,
1170            buffer![0i32, 0, 100, 100, 100].into_array(),
1171            &mut ctx
1172        );
1173    }
1174
1175    #[test]
1176    fn test_evaluate_no_else_returns_null() {
1177        let mut ctx = SESSION.create_execution_ctx();
1178        let test_array =
1179            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1180                .unwrap()
1181                .into_array();
1182
1183        let expr = case_when_no_else(gt(get_item("value", root()), lit(3i32)), lit(100i32));
1184
1185        let result = apply_expr(&expr, &test_array);
1186        assert!(result.dtype().is_nullable());
1187        assert_arrays_eq!(
1188            result,
1189            PrimitiveArray::from_option_iter([None::<i32>, None, None, Some(100), Some(100)])
1190                .into_array(),
1191            &mut ctx
1192        );
1193    }
1194
1195    #[test]
1196    fn test_evaluate_all_conditions_false() {
1197        let mut ctx = SESSION.create_execution_ctx();
1198        let test_array =
1199            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1200                .unwrap()
1201                .into_array();
1202
1203        let expr = case_when(
1204            gt(get_item("value", root()), lit(100i32)),
1205            lit(1i32),
1206            lit(0i32),
1207        );
1208
1209        let result = apply_expr(&expr, &test_array);
1210        assert_arrays_eq!(result, buffer![0i32, 0, 0, 0, 0].into_array(), &mut ctx);
1211    }
1212
1213    #[test]
1214    fn test_evaluate_all_conditions_true() {
1215        let mut ctx = SESSION.create_execution_ctx();
1216        let test_array =
1217            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1218                .unwrap()
1219                .into_array();
1220
1221        let expr = case_when(
1222            gt(get_item("value", root()), lit(0i32)),
1223            lit(100i32),
1224            lit(0i32),
1225        );
1226
1227        let result = apply_expr(&expr, &test_array);
1228        assert_arrays_eq!(
1229            result,
1230            buffer![100i32, 100, 100, 100, 100].into_array(),
1231            &mut ctx
1232        );
1233    }
1234
1235    #[test]
1236    fn test_evaluate_all_true_no_else_returns_correct_dtype() {
1237        let mut ctx = SESSION.create_execution_ctx();
1238        // CASE WHEN value > 0 THEN 100 END — condition is always true, no ELSE.
1239        // Result must be Nullable because the implicit ELSE is NULL.
1240        let test_array = StructArray::from_fields(&[("value", buffer![1i32, 2, 3].into_array())])
1241            .unwrap()
1242            .into_array();
1243
1244        let expr = case_when_no_else(gt(get_item("value", root()), lit(0i32)), lit(100i32));
1245
1246        let result = apply_expr(&expr, &test_array);
1247        assert!(
1248            result.dtype().is_nullable(),
1249            "result dtype must be Nullable, got {:?}",
1250            result.dtype()
1251        );
1252        assert_arrays_eq!(
1253            result,
1254            PrimitiveArray::from_option_iter([Some(100i32), Some(100), Some(100)]).into_array(),
1255            &mut ctx
1256        );
1257    }
1258
1259    #[test]
1260    fn test_merge_case_branches_widens_nullability_of_later_branch() -> VortexResult<()> {
1261        let mut ctx = SESSION.create_execution_ctx();
1262        // When a later THEN branch is Nullable and branches[0] and ELSE are NonNullable,
1263        // the result dtype must still be Nullable.
1264        //
1265        // CASE WHEN value = 0 THEN 10          -- NonNullable
1266        //      WHEN value = 1 THEN nullable(20) -- Nullable
1267        //      ELSE 0                           -- NonNullable
1268        // → result must be Nullable(i32)
1269        let test_array =
1270            StructArray::from_fields(&[("value", buffer![0i32, 1, 2].into_array())])?.into_array();
1271
1272        let nullable_20 =
1273            Scalar::from(20i32).cast(&DType::Primitive(PType::I32, Nullability::Nullable))?;
1274
1275        let expr = nested_case_when(
1276            vec![
1277                (eq(get_item("value", root()), lit(0i32)), lit(10i32)),
1278                (eq(get_item("value", root()), lit(1i32)), lit(nullable_20)),
1279            ],
1280            Some(lit(0i32)),
1281        );
1282
1283        let result = apply_expr(&expr, &test_array);
1284        assert!(
1285            result.dtype().is_nullable(),
1286            "result dtype must be Nullable, got {:?}",
1287            result.dtype()
1288        );
1289        assert_arrays_eq!(
1290            result,
1291            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(0)]).into_array(),
1292            &mut ctx
1293        );
1294        Ok(())
1295    }
1296
1297    #[test]
1298    fn test_evaluate_with_literal_condition() {
1299        let mut ctx = SESSION.create_execution_ctx();
1300        let test_array = buffer![1i32, 2, 3].into_array();
1301        let expr = case_when(lit(true), lit(100i32), lit(0i32));
1302        let result = apply_expr(&expr, &test_array);
1303
1304        assert_arrays_eq!(result, buffer![100i32, 100, 100].into_array(), &mut ctx);
1305    }
1306
1307    #[test]
1308    fn test_evaluate_with_bool_column_result() {
1309        let mut ctx = SESSION.create_execution_ctx();
1310        let test_array =
1311            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1312                .unwrap()
1313                .into_array();
1314
1315        let expr = case_when(
1316            gt(get_item("value", root()), lit(2i32)),
1317            lit(true),
1318            lit(false),
1319        );
1320
1321        let result = apply_expr(&expr, &test_array);
1322        assert_arrays_eq!(
1323            result,
1324            BoolArray::from_iter([false, false, true, true, true]).into_array(),
1325            &mut ctx
1326        );
1327    }
1328
1329    #[test]
1330    fn test_evaluate_with_nullable_condition() {
1331        let mut ctx = SESSION.create_execution_ctx();
1332        let test_array = StructArray::from_fields(&[(
1333            "cond",
1334            BoolArray::from_iter([Some(true), None, Some(false), None, Some(true)]).into_array(),
1335        )])
1336        .unwrap()
1337        .into_array();
1338
1339        let expr = case_when(get_item("cond", root()), lit(100i32), lit(0i32));
1340
1341        let result = apply_expr(&expr, &test_array);
1342        assert_arrays_eq!(result, buffer![100i32, 0, 0, 0, 100].into_array(), &mut ctx);
1343    }
1344
1345    #[test]
1346    fn test_evaluate_with_nullable_result_values() {
1347        let mut ctx = SESSION.create_execution_ctx();
1348        let test_array = StructArray::from_fields(&[
1349            ("value", buffer![1i32, 2, 3, 4, 5].into_array()),
1350            (
1351                "result",
1352                PrimitiveArray::from_option_iter([Some(10), None, Some(30), None, Some(50)])
1353                    .into_array(),
1354            ),
1355        ])
1356        .unwrap()
1357        .into_array();
1358
1359        let expr = case_when(
1360            gt(get_item("value", root()), lit(2i32)),
1361            get_item("result", root()),
1362            lit(0i32),
1363        );
1364
1365        let result = apply_expr(&expr, &test_array);
1366        assert_arrays_eq!(
1367            result,
1368            PrimitiveArray::from_option_iter([Some(0i32), Some(0), Some(30), None, Some(50)])
1369                .into_array(),
1370            &mut ctx
1371        );
1372    }
1373
1374    #[test]
1375    fn test_evaluate_with_all_null_condition() {
1376        let mut ctx = SESSION.create_execution_ctx();
1377        let test_array = StructArray::from_fields(&[(
1378            "cond",
1379            BoolArray::from_iter([None, None, None]).into_array(),
1380        )])
1381        .unwrap()
1382        .into_array();
1383
1384        let expr = case_when(get_item("cond", root()), lit(100i32), lit(0i32));
1385
1386        let result = apply_expr(&expr, &test_array);
1387        assert_arrays_eq!(result, buffer![0i32, 0, 0].into_array(), &mut ctx);
1388    }
1389
1390    // ==================== N-ary Evaluate Tests ====================
1391
1392    #[test]
1393    fn test_evaluate_nary_no_else_returns_null() {
1394        let mut ctx = SESSION.create_execution_ctx();
1395        let test_array =
1396            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1397                .unwrap()
1398                .into_array();
1399
1400        // Two conditions, no ELSE — unmatched rows should be NULL
1401        let expr = nested_case_when(
1402            vec![
1403                (eq(get_item("value", root()), lit(1i32)), lit(10i32)),
1404                (eq(get_item("value", root()), lit(3i32)), lit(30i32)),
1405            ],
1406            None,
1407        );
1408
1409        let result = apply_expr(&expr, &test_array);
1410        assert!(result.dtype().is_nullable());
1411        assert_arrays_eq!(
1412            result,
1413            PrimitiveArray::from_option_iter([Some(10i32), None, Some(30), None, None])
1414                .into_array(),
1415            &mut ctx
1416        );
1417    }
1418
1419    #[test]
1420    fn test_evaluate_nary_many_conditions() {
1421        let mut ctx = SESSION.create_execution_ctx();
1422        let test_array =
1423            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4, 5].into_array())])
1424                .unwrap()
1425                .into_array();
1426
1427        // 5 WHEN/THEN pairs: each value maps to its value * 10
1428        let expr = nested_case_when(
1429            vec![
1430                (eq(get_item("value", root()), lit(1i32)), lit(10i32)),
1431                (eq(get_item("value", root()), lit(2i32)), lit(20i32)),
1432                (eq(get_item("value", root()), lit(3i32)), lit(30i32)),
1433                (eq(get_item("value", root()), lit(4i32)), lit(40i32)),
1434                (eq(get_item("value", root()), lit(5i32)), lit(50i32)),
1435            ],
1436            Some(lit(0i32)),
1437        );
1438
1439        let result = apply_expr(&expr, &test_array);
1440        assert_arrays_eq!(
1441            result,
1442            buffer![10i32, 20, 30, 40, 50].into_array(),
1443            &mut ctx
1444        );
1445    }
1446
1447    #[test]
1448    fn test_evaluate_nary_all_false_no_else() {
1449        let mut ctx = SESSION.create_execution_ctx();
1450        let test_array = StructArray::from_fields(&[("value", buffer![1i32, 2, 3].into_array())])
1451            .unwrap()
1452            .into_array();
1453
1454        // All conditions are false, no ELSE — everything should be NULL
1455        let expr = nested_case_when(
1456            vec![
1457                (gt(get_item("value", root()), lit(100i32)), lit(10i32)),
1458                (gt(get_item("value", root()), lit(200i32)), lit(20i32)),
1459            ],
1460            None,
1461        );
1462
1463        let result = apply_expr(&expr, &test_array);
1464        assert!(result.dtype().is_nullable());
1465        assert_arrays_eq!(
1466            result,
1467            PrimitiveArray::from_option_iter([None::<i32>, None, None]).into_array(),
1468            &mut ctx
1469        );
1470    }
1471
1472    #[test]
1473    fn test_evaluate_nary_overlapping_conditions_first_wins() {
1474        let mut ctx = SESSION.create_execution_ctx();
1475        let test_array =
1476            StructArray::from_fields(&[("value", buffer![10i32, 20, 30].into_array())])
1477                .unwrap()
1478                .into_array();
1479
1480        // value=10: matches cond1 (>5) and cond2 (>0), first should win
1481        // value=20: matches all three, first should win
1482        // value=30: matches all three, first should win
1483        let expr = nested_case_when(
1484            vec![
1485                (gt(get_item("value", root()), lit(5i32)), lit(1i32)),
1486                (gt(get_item("value", root()), lit(0i32)), lit(2i32)),
1487                (gt(get_item("value", root()), lit(15i32)), lit(3i32)),
1488            ],
1489            Some(lit(0i32)),
1490        );
1491
1492        let result = apply_expr(&expr, &test_array);
1493        // First matching condition always wins
1494        assert_arrays_eq!(result, buffer![1i32, 1, 1].into_array(), &mut ctx);
1495    }
1496
1497    #[test]
1498    fn test_evaluate_nary_early_exit_when_remaining_empty() {
1499        let mut ctx = SESSION.create_execution_ctx();
1500        // After branch 0 claims all rows, remaining becomes all_false.
1501        // The loop breaks before evaluating branch 1's condition.
1502        let test_array = StructArray::from_fields(&[("value", buffer![1i32, 2, 3].into_array())])
1503            .unwrap()
1504            .into_array();
1505
1506        let expr = nested_case_when(
1507            vec![
1508                (gt(get_item("value", root()), lit(0i32)), lit(100i32)),
1509                // Never evaluated due to early exit; 999 must never appear in output.
1510                (gt(get_item("value", root()), lit(0i32)), lit(999i32)),
1511            ],
1512            Some(lit(0i32)),
1513        );
1514
1515        let result = apply_expr(&expr, &test_array);
1516        assert_arrays_eq!(result, buffer![100i32, 100, 100].into_array(), &mut ctx);
1517    }
1518
1519    #[test]
1520    fn test_evaluate_nary_skips_branch_with_empty_effective_mask() {
1521        let mut ctx = SESSION.create_execution_ctx();
1522        // Branch 0 claims value=1. Branch 1 targets the same rows but they are already
1523        // matched → effective_mask is all_false → branch 1 is skipped (THEN not used).
1524        let test_array = StructArray::from_fields(&[("value", buffer![1i32, 2, 3].into_array())])
1525            .unwrap()
1526            .into_array();
1527
1528        let expr = nested_case_when(
1529            vec![
1530                (eq(get_item("value", root()), lit(1i32)), lit(10i32)),
1531                // Same condition as branch 0 — all matching rows already claimed → skipped.
1532                // 999 must never appear in output.
1533                (eq(get_item("value", root()), lit(1i32)), lit(999i32)),
1534                (eq(get_item("value", root()), lit(2i32)), lit(20i32)),
1535            ],
1536            Some(lit(0i32)),
1537        );
1538
1539        let result = apply_expr(&expr, &test_array);
1540        assert_arrays_eq!(result, buffer![10i32, 20, 0].into_array(), &mut ctx);
1541    }
1542
1543    #[test]
1544    fn test_evaluate_nary_string_output() -> VortexResult<()> {
1545        // Exercises merge_case_branches with a non-primitive (Utf8) builder.
1546        let test_array =
1547            StructArray::from_fields(&[("value", buffer![1i32, 2, 3, 4].into_array())])?
1548                .into_array();
1549
1550        // CASE WHEN value > 2 THEN 'high' WHEN value > 0 THEN 'low' ELSE 'none' END
1551        // value=1,2 → 'low' (branch 1 after branch 0 claims 3,4)
1552        // value=3,4 → 'high' (branch 0)
1553        let expr = nested_case_when(
1554            vec![
1555                (gt(get_item("value", root()), lit(2i32)), lit("high")),
1556                (gt(get_item("value", root()), lit(0i32)), lit("low")),
1557            ],
1558            Some(lit("none")),
1559        );
1560
1561        let result = apply_expr(&expr, &test_array);
1562        assert_arrays_eq!(
1563            result,
1564            VarBinViewArray::from_iter_str(["low", "low", "high", "high"]),
1565            &mut SESSION.create_execution_ctx()
1566        );
1567        Ok(())
1568    }
1569
1570    #[test]
1571    fn test_evaluate_nary_with_nullable_conditions() {
1572        let mut ctx = SESSION.create_execution_ctx();
1573        let test_array = StructArray::from_fields(&[
1574            (
1575                "cond1",
1576                BoolArray::from_iter([Some(true), None, Some(false)]).into_array(),
1577            ),
1578            (
1579                "cond2",
1580                BoolArray::from_iter([Some(false), Some(true), None]).into_array(),
1581            ),
1582        ])
1583        .unwrap()
1584        .into_array();
1585
1586        let expr = nested_case_when(
1587            vec![
1588                (get_item("cond1", root()), lit(10i32)),
1589                (get_item("cond2", root()), lit(20i32)),
1590            ],
1591            Some(lit(0i32)),
1592        );
1593
1594        let result = apply_expr(&expr, &test_array);
1595        // row 0: cond1=true → 10
1596        // row 1: cond1=NULL(→false), cond2=true → 20
1597        // row 2: cond1=false, cond2=NULL(→false) → else=0
1598        assert_arrays_eq!(result, buffer![10i32, 20, 0].into_array(), &mut ctx);
1599    }
1600
1601    // ==================== Simplify: COALESCE -> fill_null ====================
1602
1603    /// Builds a non-nullable struct scope whose named fields are all `Nullable(I64)`.
1604    fn nullable_i64_scope(fields: &[&str]) -> DType {
1605        DType::Struct(
1606            StructFields::new(
1607                fields.to_vec().into(),
1608                vec![DType::Primitive(PType::I64, Nullability::Nullable); fields.len()],
1609            ),
1610            Nullability::NonNullable,
1611        )
1612    }
1613
1614    #[test]
1615    fn test_simplify_coalesce_is_null_rewrites_to_fill_null() -> VortexResult<()> {
1616        // CASE WHEN is_null(x) THEN 0 ELSE x END  ==>  fill_null(x, 0)
1617        let expr = case_when(is_null(col("x")), lit(0i64), col("x"));
1618        let optimized = expr
1619            .bind(&nullable_i64_scope(&["x"]))?
1620            .optimize_recursive()?;
1621        assert!(
1622            optimized.to_string().starts_with("vortex.fill_null"),
1623            "expected fill_null, got {optimized}"
1624        );
1625        Ok(())
1626    }
1627
1628    #[test]
1629    fn test_simplify_coalesce_is_not_null_rewrites_to_fill_null() -> VortexResult<()> {
1630        // CASE WHEN is_not_null(x) THEN x ELSE 0 END  ==>  fill_null(x, 0)
1631        let expr = case_when(is_not_null(col("x")), col("x"), lit(0i64));
1632        let optimized = expr
1633            .bind(&nullable_i64_scope(&["x"]))?
1634            .optimize_recursive()?;
1635        assert!(
1636            optimized.to_string().starts_with("vortex.fill_null"),
1637            "expected fill_null, got {optimized}"
1638        );
1639        Ok(())
1640    }
1641
1642    #[test]
1643    fn test_simplify_does_not_fire_when_operands_differ() -> VortexResult<()> {
1644        // The is_null operand (x) and the ELSE (y) are different columns: not a COALESCE.
1645        let expr = case_when(is_null(col("x")), lit(0i64), col("y"));
1646        let optimized = expr
1647            .bind(&nullable_i64_scope(&["x", "y"]))?
1648            .optimize_recursive()?;
1649        let s = optimized.to_string();
1650        assert!(s.contains("CASE"), "expected CASE WHEN to remain, got {s}");
1651        assert!(!s.contains("fill_null"), "must not rewrite, got {s}");
1652        Ok(())
1653    }
1654
1655    #[test]
1656    fn test_simplify_does_not_fire_for_non_constant_fill() -> VortexResult<()> {
1657        // COALESCE(x, c) with a *column* fill: fill_null cannot consume a non-constant
1658        // fill value, so the rewrite must not fire.
1659        let expr = case_when(is_null(col("x")), col("c"), col("x"));
1660        let optimized = expr
1661            .bind(&nullable_i64_scope(&["x", "c"]))?
1662            .optimize_recursive()?;
1663        let s = optimized.to_string();
1664        assert!(s.contains("CASE"), "expected CASE WHEN to remain, got {s}");
1665        assert!(!s.contains("fill_null"), "must not rewrite, got {s}");
1666        Ok(())
1667    }
1668
1669    #[test]
1670    fn test_simplify_null_fill_collapses_to_input() -> VortexResult<()> {
1671        // Filling the nulls of x with NULL is a no-op, so both forms collapse to just `x`.
1672        //   CASE WHEN is_null(x)     THEN null ELSE x    END  ==>  x
1673        //   CASE WHEN is_not_null(x) THEN x    ELSE null END  ==>  x
1674        let null_fill = || {
1675            lit(Scalar::null(DType::Primitive(
1676                PType::I64,
1677                Nullability::Nullable,
1678            )))
1679        };
1680
1681        for expr in [
1682            case_when(is_null(col("x")), null_fill(), col("x")),
1683            case_when(is_not_null(col("x")), col("x"), null_fill()),
1684        ] {
1685            let optimized = expr
1686                .bind(&nullable_i64_scope(&["x"]))?
1687                .optimize_recursive()?;
1688            assert_eq!(
1689                optimized.to_string(),
1690                "$.x",
1691                "expected collapse to input column, got {optimized}"
1692            );
1693        }
1694        Ok(())
1695    }
1696
1697    #[test]
1698    fn test_simplify_null_fill_semantic_equivalence() -> VortexResult<()> {
1699        let mut ctx = SESSION.create_execution_ctx();
1700        // The collapse-to-input rewrite must preserve values (and `x`'s nullability).
1701        let array = PrimitiveArray::from_option_iter([Some(1i64), None, Some(3)]).into_array();
1702        let scope = DType::Primitive(PType::I64, Nullability::Nullable);
1703        let null_fill = lit(Scalar::null(DType::Primitive(
1704            PType::I64,
1705            Nullability::Nullable,
1706        )));
1707
1708        let original = case_when(is_null(root()), null_fill, root());
1709        let optimized = original.bind(&scope)?.optimize_recursive()?;
1710        assert_eq!(
1711            optimized.to_string(),
1712            "$",
1713            "expected collapse to root, got {optimized}"
1714        );
1715
1716        let expected = PrimitiveArray::from_option_iter([Some(1i64), None, Some(3)]).into_array();
1717        assert_arrays_eq!(apply_expr(&original, &array), expected, &mut ctx);
1718        assert_arrays_eq!(apply_bound_expr(&optimized, &array), expected, &mut ctx);
1719        Ok(())
1720    }
1721
1722    #[test]
1723    fn test_simplify_does_not_fire_without_else() -> VortexResult<()> {
1724        let expr = case_when_no_else(is_null(col("x")), lit(0i64));
1725        let optimized = expr
1726            .bind(&nullable_i64_scope(&["x"]))?
1727            .optimize_recursive()?;
1728        assert!(
1729            !optimized.to_string().contains("fill_null"),
1730            "must not rewrite a no-ELSE case_when, got {optimized}"
1731        );
1732        Ok(())
1733    }
1734
1735    #[test]
1736    fn test_simplify_does_not_fire_for_multi_pair() -> VortexResult<()> {
1737        let expr = nested_case_when(
1738            vec![
1739                (is_null(col("x")), lit(0i64)),
1740                (gt(col("x"), lit(5i64)), lit(1i64)),
1741            ],
1742            Some(col("x")),
1743        );
1744        let optimized = expr
1745            .bind(&nullable_i64_scope(&["x"]))?
1746            .optimize_recursive()?;
1747        assert!(
1748            !optimized.to_string().contains("fill_null"),
1749            "must not rewrite a multi-pair case_when, got {optimized}"
1750        );
1751        Ok(())
1752    }
1753
1754    #[test]
1755    fn test_simplify_semantic_equivalence() -> VortexResult<()> {
1756        let mut ctx = SESSION.create_execution_ctx();
1757        // The optimized expression must produce the same values as the original CASE WHEN.
1758        let array = PrimitiveArray::from_option_iter([Some(1i64), None, Some(3)]).into_array();
1759        let scope = DType::Primitive(PType::I64, Nullability::Nullable);
1760
1761        let original = case_when(is_null(root()), lit(0i64), root());
1762        let optimized = original.bind(&scope)?.optimize_recursive()?;
1763        assert!(
1764            optimized.to_string().starts_with("vortex.fill_null"),
1765            "expected fill_null, got {optimized}"
1766        );
1767
1768        // Original keeps CASE WHEN's nullable result dtype; the rewrite tightens it to
1769        // NonNullable because a non-null fill cannot leave any nulls behind. Values match.
1770        assert_arrays_eq!(
1771            apply_expr(&original, &array),
1772            PrimitiveArray::from_option_iter([Some(1i64), Some(0), Some(3)]).into_array(),
1773            &mut ctx
1774        );
1775        assert_arrays_eq!(
1776            apply_bound_expr(&optimized, &array),
1777            buffer![1i64, 0, 3].into_array(),
1778            &mut ctx
1779        );
1780        Ok(())
1781    }
1782
1783    #[test]
1784    fn test_simplify_utf8_coalesce_remains_executable() -> VortexResult<()> {
1785        let mut ctx = SESSION.create_execution_ctx();
1786        let input = VarBinViewArray::from_iter_nullable_str([Some("a"), None]).into_array();
1787
1788        for expr in [
1789            case_when(is_null(root()), lit("fallback"), root()),
1790            case_when(is_not_null(root()), root(), lit("fallback")),
1791        ] {
1792            let optimized = expr.bind(input.dtype())?.optimize_recursive()?;
1793            assert!(optimized.is::<FillNull>(), "{optimized}");
1794            let result = input.clone().apply_bound(&optimized)?;
1795            assert_arrays_eq!(
1796                result,
1797                VarBinViewArray::from_iter_str(["a", "fallback"]),
1798                &mut ctx
1799            );
1800        }
1801        Ok(())
1802    }
1803
1804    #[test]
1805    fn test_simplify_list_coalesce_rewrites_to_fill_null() -> VortexResult<()> {
1806        // Lists can fill nulls, so the COALESCE shape becomes fill_null like other dtypes.
1807        let mut ctx = SESSION.create_execution_ctx();
1808        let element_dtype = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable));
1809        let input_dtype = DType::List(Arc::clone(&element_dtype), Nullability::Nullable);
1810        let mut builder = builder_with_capacity_in(&input_dtype, 2, ctx.allocator());
1811        builder.append_scalar(&Scalar::list(
1812            Arc::clone(&element_dtype),
1813            vec![Scalar::from(1i32)],
1814            Nullability::Nullable,
1815        ))?;
1816        builder.append_scalar(&Scalar::null(input_dtype))?;
1817        let input = builder.finish();
1818        let fill = Scalar::list(
1819            element_dtype,
1820            vec![Scalar::from(2i32)],
1821            Nullability::NonNullable,
1822        );
1823
1824        let optimized = case_when(is_null(root()), lit(fill.clone()), root())
1825            .bind(input.dtype())?
1826            .optimize_recursive()?;
1827        assert!(optimized.is::<FillNull>(), "{optimized}");
1828        let result = input
1829            .clone()
1830            .apply_bound(&optimized)?
1831            .execute::<Canonical>(&mut ctx)?
1832            .into_array();
1833        assert_eq!(
1834            result.execute_scalar(0, &mut ctx)?,
1835            input.execute_scalar(0, &mut ctx)?.cast(result.dtype())?
1836        );
1837        assert_eq!(
1838            result.execute_scalar(1, &mut ctx)?,
1839            fill.cast(result.dtype())?
1840        );
1841        Ok(())
1842    }
1843
1844    #[test]
1845    fn test_simplify_list_coalesce_with_nullable_elements_keeps_case_when() -> VortexResult<()> {
1846        // FillNull keeps the input's child dtype, so a literal with nullable elements must stay a
1847        // CASE WHEN when the input list has non-nullable elements.
1848        let mut ctx = SESSION.create_execution_ctx();
1849        let non_nullable_elem = Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable));
1850        let nullable_elem = Arc::new(DType::Primitive(PType::I32, Nullability::Nullable));
1851        let input_dtype = DType::List(Arc::clone(&non_nullable_elem), Nullability::Nullable);
1852        let mut builder = builder_with_capacity_in(&input_dtype, 2, ctx.allocator());
1853        builder.append_scalar(&Scalar::list(
1854            non_nullable_elem,
1855            vec![Scalar::from(1i32)],
1856            Nullability::Nullable,
1857        ))?;
1858        builder.append_scalar(&Scalar::null(input_dtype))?;
1859        let input = builder.finish();
1860        let fill = Scalar::list(
1861            Arc::clone(&nullable_elem),
1862            vec![Scalar::null(nullable_elem.as_ref().clone())],
1863            Nullability::NonNullable,
1864        );
1865
1866        let optimized = case_when(is_null(root()), lit(fill.clone()), root())
1867            .bind(input.dtype())?
1868            .optimize_recursive()?;
1869        assert!(optimized.is::<CaseWhen>(), "{optimized}");
1870        let result = input
1871            .clone()
1872            .apply_bound(&optimized)?
1873            .execute::<Canonical>(&mut ctx)?
1874            .into_array();
1875        assert_eq!(
1876            result.execute_scalar(0, &mut ctx)?,
1877            input.execute_scalar(0, &mut ctx)?.cast(result.dtype())?
1878        );
1879        assert_eq!(
1880            result.execute_scalar(1, &mut ctx)?,
1881            fill.cast(result.dtype())?
1882        );
1883        Ok(())
1884    }
1885
1886    #[test]
1887    fn test_merge_case_branches_alternating_mask() -> VortexResult<()> {
1888        let mut ctx = SESSION.create_execution_ctx();
1889        // Alternating rows exercise compact branch assembly.
1890        let n = 100usize;
1891
1892        // Branch 0: even rows → 0, Branch 1: odd rows → 1, Else: never reached.
1893        let branch0_mask = Mask::from_indices(n, (0..n).step_by(2));
1894        let branch1_mask = Mask::from_indices(n, (1..n).step_by(2));
1895
1896        let else_value = PrimitiveArray::from_option_iter(vec![Some(99i32); n]).into_array();
1897        let output_dtype = else_value.dtype().clone();
1898        let result = merge_case_branches(
1899            &[
1900                (
1901                    branch0_mask,
1902                    PrimitiveArray::from_option_iter(vec![Some(0i32); n]).into_array(),
1903                ),
1904                (
1905                    branch1_mask,
1906                    PrimitiveArray::from_option_iter(vec![Some(1i32); n]).into_array(),
1907                ),
1908            ],
1909            &Mask::new_false(n),
1910            &else_value,
1911            &output_dtype,
1912            &mut SESSION.create_execution_ctx(),
1913        )?;
1914
1915        // Even rows → 0, odd rows → 1.
1916        let expected: Vec<Option<i32>> = (0..n)
1917            .map(|v| if v % 2 == 0 { Some(0) } else { Some(1) })
1918            .collect();
1919        assert_arrays_eq!(
1920            result,
1921            PrimitiveArray::from_option_iter(expected).into_array(),
1922            &mut ctx
1923        );
1924        Ok(())
1925    }
1926}