Skip to main content

vortex_functions/
ext_storage.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::ExecutionCtx;
6use vortex_array::IntoArray;
7use vortex_array::arrays::ConstantArray;
8use vortex_array::arrays::ExtensionArray;
9use vortex_array::arrays::extension::ExtensionArrayExt;
10use vortex_array::dtype::DType;
11use vortex_array::scalar_fn::Arity;
12use vortex_array::scalar_fn::ChildName;
13use vortex_array::scalar_fn::EmptyOptions;
14use vortex_array::scalar_fn::ExecutionArgs;
15use vortex_array::scalar_fn::ReduceNode;
16use vortex_array::scalar_fn::ScalarFnId;
17use vortex_array::scalar_fn::ScalarFnVTable;
18use vortex_error::VortexResult;
19use vortex_error::vortex_bail;
20use vortex_session::VortexSession;
21use vortex_session::registry::CachedId;
22
23/// Extract the storage values from an extension array.
24#[derive(Clone)]
25pub struct ExtStorage;
26
27impl ScalarFnVTable for ExtStorage {
28    type Options = EmptyOptions;
29
30    fn id(&self) -> ScalarFnId {
31        static ID: CachedId = CachedId::new("vortex.ext.storage");
32        *ID
33    }
34
35    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
36        Ok(Some(vec![]))
37    }
38
39    fn deserialize(
40        &self,
41        _metadata: &[u8],
42        _session: &VortexSession,
43    ) -> VortexResult<Self::Options> {
44        Ok(EmptyOptions)
45    }
46
47    fn arity(&self, _options: &Self::Options) -> Arity {
48        Arity::Exact(1)
49    }
50
51    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
52        match child_idx {
53            0 => ChildName::from("input"),
54            _ => unreachable!("Invalid child index {child_idx} for ext_storage()"),
55        }
56    }
57
58    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
59        let DType::Extension(ext_dtype) = &arg_dtypes[0] else {
60            vortex_bail!("ext_storage() requires Extension, got {}", arg_dtypes[0]);
61        };
62
63        Ok(ext_dtype.storage_dtype().clone())
64    }
65
66    fn execute(
67        &self,
68        _options: &Self::Options,
69        args: &dyn ExecutionArgs,
70        ctx: &mut ExecutionCtx,
71    ) -> VortexResult<ArrayRef> {
72        let input = args.get(0)?;
73
74        if !matches!(input.dtype(), DType::Extension(_)) {
75            vortex_bail!("ext_storage() requires Extension, got {}", input.dtype());
76        }
77
78        if let Some(scalar) = input.as_constant() {
79            let storage_scalar = scalar.as_extension().to_storage_scalar();
80            return Ok(ConstantArray::new(storage_scalar, args.row_count()).into_array());
81        }
82
83        let input = input.execute::<ExtensionArray>(ctx)?;
84        Ok(input.storage_array().clone())
85    }
86
87    fn reduce<T: ReduceNode>(&self, _options: &Self::Options, node: &T) -> VortexResult<Option<T>> {
88        Ok(node
89            .child(0)
90            .as_constant()
91            .map(|scalar| node.new_constant(scalar.as_extension().to_storage_scalar())))
92    }
93
94    fn is_strict(&self, _options: &Self::Options) -> bool {
95        true
96    }
97
98    fn is_infallible(&self, _options: &Self::Options) -> bool {
99        true
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use std::sync::LazyLock;
106
107    use rstest::rstest;
108    use vortex_array::IntoArray;
109    use vortex_array::VortexSessionExecute;
110    use vortex_array::arrays::Constant;
111    use vortex_array::arrays::ConstantArray;
112    use vortex_array::arrays::ExtensionArray;
113    use vortex_array::arrays::PrimitiveArray;
114    use vortex_array::arrays::StructArray;
115    use vortex_array::assert_arrays_eq;
116    use vortex_array::dtype::DType;
117    use vortex_array::dtype::Nullability;
118    use vortex_array::dtype::PType;
119    use vortex_array::dtype::extension::ExtDTypeRef;
120    use vortex_array::dtype::extension::ForeignExtDType;
121    use vortex_array::extension::datetime::TimeUnit;
122    use vortex_array::extension::datetime::Timestamp;
123    use vortex_array::optimizer::ArrayOptimizer;
124    use vortex_array::scalar::Scalar;
125    use vortex_buffer::buffer;
126    use vortex_error::VortexResult;
127    use vortex_expr::ArrayExprExt;
128    use vortex_expr::get_item;
129    use vortex_expr::root;
130    use vortex_session::VortexSession;
131    use vortex_session::registry::CachedId;
132
133    use crate::expr::ext_storage;
134    use crate::expr::select;
135
136    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
137        let session = VortexSession::empty();
138
139        vortex_array::initialize(&session);
140
141        crate::initialize(&session);
142
143        session
144    });
145
146    fn ext_dtype(nullability: Nullability) -> ExtDTypeRef {
147        Timestamp::new(TimeUnit::Nanoseconds, nullability).erased()
148    }
149
150    #[test]
151    fn extracts_extension_storage_array() -> VortexResult<()> {
152        let storage = buffer![2i64, 4, 6].into_array();
153        let array =
154            ExtensionArray::new(ext_dtype(Nullability::NonNullable), storage.clone()).into_array();
155
156        let result = array.apply(&ext_storage(root()))?;
157
158        assert_eq!(
159            result.dtype(),
160            &DType::Primitive(PType::I64, Nullability::NonNullable)
161        );
162        assert_arrays_eq!(result, storage, &mut SESSION.create_execution_ctx());
163        Ok(())
164    }
165
166    #[test]
167    fn extracts_nullable_extension_storage_array() -> VortexResult<()> {
168        let storage = PrimitiveArray::from_option_iter([Some(2i64), None, Some(6)]).into_array();
169        let array =
170            ExtensionArray::new(ext_dtype(Nullability::Nullable), storage.clone()).into_array();
171
172        let result = array.apply(&ext_storage(root()))?;
173
174        assert_eq!(
175            result.dtype(),
176            &DType::Primitive(PType::I64, Nullability::Nullable)
177        );
178        assert_arrays_eq!(result, storage, &mut SESSION.create_execution_ctx());
179        Ok(())
180    }
181
182    #[test]
183    fn extracts_constant_extension_storage_scalar() -> VortexResult<()> {
184        let storage_scalar = Scalar::primitive(4i64, Nullability::NonNullable);
185        let scalar =
186            Scalar::extension_ref(ext_dtype(Nullability::NonNullable), storage_scalar.clone());
187        let array = ConstantArray::new(scalar, 3).into_array();
188
189        let result = array.apply(&ext_storage(root()))?;
190
191        assert_eq!(
192            result.dtype(),
193            &DType::Primitive(PType::I64, Nullability::NonNullable)
194        );
195        assert_arrays_eq!(
196            result,
197            ConstantArray::new(storage_scalar, 3),
198            &mut SESSION.create_execution_ctx()
199        );
200        Ok(())
201    }
202
203    #[rstest]
204    fn constant_storage_reduces(
205        #[values(false, true)] null: bool,
206        #[values(0, 3)] len: usize,
207    ) -> VortexResult<()> {
208        let storage = if null {
209            Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable))
210        } else {
211            Scalar::primitive(4i64, Nullability::Nullable)
212        };
213        let scalar = Scalar::extension_ref(ext_dtype(Nullability::Nullable), storage.clone());
214        let result = ConstantArray::new(scalar, len)
215            .into_array()
216            .apply(&ext_storage(root()))?
217            .optimize_ctx(&SESSION)?;
218
219        assert_eq!(result.as_::<Constant>().scalar(), &storage);
220        assert_eq!(result.len(), len);
221        Ok(())
222    }
223
224    #[test]
225    fn nested_constant_field_reduces_through_select_and_storage() -> VortexResult<()> {
226        static EXT_ID: CachedId = CachedId::new("test.measurement");
227        let storage_array =
228            StructArray::from_fields(&[("value", ConstantArray::new(42i32, 1).into_array())])?;
229        let storage = Scalar::struct_(storage_array.dtype().clone(), [Scalar::from(42i32)]);
230        let dtype = ForeignExtDType::from_parts(*EXT_ID, vec![], storage.dtype().clone())?;
231        let measurement = Scalar::extension_ref(dtype, storage);
232        let array = StructArray::from_fields(&[
233            (
234                "measurement",
235                ConstantArray::new(measurement, 3).into_array(),
236            ),
237            ("other", buffer![1i32, 2, 3].into_array()),
238        ])?
239        .into_array();
240        let expr = get_item(
241            "value",
242            ext_storage(get_item("measurement", select(["measurement"], root()))),
243        );
244
245        let result = array.apply(&expr)?.optimize_ctx(&SESSION)?;
246
247        assert_eq!(result.as_::<Constant>().scalar(), &Scalar::from(42i32));
248        assert_eq!(result.len(), 3);
249        Ok(())
250    }
251
252    #[test]
253    fn rejects_non_extension_input() {
254        let dtype = DType::Primitive(PType::U64, Nullability::NonNullable);
255        let err = ext_storage(root()).return_dtype(&dtype).unwrap_err();
256        assert!(err.to_string().contains("requires Extension"));
257    }
258
259    #[test]
260    fn test_display() {
261        assert_eq!(ext_storage(root()).to_string(), "vortex.ext.storage($)");
262    }
263}