gabotechs commented on code in PR #113:
URL: 
https://github.com/apache/datafusion-iceberg/pull/113#discussion_r4640475581


##########
crates/datafusion/src/read/file_scan_task_provider/lazy.rs:
##########
@@ -0,0 +1,313 @@
+// 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.
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use datafusion::arrow::datatypes::{Schema, SchemaRef};
+use datafusion::common::stats::Precision;
+use datafusion::common::{Result, Statistics, exec_err};
+use datafusion::execution::TaskContext;
+use datafusion::physical_plan::Partitioning;
+use datafusion::prelude::Expr;
+use futures::TryStreamExt;
+use iceberg::expr::Predicate;
+use iceberg::table::Table;
+
+use super::eager::EagerFileScanTaskProvider;
+use super::provider::{FileScanTaskProvider, FileScanTaskProviderContext};
+use crate::IcebergDataFusionConfig;
+use crate::read::convert_filters_to_predicate;
+use crate::to_datafusion_error;
+
+/// Snapshot summary field from the spec's "Optional Snapshot Summary Fields".
+const TOTAL_RECORDS: &str = "total-records";
+
+/// Discovers files while executing, in a single partition: the files of a
+/// snapshot that may match a predicate.
+#[derive(Debug, Clone)]
+pub struct LazyFileScanTaskProvider {
+    table: Table,
+    schema: SchemaRef,
+    snapshot_id: Option<i64>,
+    projection: Vec<String>,
+    predicate: Option<Predicate>,
+}
+
+impl LazyFileScanTaskProvider {
+    /// Consumes discovery and retains its tasks in round-robin groups, using 
the
+    /// context's target partition count. The result no longer retains the 
table.
+    /// Empty discovery produces one empty group. Dropping this future drops 
the
+    /// discovery stream; this method does not spawn a background collector.
+    pub async fn into_eager(
+        self,
+        context: Arc<TaskContext>,
+    ) -> Result<EagerFileScanTaskProvider> {
+        let target = context.session_config().target_partitions();
+        if target == 0 {
+            return exec_err!(
+                "Iceberg eager planning requires at least one target partition"
+            );
+        }
+        let statistics = self.partition_statistics(None, &self.schema)?;
+        let mut tasks = Arc::new(self).open(
+            0,
+            FileScanTaskProviderContext {
+                task_context: &context,
+            },
+        )?;
+        let mut groups = Vec::new();
+        let mut partition = 0;
+        while let Some(task) = 
tasks.try_next().await.map_err(to_datafusion_error)? {
+            if partition == groups.len() {
+                groups.push(Vec::new());
+            }
+            groups[partition].push(task);
+            partition = (partition + 1) % target;
+        }
+        if groups.is_empty() {
+            groups.push(Vec::new());
+        }
+        let mut provider = EagerFileScanTaskProvider::try_new(groups)?;
+        provider.statistics = Some(statistics);
+        Ok(provider)
+    }
+
+    /// Table retained for discovery, including its metadata and storage 
access.
+    pub fn table(&self) -> &Table {
+        &self.table
+    }
+
+    /// Output schema after projection, matching the columns selected by 
discovery.
+    pub fn schema(&self) -> SchemaRef {
+        self.schema.clone()
+    }
+
+    /// Names of the columns selected during discovery, in output schema order.
+    pub fn projection(&self) -> &[String] {
+        &self.projection
+    }
+
+    /// Snapshot to scan, or the table's current one if `None`.
+    pub fn snapshot_id(&self) -> Option<i64> {
+        self.snapshot_id
+    }
+
+    /// Filter used to skip files, if any.
+    pub fn predicate(&self) -> Option<&Predicate> {
+        self.predicate.as_ref()
+    }
+}
+
+/// Builds a task provider and its projected schema from a table scan request.
+///
+/// Configuration is supplied at construction. 
`iceberg.execution.eager_file_planning`
+/// selects eager collection; otherwise discovery remains deferred until 
execution.
+/// The projected schema is returned alongside the provider so callers never 
need
+/// to recover it by downcasting an eager or lazy implementation. Reader 
settings
+/// and fetch belong to the data-source builder.
+///
+/// ```
+/// # use std::sync::Arc;
+/// # use datafusion::{arrow::datatypes::SchemaRef, common::Result, 
execution::TaskContext, prelude::Expr};
+/// # use iceberg::table::Table;
+/// # use iceberg_datafusion::read::{FileScanTaskProvider, 
FileScanTaskProviderBuilder};
+/// async fn plan_tasks(
+///     context: Arc<TaskContext>,
+///     table: Table,
+///     schema: SchemaRef,
+///     projection: Option<&Vec<usize>>,
+///     filters: &[Expr],
+/// ) -> Result<(SchemaRef, Arc<dyn FileScanTaskProvider>)> {
+///     FileScanTaskProviderBuilder::new(context, table, schema)
+///         .with_projection(projection)
+///         .with_filters(filters)
+///         .build()
+///         .await
+/// }
+/// ```
+#[derive(Debug, Clone)]
+pub struct FileScanTaskProviderBuilder {
+    context: Arc<TaskContext>,
+    table: Table,
+    schema: SchemaRef,
+    projection: Option<Vec<usize>>,
+    snapshot_id: Option<i64>,
+    predicate: Option<Predicate>,
+}
+
+impl FileScanTaskProviderBuilder {
+    /// Starts with the planning context and the schema advertised by the table
+    /// provider. Projection indices refer to this schema, not the table's 
current
+    /// schema. Pass an already-projected schema and omit projection to retain 
it.
+    pub fn new(context: Arc<TaskContext>, table: Table, schema: SchemaRef) -> 
Self {
+        Self {
+            context,
+            table,
+            schema,
+            projection: None,
+            snapshot_id: None,
+            predicate: None,
+        }
+    }
+
+    /// Selects columns from the supplied schema in this order, or all its 
columns
+    /// for `None`. Indices are validated when [`Self::build`] is called.
+    pub fn with_projection(mut self, projection: Option<&Vec<usize>>) -> Self {
+        self.projection = projection.cloned();
+        self
+    }
+
+    /// Selects a snapshot, or the retained table's current snapshot for 
`None`.
+    /// The supplied schema is not replaced with the snapshot's schema.
+    pub fn with_snapshot_id(mut self, snapshot_id: Option<i64>) -> Self {
+        self.snapshot_id = snapshot_id;
+        self
+    }
+
+    /// Sets the predicate used to prune files and filter their rows.
+    pub fn with_predicate(mut self, predicate: Option<Predicate>) -> Self {
+        self.predicate = predicate;
+        self
+    }
+
+    /// Pushes down supported parts of DataFusion filters. The caller must 
still
+    /// apply the original filters, as unsupported parts are omitted.
+    pub fn with_filters(self, filters: &[Expr]) -> Self {
+        self.with_predicate(convert_filters_to_predicate(filters))
+    }
+
+    /// Validates projection and builds the configured eager or lazy provider.
+    /// Lazy mode performs no file discovery; eager mode awaits 
[`LazyFileScanTaskProvider::into_eager`].
+    /// The returned schema matches the columns selected by both 
implementations.
+    ///
+    /// # Errors
+    ///
+    /// Returns projection errors, or discovery errors when eager planning is 
enabled.
+    pub async fn build(self) -> Result<(SchemaRef, Arc<dyn 
FileScanTaskProvider>)> {

Review Comment:
   Something that slipped through my last review:
   
   To keep a clean builder contract, it should here should be just returning a 
`FileScanTaskProvider` and nothing more.
   
   Before we release this, I think it's worth cleaning this up and thread the 
projected schema in a different way.



-- 
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]

Reply via email to