gabotechs commented on code in PR #67: URL: https://github.com/apache/datafusion-iceberg/pull/67#discussion_r4599120617
########## crates/datafusion/src/read/builder.rs: ########## @@ -0,0 +1,453 @@ +// 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. + +//! Session-configured construction of table scans and already-planned scans. + +use std::fmt::{Debug, Formatter}; +use std::sync::Arc; + +use datafusion::arrow::datatypes::SchemaRef; +use datafusion::common::Result; +use datafusion::datasource::source::DataSource; +use datafusion::execution::TaskContext; +use datafusion::prelude::Expr; +use iceberg::arrow::ArrowReader; +use iceberg::expr::Predicate; +use iceberg::io::FileIO; +use iceberg::scan::FileScanTask; +use iceberg::table::Table; + +use super::eager::EagerIcebergDataSource; +use super::file_planning::PlannedFileScan; +use super::predicate::convert_filters_to_predicate; +use super::scan::{IcebergDataSource, build_table_scan}; +use crate::IcebergDataFusionConfig; + +/// Builds a scan using the session settings and memory pool in a task context. +/// +/// Obtain the context from `SessionContext::task_ctx()` or the `Session` passed to +/// a table provider. Eager planning, target partitions, batch size and page-index +/// settings come from that context, not separate builder options. +/// +/// Select either a table or already-planned files after supplying the schema. +/// Only table input exposes discovery projection, snapshot and filter settings. +/// Table scans finish asynchronously; reconstruction finishes synchronously and +/// never discovers files. Both return an `Arc<dyn DataSource>`. +/// +/// ``` +/// # use datafusion::arrow::datatypes::SchemaRef; +/// # use datafusion::common::Result; +/// # use datafusion::datasource::source::DataSource; +/// # use datafusion::execution::TaskContext; +/// # use iceberg::table::Table; +/// # use iceberg_datafusion::read::IcebergDataSourceBuilder; +/// # use std::sync::Arc; +/// async fn scan(table: Table, schema: SchemaRef, context: &TaskContext) +/// -> Result<Arc<dyn DataSource>> +/// { +/// IcebergDataSourceBuilder::new(context) +/// .with_schema(schema) +/// .with_table(table) +/// .build() +/// .await +/// } +/// ``` +/// +/// Reconstruction uses the same entry point but has no asynchronous discovery: +/// ``` +/// # use datafusion::arrow::datatypes::SchemaRef; +/// # use datafusion::common::Result; +/// # use datafusion::datasource::source::DataSource; +/// # use datafusion::execution::TaskContext; +/// # use iceberg::arrow::ArrowReader; +/// # use iceberg::io::FileIO; +/// # use iceberg::scan::FileScanTask; +/// # use iceberg_datafusion::read::IcebergDataSourceBuilder; +/// # use std::sync::Arc; +/// fn restore(context: &TaskContext, schema: SchemaRef, +/// groups: Vec<Vec<FileScanTask>>, file_io: FileIO, reader: ArrowReader) +/// -> Result<Arc<dyn DataSource>> +/// { +/// IcebergDataSourceBuilder::new(context) +/// .with_schema(schema) +/// .with_planned_files(groups) +/// .with_file_io(file_io) +/// .with_reader(reader) +/// .build() +/// } +/// ``` +/// +/// Planned input cannot request snapshot discovery: +/// ```compile_fail,E0599 +/// # use datafusion::arrow::datatypes::SchemaRef; +/// # use datafusion::execution::TaskContext; +/// # use iceberg::arrow::ArrowReader; +/// # use iceberg::io::FileIO; +/// # use iceberg::scan::FileScanTask; +/// # use iceberg_datafusion::read::IcebergDataSourceBuilder; +/// fn invalid(context: &TaskContext, schema: SchemaRef, +/// groups: Vec<Vec<FileScanTask>>, file_io: FileIO, reader: ArrowReader) +/// { +/// IcebergDataSourceBuilder::new(context) +/// .with_schema(schema) +/// .with_planned_files(groups) +/// .with_file_io(file_io) +/// .with_reader(reader) +/// .with_snapshot_id(Some(1)); +/// } +/// ``` +/// +/// Reconstruction cannot finish without a process-local reader: +/// ```compile_fail,E0599 +/// # use datafusion::arrow::datatypes::SchemaRef; +/// # use datafusion::execution::TaskContext; +/// # use iceberg::io::FileIO; +/// # use iceberg::scan::FileScanTask; +/// # use iceberg_datafusion::read::IcebergDataSourceBuilder; +/// fn invalid(context: &TaskContext, schema: SchemaRef, +/// groups: Vec<Vec<FileScanTask>>, file_io: FileIO) +/// { +/// IcebergDataSourceBuilder::new(context) +/// .with_schema(schema) +/// .with_planned_files(groups) +/// .with_file_io(file_io) +/// .build(); +/// } +/// ``` +#[derive(Clone)] +#[must_use] +pub struct IcebergDataSourceBuilder<'a, Input = NeedsSchema> { + context: &'a TaskContext, + input: Input, + fetch: Option<usize>, Review Comment: Tried experimenting with a different idea, and it's actually turning out to be quite nice: - https://github.com/apache/datafusion-iceberg/pull/109 The TL;DR is: rather than having two different `DataSource` implementations, just have a singe `IcebergDataSource` with a new `trait FileScanTaskProvider` that has both eager and lazy implementations, and that can be used by DFD to implement a WorkUnitFeed-based provider as well. This collaterally simplifies the builder significantly, as there's no longer a need for building multiple things through the same builder, resulting in decently small amount of pretty simple code. I've not been fighting as much as you with this, so I might be missing something. ########## crates/datafusion/src/read/scan.rs: ########## @@ -181,48 +99,24 @@ impl DataSource for IcebergDataSource { fn open( &self, - _partition: usize, - context: Arc<TaskContext>, + partition: usize, + _context: Arc<TaskContext>, ) -> Result<SendableRecordBatchStream> { - let fut = get_batch_stream( - self.table.clone(), + if partition != 0 { + return internal_err!("Iceberg scan partition {partition} does not exist"); + } + let scan = build_table_scan( + &self.table, self.snapshot_id, - Some(self.projection.clone()), - self.predicate.clone(), - context - .session_config() - .options() - .execution - .parquet - .enable_page_index, - context.session_config().batch_size(), + Some(&self.projection), + self.predicate.as_ref(), + )?; + let tasks: FileScanTaskStream = Box::pin( + futures::stream::once(async move { scan.plan_files().await }).try_flatten(), ); - let stream = futures::stream::once(fut).try_flatten(); - - // Apply the fetch if specified. - let limited_stream: Pin<Box<dyn Stream<Item = Result<RecordBatch>> + Send>> = - if let Some(limit) = self.fetch { - let mut remaining = limit; - Box::pin(stream.try_filter_map(move |batch| { - futures::future::ready(if remaining == 0 { - Ok(None) - } else if batch.num_rows() <= remaining { - remaining -= batch.num_rows(); - Ok(Some(batch)) - } else { - let limited_batch = batch.slice(0, remaining); - remaining = 0; - Ok(Some(limited_batch)) - }) - })) - } else { - Box::pin(stream) - }; - - Ok(Box::pin(RecordBatchStreamAdapter::new( - self.schema.clone(), - limited_stream, - ))) + let mut reader = ScanReader::new(self.reader.clone()); + reader.metrics = self.metrics.clone(); + reader.open(tasks, self.schema.clone(), self.fetch, partition) Review Comment: This signals that the `ScanReader` abstraction is probably not the right one. If you need to override it's values right after constructing one for it to work, it's probably not the right abstraction on the first place. I see `reader.rs` a ~70 LOC file that exposes a struct just for the sake of encapsulating 3 statements in one method. I think it's not worth it, I'd just remove `reader.rs` and inline the contents where they're used. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
