alamb commented on a change in pull request #1138:
URL: https://github.com/apache/arrow-datafusion/pull/1138#discussion_r732217195
##########
File path: datafusion/src/physical_plan/file_format/json.rs
##########
@@ -120,19 +113,31 @@ impl ExecutionPlan for NdJsonExec {
async fn execute(&self, partition: usize) ->
Result<SendableRecordBatchStream> {
let proj = self.projection.as_ref().map(|p| {
p.iter()
- .map(|col_idx| self.schema.field(*col_idx).name())
+ .map(|col_idx| self.file_schema.field(*col_idx).name())
.cloned()
.collect()
});
- let file = self
- .object_store
- .file_reader(self.files[partition].file_meta.sized_file.clone())?
- .sync_reader()?;
-
- let json_reader = json::Reader::new(file, self.schema(),
self.batch_size, proj);
+ let batch_size = self.batch_size;
+ let file_schema = Arc::clone(&self.file_schema);
+
+ // The avro reader cannot limit the number of records, so `remaining`
is ignored.
Review comment:
```suggestion
// The json reader cannot limit the number of records, so
`remaining` is ignored.
```
##########
File path: datafusion/src/physical_plan/file_format/file_stream.rs
##########
@@ -0,0 +1,274 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A generic stream over file format readers that can be used by
+//! any file format that read its files from start to end.
+//!
+//! Note: Most traits here need to be marked `Sync + Send` to be
+//! compliant with the `SendableRecordBatchStream` trait.
+
+use crate::{
+ datasource::{object_store::ObjectStore, PartitionedFile},
+ error::Result as DataFusionResult,
+ physical_plan::RecordBatchStream,
+};
+use arrow::{
+ datatypes::SchemaRef,
+ error::{ArrowError, Result as ArrowResult},
+ record_batch::RecordBatch,
+};
+use futures::Stream;
+use std::{
+ io::Read,
+ iter,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+};
+
+pub type FileIter =
+ Box<dyn Iterator<Item = DataFusionResult<Box<dyn Read + Send + Sync>>> +
Send + Sync>;
+pub type BatchIter = Box<dyn Iterator<Item = ArrowResult<RecordBatch>> + Send
+ Sync>;
+
+/// A stream that iterates record batch by record batch, file over file.
+pub struct FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ /// An iterator over record batches of the last file returned by file_iter
+ batch_iter: BatchIter,
+ /// An iterator over input files
+ file_iter: FileIter,
+ /// The stream schema (file schema after projection)
+ schema: SchemaRef,
+ /// The remaining number of records to parse, None if no limit
+ remain: Option<usize>,
+ /// A closure that takes a reader and an optional remaining number of lines
+ /// (before reaching the limit) and returns a batch iterator. If the file
reader
+ /// is not capable of limiting the number of records in the last batch,
the file
+ /// stream will take care of truncating it.
+ file_reader: F,
+}
+
+impl<F> FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ pub fn new(
+ object_store: Arc<dyn ObjectStore>,
+ files: Vec<PartitionedFile>,
+ file_reader: F,
+ schema: SchemaRef,
+ limit: Option<usize>,
+ ) -> Self {
+ let read_iter = files.into_iter().map(move |f| -> DataFusionResult<_> {
+ object_store
+ .file_reader(f.file_meta.sized_file)?
+ .sync_reader()
+ });
+
+ Self {
+ file_iter: Box::new(read_iter),
+ batch_iter: Box::new(iter::empty()),
+ remain: limit,
+ schema,
+ file_reader,
+ }
+ }
+
+ /// Acts as a flat_map of record batches over files.
+ fn next_batch(&mut self) -> Option<ArrowResult<RecordBatch>> {
+ match self.batch_iter.next() {
+ Some(batch) => Some(batch),
+ None => match self.file_iter.next() {
+ Some(Ok(f)) => {
+ self.batch_iter = (self.file_reader)(f, &self.remain);
+ self.next_batch()
+ }
+ Some(Err(e)) =>
Some(Err(ArrowError::ExternalError(Box::new(e)))),
+ None => None,
+ },
+ }
+ }
+}
+
+impl<F> Stream for FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ type Item = ArrowResult<RecordBatch>;
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ // check if finished or no limit
+ match self.remain {
+ Some(r) if r == 0 => return Poll::Ready(None),
+ None => return Poll::Ready(self.get_mut().next_batch()),
+ Some(r) => r,
+ };
+
+ Poll::Ready(match self.as_mut().next_batch() {
+ Some(Ok(item)) => {
+ if let Some(remain) = self.remain.as_mut() {
+ if *remain >= item.num_rows() {
+ *remain -= item.num_rows();
+ Some(Ok(item))
+ } else {
+ let len = *remain;
+ *remain = 0;
+ Some(Ok(RecordBatch::try_new(
+ item.schema(),
+ item.columns()
+ .iter()
+ .map(|column| column.slice(0, len))
+ .collect(),
+ )?))
+ }
+ } else {
+ Some(Ok(item))
+ }
+ }
+ other => other,
+ })
+ }
+}
+
+impl<F> RecordBatchStream for FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ fn schema(&self) -> SchemaRef {
+ Arc::clone(&self.schema)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use futures::StreamExt;
+
+ use super::*;
+ use crate::{
+ error::Result,
+ test::{make_partition, object_store::TestObjectStore},
+ };
+
+ /// helper that creates a stream of 2 files with the same pair of batches
in each ([0,1,2] and [0,1])
+ async fn create_and_collect(limit: Option<usize>) -> Vec<RecordBatch> {
+ let records = vec![make_partition(3), make_partition(2)];
+
+ let source_schema = records[0].schema();
+
+ let reader = move |_file, _remain: &Option<usize>| {
+ // this reder returns the same batch regardless of the file
Review comment:
```suggestion
// this reader returns the same batch regardless of the file
```
##########
File path: datafusion/src/physical_plan/file_format/json.rs
##########
@@ -58,25 +51,25 @@ impl NdJsonExec {
/// TODO: support partitiond file list (Vec<Vec<PartitionedFile>>)
Review comment:
I believe the TODO is now complete and the comment could be removed
##########
File path: datafusion/src/physical_plan/file_format/file_stream.rs
##########
@@ -0,0 +1,274 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A generic stream over file format readers that can be used by
+//! any file format that read its files from start to end.
+//!
+//! Note: Most traits here need to be marked `Sync + Send` to be
+//! compliant with the `SendableRecordBatchStream` trait.
+
+use crate::{
Review comment:
nice tests
##########
File path: datafusion/src/physical_plan/file_format/avro.rs
##########
@@ -54,41 +50,40 @@ pub struct AvroExec {
impl AvroExec {
/// Create a new JSON reader execution plan provided file list and schema
Review comment:
```suggestion
/// Create a new Avro reader execution plan provided file list and schema
```
##########
File path: datafusion/src/physical_plan/file_format/file_stream.rs
##########
@@ -0,0 +1,274 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A generic stream over file format readers that can be used by
+//! any file format that read its files from start to end.
+//!
+//! Note: Most traits here need to be marked `Sync + Send` to be
+//! compliant with the `SendableRecordBatchStream` trait.
+
+use crate::{
+ datasource::{object_store::ObjectStore, PartitionedFile},
+ error::Result as DataFusionResult,
+ physical_plan::RecordBatchStream,
+};
+use arrow::{
+ datatypes::SchemaRef,
+ error::{ArrowError, Result as ArrowResult},
+ record_batch::RecordBatch,
+};
+use futures::Stream;
+use std::{
+ io::Read,
+ iter,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+};
+
+pub type FileIter =
+ Box<dyn Iterator<Item = DataFusionResult<Box<dyn Read + Send + Sync>>> +
Send + Sync>;
+pub type BatchIter = Box<dyn Iterator<Item = ArrowResult<RecordBatch>> + Send
+ Sync>;
+
+/// A stream that iterates record batch by record batch, file over file.
+pub struct FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
Review comment:
Something about feels overly complicated to me.
I wonder it would be possible to combine the `file_iter` and `file_reader`
together into an iterator that returns` BatchIters`? The only thing
`FileStream` seems to do is to take the output of the `file_iterator` and pass
it to `file_reader`.
I may be missing something too
##########
File path: datafusion/src/datasource/file_format/avro.rs
##########
@@ -64,8 +64,7 @@ impl FileFormat for AvroFormat {
) -> Result<Arc<dyn ExecutionPlan>> {
let exec = AvroExec::new(
conf.object_store,
- // flattening this for now because CsvExec does not support
partitioning yet
Review comment:
❤️
##########
File path: datafusion/src/physical_plan/file_format/file_stream.rs
##########
@@ -0,0 +1,274 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A generic stream over file format readers that can be used by
+//! any file format that read its files from start to end.
+//!
+//! Note: Most traits here need to be marked `Sync + Send` to be
+//! compliant with the `SendableRecordBatchStream` trait.
+
+use crate::{
+ datasource::{object_store::ObjectStore, PartitionedFile},
+ error::Result as DataFusionResult,
+ physical_plan::RecordBatchStream,
+};
+use arrow::{
+ datatypes::SchemaRef,
+ error::{ArrowError, Result as ArrowResult},
+ record_batch::RecordBatch,
+};
+use futures::Stream;
+use std::{
+ io::Read,
+ iter,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+};
+
+pub type FileIter =
+ Box<dyn Iterator<Item = DataFusionResult<Box<dyn Read + Send + Sync>>> +
Send + Sync>;
+pub type BatchIter = Box<dyn Iterator<Item = ArrowResult<RecordBatch>> + Send
+ Sync>;
+
+/// A stream that iterates record batch by record batch, file over file.
+pub struct FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ /// An iterator over record batches of the last file returned by file_iter
+ batch_iter: BatchIter,
+ /// An iterator over input files
+ file_iter: FileIter,
+ /// The stream schema (file schema after projection)
+ schema: SchemaRef,
+ /// The remaining number of records to parse, None if no limit
+ remain: Option<usize>,
+ /// A closure that takes a reader and an optional remaining number of lines
+ /// (before reaching the limit) and returns a batch iterator. If the file
reader
+ /// is not capable of limiting the number of records in the last batch,
the file
+ /// stream will take care of truncating it.
+ file_reader: F,
+}
+
+impl<F> FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ pub fn new(
+ object_store: Arc<dyn ObjectStore>,
+ files: Vec<PartitionedFile>,
+ file_reader: F,
+ schema: SchemaRef,
+ limit: Option<usize>,
+ ) -> Self {
+ let read_iter = files.into_iter().map(move |f| -> DataFusionResult<_> {
+ object_store
+ .file_reader(f.file_meta.sized_file)?
+ .sync_reader()
+ });
+
+ Self {
+ file_iter: Box::new(read_iter),
+ batch_iter: Box::new(iter::empty()),
+ remain: limit,
+ schema,
+ file_reader,
+ }
+ }
+
+ /// Acts as a flat_map of record batches over files.
+ fn next_batch(&mut self) -> Option<ArrowResult<RecordBatch>> {
+ match self.batch_iter.next() {
+ Some(batch) => Some(batch),
+ None => match self.file_iter.next() {
+ Some(Ok(f)) => {
+ self.batch_iter = (self.file_reader)(f, &self.remain);
+ self.next_batch()
+ }
+ Some(Err(e)) =>
Some(Err(ArrowError::ExternalError(Box::new(e)))),
+ None => None,
+ },
+ }
+ }
+}
+
+impl<F> Stream for FileStream<F>
+where
+ F: FnMut(Box<dyn Read + Send + Sync>, &Option<usize>) -> BatchIter
+ + Send
+ + Unpin
+ + 'static,
+{
+ type Item = ArrowResult<RecordBatch>;
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ // check if finished or no limit
+ match self.remain {
+ Some(r) if r == 0 => return Poll::Ready(None),
+ None => return Poll::Ready(self.get_mut().next_batch()),
+ Some(r) => r,
+ };
+
+ Poll::Ready(match self.as_mut().next_batch() {
+ Some(Ok(item)) => {
+ if let Some(remain) = self.remain.as_mut() {
+ if *remain >= item.num_rows() {
+ *remain -= item.num_rows();
+ Some(Ok(item))
+ } else {
+ let len = *remain;
+ *remain = 0;
+ Some(Ok(RecordBatch::try_new(
+ item.schema(),
+ item.columns()
+ .iter()
+ .map(|column| column.slice(0, len))
+ .collect(),
Review comment:
Even in plans when `limit` is pushed down to the `TableProvider` scan,
there is still at least one `LimitExec` above it. Thus I think it is likely
fine to avoid slicing up the record batches here (though also as you point out,
it also likely won't hurt)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]