vortex_array/scalar_fn/fns/
is_null.rs1use std::fmt::Formatter;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_session::VortexSession;
9
10use crate::ArrayRef;
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#[derive(Clone)]
31pub struct IsNull;
32
33impl ScalarFnVTable for IsNull {
34 type Options = EmptyOptions;
35
36 fn id(&self) -> ScalarFnId {
37 ScalarFnId::new_ref("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(&self, _data: &Self::Options, mut args: ExecutionArgs) -> VortexResult<ArrayRef> {
79 let child = args.inputs.pop().vortex_expect("Missing input child");
80 if let Some(scalar) = child.as_constant() {
81 return Ok(ConstantArray::new(scalar.is_null(), args.row_count).into_array());
82 }
83
84 match child.validity()? {
85 Validity::NonNullable | Validity::AllValid => {
86 Ok(ConstantArray::new(false, args.row_count).into_array())
87 }
88 Validity::AllInvalid => Ok(ConstantArray::new(true, args.row_count).into_array()),
89 Validity::Array(a) => a.not(),
90 }
91 }
92
93 fn stat_falsification(
94 &self,
95 _options: &Self::Options,
96 expr: &Expression,
97 catalog: &dyn StatsCatalog,
98 ) -> Option<Expression> {
99 let null_count_expr = expr.child(0).stat_expression(Stat::NullCount, catalog)?;
100 Some(eq(null_count_expr, lit(0u64)))
101 }
102
103 fn is_null_sensitive(&self, _instance: &Self::Options) -> bool {
104 true
105 }
106
107 fn is_fallible(&self, _instance: &Self::Options) -> bool {
108 false
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use vortex_buffer::buffer;
115 use vortex_error::VortexExpect as _;
116 use vortex_utils::aliases::hash_map::HashMap;
117 use vortex_utils::aliases::hash_set::HashSet;
118
119 use crate::IntoArray;
120 use crate::arrays::PrimitiveArray;
121 use crate::arrays::StructArray;
122 use crate::dtype::DType;
123 use crate::dtype::Field;
124 use crate::dtype::FieldPath;
125 use crate::dtype::FieldPathSet;
126 use crate::dtype::Nullability;
127 use crate::expr::col;
128 use crate::expr::eq;
129 use crate::expr::get_item;
130 use crate::expr::is_null;
131 use crate::expr::lit;
132 use crate::expr::pruning::checked_pruning_expr;
133 use crate::expr::root;
134 use crate::expr::stats::Stat;
135 use crate::expr::test_harness;
136 use crate::scalar::Scalar;
137
138 #[test]
139 fn dtype() {
140 let dtype = test_harness::struct_dtype();
141 assert_eq!(
142 is_null(root()).return_dtype(&dtype).unwrap(),
143 DType::Bool(Nullability::NonNullable)
144 );
145 }
146
147 #[test]
148 fn replace_children() {
149 let expr = is_null(root());
150 expr.with_children([root()])
151 .vortex_expect("operation should succeed in test");
152 }
153
154 #[test]
155 fn evaluate_mask() {
156 let test_array =
157 PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
158 .into_array();
159 let expected = [false, true, false, true, false];
160
161 let result = test_array.clone().apply(&is_null(root())).unwrap();
162
163 assert_eq!(result.len(), test_array.len());
164 assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
165
166 for (i, expected_value) in expected.iter().enumerate() {
167 assert_eq!(
168 result.scalar_at(i).unwrap(),
169 Scalar::bool(*expected_value, Nullability::NonNullable)
170 );
171 }
172 }
173
174 #[test]
175 fn evaluate_all_false() {
176 let test_array = buffer![1, 2, 3, 4, 5].into_array();
177
178 let result = test_array.clone().apply(&is_null(root())).unwrap();
179
180 assert_eq!(result.len(), test_array.len());
181 for i in 0..result.len() {
183 assert_eq!(
184 result.scalar_at(i).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 for i in 0..result.len() {
201 assert_eq!(
202 result.scalar_at(i).unwrap(),
203 Scalar::bool(true, Nullability::NonNullable)
204 );
205 }
206 }
207
208 #[test]
209 fn evaluate_struct() {
210 let test_array = StructArray::from_fields(&[(
211 "a",
212 PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)])
213 .into_array(),
214 )])
215 .unwrap()
216 .into_array();
217 let expected = [false, true, false, true, false];
218
219 let result = test_array
220 .clone()
221 .apply(&is_null(get_item("a", root())))
222 .unwrap();
223
224 assert_eq!(result.len(), test_array.len());
225 assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
226
227 for (i, expected_value) in expected.iter().enumerate() {
228 assert_eq!(
229 result.scalar_at(i).unwrap(),
230 Scalar::bool(*expected_value, Nullability::NonNullable)
231 );
232 }
233 }
234
235 #[test]
236 fn test_display() {
237 let expr = is_null(get_item("name", root()));
238 assert_eq!(expr.to_string(), "is_null($.name)");
239
240 let expr2 = is_null(root());
241 assert_eq!(expr2.to_string(), "is_null($)");
242 }
243
244 #[test]
245 fn test_is_null_falsification() {
246 let expr = is_null(col("a"));
247
248 let (pruning_expr, st) = checked_pruning_expr(
249 &expr,
250 &FieldPathSet::from_iter([FieldPath::from_iter([
251 Field::Name("a".into()),
252 Field::Name("null_count".into()),
253 ])]),
254 )
255 .unwrap();
256
257 assert_eq!(&pruning_expr, &eq(col("a_null_count"), lit(0u64)));
258 assert_eq!(
259 st.map(),
260 &HashMap::from_iter([(FieldPath::from_name("a"), HashSet::from([Stat::NullCount]))])
261 );
262 }
263
264 #[test]
265 fn test_is_null_sensitive() {
266 assert!(is_null(col("a")).signature().is_null_sensitive());
268 }
269}