Skip to main content

vortex_array/scalar_fn/fns/
is_null.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexExpect as _;
5use vortex_error::VortexResult;
6use vortex_session::VortexSession;
7use vortex_session::registry::CachedId;
8
9use crate::ArrayRef;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::arrays::ConstantArray;
13use crate::arrays::ScalarFnArray;
14use crate::builtins::ArrayBuiltins;
15use crate::dtype::DType;
16use crate::dtype::Nullability;
17use crate::scalar_fn::Arity;
18use crate::scalar_fn::ChildName;
19use crate::scalar_fn::EmptyOptions;
20use crate::scalar_fn::ExecutionArgs;
21use crate::scalar_fn::ReduceNode;
22use crate::scalar_fn::ScalarFnId;
23use crate::scalar_fn::ScalarFnVTable;
24use crate::scalar_fn::ScalarFnVTableExt;
25use crate::scalar_fn::fns::is_not_null::reduce_null;
26use crate::validity::Validity;
27
28/// Expression that checks for null values.
29#[derive(Clone)]
30pub struct IsNull;
31
32impl IsNull {
33    /// Creates a lazy null check over `input`.
34    #[expect(clippy::new_ret_no_self, reason = "constructs the lazy result array")]
35    pub fn new(input: ArrayRef) -> ScalarFnArray {
36        ScalarFnArray::try_new(IsNull.bind(EmptyOptions), [input])
37            .vortex_expect("IsNull has one child and an infallible return dtype")
38    }
39}
40
41impl ScalarFnVTable for IsNull {
42    type Options = EmptyOptions;
43
44    fn id(&self) -> ScalarFnId {
45        static ID: CachedId = CachedId::new("vortex.is_null");
46        *ID
47    }
48
49    fn serialize(&self, _instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
50        Ok(Some(vec![]))
51    }
52
53    fn deserialize(
54        &self,
55        _metadata: &[u8],
56        _session: &VortexSession,
57    ) -> VortexResult<Self::Options> {
58        Ok(EmptyOptions)
59    }
60
61    fn arity(&self, _options: &Self::Options) -> Arity {
62        Arity::Exact(1)
63    }
64
65    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
66        match child_idx {
67            0 => ChildName::from("input"),
68            _ => unreachable!("Invalid child index {} for IsNull expression", child_idx),
69        }
70    }
71
72    fn return_dtype(&self, _options: &Self::Options, _arg_dtypes: &[DType]) -> VortexResult<DType> {
73        Ok(DType::Bool(Nullability::NonNullable))
74    }
75
76    fn execute(
77        &self,
78        _data: &Self::Options,
79        args: &dyn ExecutionArgs,
80        _ctx: &mut ExecutionCtx,
81    ) -> VortexResult<ArrayRef> {
82        let child = args.get(0)?;
83        if let Some(scalar) = child.as_constant() {
84            return Ok(ConstantArray::new(scalar.is_null(), args.row_count()).into_array());
85        }
86
87        match child.validity()? {
88            Validity::NonNullable | Validity::AllValid => {
89                Ok(ConstantArray::new(false, args.row_count()).into_array())
90            }
91            Validity::AllInvalid => Ok(ConstantArray::new(true, args.row_count()).into_array()),
92            Validity::Array(a) => a.not(),
93        }
94    }
95
96    fn reduce<T: ReduceNode>(&self, _options: &Self::Options, node: &T) -> VortexResult<Option<T>> {
97        reduce_null(true, node)
98    }
99
100    fn is_strict(&self, _instance: &Self::Options) -> bool {
101        // Null input produces the non-null boolean value `true`.
102        false
103    }
104
105    fn is_infallible(&self, _instance: &Self::Options) -> bool {
106        true
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use std::sync::LazyLock;
113
114    use vortex_buffer::buffer;
115    use vortex_error::VortexResult;
116    use vortex_session::VortexSession;
117
118    use crate::IntoArray;
119    use crate::VortexSessionExecute;
120    use crate::array_session;
121    use crate::arrays::PrimitiveArray;
122    use crate::arrays::StructArray;
123    use crate::dtype::DType;
124    use crate::dtype::Nullability;
125    use crate::expr::col;
126    use crate::expr::eq;
127    use crate::expr::get_item;
128    use crate::expr::is_null;
129    use crate::expr::lit;
130    use crate::expr::or;
131    use crate::expr::root;
132    use crate::expr::test_harness;
133    use crate::scalar::Scalar;
134    use crate::stats::StatsSession;
135    use crate::stats::all_non_null;
136    use crate::stats::null_count;
137
138    static STATS_SESSION: LazyLock<VortexSession> =
139        LazyLock::new(|| VortexSession::empty().with::<StatsSession>());
140
141    #[test]
142    fn dtype() {
143        let dtype = test_harness::struct_dtype();
144        assert_eq!(
145            is_null(root()).return_dtype(&dtype).unwrap(),
146            DType::Bool(Nullability::NonNullable)
147        );
148    }
149
150    #[test]
151    fn evaluate_mask() {
152        let test_array =
153            PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
154                .into_array();
155        let expected = [false, true, false, true, false];
156
157        let result = test_array.clone().apply(&is_null(root())).unwrap();
158
159        assert_eq!(result.len(), test_array.len());
160        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
161
162        for (i, expected_value) in expected.iter().enumerate() {
163            assert_eq!(
164                result
165                    .execute_scalar(i, &mut array_session().create_execution_ctx())
166                    .unwrap(),
167                Scalar::bool(*expected_value, Nullability::NonNullable)
168            );
169        }
170    }
171
172    #[test]
173    fn evaluate_all_false() {
174        let test_array = buffer![1, 2, 3, 4, 5].into_array();
175
176        let result = test_array.clone().apply(&is_null(root())).unwrap();
177
178        assert_eq!(result.len(), test_array.len());
179        // All values should be false (non-nullable input)
180        for i in 0..result.len() {
181            assert_eq!(
182                result
183                    .execute_scalar(i, &mut array_session().create_execution_ctx())
184                    .unwrap(),
185                Scalar::bool(false, Nullability::NonNullable)
186            );
187        }
188    }
189
190    #[test]
191    fn evaluate_all_true() {
192        let test_array =
193            PrimitiveArray::from_option_iter(vec![None::<i32>, None, None, None, None])
194                .into_array();
195
196        let result = test_array.clone().apply(&is_null(root())).unwrap();
197
198        assert_eq!(result.len(), test_array.len());
199        // All values should be true (all nulls)
200        for i in 0..result.len() {
201            assert_eq!(
202                result
203                    .execute_scalar(i, &mut array_session().create_execution_ctx())
204                    .unwrap(),
205                Scalar::bool(true, Nullability::NonNullable)
206            );
207        }
208    }
209
210    #[test]
211    fn evaluate_struct() {
212        let test_array = StructArray::from_fields(&[(
213            "a",
214            PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
215                .into_array(),
216        )])
217        .unwrap()
218        .into_array();
219        let expected = [false, true, false, true, false];
220
221        let result = test_array
222            .clone()
223            .apply(&is_null(get_item("a", root())))
224            .unwrap();
225
226        assert_eq!(result.len(), test_array.len());
227        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
228
229        for (i, expected_value) in expected.iter().enumerate() {
230            assert_eq!(
231                result
232                    .execute_scalar(i, &mut array_session().create_execution_ctx())
233                    .unwrap(),
234                Scalar::bool(*expected_value, Nullability::NonNullable)
235            );
236        }
237    }
238
239    #[test]
240    fn test_display() {
241        let expr = is_null(get_item("name", root()));
242        assert_eq!(expr.to_string(), "vortex.is_null($.name)");
243
244        let expr2 = is_null(root());
245        assert_eq!(expr2.to_string(), "vortex.is_null($)");
246    }
247
248    #[test]
249    fn test_is_null_falsification() -> VortexResult<()> {
250        let expr = is_null(col("a"));
251        let dtype = test_harness::struct_dtype();
252
253        assert_eq!(
254            expr.bind(&dtype)?.falsify(&STATS_SESSION)?,
255            Some(or(eq(null_count(col("a")), lit(0u64)), all_non_null(col("a")),).bind(&dtype)?)
256        );
257        Ok(())
258    }
259
260    #[test]
261    fn test_is_null_is_not_strict() {
262        assert!(
263            !is_null(col("a"))
264                .as_scalar()
265                .is_some_and(|f| f.signature().is_strict())
266        );
267    }
268}