vortex_array/arrays/scalar_fn/vtable/
mod.rs1mod operations;
4mod validity;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::hash::Hash;
8use std::hash::Hasher;
9use std::marker::PhantomData;
10use std::ops::Deref;
11
12use itertools::Itertools;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_error::vortex_ensure;
16use vortex_error::vortex_panic;
17use vortex_session::VortexSession;
18use vortex_session::registry::CachedId;
19
20use crate::ArrayEq;
21use crate::ArrayHash;
22use crate::ArrayRef;
23use crate::ArraySlots;
24use crate::EqMode;
25use crate::IntoArray;
26use crate::array::Array;
27use crate::array::ArrayId;
28use crate::array::ArrayParts;
29use crate::array::ArrayView;
30use crate::array::VTable;
31use crate::array::with_empty_buffers;
32use crate::arrays::scalar_fn::array::ScalarFnArrayExt;
33use crate::arrays::scalar_fn::array::ScalarFnData;
34use crate::arrays::scalar_fn::rules::PARENT_RULES;
35use crate::arrays::scalar_fn::rules::RULES;
36use crate::buffer::BufferHandle;
37use crate::dtype::DType;
38use crate::executor::ExecutionCtx;
39use crate::executor::ExecutionResult;
40use crate::expr::Expression;
41use crate::expr::display::ExprDisplay;
42use crate::matcher::Matcher;
43use crate::scalar_fn;
44use crate::scalar_fn::Arity;
45use crate::scalar_fn::ChildName;
46use crate::scalar_fn::ExecutionArgs;
47use crate::scalar_fn::ScalarFnId;
48use crate::scalar_fn::ScalarFnVTableExt;
49use crate::scalar_fn::VecExecutionArgs;
50use crate::serde::ArrayChildren;
51
52pub type ScalarFnArray = Array<ScalarFn>;
54
55#[derive(Clone, Debug)]
56pub struct ScalarFn {
57 pub(super) id: ScalarFnId,
58}
59
60impl ArrayHash for ScalarFnData {
61 fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
62 self.scalar_fn().hash(state);
63 }
64}
65
66impl ArrayEq for ScalarFnData {
67 fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
68 self.scalar_fn() == other.scalar_fn()
69 }
70}
71
72impl VTable for ScalarFn {
73 type TypedArrayData = ScalarFnData;
74 type OperationsVTable = Self;
75 type ValidityVTable = Self;
76
77 fn id(&self) -> ArrayId {
78 self.id
79 }
80
81 fn validate(
82 &self,
83 data: &ScalarFnData,
84 dtype: &DType,
85 len: usize,
86 slots: &[Option<ArrayRef>],
87 ) -> VortexResult<()> {
88 vortex_ensure!(
89 data.scalar_fn.id() == self.id,
90 "ScalarFnArray data scalar_fn does not match vtable"
91 );
92 vortex_ensure!(
93 slots.iter().flatten().all(|c| c.len() == len),
94 "All child arrays must have the same length as the scalar function array"
95 );
96
97 let child_dtypes = slots
98 .iter()
99 .flatten()
100 .map(|c| c.dtype().clone())
101 .collect_vec();
102 vortex_ensure!(
103 data.scalar_fn.return_dtype(&child_dtypes)? == *dtype,
104 "ScalarFnArray dtype does not match scalar function return dtype"
105 );
106 Ok(())
107 }
108
109 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
110 0
111 }
112
113 fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
114 vortex_panic!("ScalarFnArray buffer index {idx} out of bounds")
115 }
116
117 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
118 None
119 }
120
121 fn with_buffers(
122 &self,
123 array: ArrayView<'_, Self>,
124 buffers: &[BufferHandle],
125 ) -> VortexResult<ArrayParts<Self>> {
126 with_empty_buffers(self, array, buffers)
127 }
128
129 fn serialize(
130 _array: ArrayView<'_, Self>,
131 _session: &VortexSession,
132 ) -> VortexResult<Option<Vec<u8>>> {
133 Ok(None)
135 }
136
137 fn deserialize(
138 &self,
139 _dtype: &DType,
140 _len: usize,
141 _metadata: &[u8],
142 _buffers: &[BufferHandle],
143 _children: &dyn ArrayChildren,
144 _session: &VortexSession,
145 ) -> VortexResult<ArrayParts<Self>> {
146 vortex_bail!("Deserialization of ScalarFnVTable metadata is not supported");
147 }
148
149 fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String {
150 array
151 .scalar_fn()
152 .signature()
153 .child_name(idx)
154 .as_ref()
155 .to_string()
156 }
157
158 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
159 let args = VecExecutionArgs::new(array.children(), array.len());
160 array
161 .scalar_fn()
162 .execute(&args, ctx)
163 .map(ExecutionResult::done)
164 }
165
166 fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
167 RULES.evaluate(array)
168 }
169
170 fn reduce_parent(
171 array: ArrayView<'_, Self>,
172 parent: &ArrayRef,
173 child_idx: usize,
174 ) -> VortexResult<Option<ArrayRef>> {
175 PARENT_RULES.evaluate(array, parent, child_idx)
176 }
177}
178
179pub trait ScalarFnFactoryExt: scalar_fn::ScalarFnVTable {
181 fn try_new_array(
182 &self,
183 len: usize,
184 options: Self::Options,
185 children: impl Into<Vec<ArrayRef>>,
186 ) -> VortexResult<ArrayRef> {
187 let scalar_fn = scalar_fn::TypedScalarFnInstance::new(self.clone(), options).erased();
188
189 let children = children.into();
190 vortex_ensure!(
191 children.iter().all(|c| c.len() == len),
192 "All child arrays must have the same length as the scalar function array"
193 );
194
195 let child_dtypes = children.iter().map(|c| c.dtype().clone()).collect_vec();
196 let dtype = scalar_fn.return_dtype(&child_dtypes)?;
197
198 let data = ScalarFnData {
199 scalar_fn: scalar_fn.clone(),
200 };
201 let vtable = ScalarFn { id: scalar_fn.id() };
202 Ok(unsafe {
203 Array::from_parts_unchecked(
204 ArrayParts::new(vtable, dtype, len, data)
205 .with_slots(children.into_iter().map(Some).collect::<ArraySlots>()),
206 )
207 }
208 .into_array())
209 }
210}
211impl<V: scalar_fn::ScalarFnVTable> ScalarFnFactoryExt for V {}
212
213#[derive(Debug)]
215pub struct AnyScalarFn;
216impl Matcher for AnyScalarFn {
217 type Match<'a> = ArrayView<'a, ScalarFn>;
218
219 fn matches(array: &ArrayRef) -> bool {
220 array.is::<ScalarFn>()
221 }
222
223 fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
224 array.as_opt::<ScalarFn>()
225 }
226}
227
228#[derive(Debug, Default)]
230pub struct ExactScalarFn<F: scalar_fn::ScalarFnVTable>(PhantomData<F>);
231
232impl<F: scalar_fn::ScalarFnVTable> Matcher for ExactScalarFn<F> {
233 type Match<'a> = ScalarFnArrayView<'a, F>;
234
235 fn matches(array: &ArrayRef) -> bool {
236 if let Some(scalar_fn_array) = array.as_opt::<ScalarFn>() {
237 scalar_fn_array.data().scalar_fn().is::<F>()
238 } else {
239 false
240 }
241 }
242
243 fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
244 let scalar_fn_array = array.as_opt::<ScalarFn>()?;
245 let scalar_fn_data = scalar_fn_array.data();
246 let scalar_fn = scalar_fn_data.scalar_fn().downcast_ref::<F>()?;
247 Some(ScalarFnArrayView {
248 array,
249 vtable: scalar_fn.vtable(),
250 options: scalar_fn.options(),
251 })
252 }
253}
254
255pub struct ScalarFnArrayView<'a, F: scalar_fn::ScalarFnVTable> {
256 array: &'a ArrayRef,
257 pub vtable: &'a F,
258 pub options: &'a F::Options,
259}
260
261impl<F: scalar_fn::ScalarFnVTable> Deref for ScalarFnArrayView<'_, F> {
262 type Target = ArrayRef;
263
264 fn deref(&self) -> &Self::Target {
265 self.array
266 }
267}
268
269#[derive(Clone)]
271struct ArrayExpr;
272
273#[derive(Clone, Debug)]
274struct FakeEq<T>(T);
275
276impl<T> PartialEq<Self> for FakeEq<T> {
277 fn eq(&self, _other: &Self) -> bool {
278 false
279 }
280}
281
282impl<T> Eq for FakeEq<T> {}
283
284impl<T> Hash for FakeEq<T> {
285 fn hash<H: Hasher>(&self, _state: &mut H) {}
286}
287
288impl Display for FakeEq<ArrayRef> {
289 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
290 write!(f, "{}", self.0.encoding_id())
291 }
292}
293
294impl scalar_fn::ScalarFnVTable for ArrayExpr {
295 type Options = FakeEq<ArrayRef>;
296
297 fn id(&self) -> ScalarFnId {
298 static ID: CachedId = CachedId::new("vortex.array");
299 *ID
300 }
301
302 fn arity(&self, _options: &Self::Options) -> Arity {
303 Arity::Exact(0)
304 }
305
306 fn child_name(&self, _options: &Self::Options, _child_idx: usize) -> ChildName {
307 todo!()
308 }
309
310 fn fmt_sql(
311 &self,
312 options: &Self::Options,
313 _expr: &dyn ExprDisplay,
314 f: &mut Formatter<'_>,
315 ) -> std::fmt::Result {
316 write!(f, "{}", options.0.encoding_id())
317 }
318
319 fn return_dtype(&self, options: &Self::Options, _arg_dtypes: &[DType]) -> VortexResult<DType> {
320 Ok(options.0.dtype().clone())
321 }
322
323 fn execute(
324 &self,
325 options: &Self::Options,
326 _args: &dyn ExecutionArgs,
327 ctx: &mut ExecutionCtx,
328 ) -> VortexResult<ArrayRef> {
329 crate::Executable::execute(options.0.clone(), ctx)
330 }
331
332 fn validity(
333 &self,
334 options: &Self::Options,
335 _expression: &Expression,
336 ) -> VortexResult<Option<Expression>> {
337 let validity_array = options.0.validity()?.to_array(options.0.len());
338 Ok(Some(ArrayExpr.new_expr(FakeEq(validity_array), [])))
339 }
340
341 fn is_strict(&self, _options: &Self::Options) -> bool {
342 true
343 }
344}