Skip to main content

vortex_array/scalar_fn/builtin/boolean/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The Kleene boolean scalar function and its encoding-specific execution adaptor.
5//!
6//! [`Boolean`] binds a [`BooleanOperator`] to two boolean operands. Execution can use
7//! encoding-specific kernels through [`BooleanExecuteAdaptor`] or the native kernel.
8
9use std::fmt::Formatter;
10
11use prost::Message;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_session::VortexSession;
15use vortex_session::registry::CachedId;
16
17use crate::AnyColumnar;
18use crate::ArrayRef;
19use crate::ExecutionCtx;
20use crate::arrays::Constant;
21use crate::arrays::ScalarFnArray;
22use crate::dtype::DType;
23use crate::dtype::Nullability;
24use crate::matcher::Matcher;
25use crate::proto::expr as pb;
26use crate::require_input;
27use crate::scalar::Scalar;
28use crate::scalar_fn::Arity;
29use crate::scalar_fn::ChildName;
30use crate::scalar_fn::ExecutionArgs;
31use crate::scalar_fn::ReduceNode;
32use crate::scalar_fn::ScalarFnExecutionResult;
33use crate::scalar_fn::ScalarFnId;
34use crate::scalar_fn::ScalarFnVTable;
35use crate::scalar_fn::ScalarFnVTableExt;
36use crate::scalar_fn::builtin::binary::binary_child_name;
37use crate::scalar_fn::builtin::binary::fmt_infix;
38use crate::scalar_fn::builtin::cast::Cast;
39use crate::scalar_fn::builtin::operators::BooleanOperator;
40use crate::scalar_fn::display::ExprDisplay;
41
42mod kernel;
43pub use kernel::BooleanExecuteAdaptor;
44pub use kernel::BooleanKernel;
45#[expect(deprecated)]
46pub use kernel::and_kleene;
47pub use kernel::kleene_boolean_buffer_scalar;
48pub use kernel::kleene_boolean_buffers;
49#[expect(deprecated)]
50pub use kernel::or_kleene;
51
52/// A Kleene boolean operation over two boolean operands with a [`BooleanOperator`].
53#[derive(Clone)]
54pub struct Boolean;
55
56impl Boolean {
57    /// Creates a lazy boolean operation over `lhs` and `rhs`.
58    ///
59    /// # Errors
60    ///
61    /// Returns an error if the children have different lengths or are not boolean.
62    pub fn try_new(
63        lhs: ArrayRef,
64        rhs: ArrayRef,
65        operator: BooleanOperator,
66    ) -> VortexResult<ScalarFnArray> {
67        ScalarFnArray::try_new(Boolean.bind(operator), [lhs, rhs])
68    }
69}
70
71/// Kleene and/or lookup table where both arguments are constant and non-NULL.
72/// is_and, left, right
73const KLEENE_LUT: [[[bool; 2]; 2]; 2] = [
74    [[false, true], [true, true]],   // or
75    [[false, false], [false, true]], // and
76];
77
78impl ScalarFnVTable for Boolean {
79    type Options = BooleanOperator;
80
81    fn id(&self) -> ScalarFnId {
82        static ID: CachedId = CachedId::new("vortex.boolean");
83        *ID
84    }
85
86    fn serialize(&self, operator: &BooleanOperator) -> VortexResult<Option<Vec<u8>>> {
87        Ok(Some(
88            pb::BooleanOpts {
89                op: pb::boolean_opts::BooleanOp::from(*operator).into(),
90            }
91            .encode_to_vec(),
92        ))
93    }
94
95    fn deserialize(
96        &self,
97        metadata: &[u8],
98        _session: &VortexSession,
99    ) -> VortexResult<BooleanOperator> {
100        let opts = pb::BooleanOpts::decode(metadata)?;
101
102        Ok(pb::boolean_opts::BooleanOp::try_from(opts.op)?.into())
103    }
104
105    fn arity(&self, _operator: &BooleanOperator) -> Arity {
106        Arity::Exact(2)
107    }
108
109    fn child_name(&self, _operator: &BooleanOperator, child_idx: usize) -> ChildName {
110        binary_child_name(child_idx)
111    }
112
113    fn fmt_sql(
114        &self,
115        operator: &BooleanOperator,
116        expr: &dyn ExprDisplay,
117        f: &mut Formatter<'_>,
118    ) -> std::fmt::Result {
119        fmt_infix(operator, expr, f)
120    }
121
122    fn return_dtype(
123        &self,
124        operator: &BooleanOperator,
125        arg_dtypes: &[DType],
126    ) -> VortexResult<DType> {
127        let lhs = &arg_dtypes[0];
128        let rhs = &arg_dtypes[1];
129
130        if !(lhs.is_boolean() && rhs.is_boolean()) {
131            vortex_bail!("'{operator}' requires bool operands, got {lhs} and {rhs}",);
132        }
133
134        Ok(DType::Bool((lhs.is_nullable() || rhs.is_nullable()).into()))
135    }
136
137    fn execute(
138        &self,
139        operator: &BooleanOperator,
140        args: &dyn ExecutionArgs,
141        ctx: &mut ExecutionCtx,
142    ) -> VortexResult<ArrayRef> {
143        let lhs = args.get(0)?;
144        let rhs = args.get(1)?;
145
146        kernel::execute_boolean(lhs, rhs, *operator, ctx)
147    }
148
149    fn simplify<T: ReduceNode>(
150        &self,
151        operator: &BooleanOperator,
152        node: &T,
153    ) -> VortexResult<Option<T>> {
154        let lhs = node.child(0);
155        let rhs = node.child(1);
156
157        let bool_constant = |node: &T| node.as_constant()?.as_bool_opt().map(|value| value.value());
158
159        // AND/OR use Kleene three-valued logic. `None` below is a boolean null.
160        //
161        // AND:
162        // - false AND x => false
163        // - true  AND x => x
164        // - null  AND null => null
165        //
166        // OR:
167        // - true  OR x => true
168        // - false OR x => x
169        // - null  OR null => null
170        //
171        // Other null cases either fall out of the identity/annihilator rules
172        // above (`null AND true`, `null OR false`) or cannot be reduced under
173        // Kleene semantics (`null AND x`, `null OR x` for non-constant `x`).
174        // Reduction must keep the result nullability binding inferred: the annihilator
175        // constant and the identity child can both be less nullable than `lhs OP rhs`.
176        let result_nullable = lhs.node_dtype()?.is_nullable() || rhs.node_dtype()?.is_nullable();
177        let nullability = Nullability::from(result_nullable);
178        let bool_constant_node = |value: bool| node.new_constant(Scalar::bool(value, nullability));
179        let widen = |child: T| -> VortexResult<T> {
180            if child.node_dtype()?.is_nullable() == result_nullable {
181                Ok(child)
182            } else {
183                child.new_node(
184                    Cast.bind(DType::Bool(nullability)),
185                    std::slice::from_ref(&child),
186                )
187            }
188        };
189
190        Ok(match operator {
191            BooleanOperator::And => match (bool_constant(&lhs), bool_constant(&rhs)) {
192                (Some(Some(false)), _) | (_, Some(Some(false))) => Some(bool_constant_node(false)),
193                (Some(Some(true)), _) => Some(widen(rhs)?),
194                (_, Some(Some(true))) => Some(widen(lhs)?),
195                (Some(None), Some(None)) => Some(widen(lhs)?),
196                _ => None,
197            },
198            BooleanOperator::Or => match (bool_constant(&lhs), bool_constant(&rhs)) {
199                (Some(Some(true)), _) | (_, Some(Some(true))) => Some(bool_constant_node(true)),
200                (Some(Some(false)), _) => Some(widen(rhs)?),
201                (_, Some(Some(false))) => Some(widen(lhs)?),
202                (Some(None), Some(None)) => Some(widen(lhs)?),
203                _ => None,
204            },
205        })
206    }
207
208    fn reduce<T: ReduceNode>(
209        &self,
210        operator: &BooleanOperator,
211        node: &T,
212    ) -> VortexResult<Option<T>> {
213        let left = node.child(0);
214        let right = node.child(1);
215
216        let left_const = left.as_constant();
217        let right_const = right.as_constant();
218
219        // We don't handle Kleene NULL reduction here (.value() returns None
220        // for NULL). This will be reduced in the boolean kernel during
221        // execution. Not handling the case keeps the code much simpler.
222        let left_const = left_const
223            .and_then(|s| s.value().cloned())
224            .map(|v| v.as_bool());
225        let right_const = right_const
226            .and_then(|s| s.value().cloned())
227            .map(|v| v.as_bool());
228        let is_and = *operator == BooleanOperator::And;
229        let nullability = node.node_dtype()?.nullability();
230
231        let (constant, other) = match (left_const, right_const) {
232            (None, None) => return Ok(None),
233            (Some(left_const), Some(right_const)) => {
234                return Ok(Some(left.new_constant(Scalar::bool(
235                    KLEENE_LUT[is_and as usize][left_const as usize][right_const as usize],
236                    nullability,
237                ))));
238            }
239            (Some(constant), None) => (constant, right),
240            (None, Some(constant)) => (constant, left),
241        };
242
243        // `x AND true` and `x OR false` are `x`, but only when `x` already has the result's
244        // nullability: otherwise leave the cast to the boolean kernel.
245        if constant == is_and {
246            return Ok((other.node_dtype()?.nullability() == nullability).then_some(other));
247        }
248        // `x AND false` and `x OR true` are the constant itself.
249        Ok(Some(
250            other.new_constant(Scalar::bool(constant, nullability)),
251        ))
252    }
253
254    fn execute_step(
255        &self,
256        operator: &BooleanOperator,
257        args: &dyn ExecutionArgs,
258        ctx: &mut ExecutionCtx,
259    ) -> VortexResult<ScalarFnExecutionResult> {
260        let columnar = |idx| args.input_matches(idx, AnyColumnar::matches);
261        let constant = |idx| args.input_matches(idx, |array| array.is::<Constant>());
262
263        // A constant operand can decide the result, such as `false AND x`, so `execute` does not
264        // need the other operand executed.
265        let ready = (columnar(0)? && columnar(1)?) || constant(0)? || constant(1)?;
266        if !ready {
267            require_input!(args, 0 => AnyColumnar);
268            require_input!(args, 1 => AnyColumnar);
269        }
270
271        self.execute(operator, args, ctx)
272            .map(ScalarFnExecutionResult::done)
273    }
274
275    fn is_strict(&self, _operator: &BooleanOperator) -> bool {
276        false
277    }
278
279    fn is_infallible(&self, _operator: &BooleanOperator) -> bool {
280        true
281    }
282}