Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions crates/datafusion/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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::sync::LazyLock;

use datafusion::common::{config_namespace, extensions_options};
use datafusion::config::ConfigExtension;
use datafusion::prelude::SessionConfig;

extensions_options! {
/// Session options for Iceberg tables, under `iceberg.<group>.<option>`.
///
/// Register this extension before setting Iceberg options:
/// ```
/// use datafusion::prelude::SessionConfig;
/// use iceberg_datafusion::IcebergDataFusionConfig;
///
/// let config = SessionConfig::new()
/// .with_option_extension(IcebergDataFusionConfig::default())
/// .set_bool("iceberg.execution.eager_file_planning", true);
/// ```
pub struct IcebergDataFusionConfig {
/// Options for executing table scans.
pub execution: IcebergExecutionConfig, default = IcebergExecutionConfig::default()
}
}

config_namespace! {
/// Options for executing Iceberg scans, under `iceberg.execution`.
pub struct IcebergExecutionConfig {
/// Discover file tasks in TableProvider::scan instead of at execution, and
/// split them across up to the session's target partitions.
pub eager_file_planning: bool, default = false
}
}

impl ConfigExtension for IcebergDataFusionConfig {
const PREFIX: &'static str = "iceberg";
}

static DEFAULT: LazyLock<IcebergDataFusionConfig> =
LazyLock::new(IcebergDataFusionConfig::default);

impl IcebergDataFusionConfig {
pub fn from_config_or_default(cfg: &SessionConfig) -> &Self {
match cfg.options().extensions.get::<Self>() {
Some(v) => v,
None => &DEFAULT,
}
}
}
3 changes: 3 additions & 0 deletions crates/datafusion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
mod catalog;
pub use catalog::*;

mod config;
pub use config::{IcebergDataFusionConfig, IcebergExecutionConfig};

mod error;
pub use error::*;

Expand Down
126 changes: 126 additions & 0 deletions crates/datafusion/src/read/file_scan_task_provider/eager.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// 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 datafusion::arrow::datatypes::Schema;
use datafusion::common::{Result, Statistics, exec_err};
use datafusion::physical_plan::Partitioning;
use futures::StreamExt;
use iceberg::scan::FileScanTask;
use std::collections::BTreeSet;
use std::fmt::Formatter;
use std::sync::Arc;

use super::provider::{FileScanTaskProvider, FileScanTaskProviderContext};

/// Files discovered before execution, in groups that each become one output
/// partition. Group order and empty groups are retained.
#[derive(Debug)]
pub struct EagerFileScanTaskProvider {
file_scan_tasks: Vec<Vec<FileScanTask>>,
/// Whole-assignment statistics retained when converting lazy discovery;
/// external assignments have no retained estimates.
pub(super) statistics: Option<Statistics>,
}

impl EagerFileScanTaskProvider {
/// Reads `file_scan_tasks`, one output partition per group.
///
/// # Errors
///
/// Returns an error if there are no groups. Empty groups are allowed.
pub fn try_new(file_scan_tasks: Vec<Vec<FileScanTask>>) -> Result<Self> {
if file_scan_tasks.is_empty() {
return exec_err!(
"An Iceberg task provider requires at least one file group"
);
}
Ok(Self {
file_scan_tasks,
statistics: None,
})
}

/// All file tasks, in partition order and then group order.
pub fn tasks(&self) -> impl Iterator<Item = &FileScanTask> {
self.file_scan_tasks.iter().flatten()
}

/// The file tasks of each partition.
pub fn groups(&self) -> &[Vec<FileScanTask>] {
&self.file_scan_tasks
}
}

impl FileScanTaskProvider for EagerFileScanTaskProvider {
fn partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(self.groups().len())
}

fn open(
self: Arc<Self>,
partition: usize,
_context: FileScanTaskProviderContext,
) -> Result<iceberg::scan::FileScanTaskStream> {
let Some(count) = self.groups().get(partition).map(Vec::len) else {
return exec_err!("Invalid Iceberg scan partition {partition}");
};
// Clone each task as it's read; holding `self` keeps the groups alive
// after the data source is dropped.
Ok(futures::stream::iter(0..count)
.map(move |offset| Ok(self.groups()[partition][offset].clone()))
.boxed())
}

fn partition_statistics(
&self,
partition: Option<usize>,
schema: &Schema,
) -> Result<Statistics> {
if partition.is_some_and(|partition| partition >= self.groups().len()) {
return exec_err!("Invalid Iceberg scan partition {partition:?}");
}
if (partition.is_none() || self.groups().len() == 1)
&& let Some(statistics) = &self.statistics
{
return Ok(statistics.clone());
}
Ok(Statistics::new_unknown(schema))
}

fn fmt_as(&self, f: &mut Formatter) -> std::fmt::Result {
write!(
f,
", provider=eager, planned_files={}",
self.tasks().count()
)?;
// Assigned tasks may have different predicates. Report the distinct task
// predicates rather than assuming a single filter applies to every file.
let predicates = self
.tasks()
.filter_map(FileScanTask::predicate)
.map(ToString::to_string)
.collect::<BTreeSet<_>>();
if !predicates.is_empty() {
write!(
f,
", predicates=[{}]",
predicates.into_iter().collect::<Vec<_>>().join(", ")
)?;
}
Ok(())
}
}
Loading