Skip to content
Open
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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ The playground config holds `[[catalogs]]` entries with `name`, `type` (`rest` o

### Catalog → schema → table

`IcebergCatalogProvider::catalog_builder(client)` discovers namespaces and table names at construction. `with_fixed_tables` supplies the names locally and allows appends with fixed membership. `static_builder()` accepts detached tables and historical snapshots and builds a read-only catalog synchronously.
`IcebergCatalogProvider::catalog_builder(client)` discovers namespaces and table names at construction. Namespaces stay fixed, but table lookups, `CREATE TABLE` and `DROP TABLE` ask the catalog, so they see tables other clients create or drop later; the listed names only serve listings. `with_fixed_tables` supplies the names locally and allows appends with fixed membership. `static_builder()` accepts detached tables and historical snapshots and builds a read-only catalog synchronously.

- Names like `<table>$snapshots`, `$manifests`, and `$history` resolve to `IcebergMetadataTableProvider`.
- SQL `CREATE TABLE` and `DROP TABLE` reach the *synchronous* `SchemaProvider::register_table` and `deregister_table` methods, which call the async catalog through `spawn_blocking` + `block_on`. `register_table` rejects input tables that contain rows, so CTAS isn't supported. It auto-assigns field IDs and uses format V2 unless the schema needs V3.
- SQL `CREATE TABLE` and `DROP TABLE` reach the *synchronous* `SchemaProvider::register_table` and `deregister_table` methods, which call the async catalog through `spawn_blocking` + `block_on`. Both reject names containing `$`, which lookups read as metadata tables. `register_table` rejects input tables that contain rows, so CTAS isn't supported. It auto-assigns field IDs and uses format V2 unless the schema needs V3.

### Table providers (`table_provider/`)

Expand Down
3 changes: 2 additions & 1 deletion crates/datafusion/src/catalog/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ pub struct IcebergCatalogProvider {

impl IcebergCatalogProvider {
/// Starts a live catalog builder with a REST client, in-memory catalog, or caching wrapper.
/// By default, building the provider discovers namespaces and table names.
/// By default, building the provider discovers namespaces and table names;
/// tables other clients create or drop later are found by name when queried.
pub fn catalog_builder(catalog: Arc<dyn Catalog>) -> IcebergCatalogProviderBuilder {
IcebergCatalogProviderBuilder {
catalog,
Expand Down
89 changes: 68 additions & 21 deletions crates/datafusion/src/catalog/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use dashmap::DashMap;
use datafusion::catalog::SchemaProvider;
use datafusion::common::{
config_err, exec_datafusion_err, exec_err, not_impl_datafusion_err,
plan_datafusion_err,
plan_datafusion_err, plan_err,
};
use datafusion::datasource::TableProvider;
use datafusion::error::Result;
Expand All @@ -33,7 +33,7 @@ use iceberg::arrow::arrow_schema_to_schema_auto_assign_ids;
use iceberg::inspect::MetadataTableType;
use iceberg::spec::FormatVersion;
use iceberg::table::Table;
use iceberg::{Catalog, NamespaceIdent, TableCreation, TableIdent};
use iceberg::{Catalog, ErrorKind, NamespaceIdent, TableCreation, TableIdent};

use crate::metadata::IcebergMetadataTableProvider;
use crate::table_provider::IcebergTableProvider;
Expand All @@ -43,7 +43,12 @@ use crate::to_datafusion_error;
#[derive(Debug)]
pub(crate) struct IcebergSchemaProvider {
pub(super) namespace: NamespaceIdent,
ddl_catalog: Option<Arc<dyn Catalog>>,
/// The catalog this namespace mirrors: lookups of names missing from
/// `tables`, and DDL, go to it. `None` for a fixed set of tables.
catalog: Option<Arc<dyn Catalog>>,
/// The tables when the namespace was built, updated by DDL through it but
/// not by other clients. With `catalog` set, only `table_names` and
/// `table_exist` rely on it.
tables: Arc<DashMap<String, Registration>>,
}

Expand All @@ -58,7 +63,7 @@ impl IcebergSchemaProvider {
pub(super) fn fixed(namespace: NamespaceIdent) -> Self {
Self {
namespace,
ddl_catalog: None,
catalog: None,
tables: Arc::default(),
}
}
Expand All @@ -72,7 +77,7 @@ impl IcebergSchemaProvider {
.await
.map_err(to_datafusion_error)?;
let schema = Self {
ddl_catalog: Some(catalog.clone()),
catalog: Some(catalog.clone()),
..Self::fixed(namespace)
};
for id in tables {
Expand Down Expand Up @@ -102,7 +107,7 @@ impl IcebergSchemaProvider {
}

fn catalog_for_ddl(&self) -> Result<Arc<dyn Catalog>> {
self.ddl_catalog.clone().ok_or_else(|| {
self.catalog.clone().ok_or_else(|| {
not_impl_datafusion_err!(
"Cannot change membership of a fixed Iceberg table registration in {}",
self.namespace
Expand Down Expand Up @@ -148,13 +153,21 @@ impl SchemaProvider for IcebergSchemaProvider {
}
None => (name, None),
};
let Some(entry) = self.tables.get(table_name).map(|e| e.value().clone()) else {
return Ok(None);
// Another client may have created the table after the listing, so ask
// the catalog unless the set is fixed.
let entry = match self.tables.get(table_name) {
Some(entry) => entry.value().clone(),
None => match &self.catalog {
Some(catalog) => Registration::Live(catalog.clone()),
None => return Ok(None),
},
};
let provider: Arc<dyn TableProvider> = match entry {
Registration::Live(catalog) => {
let id = TableIdent::new(self.namespace.clone(), table_name.into());
let table = catalog.load_table(&id).await.map_err(to_datafusion_error)?;
let Some(table) = load_if_exists(catalog.as_ref(), &id).await? else {
return Ok(None);
};
match metadata_table_type {
Some(kind) => {
Arc::new(IcebergMetadataTableProvider::try_new(table, kind)?)
Expand All @@ -181,10 +194,7 @@ impl SchemaProvider for IcebergSchemaProvider {
table: Arc<dyn TableProvider>,
) -> Result<Option<Arc<dyn TableProvider>>> {
let catalog = self.catalog_for_ddl()?;
// Check if table already exists
if self.table_exist(name.as_str()) {
return exec_err!("Table {name} already exists");
}
ensure_not_metadata_name(&name)?;

// Convert DataFusion schema to Iceberg schema
// DataFusion schemas don't have field IDs, so we use the function that assigns them automatically
Expand Down Expand Up @@ -216,6 +226,8 @@ impl SchemaProvider for IcebergSchemaProvider {
// Verify the input table is empty - CREATE TABLE only accepts schema definition
ensure_table_is_empty(&table).await?;

// The catalog rejects a name that's taken. `tables` can't:
// other clients create and drop tables without updating it.
catalog
.create_table(&namespace, table_creation)
.await
Expand All @@ -235,10 +247,7 @@ impl SchemaProvider for IcebergSchemaProvider {

fn deregister_table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
let catalog = self.catalog_for_ddl()?;
// Check if table exists
if !self.table_exist(name) {
return Ok(None);
}
ensure_not_metadata_name(name)?;

let namespace = self.namespace.clone();
let tables = self.tables.clone();
Expand All @@ -248,11 +257,18 @@ impl SchemaProvider for IcebergSchemaProvider {
let result = tokio::task::spawn_blocking(move || {
let rt = tokio::runtime::Handle::current();
rt.block_on(async move {
// Load the table before dropping it, to return its provider
// Load the table to return its provider. It may be missing from
// `tables` if another client created it.
let ident = TableIdent::new(namespace, table_name.clone());
let removed =
IcebergTableProvider::from_catalog(catalog.clone(), ident.clone())
.await?;
let Some(table) = load_if_exists(catalog.as_ref(), &ident).await? else {
tables.remove(&table_name);
return Ok(None);
};
let removed = IcebergTableProvider::from_loaded(
catalog.clone(),
ident.clone(),
&table,
)?;
catalog
.drop_table(&ident)
.await
Expand All @@ -269,6 +285,37 @@ impl SchemaProvider for IcebergSchemaProvider {
}
}

/// Loads a table, or returns `None` if the catalog has no such table or
/// namespace, for example because another client dropped it after the listing.
async fn load_if_exists(
catalog: &dyn Catalog,
ident: &TableIdent,
) -> Result<Option<Table>> {
match catalog.load_table(ident).await {
Ok(table) => Ok(Some(table)),
Err(e)
if matches!(
e.kind(),
ErrorKind::TableNotFound | ErrorKind::NamespaceNotFound
) =>
{
Ok(None)
}
Err(e) => Err(to_datafusion_error(e)),
}
}

/// Rejects a name that `table()` reads as a metadata table (`t$snapshots`): a
/// table created under it couldn't be read, and dropping it would drop nothing.
fn ensure_not_metadata_name(name: &str) -> Result<()> {
if name.contains('$') {
return plan_err!(
"Iceberg table name {name} can't contain '$', which marks a metadata table"
);
}
Ok(())
}

/// Verifies that a table provider contains no data by scanning with LIMIT 1.
/// Returns an error if the table has any rows.
async fn ensure_table_is_empty(table: &Arc<dyn TableProvider>) -> Result<()> {
Expand Down
Loading