1use std::any::Any;
27use std::borrow::Cow;
28use std::fmt::Debug;
29use std::sync::Arc;
30
31use arrow_array::Array as ArrowArray;
32use arrow_array::ArrayRef as ArrowArrayRef;
33use arrow_array::RecordBatch;
34use arrow_array::RunArray;
35use arrow_array::cast::AsArray;
36use arrow_array::make_array;
37use arrow_array::types::Int16Type;
38use arrow_array::types::Int32Type;
39use arrow_array::types::Int64Type;
40use arrow_array::types::RunEndIndexType;
41use arrow_schema::DataType;
42use arrow_schema::Field;
43use arrow_schema::FieldRef;
44use arrow_schema::Fields;
45use arrow_schema::Schema;
46use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
47use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY;
48use base64::Engine;
49use base64::prelude::BASE64_STANDARD;
50use tracing::debug;
51use tracing::trace;
52use vortex_array::ArrayRef;
53use vortex_array::ExecutionCtx;
54use vortex_array::IntoArray;
55use vortex_array::arrays::DictArray;
56use vortex_array::arrays::ExtensionArray;
57use vortex_array::arrays::FixedSizeListArray;
58use vortex_array::arrays::ListArray;
59use vortex_array::arrays::ListViewArray;
60use vortex_array::arrays::StructArray;
61use vortex_array::arrays::extension::ExtensionArrayExt;
62use vortex_array::dtype::DType;
63use vortex_array::dtype::FieldName;
64use vortex_array::dtype::FieldNames;
65use vortex_array::dtype::NativePType;
66use vortex_array::dtype::Nullability;
67use vortex_array::dtype::StructFields;
68use vortex_array::dtype::extension::ExtDTypeRef;
69use vortex_array::dtype::extension::ExtId;
70use vortex_array::dtype::session::DTypeSession;
71use vortex_array::dtype::session::ExtDTypeRegistry;
72use vortex_array::extension::datetime::AnyTemporal;
73use vortex_array::validity::Validity;
74use vortex_error::VortexResult;
75use vortex_error::vortex_bail;
76use vortex_error::vortex_ensure;
77use vortex_error::vortex_ensure_eq;
78use vortex_error::vortex_err;
79use vortex_session::ArcSwapMap;
80use vortex_session::SessionExt;
81use vortex_session::SessionGuard;
82use vortex_session::SessionVar;
83use vortex_session::registry::Id;
84
85use crate::ArrowExportOptions;
86use crate::IntoVortexArray;
87use crate::convert::from_arrow_dyn;
88use crate::convert::map_from_arrow_parts;
89use crate::convert::nulls;
90use crate::convert::remove_nulls;
91use crate::convert::trim_map_entries;
92use crate::convert::trim_offsets;
93use crate::dtype::from_arrow_data_type;
94use crate::dtype::to_data_type_naive;
95use crate::executor::execute_arrow_naive;
96use crate::run_end_import::run_end_from_arrow;
97
98pub enum ArrowExport {
104 Unsupported(ArrayRef),
106 Exported(ArrowArrayRef),
108}
109
110pub enum ArrowImport {
116 Unsupported(ArrowArrayRef),
118 Imported(ArrayRef),
120}
121
122pub trait IntoArrowField<'a> {
135 fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field>;
137}
138
139impl<'a> IntoArrowField<'a> for &'a Field {
140 fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
141 Cow::Borrowed(self)
142 }
143}
144
145impl<'a> IntoArrowField<'a> for &'a FieldRef {
146 fn into_arrow_field(self, _data_type: &DataType) -> Cow<'a, Field> {
147 Cow::Borrowed(self.as_ref())
148 }
149}
150
151impl<'a> IntoArrowField<'a> for bool {
152 fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
153 Cow::Owned(Field::new("", data_type.clone(), self))
154 }
155}
156
157impl<'a> IntoArrowField<'a> for Nullability {
158 fn into_arrow_field(self, data_type: &DataType) -> Cow<'a, Field> {
159 self.is_nullable().into_arrow_field(data_type)
160 }
161}
162
163pub trait ArrowExportVTable: 'static + Send + Sync + Debug {
168 fn arrow_ext_id(&self) -> Id;
170
171 fn vortex_id(&self) -> Id;
175
176 fn to_arrow_field(
179 &self,
180 name: &str,
181 dtype: &DType,
182 session: &ArrowSession,
183 ) -> VortexResult<Option<Field>>;
184
185 fn execute_arrow(
191 &self,
192 array: ArrayRef,
193 target: &Field,
194 options: &ArrowExportOptions,
195 ctx: &mut ExecutionCtx,
196 ) -> VortexResult<ArrowExport>;
197}
198
199pub trait ArrowImportVTable: 'static + Send + Sync + Debug {
214 fn arrow_ext_id(&self) -> Id;
216
217 #[allow(clippy::wrong_self_convention)]
224 fn from_arrow_field(
225 &self,
226 field: &Field,
227 session: &ArrowSession,
228 ) -> VortexResult<Option<DType>>;
229
230 #[allow(clippy::wrong_self_convention)]
239 fn from_arrow_array(
240 &self,
241 array: ArrowArrayRef,
242 field: &Field,
243 dtype: &DType,
244 session: &ArrowSession,
245 ) -> VortexResult<ArrowImport>;
246}
247
248pub type ArrowExportVTableRef = Arc<dyn ArrowExportVTable>;
249pub type ArrowImportVTableRef = Arc<dyn ArrowImportVTable>;
250
251type ArrowExporterRegistry = ArcSwapMap<Id, Arc<[ArrowExportVTableRef]>>;
253type VortexExporterRegistry = ArcSwapMap<ExtId, Arc<[ArrowExportVTableRef]>>;
255type ArrowImporterRegistry = ArcSwapMap<Id, Arc<[ArrowImportVTableRef]>>;
257
258#[derive(Clone, Debug, Default)]
291pub struct ArrowSession {
292 exporters: ArrowExporterRegistry,
293 exporters_by_vortex: VortexExporterRegistry,
294 importers: ArrowImporterRegistry,
295 ext_dtypes: ExtDTypeRegistry,
299}
300
301impl ArrowSession {
302 pub(crate) fn new(dtype_session: &DTypeSession) -> Self {
304 Self {
305 ext_dtypes: dtype_session.registry().clone(),
306 ..Self::default()
307 }
308 }
309
310 pub fn register_exporter(&self, exporter: ArrowExportVTableRef) {
313 self.exporters.push(
314 exporter.arrow_ext_id(),
315 ArrowExportVTableRef::clone(&exporter),
316 );
317 self.exporters_by_vortex
318 .push(exporter.vortex_id(), exporter);
319 }
320
321 pub fn register_importer(&self, importer: ArrowImportVTableRef) {
323 self.importers.push(importer.arrow_ext_id(), importer);
324 }
325
326 fn exporters(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
327 self.exporters.get(id).unwrap_or_else(|| Arc::from([]))
328 }
329
330 fn exporters_by_vortex(&self, id: &Id) -> Arc<[ArrowExportVTableRef]> {
331 self.exporters_by_vortex
332 .get(id)
333 .unwrap_or_else(|| Arc::from([]))
334 }
335
336 fn importers(&self, id: &Id) -> Arc<[ArrowImportVTableRef]> {
337 self.importers.get(id).unwrap_or_else(|| Arc::from([]))
338 }
339
340 pub fn to_arrow_field(&self, name: &str, dtype: &DType) -> VortexResult<Field> {
348 match dtype {
350 DType::List(elem_dtype, nullability) => {
351 let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
352 Ok(Field::new_list(name, elem_field, nullability.is_nullable()))
353 }
354 DType::FixedSizeList(elem_dtype, elem_size, nullability) => {
355 let elem_field = self.to_arrow_field(Field::LIST_FIELD_DEFAULT_NAME, elem_dtype)?;
356 Ok(Field::new_fixed_size_list(
357 name,
358 elem_field,
359 (*elem_size).try_into()?,
360 nullability.is_nullable(),
361 ))
362 }
363 DType::Map(map_dtype, nullability) => {
364 let key = self.to_arrow_field("key", &map_dtype.key_dtype())?;
365 let value = self.to_arrow_field("value", &map_dtype.value_dtype())?;
366 let entries = Field::new_struct("entries", Fields::from(vec![key, value]), false);
367 Ok(Field::new(
368 name,
369 DataType::Map(Arc::new(entries), map_dtype.keys_sorted()),
370 nullability.is_nullable(),
371 ))
372 }
373 DType::Struct(fields, nullability) => {
374 let arrow_fields = Fields::from_iter(
375 fields
376 .fields()
377 .zip(fields.names().iter())
378 .map(|(field, name)| self.to_arrow_field(name.as_ref(), &field))
379 .collect::<VortexResult<Vec<_>>>()?,
380 );
381 Ok(Field::new_struct(
382 name,
383 arrow_fields,
384 nullability.is_nullable(),
385 ))
386 }
387 DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
388 match self.to_arrow_field_with_exporter(name, ext)? {
389 Some(field) => Ok(field),
390 None => self.to_arrow_field_without_exporter(name, ext),
391 }
392 }
393 DType::Variant(_) => {
394 Ok(Field::new(
398 name,
399 DataType::Struct(
400 vec![
401 Field::new("metadata", DataType::BinaryView, dtype.is_nullable()),
402 Field::new("value", DataType::BinaryView, dtype.is_nullable()),
403 ]
404 .into(),
405 ),
406 dtype.is_nullable(),
407 )
408 .with_metadata(
409 [(
410 EXTENSION_TYPE_NAME_KEY.to_string(),
411 "arrow.parquet.variant".to_string(),
412 )]
413 .into(),
414 ))
415 }
416 _ => Ok(Field::new(
417 name,
418 to_data_type_naive(dtype)?,
419 dtype.is_nullable(),
420 )),
421 }
422 }
423
424 pub fn to_arrow_schema(&self, dtype: &DType) -> VortexResult<Schema> {
428 let DType::Struct(struct_dtype, _) = dtype else {
429 vortex_bail!("to_arrow_schema requires a top-level struct dtype, got {dtype}");
430 };
431 let mut fields = Vec::with_capacity(struct_dtype.names().len());
432 for (name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
433 fields.push(self.to_arrow_field(name.as_ref(), &field_dtype)?);
434 }
435 Ok(Schema::new(fields))
436 }
437
438 pub fn to_arrow_datatype(&self, dtype: &DType) -> VortexResult<DataType> {
445 Ok(self.default_arrow_export_field(dtype)?.data_type().clone())
446 }
447
448 pub fn default_arrow_export_field(&self, dtype: &DType) -> VortexResult<Field> {
459 match dtype {
460 DType::Extension(ext) if !ext.is::<AnyTemporal>() => {
461 self.to_arrow_field_with_exporter("", ext)?.ok_or_else(|| {
462 vortex_err!(
463 "an Arrow export without a target field needs an extension type with an Arrow plugin, got {ext}"
464 )
465 })
466 }
467 _ => self.to_arrow_field("", dtype),
468 }
469 }
470
471 fn to_arrow_field_with_exporter(
474 &self,
475 name: &str,
476 ext_dtype: &ExtDTypeRef,
477 ) -> VortexResult<Option<Field>> {
478 let dtype = DType::Extension(ext_dtype.clone());
479
480 for plugin in self.exporters_by_vortex(&ext_dtype.id()).iter() {
481 if let Some(field) = plugin.to_arrow_field(name, &dtype, self)? {
482 return Ok(Some(field));
483 }
484 }
485
486 Ok(None)
487 }
488
489 fn to_arrow_field_without_exporter(
492 &self,
493 name: &str,
494 ext_dtype: &ExtDTypeRef,
495 ) -> VortexResult<Field> {
496 let mut field = self.to_arrow_field(name, ext_dtype.storage_dtype())?;
497 if let Some(storage_name) = field.extension_type_name() {
498 vortex_bail!(
499 "the Arrow storage of {ext_dtype} must not be an Arrow extension type, got {storage_name}"
500 );
501 }
502
503 let metadata = BASE64_STANDARD.encode(ext_dtype.serialize_metadata()?);
504 field.metadata_mut().extend([
505 (
506 EXTENSION_TYPE_NAME_KEY.to_owned(),
507 ext_dtype.id().to_string(),
508 ),
509 (EXTENSION_TYPE_METADATA_KEY.to_owned(), metadata),
510 ]);
511
512 Ok(field)
513 }
514
515 #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
521 fn rebuild_ext_dtype_by_vortex_id(
522 &self,
523 field: &Field,
524 storage_dtype: &DType,
525 ) -> VortexResult<Option<ExtDTypeRef>> {
526 let Some(dtype_plugin) = field
527 .extension_type_name()
528 .and_then(|name| self.ext_dtypes.get(&Id::new(name)))
529 else {
530 return Ok(None);
531 };
532
533 dtype_plugin
534 .deserialize(&decode_ext_metadata(field)?, storage_dtype.clone())
535 .map(Some)
536 }
537
538 #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
552 pub fn from_arrow_field(&self, field: &Field) -> VortexResult<DType> {
553 if let DataType::Dictionary(_, value_type) = field.data_type() {
554 return self
555 .from_arrow_field(&field.clone().with_data_type(value_type.as_ref().clone()));
556 }
557
558 if let Some(name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
559 for plugin in self.importers(&Id::new(name)).iter() {
560 if let Some(dtype) = plugin.from_arrow_field(field, self)? {
561 return Ok(dtype);
562 }
563 }
564 if name == "arrow.parquet.variant" {
566 return Ok(DType::Variant(field.is_nullable().into()));
567 }
568 }
569
570 let storage_dtype =
571 self.from_arrow_datatype(field.data_type(), field.is_nullable().into())?;
572
573 Ok(
574 match self.rebuild_ext_dtype_by_vortex_id(field, &storage_dtype)? {
575 Some(ext_dtype) => DType::Extension(ext_dtype),
576 None => storage_dtype,
577 },
578 )
579 }
580
581 pub fn from_arrow_datatype(
592 &self,
593 data_type: &DataType,
594 nullability: Nullability,
595 ) -> VortexResult<DType> {
596 Ok(match data_type {
597 DataType::List(elem)
598 | DataType::LargeList(elem)
599 | DataType::ListView(elem)
600 | DataType::LargeListView(elem) => {
601 DType::List(Arc::new(self.from_arrow_field(elem.as_ref())?), nullability)
602 }
603 DataType::FixedSizeList(elem, size) => DType::FixedSizeList(
604 Arc::new(self.from_arrow_field(elem.as_ref())?),
605 *size as u32,
606 nullability,
607 ),
608 DataType::Map(entries, keys_sorted) => {
609 vortex_ensure!(
610 !entries.is_nullable(),
611 "Arrow map entries field must be non-nullable"
612 );
613 let DataType::Struct(fields) = entries.data_type() else {
614 vortex_bail!(
615 "Arrow map entries field must have Struct type, got {:?}",
616 entries.data_type()
617 );
618 };
619 vortex_ensure_eq!(
620 fields.len(),
621 2,
622 "Arrow map entries struct must contain exactly two fields"
623 );
624 vortex_ensure!(
625 !fields[0].is_nullable(),
626 "Arrow map key field must be non-nullable"
627 );
628 DType::map(
629 self.from_arrow_field(fields[0].as_ref())?,
630 self.from_arrow_field(fields[1].as_ref())?,
631 *keys_sorted,
632 nullability,
633 )?
634 }
635 DataType::Struct(fields) => DType::Struct(self.from_arrow_fields(fields)?, nullability),
636 DataType::Dictionary(_, value_type) => {
637 self.from_arrow_datatype(value_type.as_ref(), nullability)?
638 }
639 DataType::RunEndEncoded(_, value_field) => {
640 self.from_arrow_field(&run_end_values_field(value_field, nullability))?
641 }
642 _ => from_arrow_data_type(data_type, nullability)?,
643 })
644 }
645
646 pub fn from_arrow_fields(&self, fields: &Fields) -> VortexResult<StructFields> {
649 fields
650 .iter()
651 .map(|f| {
652 self.from_arrow_field(f)
653 .map(|dt| (FieldName::from(f.name().as_str()), dt))
654 })
655 .collect::<VortexResult<StructFields>>()
656 }
657
658 pub fn from_arrow_schema(&self, schema: &Schema) -> VortexResult<DType> {
662 Ok(DType::Struct(
663 self.from_arrow_fields(schema.fields())?,
664 Nullability::NonNullable,
665 ))
666 }
667
668 pub fn from_arrow_record_batch(
676 &self,
677 batch: RecordBatch,
678 schema: &Schema,
679 ) -> VortexResult<ArrayRef> {
680 vortex_ensure_eq!(batch.num_columns(), schema.fields().len());
681 let length = batch.num_rows();
682 let names = FieldNames::from_iter(
683 schema
684 .fields()
685 .iter()
686 .map(|f| FieldName::from(f.name().as_str())),
687 );
688 let mut columns = Vec::with_capacity(schema.fields().len());
689 for (col, field) in batch.columns().iter().zip(schema.fields().iter()) {
690 columns.push(self.from_arrow_array_inner(ArrowArrayRef::clone(col), field)?);
691 }
692 Ok(StructArray::try_new(names, columns, length, Validity::NonNullable)?.into_array())
693 }
694
695 pub fn execute_arrow(
711 &self,
712 array: ArrayRef,
713 target: Option<&Field>,
714 ctx: &mut ExecutionCtx,
715 ) -> VortexResult<ArrowArrayRef> {
716 self.exporter(&ArrowExportOptions::default())
717 .execute_arrow(array, target, ctx)
718 }
719
720 pub fn exporter<'a>(&'a self, options: &'a ArrowExportOptions) -> ArrowExporter<'a> {
744 ArrowExporter {
745 session: self,
746 options,
747 }
748 }
749
750 pub fn from_arrow_array<'a>(
776 &self,
777 array: ArrowArrayRef,
778 field: impl IntoArrowField<'a>,
779 ) -> VortexResult<ArrayRef> {
780 let field = field.into_arrow_field(array.data_type());
781 self.from_arrow_array_inner(array, field.as_ref())
782 }
783
784 #[allow(clippy::wrong_self_convention)]
790 fn from_arrow_array_inner(
791 &self,
792 array: ArrowArrayRef,
793 field: &Field,
794 ) -> VortexResult<ArrayRef> {
795 if let DataType::Dictionary(..) = field.data_type() {
796 return self.dictionary_from_arrow(array.as_ref(), field);
797 }
798
799 let mut current = array;
800
801 if let Some(extension_name) = field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
802 #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
803 let importers = self.importers(&Id::new(extension_name));
804 if !importers.is_empty() {
805 let dtype = self.from_arrow_field(field)?;
806 let len = current.len();
807
808 for plugin in importers.iter() {
809 match plugin.from_arrow_array(current, field, &dtype, self)? {
810 ArrowImport::Imported(arr) => {
814 vortex_ensure_eq!(
815 arr.len(),
816 len,
817 "Arrow importer {} returned {} elements for an array of {}",
818 plugin.arrow_ext_id(),
819 arr.len(),
820 len
821 );
822 return Ok(arr);
823 }
824 ArrowImport::Unsupported(arr) => {
825 vortex_ensure_eq!(
826 arr.len(),
827 len,
828 "Arrow importer {} declined and returned {} elements for an array of {}",
829 plugin.arrow_ext_id(),
830 arr.len(),
831 len
832 );
833 current = arr;
834 }
835 }
836 }
837 }
838 }
839
840 let imported = self.from_arrow_array_canonical(current.as_ref(), field)?;
841
842 match self.rebuild_ext_dtype_by_vortex_id(field, imported.dtype())? {
843 Some(ext_dtype) => Ok(ExtensionArray::try_new(ext_dtype, imported)?.into_array()),
844 None => Ok(imported),
845 }
846 }
847
848 #[allow(clippy::wrong_self_convention)]
851 fn from_arrow_array_canonical(
852 &self,
853 array: &dyn ArrowArray,
854 field: &Field,
855 ) -> VortexResult<ArrayRef> {
856 match field.data_type() {
857 DataType::Struct(fields) => {
858 let arrow_struct = array.as_struct();
859 let names = FieldNames::from_iter(
860 fields.iter().map(|f| FieldName::from(f.name().as_str())),
861 );
862 let columns = arrow_struct
863 .columns()
864 .iter()
865 .zip(fields.iter())
866 .map(|(col, child_field)| {
867 let inner = if col.null_count() > 0 && !child_field.is_nullable() {
870 make_array(remove_nulls(col.to_data())?)
871 } else {
872 ArrowArrayRef::clone(col)
873 };
874 self.from_arrow_array_inner(inner, child_field.as_ref())
875 })
876 .collect::<VortexResult<Vec<_>>>()?;
877 let validity = nulls(arrow_struct.nulls(), field.is_nullable())?;
878 Ok(
879 StructArray::try_new(names, columns, arrow_struct.len(), validity)?
880 .into_array(),
881 )
882 }
883 DataType::List(elem_field) => {
884 let list = array.as_list::<i32>();
885 let (offsets, referenced) = trim_offsets(list.offsets());
886 let elements = self.from_arrow_array(
887 list.values().slice(referenced.start, referenced.len()),
888 elem_field.as_ref(),
889 )?;
890 let validity = nulls(list.nulls(), field.is_nullable())?;
891 Ok(
894 unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
895 .into_array(),
896 )
897 }
898 DataType::LargeList(elem_field) => {
899 let list = array.as_list::<i64>();
900 let (offsets, referenced) = trim_offsets(list.offsets());
901 let elements = self.from_arrow_array(
902 list.values().slice(referenced.start, referenced.len()),
903 elem_field.as_ref(),
904 )?;
905 let validity = nulls(list.nulls(), field.is_nullable())?;
906 Ok(
909 unsafe { ListArray::new_unchecked(elements, offsets.into_array(), validity) }
910 .into_array(),
911 )
912 }
913 DataType::FixedSizeList(elem_field, list_size) => {
914 let fsl = array.as_fixed_size_list();
915 let elements = self.from_arrow_array_inner(
916 ArrowArrayRef::clone(fsl.values()),
917 elem_field.as_ref(),
918 )?;
919 let validity = nulls(fsl.nulls(), field.is_nullable())?;
920 Ok(
921 FixedSizeListArray::try_new(elements, *list_size as u32, validity, fsl.len())?
922 .into_array(),
923 )
924 }
925 DataType::ListView(elem_field) => {
926 let list = array.as_list_view::<i32>();
927 let elements = self
928 .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
929 let offsets = list.offsets().clone().into_array();
930 let sizes = list.sizes().clone().into_array();
931 let validity = nulls(list.nulls(), field.is_nullable())?;
932 Ok(
935 unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
936 .into_array(),
937 )
938 }
939 DataType::LargeListView(elem_field) => {
940 let list = array.as_list_view::<i64>();
941 let elements = self
942 .from_arrow_array(ArrowArrayRef::clone(list.values()), elem_field.as_ref())?;
943 let offsets = list.offsets().clone().into_array();
944 let sizes = list.sizes().clone().into_array();
945 let validity = nulls(list.nulls(), field.is_nullable())?;
946 Ok(
949 unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) }
950 .into_array(),
951 )
952 }
953 DataType::Map(entries_field, keys_sorted) => {
954 let map = array.as_map();
955 let (entries, offsets) = trim_map_entries(map);
956 let entries_array: ArrowArrayRef = Arc::new(entries);
957 let entries = self.from_arrow_array_inner(entries_array, entries_field.as_ref())?;
958 map_from_arrow_parts(
959 entries,
960 &offsets,
961 map.nulls(),
962 *keys_sorted,
963 field.is_nullable(),
964 )
965 }
966 DataType::RunEndEncoded(ends_field, values_field) => {
967 let values_field = run_end_values_field(values_field, field.is_nullable().into());
968 match ends_field.data_type() {
969 DataType::Int16 => self.run_end_from_arrow::<Int16Type>(array, &values_field),
970 DataType::Int32 => self.run_end_from_arrow::<Int32Type>(array, &values_field),
971 DataType::Int64 => self.run_end_from_arrow::<Int64Type>(array, &values_field),
972 ends_dt => vortex_bail!(
973 "Arrow run-end array run ends must be Int16, Int32 or Int64, got {ends_dt}"
974 ),
975 }
976 }
977 _ => from_arrow_dyn(array, field.is_nullable()),
978 }
979 }
980
981 #[allow(clippy::wrong_self_convention)]
984 fn run_end_from_arrow<R: RunEndIndexType>(
985 &self,
986 array: &dyn ArrowArray,
987 values_field: &Field,
988 ) -> VortexResult<ArrayRef>
989 where
990 R::Native: NativePType,
991 {
992 let run_array = array
993 .as_any()
994 .downcast_ref::<RunArray<R>>()
995 .ok_or_else(|| vortex_err!("expected an Arrow RunArray, got {}", array.data_type()))?;
996 run_end_from_arrow(run_array, |values| {
997 self.from_arrow_array_inner(values, values_field)
998 })
999 }
1000
1001 fn dictionary_from_arrow(
1004 &self,
1005 array: &dyn ArrowArray,
1006 field: &Field,
1007 ) -> VortexResult<ArrayRef> {
1008 let dict = array.as_any_dictionary_opt().ok_or_else(|| {
1009 vortex_err!(
1010 "expected an Arrow DictionaryArray, got {}",
1011 array.data_type()
1012 )
1013 })?;
1014
1015 let values_field = field
1016 .clone()
1017 .with_data_type(dict.values().data_type().clone());
1018 let values =
1019 self.from_arrow_array_inner(ArrowArrayRef::clone(dict.values()), &values_field)?;
1020
1021 let codes = dict.keys();
1022 let codes = from_arrow_dyn(codes, codes.is_nullable())?;
1023
1024 Ok(unsafe { DictArray::new_unchecked(codes, values) }.into_array())
1027 }
1028}
1029
1030fn run_end_values_field(values_field: &FieldRef, nullability: Nullability) -> Field {
1033 values_field
1034 .as_ref()
1035 .clone()
1036 .with_nullable(nullability.into())
1037}
1038
1039fn decode_ext_metadata(field: &Field) -> VortexResult<Vec<u8>> {
1043 let encoded = field.extension_type_metadata().unwrap_or_default();
1044
1045 BASE64_STANDARD.decode(encoded).map_err(|err| {
1046 vortex_err!(
1047 "Arrow field {:?} must carry base64 extension metadata, got {encoded:?}: {err}",
1048 field.name()
1049 )
1050 })
1051}
1052
1053impl SessionVar for ArrowSession {
1054 fn as_any(&self) -> &dyn Any {
1055 self
1056 }
1057
1058 fn as_any_mut(&mut self) -> &mut dyn Any {
1059 self
1060 }
1061}
1062
1063#[derive(Clone, Copy, Debug)]
1065pub struct ArrowExporter<'a> {
1066 session: &'a ArrowSession,
1067 options: &'a ArrowExportOptions,
1068}
1069
1070impl ArrowExporter<'_> {
1071 pub(crate) fn options(&self) -> &ArrowExportOptions {
1072 self.options
1073 }
1074
1075 #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
1080 pub fn execute_arrow(
1081 &self,
1082 array: ArrayRef,
1083 target: Option<&Field>,
1084 ctx: &mut ExecutionCtx,
1085 ) -> VortexResult<ArrowArrayRef> {
1086 let arrow_field;
1090 let target_field = match target {
1091 Some(field) => field,
1092 None => {
1093 arrow_field = self.session.default_arrow_export_field(array.dtype())?;
1094 &arrow_field
1095 }
1096 };
1097
1098 if let Some(arrow_ext_name) = target_field.metadata().get(EXTENSION_TYPE_NAME_KEY) {
1099 let arrow_ext_id = Id::new(arrow_ext_name);
1100
1101 let len = array.len();
1104 let mut current = array;
1105
1106 for plugin in self.session.exporters(&arrow_ext_id).iter() {
1107 trace!(
1108 plugin = ?plugin,
1109 extension_name = arrow_ext_name,
1110 "probing plugin for converting Arrow array"
1111 );
1112
1113 match plugin.execute_arrow(current, target_field, self.options, ctx)? {
1114 ArrowExport::Exported(arrow) => {
1115 vortex_ensure_eq!(
1116 arrow.len(),
1117 len,
1118 "Arrow array length does not match Vortex array length after conversion to {:?}",
1119 arrow
1120 );
1121 return Ok(arrow);
1122 }
1123 ArrowExport::Unsupported(array) => current = array,
1124 }
1125 }
1126
1127 if let Some(ext_dtype) = current
1128 .dtype()
1129 .as_extension_opt()
1130 .filter(|ext_dtype| ext_dtype.id() == arrow_ext_id)
1131 .cloned()
1132 {
1133 return self.execute_arrow_ext_storage(current, &ext_dtype, target_field, ctx);
1134 }
1135
1136 debug!(
1137 extension_id = arrow_ext_name,
1138 data_type = ?target_field.data_type(),
1139 "unsupported Arrow extension type encountered, falling back to naive execution"
1140 );
1141
1142 return execute_arrow_naive(current, Some(target_field.data_type()), self, ctx);
1143 }
1144
1145 execute_arrow_naive(array, target.map(|field| field.data_type()), self, ctx)
1146 }
1147
1148 fn execute_arrow_ext_storage(
1151 &self,
1152 array: ArrayRef,
1153 ext_dtype: &ExtDTypeRef,
1154 target: &Field,
1155 ctx: &mut ExecutionCtx,
1156 ) -> VortexResult<ArrowArrayRef> {
1157 match self
1158 .session
1159 .rebuild_ext_dtype_by_vortex_id(target, ext_dtype.storage_dtype())?
1160 {
1161 Some(target_dtype) => vortex_ensure!(
1162 target_dtype == *ext_dtype,
1163 "Arrow field {:?} must name {ext_dtype}, got {target_dtype}",
1164 target.name()
1165 ),
1166 None => vortex_ensure!(
1167 decode_ext_metadata(target)? == ext_dtype.serialize_metadata()?,
1168 "Arrow field {:?} must carry the metadata of {ext_dtype}, got {:?}",
1169 target.name(),
1170 target.extension_type_metadata().unwrap_or_default()
1171 ),
1172 }
1173
1174 let storage = array
1175 .execute::<ExtensionArray>(ctx)?
1176 .storage_array()
1177 .clone();
1178
1179 execute_arrow_naive(storage, Some(target.data_type()), self, ctx)
1180 }
1181}
1182
1183pub trait ArrowSessionExt: SessionExt {
1185 fn arrow(&self) -> SessionGuard<'_, ArrowSession>;
1187}
1188
1189impl<S: SessionExt> ArrowSessionExt for S {
1190 fn arrow(&self) -> SessionGuard<'_, ArrowSession> {
1191 self.get::<ArrowSession>()
1192 }
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197 use std::ops::Range;
1198 use std::sync::Arc;
1199 use std::sync::LazyLock;
1200
1201 use arrow_array::DictionaryArray;
1202 use arrow_array::GenericListArray;
1203 use arrow_array::GenericListViewArray;
1204 use arrow_array::Int32Array;
1205 use arrow_array::Int64Array;
1206 use arrow_array::MapArray;
1207 use arrow_array::StringArray;
1208 use arrow_array::StructArray;
1209 use arrow_array::types::Int32Type;
1210 use arrow_buffer::OffsetBuffer;
1211 use arrow_buffer::ScalarBuffer;
1212 use arrow_schema::DataType;
1213 use arrow_schema::Field;
1214 use arrow_schema::FieldRef;
1215 use arrow_schema::Fields;
1216 use rstest::rstest;
1217 use vortex_array::IntoArray;
1218 use vortex_array::VortexSessionExecute as _;
1219 use vortex_array::arrays::Dict;
1220 use vortex_array::arrays::ListArray;
1221 use vortex_array::arrays::PrimitiveArray;
1222 use vortex_array::arrays::VarBinViewArray;
1223 use vortex_array::assert_arrays_eq;
1224 use vortex_array::dtype::DType;
1225 use vortex_array::dtype::Nullability;
1226 use vortex_array::dtype::PType;
1227 use vortex_array::validity::Validity;
1228 use vortex_error::VortexResult;
1229 use vortex_session::VortexSession;
1230 use vortex_session::registry::CachedId;
1231
1232 use super::*;
1233
1234 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1235
1236 #[rstest]
1237 #[case::prefix(0, 2)]
1238 #[case::middle(500, 2)]
1239 #[case::empty(500, 0)]
1240 #[case::empty_at_end(1000, 0)]
1241 fn test_sliced_list_imports_only_its_rows(
1242 #[values(false, true)] large: bool,
1243 #[case] start: usize,
1244 #[case] len: usize,
1245 ) -> VortexResult<()> {
1246 let lists = |rows: Range<i64>| -> ArrowArrayRef {
1247 let values = Arc::new(Int64Array::from_iter_values(
1248 rows.flat_map(|row| [row, row + 1]),
1249 ));
1250 let len = values.len() / 2;
1251 let field = Arc::new(Field::new("item", DataType::Int64, false));
1252 if large {
1253 Arc::new(GenericListArray::<i64>::new(
1254 field,
1255 OffsetBuffer::from_repeated_length(2, len),
1256 values,
1257 None,
1258 ))
1259 } else {
1260 Arc::new(GenericListArray::<i32>::new(
1261 field,
1262 OffsetBuffer::from_repeated_length(2, len),
1263 values,
1264 None,
1265 ))
1266 }
1267 };
1268 let session = ArrowSession::default();
1269 let sliced = session.from_arrow_array(lists(0..1000).slice(start, len), false)?;
1270 let fresh = session.from_arrow_array(lists(start as i64..(start + len) as i64), false)?;
1271 assert_eq!(sliced.nbytes(), fresh.nbytes());
1272 let mut ctx = SESSION.create_execution_ctx();
1273 let expected = ListArray::new(
1274 PrimitiveArray::from_iter(
1275 (start as i64..(start + len) as i64).flat_map(|row| [row, row + 1]),
1276 )
1277 .into_array(),
1278 PrimitiveArray::from_iter((0..=len as u64).map(|row| row * 2)).into_array(),
1279 Validity::NonNullable,
1280 &mut ctx,
1281 );
1282 assert_arrays_eq!(sliced, expected, &mut ctx);
1283 assert_arrays_eq!(fresh, expected, &mut ctx);
1284 Ok(())
1285 }
1286
1287 #[test]
1288 fn from_arrow_fields_matches_schema_conversion() -> VortexResult<()> {
1289 let session = ArrowSession::default();
1290 let fields = Fields::from(vec![
1291 Field::new("a", DataType::Int32, false),
1292 Field::new("b", DataType::Utf8View, true),
1293 ]);
1294 let struct_fields = session.from_arrow_fields(&fields)?;
1295 let schema_dtype = session.from_arrow_schema(&Schema::new(fields))?;
1296 let expected = StructFields::from_iter([
1297 ("a", DType::Primitive(PType::I32, Nullability::NonNullable)),
1298 ("b", DType::Utf8(Nullability::Nullable)),
1299 ]);
1300 assert_eq!(struct_fields, expected);
1301 assert_eq!(
1302 schema_dtype,
1303 DType::Struct(struct_fields, Nullability::NonNullable)
1304 );
1305 Ok(())
1306 }
1307
1308 #[test]
1309 fn from_arrow_field_maps_variant_without_importer() -> VortexResult<()> {
1310 let session = ArrowSession::default();
1311 let storage = DataType::Struct(
1312 vec![
1313 Field::new("metadata", DataType::BinaryView, false),
1314 Field::new("value", DataType::BinaryView, true),
1315 ]
1316 .into(),
1317 );
1318 let field = Field::new("v", storage, true).with_metadata(
1319 [(
1320 "ARROW:extension:name".to_string(),
1321 "arrow.parquet.variant".to_string(),
1322 )]
1323 .into(),
1324 );
1325 assert_eq!(
1326 session.from_arrow_field(&field)?,
1327 DType::Variant(Nullability::Nullable)
1328 );
1329 Ok(())
1330 }
1331
1332 static REJECT_DICTIONARY_ID: CachedId = CachedId::new("test.reject_dictionary");
1333
1334 #[derive(Debug)]
1336 struct DictionaryRejectingImporter;
1337
1338 impl ArrowImportVTable for DictionaryRejectingImporter {
1339 fn arrow_ext_id(&self) -> Id {
1340 *REJECT_DICTIONARY_ID
1341 }
1342
1343 fn from_arrow_field(
1344 &self,
1345 field: &Field,
1346 session: &ArrowSession,
1347 ) -> VortexResult<Option<DType>> {
1348 vortex_ensure!(
1349 !matches!(field.data_type(), DataType::Dictionary(..)),
1350 "an importer must never see a dictionary field, got {}",
1351 field.data_type()
1352 );
1353 session
1354 .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1355 .map(Some)
1356 }
1357
1358 fn from_arrow_array(
1359 &self,
1360 array: ArrowArrayRef,
1361 field: &Field,
1362 _dtype: &DType,
1363 session: &ArrowSession,
1364 ) -> VortexResult<ArrowImport> {
1365 vortex_ensure!(
1366 !matches!(array.data_type(), DataType::Dictionary(..)),
1367 "an importer must never see a dictionary array, got {}",
1368 array.data_type()
1369 );
1370 session
1371 .from_arrow_array(array, field.is_nullable())
1372 .map(ArrowImport::Imported)
1373 }
1374 }
1375
1376 #[rstest]
1381 #[case::plain(None)]
1382 #[case::extension_name(Some(*REJECT_DICTIONARY_ID))]
1383 fn dictionary_imports_as_dict_encoding(#[case] extension_name: Option<Id>) -> VortexResult<()> {
1384 let session = ArrowSession::default();
1385 session.register_importer(Arc::new(DictionaryRejectingImporter));
1386 let dict: ArrowArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(
1387 Int32Array::from(vec![0, 1, 0, 1]),
1388 Arc::new(StringArray::from(vec!["a", "b"])),
1389 )?);
1390 let metadata = extension_name
1391 .map(|id| (EXTENSION_TYPE_NAME_KEY.to_string(), id.to_string()))
1392 .into_iter()
1393 .collect();
1394 let field = Field::new("s", dict.data_type().clone(), false).with_metadata(metadata);
1395
1396 let dtype = session.from_arrow_field(&field)?;
1397 assert_eq!(dtype, DType::Utf8(Nullability::NonNullable));
1398
1399 let array = session.from_arrow_array(dict, &field)?;
1400 assert!(array.is::<Dict>(), "expected a Dict encoding, got {array}");
1401 assert_eq!(array.dtype(), &dtype);
1402 assert_arrays_eq!(
1403 array,
1404 VarBinViewArray::from_iter_str(["a", "b", "a", "b"]),
1405 &mut SESSION.create_execution_ctx()
1406 );
1407 Ok(())
1408 }
1409
1410 static TRUNCATE_ID: CachedId = CachedId::new("test.truncate");
1411
1412 #[derive(Debug)]
1415 struct TruncatingImporter {
1416 decline: bool,
1417 }
1418
1419 impl ArrowImportVTable for TruncatingImporter {
1420 fn arrow_ext_id(&self) -> Id {
1421 *TRUNCATE_ID
1422 }
1423
1424 fn from_arrow_field(
1425 &self,
1426 field: &Field,
1427 session: &ArrowSession,
1428 ) -> VortexResult<Option<DType>> {
1429 session
1430 .from_arrow_datatype(field.data_type(), field.is_nullable().into())
1431 .map(Some)
1432 }
1433
1434 fn from_arrow_array(
1435 &self,
1436 array: ArrowArrayRef,
1437 field: &Field,
1438 _dtype: &DType,
1439 session: &ArrowSession,
1440 ) -> VortexResult<ArrowImport> {
1441 let truncated = array.slice(0, array.len() - 1);
1442 if self.decline {
1443 return Ok(ArrowImport::Unsupported(truncated));
1444 }
1445 session
1446 .from_arrow_array(truncated, field.is_nullable())
1447 .map(ArrowImport::Imported)
1448 }
1449 }
1450
1451 fn truncated_field(name: &str, data_type: DataType) -> FieldRef {
1452 Arc::new(
1453 Field::new(name, data_type, false).with_metadata(
1454 [(
1455 EXTENSION_TYPE_NAME_KEY.to_string(),
1456 "test.truncate".to_string(),
1457 )]
1458 .into(),
1459 ),
1460 )
1461 }
1462
1463 fn list_with_truncated_child() -> ArrowArrayRef {
1464 Arc::new(GenericListArray::<i32>::new(
1465 truncated_field("item", DataType::Int64),
1466 OffsetBuffer::new(vec![0, 5].into()),
1467 Arc::new(Int64Array::from_iter_values(0..5)),
1468 None,
1469 ))
1470 }
1471
1472 fn list_view_with_truncated_child() -> ArrowArrayRef {
1473 Arc::new(GenericListViewArray::<i32>::new(
1474 truncated_field("item", DataType::Int64),
1475 ScalarBuffer::from(vec![0]),
1476 ScalarBuffer::from(vec![5]),
1477 Arc::new(Int64Array::from_iter_values(0..5)),
1478 None,
1479 ))
1480 }
1481
1482 fn map_with_truncated_child() -> ArrowArrayRef {
1483 let key_field = Arc::new(Field::new("key", DataType::Int64, false));
1484 let value_field = Arc::new(Field::new("value", DataType::Int64, false));
1485 let entries = StructArray::new(
1486 Fields::from(vec![key_field, value_field]),
1487 vec![
1488 Arc::new(Int64Array::from_iter_values(0..5)),
1489 Arc::new(Int64Array::from_iter_values(5..10)),
1490 ],
1491 None,
1492 );
1493 Arc::new(MapArray::new(
1494 truncated_field("entries", entries.data_type().clone()),
1495 OffsetBuffer::new(vec![0, 5].into()),
1496 entries,
1497 None,
1498 false,
1499 ))
1500 }
1501
1502 #[rstest]
1503 #[case::list(list_with_truncated_child())]
1504 #[case::list_view(list_view_with_truncated_child())]
1505 #[case::map(map_with_truncated_child())]
1506 fn test_rejects_importer_that_changes_child_length(
1507 #[case] array: ArrowArrayRef,
1508 #[values(false, true)] decline: bool,
1509 ) {
1510 let session = ArrowSession::default();
1511 session.register_importer(Arc::new(TruncatingImporter { decline }));
1512
1513 let err = session
1514 .from_arrow_array(array, false)
1515 .expect_err("a child importer that drops elements must be rejected");
1516 assert!(
1517 err.to_string()
1518 .contains("returned 4 elements for an array of 5"),
1519 "unexpected error: {err}"
1520 );
1521 }
1522}