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 std::fmt::Formatter;
5
6use vortex_error::VortexResult;
7use vortex_session::VortexSession;
8
9use crate::ArrayRef;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::arrays::ConstantArray;
13use crate::builtins::ArrayBuiltins;
14use crate::dtype::DType;
15use crate::dtype::Nullability;
16use crate::expr::Expression;
17use crate::expr::StatsCatalog;
18use crate::expr::eq;
19use crate::expr::lit;
20use crate::expr::stats::Stat;
21use crate::scalar_fn::Arity;
22use crate::scalar_fn::ChildName;
23use crate::scalar_fn::EmptyOptions;
24use crate::scalar_fn::ExecutionArgs;
25use crate::scalar_fn::ScalarFnId;
26use crate::scalar_fn::ScalarFnVTable;
27use crate::validity::Validity;
28
29/// Expression that checks for null values.
30#[derive(Clone)]
31pub struct IsNull;
32
33impl ScalarFnVTable for IsNull {
34    type Options = EmptyOptions;
35
36    fn id(&self) -> ScalarFnId {
37        ScalarFnId::from("vortex.is_null")
38    }
39
40    fn serialize(&self, _instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
41        Ok(Some(vec![]))
42    }
43
44    fn deserialize(
45        &self,
46        _metadata: &[u8],
47        _session: &VortexSession,
48    ) -> VortexResult<Self::Options> {
49        Ok(EmptyOptions)
50    }
51
52    fn arity(&self, _options: &Self::Options) -> Arity {
53        Arity::Exact(1)
54    }
55
56    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
57        match child_idx {
58            0 => ChildName::from("input"),
59            _ => unreachable!("Invalid child index {} for IsNull expression", child_idx),
60        }
61    }
62
63    fn fmt_sql(
64        &self,
65        _options: &Self::Options,
66        expr: &Expression,
67        f: &mut Formatter<'_>,
68    ) -> std::fmt::Result {
69        write!(f, "is_null(")?;
70        expr.child(0).fmt_sql(f)?;
71        write!(f, ")")
72    }
73
74    fn return_dtype(&self, _options: &Self::Options, _arg_dtypes: &[DType]) -> VortexResult<DType> {
75        Ok(DType::Bool(Nullability::NonNullable))
76    }
77
78    fn execute(
79        &self,
80        _data: &Self::Options,
81        args: &dyn ExecutionArgs,
82        _ctx: &mut ExecutionCtx,
83    ) -> VortexResult<ArrayRef> {
84        let child = args.get(0)?;
85        if let Some(scalar) = child.as_constant() {
86            return Ok(ConstantArray::new(scalar.is_null(), args.row_count()).into_array());
87        }
88
89        match child.validity()? {
90            Validity::NonNullable | Validity::AllValid => {
91                Ok(ConstantArray::new(false, args.row_count()).into_array())
92            }
93            Validity::AllInvalid => Ok(ConstantArray::new(true, args.row_count()).into_array()),
94            Validity::Array(a) => a.not(),
95        }
96    }
97
98    fn stat_falsification(
99        &self,
100        _options: &Self::Options,
101        expr: &Expression,
102        catalog: &dyn StatsCatalog,
103    ) -> Option<Expression> {
104        let null_count_expr = expr.child(0).stat_expression(Stat::NullCount, catalog)?;
105        Some(eq(null_count_expr, lit(0u64)))
106    }
107
108    fn is_null_sensitive(&self, _instance: &Self::Options) -> bool {
109        true
110    }
111
112    fn is_fallible(&self, _instance: &Self::Options) -> bool {
113        false
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use vortex_buffer::buffer;
120    use vortex_error::VortexExpect as _;
121    use vortex_utils::aliases::hash_map::HashMap;
122    use vortex_utils::aliases::hash_set::HashSet;
123
124    use crate::IntoArray;
125    use crate::LEGACY_SESSION;
126    use crate::VortexSessionExecute;
127    use crate::arrays::PrimitiveArray;
128    use crate::arrays::StructArray;
129    use crate::dtype::DType;
130    use crate::dtype::Field;
131    use crate::dtype::FieldPath;
132    use crate::dtype::FieldPathSet;
133    use crate::dtype::Nullability;
134    use crate::expr::col;
135    use crate::expr::eq;
136    use crate::expr::get_item;
137    use crate::expr::is_null;
138    use crate::expr::lit;
139    use crate::expr::pruning::checked_pruning_expr;
140    use crate::expr::root;
141    use crate::expr::stats::Stat;
142    use crate::expr::test_harness;
143    use crate::scalar::Scalar;
144
145    #[test]
146    fn dtype() {
147        let dtype = test_harness::struct_dtype();
148        assert_eq!(
149            is_null(root()).return_dtype(&dtype).unwrap(),
150            DType::Bool(Nullability::NonNullable)
151        );
152    }
153
154    #[test]
155    fn replace_children() {
156        let expr = is_null(root());
157        expr.with_children([root()])
158            .vortex_expect("operation should succeed in test");
159    }
160
161    #[test]
162    fn evaluate_mask() {
163        let test_array =
164            PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
165                .into_array();
166        let expected = [false, true, false, true, false];
167
168        let result = test_array.clone().apply(&is_null(root())).unwrap();
169
170        assert_eq!(result.len(), test_array.len());
171        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
172
173        for (i, expected_value) in expected.iter().enumerate() {
174            assert_eq!(
175                result
176                    .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
177                    .unwrap(),
178                Scalar::bool(*expected_value, Nullability::NonNullable)
179            );
180        }
181    }
182
183    #[test]
184    fn evaluate_all_false() {
185        let test_array = buffer![1, 2, 3, 4, 5].into_array();
186
187        let result = test_array.clone().apply(&is_null(root())).unwrap();
188
189        assert_eq!(result.len(), test_array.len());
190        // All values should be false (non-nullable input)
191        for i in 0..result.len() {
192            assert_eq!(
193                result
194                    .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
195                    .unwrap(),
196                Scalar::bool(false, Nullability::NonNullable)
197            );
198        }
199    }
200
201    #[test]
202    fn evaluate_all_true() {
203        let test_array =
204            PrimitiveArray::from_option_iter(vec![None::<i32>, None, None, None, None])
205                .into_array();
206
207        let result = test_array.clone().apply(&is_null(root())).unwrap();
208
209        assert_eq!(result.len(), test_array.len());
210        // All values should be true (all nulls)
211        for i in 0..result.len() {
212            assert_eq!(
213                result
214                    .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
215                    .unwrap(),
216                Scalar::bool(true, Nullability::NonNullable)
217            );
218        }
219    }
220
221    #[test]
222    fn evaluate_struct() {
223        let test_array = StructArray::from_fields(&[(
224            "a",
225            PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
226                .into_array(),
227        )])
228        .unwrap()
229        .into_array();
230        let expected = [false, true, false, true, false];
231
232        let result = test_array
233            .clone()
234            .apply(&is_null(get_item("a", root())))
235            .unwrap();
236
237        assert_eq!(result.len(), test_array.len());
238        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
239
240        for (i, expected_value) in expected.iter().enumerate() {
241            assert_eq!(
242                result
243                    .execute_scalar(i, &mut LEGACY_SESSION.create_execution_ctx())
244                    .unwrap(),
245                Scalar::bool(*expected_value, Nullability::NonNullable)
246            );
247        }
248    }
249
250    #[test]
251    fn test_display() {
252        let expr = is_null(get_item("name", root()));
253        assert_eq!(expr.to_string(), "is_null($.name)");
254
255        let expr2 = is_null(root());
256        assert_eq!(expr2.to_string(), "is_null($)");
257    }
258
259    #[test]
260    fn test_is_null_falsification() {
261        let expr = is_null(col("a"));
262
263        let (pruning_expr, st) = checked_pruning_expr(
264            &expr,
265            &FieldPathSet::from_iter([FieldPath::from_iter([
266                Field::Name("a".into()),
267                Field::Name("null_count".into()),
268            ])]),
269        )
270        .unwrap();
271
272        assert_eq!(&pruning_expr, &eq(col("a_null_count"), lit(0u64)));
273        assert_eq!(
274            st.map(),
275            &HashMap::from_iter([(FieldPath::from_name("a"), HashSet::from([Stat::NullCount]))])
276        );
277    }
278
279    #[test]
280    fn test_is_null_sensitive() {
281        // is_null itself is null-sensitive
282        assert!(is_null(col("a")).signature().is_null_sensitive());
283    }
284}