Skip to main content

vortex_arrow/
scan.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Arrow output adapters for scan drivers.
5
6use std::future;
7use std::sync::Arc;
8
9use arrow_array::RecordBatch;
10use arrow_array::cast::AsArray;
11use arrow_schema::Field;
12use arrow_schema::SchemaRef;
13use futures::StreamExt;
14use futures::stream;
15use futures::stream::BoxStream;
16use vortex_array::VortexSessionExecute;
17use vortex_error::VortexResult;
18use vortex_scan::execution::driver::ScanDriver;
19use vortex_scan::prepare::ScanBuilder;
20
21use crate::ArrowSessionExt;
22use crate::ExecuteArrowExt;
23
24/// Arrow record-batch output for a scan driver.
25pub trait ArrowScanExt {
26    /// Runs the scan, executing each batch to an Arrow [`RecordBatch`].
27    ///
28    /// When `schema` is `None`, the session derives it from the scan's output dtype. Conversion
29    /// and decompression run on the worker producing each batch, in parallel across chunks.
30    fn run_record_batches(
31        self,
32        builder: impl Into<ScanBuilder>,
33        schema: Option<SchemaRef>,
34    ) -> BoxStream<'static, VortexResult<RecordBatch>>;
35}
36
37impl ArrowScanExt for ScanDriver {
38    fn run_record_batches(
39        self,
40        builder: impl Into<ScanBuilder>,
41        schema: Option<SchemaRef>,
42    ) -> BoxStream<'static, VortexResult<RecordBatch>> {
43        let builder = builder.into();
44        let session = builder.session().clone();
45        let schema = match schema {
46            Some(schema) => schema,
47            None => match session.arrow().to_arrow_schema(builder.dtype()) {
48                Ok(schema) => Arc::new(schema),
49                Err(error) => return stream::once(future::ready(Err(error))).boxed(),
50            },
51        };
52        let field = Field::new_struct("", schema.fields().clone(), false);
53        self.run_mapped(builder, move |batch| {
54            let mut ctx = session.create_execution_ctx();
55            let arrow = batch.execute_arrow(Some(&field), &mut ctx)?;
56            Ok(RecordBatch::from(arrow.as_struct().clone()))
57        })
58    }
59}