diff --git a/crates/datafusion/src/catalog/schema.rs b/crates/datafusion/src/catalog/schema.rs index 40492e6..6c99e7a 100644 --- a/crates/datafusion/src/catalog/schema.rs +++ b/crates/datafusion/src/catalog/schema.rs @@ -26,7 +26,6 @@ use datafusion::common::{ }; use datafusion::datasource::TableProvider; use datafusion::error::Result; -use datafusion::execution::TaskContext; use datafusion::prelude::SessionContext; use futures::TryStreamExt; use iceberg::arrow::arrow_schema_to_schema_auto_assign_ids; @@ -213,7 +212,6 @@ impl SchemaProvider for IcebergSchemaProvider { // Create a new runtime handle to execute the async work let rt = tokio::runtime::Handle::current(); rt.block_on(async move { - // Verify the input table is empty - CREATE TABLE only accepts schema definition ensure_table_is_empty(&table).await?; catalog @@ -269,22 +267,20 @@ impl SchemaProvider for IcebergSchemaProvider { } } -/// Verifies that a table provider contains no data by scanning with LIMIT 1. -/// Returns an error if the table has any rows. +/// Returns an error if the table has a row. `CREATE TABLE … AS` can't write +/// rows, so it creates a table only when the query returns none. The rows can +/// be in any partition: DataFusion keeps the query's partitioning. async fn ensure_table_is_empty(table: &Arc) -> Result<()> { - let session_ctx = SessionContext::new(); - let exec_plan = table.scan(&session_ctx.state(), None, &[], Some(1)).await?; - - let task_ctx = Arc::new(TaskContext::default()); - let stream = exec_plan.execute(0, task_ctx)?; - - let batches: Vec<_> = stream.try_collect().await?; - let has_data = batches.iter().any(|batch| batch.num_rows() > 0); - - if has_data { - return exec_err!("register_table does not support tables with data."); + let state = SessionContext::new().state(); + let plan = table.scan(&state, None, &[], Some(1)).await?; + for partition in 0..plan.properties().output_partitioning().partition_count() { + let mut stream = plan.execute(partition, state.task_ctx())?; + while let Some(batch) = stream.try_next().await? { + if batch.num_rows() > 0 { + return exec_err!("register_table does not support tables with data."); + } + } } - Ok(()) } diff --git a/crates/datafusion/tests/catalog_provider.rs b/crates/datafusion/tests/catalog_provider.rs index 90f6967..4373688 100644 --- a/crates/datafusion/tests/catalog_provider.rs +++ b/crates/datafusion/tests/catalog_provider.rs @@ -21,8 +21,12 @@ use std::collections::HashMap; use std::error::Error; use std::sync::Arc; +use datafusion::arrow::array::Int32Array; use datafusion::arrow::datatypes::{DataType, Field, Schema as ArrowSchema}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::arrow::util::pretty::pretty_format_batches; use datafusion::catalog::CatalogProvider; +use datafusion::datasource::MemTable; use datafusion::execution::context::SessionContext; use datafusion::parquet::arrow::PARQUET_FIELD_ID_META_KEY; use iceberg::spec::{NestedField, PrimitiveType, Schema, Type}; @@ -236,3 +240,59 @@ async fn static_builder_accumulates_tables_by_identifier() -> Result<(), Box Result<(), Box> { + let fixtures = FixtureCatalog::try_new().await?; + fixtures + .catalog() + .create_namespace(&NamespaceIdent::new("ns".to_string()), HashMap::new()) + .await?; + let ctx = SessionContext::new(); + ctx.register_catalog( + "c", + Arc::new( + IcebergCatalogProvider::catalog_builder(fixtures.catalog()) + .build() + .await?, + ), + ); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "id", + DataType::Int32, + false, + )])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]) + }; + // One row, in the middle partition and after an empty batch, so a check of + // only the first or last partition, or the first batch, misses it. The + // CTAS input keeps this layout. + let partitions = vec![vec![], vec![batch(vec![])?, batch(vec![1])?], vec![]]; + ctx.register_table("src", Arc::new(MemTable::try_new(schema, partitions)?))?; + + let err = ctx + .sql("CREATE TABLE c.ns.t AS SELECT * FROM src") + .await + .unwrap_err(); + insta::assert_snapshot!(err, @"Execution error: register_table does not support tables with data."); + + // Creating `t` now also shows the refused statement didn't create it. + ctx.sql("CREATE TABLE c.ns.t AS SELECT * FROM src WHERE id > 1") + .await?; + let count = ctx + .sql("SELECT count(*) FROM c.ns.t") + .await? + .collect() + .await?; + insta::assert_snapshot!(pretty_format_batches(&count)?, @r" + +----------+ + | count(*) | + +----------+ + | 0 | + +----------+ + "); + Ok(()) +}