Skip to main content

vortex_array/scalar_fn/fns/fill_null/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6use std::fmt::Formatter;
7
8pub use kernel::*;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_err;
13use vortex_session::VortexSession;
14
15use crate::AnyColumnar;
16use crate::ArrayRef;
17use crate::CanonicalView;
18use crate::ColumnarView;
19use crate::ExecutionCtx;
20use crate::arrays::BoolVTable;
21use crate::arrays::DecimalVTable;
22use crate::arrays::PrimitiveVTable;
23use crate::builtins::ArrayBuiltins;
24use crate::dtype::DType;
25use crate::expr::Expression;
26use crate::scalar::Scalar;
27use crate::scalar_fn::Arity;
28use crate::scalar_fn::ChildName;
29use crate::scalar_fn::EmptyOptions;
30use crate::scalar_fn::ExecutionArgs;
31use crate::scalar_fn::ScalarFnId;
32use crate::scalar_fn::ScalarFnVTable;
33
34/// An expression that replaces null values in the input with a fill value.
35#[derive(Clone)]
36pub struct FillNull;
37
38impl ScalarFnVTable for FillNull {
39    type Options = EmptyOptions;
40
41    fn id(&self) -> ScalarFnId {
42        ScalarFnId::from("vortex.fill_null")
43    }
44
45    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
46        Ok(Some(vec![]))
47    }
48
49    fn deserialize(
50        &self,
51        _metadata: &[u8],
52        _session: &VortexSession,
53    ) -> VortexResult<Self::Options> {
54        Ok(EmptyOptions)
55    }
56
57    fn arity(&self, _options: &Self::Options) -> Arity {
58        Arity::Exact(2)
59    }
60
61    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
62        match child_idx {
63            0 => ChildName::from("input"),
64            1 => ChildName::from("fill_value"),
65            _ => unreachable!("Invalid child index {} for FillNull expression", child_idx),
66        }
67    }
68
69    fn fmt_sql(
70        &self,
71        _options: &Self::Options,
72        expr: &Expression,
73        f: &mut Formatter<'_>,
74    ) -> std::fmt::Result {
75        write!(f, "fill_null(")?;
76        expr.child(0).fmt_sql(f)?;
77        write!(f, ", ")?;
78        expr.child(1).fmt_sql(f)?;
79        write!(f, ")")
80    }
81
82    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
83        vortex_ensure!(
84            arg_dtypes[0].eq_ignore_nullability(&arg_dtypes[1]),
85            "fill_null requires input and fill value to have the same base type, got {} and {}",
86            arg_dtypes[0],
87            arg_dtypes[1]
88        );
89        // The result dtype takes the nullability of the fill value.
90        Ok(arg_dtypes[0]
91            .clone()
92            .with_nullability(arg_dtypes[1].nullability()))
93    }
94
95    fn execute(&self, _options: &Self::Options, args: ExecutionArgs) -> VortexResult<ArrayRef> {
96        let [input, fill_value]: [ArrayRef; _] = args
97            .inputs
98            .try_into()
99            .map_err(|_| vortex_err!("Wrong arg count"))?;
100
101        let fill_scalar = fill_value
102            .as_constant()
103            .ok_or_else(|| vortex_err!("fill_null fill_value must be a constant/scalar"))?;
104
105        let Some(columnar) = input.as_opt::<AnyColumnar>() else {
106            return input.execute::<ArrayRef>(args.ctx)?.fill_null(fill_scalar);
107        };
108
109        match columnar {
110            ColumnarView::Canonical(canonical) => {
111                fill_null_canonical(canonical, &fill_scalar, args.ctx)
112            }
113            ColumnarView::Constant(constant) => fill_null_constant(constant, &fill_scalar),
114        }
115    }
116
117    fn simplify(
118        &self,
119        _options: &Self::Options,
120        expr: &Expression,
121        ctx: &dyn crate::scalar_fn::SimplifyCtx,
122    ) -> VortexResult<Option<Expression>> {
123        let input_dtype = ctx.return_dtype(expr.child(0))?;
124
125        if !input_dtype.is_nullable() {
126            return Ok(Some(expr.child(0).clone()));
127        }
128
129        Ok(None)
130    }
131
132    fn validity(
133        &self,
134        _options: &Self::Options,
135        expression: &Expression,
136    ) -> VortexResult<Option<Expression>> {
137        // After fill_null, the result validity depends on the fill value's nullability.
138        // If fill_value is non-nullable, the result is always valid.
139        Ok(Some(expression.child(1).validity()?))
140    }
141
142    fn is_null_sensitive(&self, _options: &Self::Options) -> bool {
143        true
144    }
145
146    fn is_fallible(&self, _options: &Self::Options) -> bool {
147        false
148    }
149}
150
151/// Fill nulls on a canonical array by directly dispatching to the appropriate kernel.
152///
153/// Returns the filled array, or bails if no kernel is registered for the canonical type.
154fn fill_null_canonical(
155    canonical: CanonicalView<'_>,
156    fill_value: &Scalar,
157    ctx: &mut ExecutionCtx,
158) -> VortexResult<ArrayRef> {
159    if let Some(result) = precondition(canonical.as_ref(), fill_value)? {
160        // The result of precondition may return another ScalarFn, in which case we should
161        // apply it immediately.
162        // TODO(aduffy): Remove this once we have better driver check. We're also implicitly
163        //  relying on the fact that Cast execution will do an optimize on its result.
164        return result.execute::<ArrayRef>(ctx);
165    }
166    match canonical {
167        CanonicalView::Bool(a) => <BoolVTable as FillNullKernel>::fill_null(a, fill_value, ctx)?
168            .ok_or_else(|| vortex_err!("FillNullKernel for BoolArray returned None")),
169        CanonicalView::Primitive(a) => {
170            <PrimitiveVTable as FillNullKernel>::fill_null(a, fill_value, ctx)?
171                .ok_or_else(|| vortex_err!("FillNullKernel for PrimitiveArray returned None"))
172        }
173        CanonicalView::Decimal(a) => {
174            <DecimalVTable as FillNullKernel>::fill_null(a, fill_value, ctx)?
175                .ok_or_else(|| vortex_err!("FillNullKernel for DecimalArray returned None"))
176        }
177        other => vortex_bail!(
178            "No FillNullKernel for canonical array {}",
179            other.as_ref().encoding_id()
180        ),
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use vortex_buffer::buffer;
187    use vortex_error::VortexExpect;
188
189    use crate::IntoArray;
190    use crate::arrays::PrimitiveArray;
191    use crate::arrays::StructArray;
192    use crate::assert_arrays_eq;
193    use crate::dtype::DType;
194    use crate::dtype::Nullability;
195    use crate::dtype::PType;
196    use crate::expr::fill_null;
197    use crate::expr::get_item;
198    use crate::expr::lit;
199    use crate::expr::root;
200
201    #[test]
202    fn dtype() {
203        let dtype = DType::Primitive(PType::I32, Nullability::Nullable);
204        assert_eq!(
205            fill_null(root(), lit(0i32)).return_dtype(&dtype).unwrap(),
206            DType::Primitive(PType::I32, Nullability::NonNullable)
207        );
208    }
209
210    #[test]
211    fn replace_children() {
212        let expr = fill_null(root(), lit(0i32));
213        expr.with_children(vec![root(), lit(0i32)])
214            .vortex_expect("operation should succeed in test");
215    }
216
217    #[test]
218    fn evaluate() {
219        let test_array =
220            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None, Some(5)])
221                .into_array();
222
223        let expr = fill_null(root(), lit(42i32));
224        let result = test_array.apply(&expr).unwrap();
225
226        assert_eq!(
227            result.dtype(),
228            &DType::Primitive(PType::I32, Nullability::NonNullable)
229        );
230        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 42, 3, 42, 5]));
231    }
232
233    #[test]
234    fn evaluate_struct_field() {
235        let test_array = StructArray::from_fields(&[(
236            "a",
237            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(),
238        )])
239        .unwrap()
240        .into_array();
241
242        let expr = fill_null(get_item("a", root()), lit(0i32));
243        let result = test_array.apply(&expr).unwrap();
244
245        assert_eq!(
246            result.dtype(),
247            &DType::Primitive(PType::I32, Nullability::NonNullable)
248        );
249        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 0, 3]));
250    }
251
252    #[test]
253    fn evaluate_non_nullable_input() {
254        let test_array = buffer![1i32, 2, 3].into_array();
255        let expr = fill_null(root(), lit(0i32));
256        let result = test_array.apply(&expr).unwrap();
257        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 2, 3]));
258    }
259
260    #[test]
261    fn test_display() {
262        let expr = fill_null(get_item("value", root()), lit(0i32));
263        assert_eq!(expr.to_string(), "fill_null($.value, 0i32)");
264    }
265}