Skip to content
Closed
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
28 changes: 12 additions & 16 deletions crates/datafusion/src/catalog/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<dyn TableProvider>) -> 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(())
}

Expand Down
60 changes: 60 additions & 0 deletions crates/datafusion/tests/catalog_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -236,3 +240,59 @@ async fn static_builder_accumulates_tables_by_identifier() -> Result<(), Box<dyn
);
Ok(())
}

/// `CREATE TABLE … AS` can't write rows, so it refuses input with a row in
/// any partition, and creates the table when every partition is empty.
#[tokio::test]
async fn create_table_as_checks_every_input_partition() -> Result<(), Box<dyn Error>> {
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<i32>| {
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(())
}