vortex_array/scalar_fn/builtin/boolean/
mod.rs1use 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#[derive(Clone)]
54pub struct Boolean;
55
56impl Boolean {
57 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
71const KLEENE_LUT: [[[bool; 2]; 2]; 2] = [
74 [[false, true], [true, true]], [[false, false], [false, true]], ];
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 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 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 if constant == is_and {
246 return Ok((other.node_dtype()?.nullability() == nullability).then_some(other));
247 }
248 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 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}