diff --git a/Cargo.lock b/Cargo.lock index 91a17ef6a..5b44b2c37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,9 +274,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b5b1682924f11ecf6929689c16cbc69efbb6dd141b06ad98ee1cb10d858c43" +checksum = "48fd7dff6ff36252331feeb62a29b343e75f24d07f5519fd8ef0b175d06570fc" dependencies = [ "ahash", "arrow-buffer", @@ -294,9 +294,9 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5d687afc6c927965a8a759f3b68de91933d9dfa2e1bb6e156bac84b85665e92" +checksum = "d2efd8a063bdc2e88c67a6f5fa130346bb0ec9089754dea276380858535030c5" dependencies = [ "bytes", "half", @@ -343,9 +343,9 @@ dependencies = [ [[package]] name = "arrow-data" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0a031c7ff5e2bdb443117054fb466af1d4df5b7f0ecbe197713dc8b113b1ba" +checksum = "1aee86955e4b574e821fd64d65bd9bf41c2c61b863750671ecb38c75fa56de5d" dependencies = [ "arrow-buffer", "arrow-schema", @@ -356,9 +356,9 @@ dependencies = [ [[package]] name = "arrow-ipc" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5dd1afadda2eb821aaf851bb4c0adef60c30cc0f1a29bd02fb99dd07fb9f58d" +checksum = "ea79f6056557715de2b463ea7f979fe54fbfd6088ffcd144401a777ef28914f9" dependencies = [ "arrow-array", "arrow-buffer", @@ -435,9 +435,9 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e87acb0c6bf6237fca7a50d7b51e801c98a18a5fe6f3bb34f7d77b85ca165388" +checksum = "f56aa009563c7100bafca7f0c4259b9ae83a439d676a6314b3a8c96f12a92f51" dependencies = [ "bitflags 2.13.1", "serde_core", @@ -446,9 +446,9 @@ dependencies = [ [[package]] name = "arrow-select" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c844141958d805b47d1208e0d12aac53fcf388ce8011639fe82aa492adde0bb4" +checksum = "83df2939d169e46983b07a65bea222bcca9aa564d33e1529877ecb3395cd20e6" dependencies = [ "ahash", "arrow-array", @@ -4961,6 +4961,7 @@ dependencies = [ "rand 0.8.7", "regex", "reqwest 0.12.28", + "reqwest 0.13.4", "roaring", "ryu", "serde", @@ -5074,6 +5075,7 @@ dependencies = [ "tar", "tempfile", "tokio", + "uuid", ] [[package]] @@ -5167,9 +5169,9 @@ dependencies = [ [[package]] name = "parquet" -version = "59.3.2" +version = "59.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb260d566f2fbdabe356d26aaa5d13403aac29b5b4e44463b8f9bd7b2b12680" +checksum = "20033034bc38d6bbb14518717e115cceed4bce3f2425232034a6f6be91877425" dependencies = [ "ahash", "arrow-array", diff --git a/DEPENDENCIES.rust.tsv b/DEPENDENCIES.rust.tsv index 9a18c5147..0f5c76346 100644 --- a/DEPENDENCIES.rust.tsv +++ b/DEPENDENCIES.rust.tsv @@ -26,18 +26,18 @@ arrayref@0.3.9 X arrayvec@0.7.8 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-pyarrow@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-channel@2.5.0 X X async-compression@0.4.42 X X @@ -429,7 +429,7 @@ paimon-vindex-core@0.6.0 X parking@2.2.1 X X parking_lot@0.12.5 X X parking_lot_core@0.9.12 X X -parquet@59.3.2 X +parquet@59.3.3 X parquet-variant@59.3.2 X parquet-variant-compute@59.3.2 X parquet-variant-json@59.3.2 X diff --git a/benchmarks/tpcds/DEPENDENCIES.rust.tsv b/benchmarks/tpcds/DEPENDENCIES.rust.tsv index 4d115a176..0aeb3cea8 100644 --- a/benchmarks/tpcds/DEPENDENCIES.rust.tsv +++ b/benchmarks/tpcds/DEPENDENCIES.rust.tsv @@ -22,17 +22,17 @@ arrayref@0.3.9 X arrayvec@0.7.8 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-stream@0.3.6 X @@ -327,7 +327,7 @@ paimon-tpcds-bench@0.6.0 X paimon-vindex-core@0.6.0 X parking_lot@0.12.5 X X parking_lot_core@0.9.12 X X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X percent-encoding@2.3.2 X X petgraph@0.8.3 X X diff --git a/bindings/c/DEPENDENCIES.rust.tsv b/bindings/c/DEPENDENCIES.rust.tsv index a8d2bd7a3..d5b24279f 100644 --- a/bindings/c/DEPENDENCIES.rust.tsv +++ b/bindings/c/DEPENDENCIES.rust.tsv @@ -14,17 +14,17 @@ approx@0.5.1 X arc-swap@1.9.2 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-stream@0.3.6 X @@ -272,7 +272,7 @@ paimon-c@0.6.0 X paimon-ftindex-core@0.2.0 X paimon-mosaic-core@0.3.0 X paimon-vindex-core@0.6.0 X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X pbkdf2@0.12.2 X X pem@4.0.0 X diff --git a/bindings/go/DEPENDENCIES.rust.tsv b/bindings/go/DEPENDENCIES.rust.tsv index a8d2bd7a3..d5b24279f 100644 --- a/bindings/go/DEPENDENCIES.rust.tsv +++ b/bindings/go/DEPENDENCIES.rust.tsv @@ -14,17 +14,17 @@ approx@0.5.1 X arc-swap@1.9.2 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-stream@0.3.6 X @@ -272,7 +272,7 @@ paimon-c@0.6.0 X paimon-ftindex-core@0.2.0 X paimon-mosaic-core@0.3.0 X paimon-vindex-core@0.6.0 X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X pbkdf2@0.12.2 X X pem@4.0.0 X diff --git a/bindings/python/DEPENDENCIES.rust.tsv b/bindings/python/DEPENDENCIES.rust.tsv index df53fae55..fb61c15a5 100644 --- a/bindings/python/DEPENDENCIES.rust.tsv +++ b/bindings/python/DEPENDENCIES.rust.tsv @@ -19,18 +19,18 @@ arrayref@0.3.9 X arrayvec@0.7.8 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-pyarrow@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-ffi@0.5.0 X @@ -356,7 +356,7 @@ paimon-mosaic-core@0.3.0 X paimon-vindex-core@0.6.0 X parking_lot@0.12.5 X X parking_lot_core@0.9.12 X X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X pbkdf2@0.12.2 X X pem@4.0.0 X diff --git a/crates/integration_tests/Cargo.toml b/crates/integration_tests/Cargo.toml index 75ec66175..b5e68ef8f 100644 --- a/crates/integration_tests/Cargo.toml +++ b/crates/integration_tests/Cargo.toml @@ -38,3 +38,4 @@ tar = "0.4" tempfile = "3" serde_json = "1" axum = { version = "0.7", features = ["macros", "tokio", "http1", "http2"] } +uuid = { version = "1", features = ["v4"] } diff --git a/crates/integration_tests/DEPENDENCIES.rust.tsv b/crates/integration_tests/DEPENDENCIES.rust.tsv index b3513ebda..2397be1db 100644 --- a/crates/integration_tests/DEPENDENCIES.rust.tsv +++ b/crates/integration_tests/DEPENDENCIES.rust.tsv @@ -13,17 +13,17 @@ approx@0.5.1 X arc-swap@1.9.2 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-stream@0.3.6 X @@ -256,7 +256,7 @@ paimon-ftindex-core@0.2.0 X paimon-integration-tests@0.6.0 X paimon-mosaic-core@0.3.0 X paimon-vindex-core@0.6.0 X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X percent-encoding@2.3.2 X X phf@0.12.1 X diff --git a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv index 0a3977ca4..3ac0f9761 100644 --- a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv +++ b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv @@ -19,17 +19,17 @@ arrayref@0.3.9 X arrayvec@0.7.8 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-channel@2.5.0 X X async-compression@0.4.42 X X @@ -368,7 +368,7 @@ paimon-vindex-core@0.6.0 X parking@2.2.1 X X parking_lot@0.12.5 X X parking_lot_core@0.9.12 X X -parquet@59.3.2 X +parquet@59.3.3 X parquet-variant@59.3.2 X parquet-variant-compute@59.3.2 X parquet-variant-json@59.3.2 X diff --git a/crates/integrations/datafusion/README.md b/crates/integrations/datafusion/README.md index a91a968ab..9864105df 100644 --- a/crates/integrations/datafusion/README.md +++ b/crates/integrations/datafusion/README.md @@ -149,4 +149,21 @@ let view = ctx.sql("SELECT * FROM analytics_view").await?; let function = ctx.sql("SELECT plus_one(score) FROM scores").await?; ``` +## Persistent CREATE TABLE AS SELECT + +Use `CREATE TABLE AS SELECT` to materialize a bounded query as a native Paimon +table. The query determines the destination schema. In this example, `scores` +resolves in the session's current catalog and database. + +```sql +CREATE TABLE paimon.reporting.results +WITH ('bucket' = '-1') +AS SELECT id, score FROM scores WHERE score > 10; +``` + +`IF NOT EXISTS` skips an existing target. If population fails after creation, +the destination remains in the catalog. For supported types, concurrent DDL, +cancellation and recovery after a commit error, see the +[SQL reference](../../../docs/src/sql.md#create-table-as-select). + See the [documentation](https://paimon.apache.org/docs/rust/datafusion/) for getting started guide and more details. diff --git a/crates/integrations/datafusion/src/format_partition_analyze.rs b/crates/integrations/datafusion/src/format_partition_analyze.rs index 01946d70c..99e97de3a 100644 --- a/crates/integrations/datafusion/src/format_partition_analyze.rs +++ b/crates/integrations/datafusion/src/format_partition_analyze.rs @@ -57,7 +57,7 @@ pub(crate) async fn execute_analyze( "ANALYZE TABLE requires COMPUTE STATISTICS".to_string(), )); } - SQLContext::ensure_partition_command_target(table_name, "ANALYZE TABLE")?; + SQLContext::ensure_main_branch_base_table(table_name, "ANALYZE TABLE")?; ctx.reject_temporary_write_target(table_name, "ANALYZE TABLE") .await?; let (catalog, _catalog_name, identifier) = ctx.resolve_catalog_and_table(table_name)?; diff --git a/crates/integrations/datafusion/src/format_partition_ddl.rs b/crates/integrations/datafusion/src/format_partition_ddl.rs index c2d4eeac9..33d39f587 100644 --- a/crates/integrations/datafusion/src/format_partition_ddl.rs +++ b/crates/integrations/datafusion/src/format_partition_ddl.rs @@ -112,7 +112,7 @@ pub(crate) async fn execute_show_partitions( show_partitions: &ShowPartitionsStatement, enable_ident_normalization: bool, ) -> DFResult { - SQLContext::ensure_partition_command_target(&show_partitions.table_name, "SHOW PARTITIONS")?; + SQLContext::ensure_main_branch_base_table(&show_partitions.table_name, "SHOW PARTITIONS")?; let (catalog, _catalog_name, identifier) = ctx.resolve_catalog_and_table(&show_partitions.table_name)?; let table = catalog diff --git a/crates/integrations/datafusion/src/format_partition_repair.rs b/crates/integrations/datafusion/src/format_partition_repair.rs index 1f018b382..78dcf44c2 100644 --- a/crates/integrations/datafusion/src/format_partition_repair.rs +++ b/crates/integrations/datafusion/src/format_partition_repair.rs @@ -36,7 +36,7 @@ pub(crate) async fn execute_msck(ctx: &SQLContext, msck: &Msck) -> DFResult Result { + use DataType::*; + if data.child_data().is_empty() { + return Ok(data); + } + let children = data + .child_data() + .iter() + .cloned() + .map(normalize_map_ordering) + .collect::, _>>()?; + let field = |original: &FieldRef, index: usize| { + Arc::new( + original + .as_ref() + .clone() + .with_data_type(children[index].data_type().clone()), + ) + }; + let data_type = match data.data_type() { + Map(entries, _) => Map(field(entries, 0), false), + Struct(fields) => Struct( + fields + .iter() + .enumerate() + .map(|(i, f)| field(f, i)) + .collect(), + ), + List(f) => List(field(f, 0)), + LargeList(f) => LargeList(field(f, 0)), + FixedSizeList(f, size) => FixedSizeList(field(f, 0), *size), + Dictionary(key, _) => Dictionary(key.clone(), Box::new(children[0].data_type().clone())), + _ => return Ok(data), + }; + if &data_type == data.data_type() { + return Ok(data); + } + data.into_builder() + .data_type(data_type) + .child_data(children) + .build() +} + +fn cast_column(column: &ArrayRef, target: &DataType) -> Result { + if column.data_type() == target { + return Ok(Arc::clone(column)); + } + if !can_cast_types(column.data_type(), target) { + let data = normalize_map_ordering(column.to_data())?; + if data.data_type() != column.data_type() { + return cast(&make_array(data), target); + } + } + cast(column, target) +} + +pub(crate) fn cast_batch_to_schema( + batch: RecordBatch, + schema: &SchemaRef, +) -> DFResult { + if batch.schema_ref() == schema { + return Ok(batch); + } + if batch.num_columns() != schema.fields().len() { + return Err(DataFusionError::Execution(format!( + "Cannot cast a batch with {} columns to a schema with {} fields", + batch.num_columns(), + schema.fields().len() + ))); + } + let columns = batch + .columns() + .iter() + .zip(schema.fields()) + .map(|(column, field)| cast_column(column, field.data_type())) + .collect::, _>>()?; + let options = RecordBatchOptions::new().with_row_count(Some(batch.num_rows())); + RecordBatch::try_new_with_options(Arc::clone(schema), columns, &options).map_err(Into::into) +} diff --git a/crates/integrations/datafusion/src/physical_plan/scan.rs b/crates/integrations/datafusion/src/physical_plan/scan.rs index 0b60f8073..fce9e6ffa 100644 --- a/crates/integrations/datafusion/src/physical_plan/scan.rs +++ b/crates/integrations/datafusion/src/physical_plan/scan.rs @@ -18,11 +18,11 @@ use std::sync::Arc; use datafusion::arrow::array::BooleanArray; -use datafusion::arrow::compute::{cast, filter_record_batch}; +use datafusion::arrow::compute::filter_record_batch; use datafusion::arrow::datatypes::{ DataType as ArrowDataType, SchemaRef as ArrowSchemaRef, TimeUnit, }; -use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions}; +use datafusion::arrow::record_batch::RecordBatch; use datafusion::common::stats::Precision; use datafusion::common::tree_node::TreeNodeRecursion; use datafusion::common::{ColumnStatistics, ScalarValue, Statistics}; @@ -64,33 +64,6 @@ use paimon::DataSplit; use crate::error::to_datafusion_error; use crate::filter_pushdown::{is_float_zero, scalar_to_datum}; -fn to_datafusion_batch(batch: RecordBatch, schema: &ArrowSchemaRef) -> DFResult { - if batch.num_columns() != schema.fields().len() { - return Err(datafusion::error::DataFusionError::Execution(format!( - "Paimon reader returned {} columns for DataFusion schema with {} fields", - batch.num_columns(), - schema.fields().len() - ))); - } - - let row_count = batch.num_rows(); - let columns = batch - .columns() - .iter() - .zip(schema.fields()) - .map(|(column, field)| { - if column.data_type() == field.data_type() { - Ok(Arc::clone(column)) - } else { - cast(column.as_ref(), field.data_type()).map_err(Into::into) - } - }) - .collect::>>()?; - let options = RecordBatchOptions::new().with_row_count(Some(row_count)); - - RecordBatch::try_new_with_options(Arc::clone(schema), columns, &options).map_err(Into::into) -} - #[derive(Debug)] struct DataFusionRowFilterFactory { predicate: Arc, @@ -1125,7 +1098,7 @@ impl PaimonTableScan { let stream = stream.map(move |result| { let mut batch = result .map_err(to_datafusion_error) - .and_then(|batch| to_datafusion_batch(batch, &batch_schema))?; + .and_then(|batch| super::cast_batch_to_schema(batch, &batch_schema))?; // The decoder hook is an optimization and may be unavailable // for a file/path. Retain every original live expression as // the exact fallback; evaluating it on decoder survivors is diff --git a/crates/integrations/datafusion/src/procedures/compat.rs b/crates/integrations/datafusion/src/procedures/compat.rs index b5fd14803..a32a5af36 100644 --- a/crates/integrations/datafusion/src/procedures/compat.rs +++ b/crates/integrations/datafusion/src/procedures/compat.rs @@ -58,7 +58,7 @@ async fn validate_write_target( Ident::with_quote('"', identifier.database()), Ident::with_quote('"', identifier.object()), ]); - SQLContext::ensure_partition_command_target(&name, operation)?; + SQLContext::ensure_main_branch_base_table(&name, operation)?; if let Some(sql_ctx) = sql_ctx { sql_ctx.ensure_no_time_travel_for_write(operation)?; sql_ctx diff --git a/crates/integrations/datafusion/src/read_files/mod.rs b/crates/integrations/datafusion/src/read_files/mod.rs index 68548c374..885ceb4f8 100644 --- a/crates/integrations/datafusion/src/read_files/mod.rs +++ b/crates/integrations/datafusion/src/read_files/mod.rs @@ -50,7 +50,7 @@ use futures::TryStreamExt; use url::Url; use options::{Format, Options}; -pub(crate) use projection::sql; +pub(crate) use projection::{execute_plan, plan_sql, sql}; const GENERATED_METADATA: &str = "paimon.read_files.generated_metadata"; diff --git a/crates/integrations/datafusion/src/read_files/projection.rs b/crates/integrations/datafusion/src/read_files/projection.rs index 3be275ac9..af37fd138 100644 --- a/crates/integrations/datafusion/src/read_files/projection.rs +++ b/crates/integrations/datafusion/src/read_files/projection.rs @@ -45,15 +45,26 @@ pub(crate) fn sql<'a>( sql: &'a str, options: SQLOptions, ) -> futures::future::BoxFuture<'a, Result> { + Box::pin(async move { + let mut state = ctx.state(); + let plan = plan_sql(&mut state, sql).await?; + execute_plan(ctx, state, plan, options).await + }) +} + +pub(crate) fn plan_sql<'a>( + state: &'a mut SessionState, + sql: &'a str, +) -> futures::future::BoxFuture<'a, Result> { // Keep this additional planning layer off SQLContext's already large future. Box::pin(async move { // The AST check below is authoritative; this avoids reparsing ordinary SQL. if !sql.to_ascii_lowercase().contains("read_files") { - return ctx.sql_with_options(sql, options).await; + return state.create_logical_plan(sql).await; } let mut statements = Parser::parse_sql(&GenericDialect, sql)?; let [statement] = statements.as_mut_slice() else { - return ctx.sql_with_options(sql, options).await; + return state.create_logical_plan(sql).await; }; struct FindSource; impl VisitorMut for FindSource { @@ -76,11 +87,10 @@ pub(crate) fn sql<'a>( } } if statement.visit(&mut FindSource).is_continue() { - return ctx.sql_with_options(sql, options).await; + return state.create_logical_plan(sql).await; } - let mut state = ctx.state(); let Some(function) = state.table_functions().get("read_files").cloned() else { - return ctx.sql_with_options(sql, options).await; + return state.create_logical_plan(sql).await; }; // Bind each source once for both schema planning and execution. The cache // belongs to this statement's cloned state, never to the shared session. @@ -100,12 +110,24 @@ pub(crate) fn sql<'a>( if let ControlFlow::Break(error) = statement.visit(&mut rewriter) { return Err(*error); } - SessionContext::new_with_state(state) - .sql_with_options(&statement.to_string(), options) - .await + state.create_logical_plan(&statement.to_string()).await }) } +pub(crate) async fn execute_plan( + ctx: &SessionContext, + state: SessionState, + plan: LogicalPlan, + options: SQLOptions, +) -> Result { + options.verify_plan(&plan)?; + match plan { + // PREPARE and other session commands take effect on the caller's context. + LogicalPlan::Statement(_) | LogicalPlan::Ddl(_) => ctx.execute_logical_plan(plan).await, + plan => Ok(DataFrame::new(state, plan)), + } +} + #[derive(Debug)] struct CachedSource { function: Arc, diff --git a/crates/integrations/datafusion/src/relation_planner.rs b/crates/integrations/datafusion/src/relation_planner.rs index 10b2679db..bf92b6e9c 100644 --- a/crates/integrations/datafusion/src/relation_planner.rs +++ b/crates/integrations/datafusion/src/relation_planner.rs @@ -17,20 +17,23 @@ //! Time-travel planning for Paimon tables and registered engines. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fmt::Debug; +use std::ops::ControlFlow; use std::sync::Arc; use datafusion::catalog::default_table_source::{provider_as_source, source_as_provider}; +use datafusion::common::config::CatalogOptions; use datafusion::common::plan_datafusion_err; use datafusion::common::TableReference; use datafusion::datasource::TableProvider; -use datafusion::error::Result as DFResult; +use datafusion::error::{DataFusionError, Result as DFResult}; use datafusion::logical_expr::builder::LogicalPlanBuilder; use datafusion::logical_expr::planner::{ PlannedRelation, RelationPlanner, RelationPlannerContext, RelationPlanning, }; -use datafusion::sql::sqlparser::ast::{self, TableFactor, TableVersion}; +use datafusion::logical_expr::{Expr, LogicalPlan, Statement}; +use datafusion::sql::sqlparser::ast::{self, TableFactor, TableVersion, VisitMut, VisitorMut}; use paimon::spec::{SCAN_TIMESTAMP_MILLIS_OPTION, SCAN_VERSION_OPTION}; use crate::catalog::{ @@ -39,6 +42,570 @@ use crate::catalog::{ }; use crate::table::{ObjectTableProvider, PaimonTableProvider}; +/// Resolves statement-local TABLE bindings to snapshot scans. +#[derive(Debug)] +pub(crate) struct SnapshotRelationPlanner { + bindings: HashMap)>, + display_qualifiers: HashMap, + cte_names: HashSet, +} + +impl SnapshotRelationPlanner { + pub(crate) fn try_new( + mut bindings: HashMap)>, + statement: &mut ast::Statement, + defaults: &CatalogOptions, + normalize: bool, + ) -> DFResult { + let mut qualifiers = SnapshotQualifiers { + bindings: &bindings, + defaults, + normalize, + private_bindings: HashSet::new(), + cte_names: HashSet::new(), + physical_tables: physical_table_references(statement, normalize)?, + scopes: Vec::new(), + query_has_select: Vec::new(), + select_sources: Vec::new(), + ambiguous_qualifier: None, + }; + let _ = statement.visit(&mut qualifiers); + if let Some(qualifier) = qualifiers.ambiguous_qualifier { + return Err(plan_datafusion_err!( + "Ambiguous snapshot qualifier '{qualifier}'. Use distinct aliases for the snapshot scans" + )); + } + let cte_names = qualifiers.cte_names; + let mut display_qualifiers = HashMap::new(); + for name in qualifiers.private_bindings { + let (table, _) = bindings.get_mut(&name).unwrap(); + display_qualifiers.insert(name.clone(), table.to_string()); + *table = TableReference::bare(name); + } + Ok(Self { + bindings, + display_qualifiers, + cte_names, + }) + } + + /// DataFusion includes qualifiers in default expression names. Restore + /// their SQL spelling before a caller persists the schema or prepares it. + pub(crate) fn restore_output_names(&self, plan: LogicalPlan) -> DFResult { + if self.display_qualifiers.is_empty() { + return Ok(plan); + } + if let LogicalPlan::Statement(Statement::Prepare(mut prepare)) = plan { + prepare.input = + Arc::new(self.restore_output_names(Arc::unwrap_or_clone(prepare.input))?); + return Ok(LogicalPlan::Statement(Statement::Prepare(prepare))); + } + let mut renamed = false; + let projection = plan + .schema() + .columns() + .into_iter() + .map(|column| { + let mut name = column.name.clone(); + for (binding, original) in &self.display_qualifiers { + if name.contains(binding) { + name = name.replace(binding, original); + } + } + if name == column.name { + Expr::Column(column) + } else { + renamed = true; + let qualifier = column.relation.clone(); + Expr::Column(column).alias_qualified(qualifier, name) + } + }) + .collect::>(); + if renamed { + LogicalPlanBuilder::from(plan).project(projection)?.build() + } else { + Ok(plan) + } + } +} + +enum ScopedQualifier<'a> { + Original, + Snapshots(Vec<&'a str>), +} + +fn physical_table_references( + statement: &ast::Statement, + normalize: bool, +) -> DFResult> { + struct TableVisitor { + normalize: bool, + query_depth: usize, + names: HashSet<*const ast::ObjectName>, + } + + impl ast::Visitor for TableVisitor { + type Break = DataFusionError; + + fn pre_visit_query(&mut self, query: &ast::Query) -> ControlFlow { + self.query_depth += 1; + if self.query_depth != 1 { + return ControlFlow::Continue(()); + } + match crate::sql_function::visit_view_table_dependencies( + query, + self.normalize, + &mut |name| { + self.names.insert(std::ptr::from_ref(name)); + Ok(()) + }, + ) { + Ok(()) => ControlFlow::Continue(()), + Err(error) => ControlFlow::Break(error), + } + } + + fn post_visit_query(&mut self, _: &ast::Query) -> ControlFlow { + self.query_depth -= 1; + ControlFlow::Continue(()) + } + } + + let mut visitor = TableVisitor { + normalize, + query_depth: 0, + names: HashSet::new(), + }; + match ast::Visit::visit(statement, &mut visitor) { + ControlFlow::Continue(()) => Ok(visitor.names), + ControlFlow::Break(error) => Err(error), + } +} + +/// DataFusion matches a bare qualifier against the last component of a full +/// table name. Bind colliding snapshots privately and resolve SQL qualifiers +/// within their original scope before DataFusion plans the join. +struct SnapshotQualifiers<'a> { + bindings: &'a HashMap)>, + defaults: &'a CatalogOptions, + normalize: bool, + private_bindings: HashSet, + cte_names: HashSet, + // Node addresses distinguish tables from same-named CTEs. Moving a FROM + // vector for traversal leaves its elements at their original addresses. + physical_tables: HashSet<*const ast::ObjectName>, + scopes: Vec>>, + query_has_select: Vec, + select_sources: Vec>, + ambiguous_qualifier: Option, +} + +impl<'binding> SnapshotQualifiers<'binding> { + fn factors(group: &ast::TableWithJoins) -> impl DoubleEndedIterator { + std::iter::once(&group.relation).chain(group.joins.iter().map(|join| &join.relation)) + } + + fn visible_factors<'a>( + relation: &'a TableFactor, + joins: &'a [ast::Join], + ) -> impl DoubleEndedIterator { + use ast::JoinOperator::{LeftAnti, LeftSemi, RightAnti, RightSemi}; + + let (relation, joins) = match joins + .iter() + .rposition(|join| matches!(join.join_operator, RightSemi(_) | RightAnti(_))) + { + Some(index) => (&joins[index].relation, &joins[index + 1..]), + None => (relation, joins), + }; + std::iter::once(relation).chain(joins.iter().filter_map(|join| { + (!matches!(join.join_operator, LeftSemi(_) | LeftAnti(_))).then_some(&join.relation) + })) + } + + fn table_qualifiers(&self, table: &TableReference) -> [TableReference; 3] { + let resolved = table.clone().resolve( + &self.defaults.default_catalog, + &self.defaults.default_schema, + ); + [ + TableReference::bare(Arc::clone(&resolved.table)), + TableReference::partial(Arc::clone(&resolved.schema), Arc::clone(&resolved.table)), + TableReference::full(resolved.catalog, resolved.schema, resolved.table), + ] + } + + fn relation_scope<'relation>( + &mut self, + factors: impl DoubleEndedIterator, + visible_only: bool, + ) -> HashMap> { + let mut sources = Vec::new(); + let mut snapshots = Vec::new(); + let mut scope = HashMap::new(); + let mut pending: Vec<_> = factors.rev().collect(); + let normalizer = datafusion::sql::planner::IdentNormalizer::new(self.normalize); + while let Some(factor) = pending.pop() { + let alias = match factor { + TableFactor::TableFunction { + expr: ast::Expr::Identifier(binding), + alias: None, + } => { + if let Some((binding, (table, _))) = self.bindings.get_key_value(&binding.value) + { + snapshots.push((table.clone(), Some(binding.as_str()))); + } + continue; + } + TableFactor::Table { + name, + args: None, + alias: None, + .. + } => { + if let Ok(table) = datafusion::sql::planner::object_name_to_table_reference( + name.clone(), + self.normalize, + ) { + if self.physical_tables.contains(&std::ptr::from_ref(name)) { + scope.extend( + self.table_qualifiers(&table) + .into_iter() + .map(|qualifier| (qualifier, ScopedQualifier::Original)), + ); + } + sources.push((table, None)); + } + continue; + } + TableFactor::NestedJoin { + table_with_joins, + alias: None, + } => { + if visible_only { + pending.extend( + Self::visible_factors( + &table_with_joins.relation, + &table_with_joins.joins, + ) + .rev(), + ); + } else { + pending.extend(Self::factors(table_with_joins).rev()); + } + continue; + } + TableFactor::NestedJoin { alias, .. } + | TableFactor::Table { alias, .. } + | TableFactor::Derived { alias, .. } + | TableFactor::Function { alias, .. } + | TableFactor::UNNEST { alias, .. } + | TableFactor::TableFunction { alias, .. } => alias, + _ => continue, + }; + if let Some(alias) = alias { + sources.push(( + TableReference::bare(normalizer.normalize(alias.name.clone())), + None, + )); + } + } + + // Live relations reserve their qualifiers before any implicit snapshot names. + sources.extend(snapshots); + let mut reserved = HashMap::<&str, Vec<&TableReference>>::new(); + for (table, binding) in &sources { + let names = reserved.entry(table.table()).or_default(); + if let Some(binding) = *binding { + let qualifiers = self.table_qualifiers(table); + // Private snapshot bindings protect outer references during decorrelation. + let overlaps_existing = qualifiers.iter().any(|qualifier| { + matches!(scope.get(qualifier), Some(ScopedQualifier::Original)) + || self + .scopes + .iter() + .any(|scope| scope.contains_key(qualifier)) + }); + if overlaps_existing || names.iter().any(|name| name.resolved_eq(table)) { + self.private_bindings.insert(binding.to_owned()); + } + for qualifier in qualifiers { + if let ScopedQualifier::Snapshots(bindings) = scope + .entry(qualifier) + .or_insert_with(|| ScopedQualifier::Snapshots(Vec::new())) + { + bindings.push(binding); + } + } + } else { + scope.insert(table.clone(), ScopedQualifier::Original); + } + names.push(table); + } + scope + } + + fn visit_joins(&mut self, group: &mut ast::TableWithJoins, preceding: &[&TableFactor]) { + self.visit_factor(&mut group.relation, preceding.iter().copied()); + for index in 0..group.joins.len() { + let (previous, rest) = group.joins.split_at_mut(index); + let join = &mut rest[0]; + let left = || Self::visible_factors(&group.relation, previous); + self.visit_factor(&mut join.relation, preceding.iter().copied().chain(left())); + // The ON clause can see its join inputs and enclosing queries. + let join_scope = + self.relation_scope(left().chain(std::iter::once(&join.relation)), true); + self.scopes.push(join_scope); + let _ = join.join_operator.visit(self); + self.scopes.pop(); + } + } + + fn visit_factor<'relation>( + &mut self, + factor: &mut TableFactor, + preceding: impl DoubleEndedIterator, + ) { + match factor { + TableFactor::NestedJoin { + table_with_joins, .. + } => { + self.relation_scope(Self::factors(table_with_joins), false); + self.visit_joins(table_with_joins, &preceding.collect::>()); + } + TableFactor::Derived { lateral: true, .. } + | TableFactor::Function { lateral: true, .. } + | TableFactor::UNNEST { .. } => { + let scope = self.relation_scope(preceding, true); + self.scopes.push(scope); + let _ = factor.visit(self); + self.scopes.pop(); + } + _ => { + let _ = factor.visit(self); + } + } + } + + fn rewrite_prefix( + &mut self, + idents: &[ast::Ident], + has_column: bool, + ) -> Option<(usize, ast::Ident)> { + let prefix_len = if has_column { + idents.len().saturating_sub(1) + } else { + idents.len() + }; + let normalizer = datafusion::sql::planner::IdentNormalizer::new(self.normalize); + let candidates: Vec<_> = (1..=prefix_len.min(3)) + .rev() + .filter_map(|len| { + let name = ast::ObjectName::from(idents[..len].to_vec()); + let table = + datafusion::sql::planner::object_name_to_table_reference(name, self.normalize) + .ok()?; + let column = has_column.then(|| normalizer.normalize(idents[len].clone())); + Some((len, table, column)) + }) + .collect(); + for scope in self.scopes.iter().rev() { + let mut matched_snapshot = false; + for (len, table, column) in &candidates { + match scope.get(table) { + Some(ScopedQualifier::Original) => return None, + Some(ScopedQualifier::Snapshots(bindings)) => { + matched_snapshot = true; + if column.as_ref().is_some_and(|column| { + !bindings.iter().any(|binding| { + self.bindings[*binding] + .1 + .schema() + .column_with_name(column) + .is_some() + }) + }) { + continue; + } + let [binding] = bindings.as_slice() else { + self.ambiguous_qualifier + .get_or_insert_with(|| table.clone()); + return None; + }; + return self + .private_bindings + .contains(*binding) + .then(|| (*len, ast::Ident::new(*binding))); + } + None => {} + } + } + if matched_snapshot { + // Let DataFusion resolve an unqualified nested field in this scope. + return None; + } + } + None + } + + fn rewrite_wildcard(&mut self, name: &mut ast::ObjectName) { + let idents: Vec<_> = name + .0 + .iter() + .map_while(|part| part.as_ident().cloned()) + .collect(); + if let Some((len, binding)) = self.rewrite_prefix(&idents, false) { + name.0 + .splice(..len, [ast::ObjectNamePart::Identifier(binding)]); + } + } +} + +impl VisitorMut for SnapshotQualifiers<'_> { + type Break = (); + + fn pre_visit_query(&mut self, query: &mut ast::Query) -> ControlFlow<()> { + if let Some(with) = &query.with { + let normalizer = datafusion::sql::planner::IdentNormalizer::new(self.normalize); + self.cte_names.extend( + with.cte_tables + .iter() + .map(|cte| normalizer.normalize(cte.alias.name.clone())), + ); + } + self.query_has_select.push(query.body.as_select().is_some()); + self.scopes.push(HashMap::new()); + ControlFlow::Continue(()) + } + + fn post_visit_query(&mut self, _: &mut ast::Query) -> ControlFlow<()> { + self.scopes.pop(); + self.query_has_select.pop(); + ControlFlow::Continue(()) + } + + fn pre_visit_select(&mut self, select: &mut ast::Select) -> ControlFlow<()> { + let mut sources = std::mem::take(&mut select.from); + // Reserve private bindings before visiting inputs in SQL visibility order. + self.relation_scope(sources.iter().flat_map(Self::factors), false); + for index in 0..sources.len() { + let (previous, rest) = sources.split_at_mut(index); + let preceding = previous + .iter() + .flat_map(|group| Self::visible_factors(&group.relation, &group.joins)) + .collect::>(); + self.visit_joins(&mut rest[0], &preceding); + } + let scope = self.relation_scope( + sources + .iter() + .flat_map(|group| Self::visible_factors(&group.relation, &group.joins)), + true, + ); + self.scopes.push(scope); + self.select_sources.push(sources); + for item in &mut select.projection { + if let ast::SelectItem::QualifiedWildcard( + ast::SelectItemQualifiedWildcardKind::ObjectName(name), + _, + ) = item + { + self.rewrite_wildcard(name); + } + } + ControlFlow::Continue(()) + } + + fn post_visit_select(&mut self, select: &mut ast::Select) -> ControlFlow<()> { + select.from = self.select_sources.pop().unwrap(); + let scope = self.scopes.pop().unwrap(); + if self.query_has_select.last() == Some(&true) { + // ORDER BY belongs to Query and is visited after its SELECT. + *self.scopes.last_mut().unwrap() = scope; + } + ControlFlow::Continue(()) + } + + fn pre_visit_expr(&mut self, expr: &mut ast::Expr) -> ControlFlow<()> { + match expr { + ast::Expr::CompoundIdentifier(idents) => { + if let Some((len, binding)) = self.rewrite_prefix(idents, true) { + idents.splice(..len, [binding]); + } + } + ast::Expr::QualifiedWildcard(name, _) => self.rewrite_wildcard(name), + ast::Expr::Function(function) => { + if let ast::FunctionArguments::List(args) = &mut function.args { + for arg in &mut args.args { + if let ast::FunctionArg::Unnamed(ast::FunctionArgExpr::QualifiedWildcard( + name, + )) = arg + { + self.rewrite_wildcard(name); + } + } + } + } + _ => {} + } + ControlFlow::Continue(()) + } +} + +impl RelationPlanner for SnapshotRelationPlanner { + fn plan_relation( + &self, + mut relation: TableFactor, + context: &mut dyn RelationPlannerContext, + ) -> DFResult { + if let TableFactor::TableFunction { + expr: ast::Expr::Identifier(binding), + alias, + } = &relation + { + if let Some((table, provider)) = self.bindings.get(&binding.value) { + return plan_scan(alias.clone(), table.clone(), provider.clone()); + } + } + if let Some(marker) = self.display_qualifiers.keys().next() { + let alias = match &mut relation { + TableFactor::Derived { alias, .. } => Some(alias), + TableFactor::Table { + name, + alias, + args: None, + .. + } if context + .object_name_to_table_reference(name.clone()) + .is_ok_and(|table| self.cte_names.contains(&table.to_string())) => + { + Some(alias) + } + _ => None, + }; + if let Some(alias) = alias { + // context.plan reenters the relation planners. The statement-local + // marker delegates that call before we restore the inner field names. + if alias.as_ref().is_some_and(|a| a.name.value == *marker) { + *alias = None; + } else { + let original = alias.replace(ast::TableAlias { + name: ast::Ident::new(marker), + explicit: true, + columns: Vec::new(), + at: None, + }); + let plan = self.restore_output_names(context.plan(relation)?)?; + return Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new( + plan, original, + )))); + } + } + } + Ok(RelationPlanning::Original(Box::new(relation))) + } +} + /// Resolves Paimon time travel, and registered engine snapshot IDs and timestamps. #[derive(Debug)] pub struct PaimonRelationPlanner; @@ -64,6 +631,7 @@ impl RelationPlanner for PaimonRelationPlanner { let TableFactor::Table { ref name, ref version, + ref alias, .. } = relation else { @@ -102,7 +670,7 @@ impl RelationPlanner for PaimonRelationPlanner { async move { routed.at_time_travel(travel).await }, "engine time travel resolution thread panicked", )?; - return plan_scan(relation, table_ref, new_provider); + return plan_scan(alias.clone(), table_ref, new_provider); } let Some(paimon_provider) = provider.downcast_ref::() else { @@ -140,18 +708,15 @@ impl RelationPlanner for PaimonRelationPlanner { ) .map_err(crate::to_datafusion_error)?; let new_provider = PaimonTableProvider::try_new(new_table)?; - plan_scan(relation, table_ref, Arc::new(new_provider)) + plan_scan(alias.clone(), table_ref, Arc::new(new_provider)) } } fn plan_scan( - relation: TableFactor, + alias: Option, table_ref: TableReference, provider: Arc, ) -> DFResult { - let TableFactor::Table { alias, .. } = relation else { - unreachable!() - }; let plan = LogicalPlanBuilder::scan(table_ref, provider_as_source(provider), None)?.build()?; Ok(RelationPlanning::Planned(Box::new(PlannedRelation::new( plan, alias, @@ -245,7 +810,7 @@ fn timestamp_as_of_millis(expr: &ast::Expr) -> DFResult { /// Parse a timestamp string to milliseconds since epoch (using local timezone). /// /// Matches Java Paimon's behavior which uses `TimeZone.getDefault()`. -fn parse_timestamp_to_millis(ts: &str) -> DFResult { +pub(crate) fn parse_timestamp_to_millis(ts: &str) -> DFResult { use chrono::{Local, NaiveDateTime, TimeZone}; let naive = NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").map_err(|e| { diff --git a/crates/integrations/datafusion/src/sql_context.rs b/crates/integrations/datafusion/src/sql_context.rs index 7eec9889a..340c8b930 100644 --- a/crates/integrations/datafusion/src/sql_context.rs +++ b/crates/integrations/datafusion/src/sql_context.rs @@ -28,6 +28,7 @@ //! - `DROP DATABASE [IF EXISTS] [catalog.]db [CASCADE]` //! - `USE [catalog.]db` //! - `CREATE TABLE db.t (col TYPE, ..., PRIMARY KEY (col, ...)) [PARTITIONED BY (col, ...)] [WITH ('key' = 'val')]` +//! - `CREATE TABLE [IF NOT EXISTS] db.t [PARTITIONED BY (col, ...)] [WITH ('key' = 'val')] AS query` //! - `ALTER TABLE db.t ADD COLUMN col TYPE` //! - `ALTER TABLE db.t DROP COLUMN col` //! - `ALTER TABLE db.t RENAME COLUMN old TO new` @@ -55,6 +56,7 @@ use datafusion::arrow::array::{ use datafusion::arrow::compute::cast; use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, Schema}; use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions}; +use datafusion::common::config::CatalogOptions; use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion}; use datafusion::common::{plan_datafusion_err, DFSchema, ScalarValue, TableReference}; use datafusion::datasource::{MemTable, TableProvider}; @@ -70,15 +72,15 @@ use datafusion::sql::sqlparser::ast::{ AlterColumnOperation, AlterTableOperation, BinaryLength, CharacterLength, ColumnDef, ColumnOption, CommentDef, CommentObject, CreateFunction, CreateFunctionBody, CreateTable, CreateTableOptions, CreateView, DataType as SqlDataType, Delete, Expr as SqlExpr, - ExprWithAlias, FromTable, FunctionBehavior, FunctionReturnType, Ident, Insert, Merge, - ObjectName, ObjectType, RenameTableNameKind, Reset, ResetStatement, Set, SetExpr, - ShowCreateObject, SqlOption, Statement, TableFactor, TableObject, Truncate, Update, Use, - Value as SqlValue, + ExprWithAlias, FromTable, FunctionBehavior, FunctionReturnType, HiveDistributionStyle, Ident, + Insert, Merge, ObjectName, ObjectType, RenameTableNameKind, Reset, ResetStatement, Set, + SetExpr, ShowCreateObject, SqlOption, Statement, TableFactor, TableObject, Truncate, Update, + Use, Value as SqlValue, }; use datafusion::sql::sqlparser::dialect::GenericDialect; use datafusion::sql::sqlparser::keywords::Keyword; use datafusion::sql::sqlparser::parser::Parser; -use datafusion::sql::sqlparser::tokenizer::{Token, Tokenizer}; +use datafusion::sql::sqlparser::tokenizer::{Location, Token, Tokenizer}; use datafusion_spark::SessionStateBuilderSpark; use futures::StreamExt; use paimon::catalog::{parse_object_name, Catalog, Identifier, ParsedObjectName}; @@ -94,6 +96,8 @@ use crate::error::to_datafusion_error; use crate::table::PaimonTableProvider; use crate::{BlobReaderRegistry, DynamicOptions}; +mod ctas; + /// A SQL context that supports registering multiple Paimon catalogs and executing SQL. /// /// # Example @@ -490,17 +494,18 @@ impl SQLContext { /// Execute a SQL statement with options for statements delegated to DataFusion. pub async fn sql_with_options(&self, sql: &str, options: SQLOptions) -> DFResult { - let is_create_table = looks_like_create_table(sql); - let enable_ident_normalization = self.ctx.enable_ident_normalization(); - let (rewritten_sql, partition_keys) = if is_create_table { - extract_partition_by(sql, enable_ident_normalization)? - } else { - (sql.to_string(), vec![]) - }; - if contains_time_travel_keyword(&rewritten_sql) { - // Time-travel queries are not DDL; skip our own parsing and handle directly. - return self.handle_time_travel_query(&rewritten_sql, options).await; - } + // Box the dispatcher so its size does not propagate to callers' futures. + Box::pin(self.execute_statement(sql, options)).await + } + + async fn execute_statement(&self, sql: &str, options: SQLOptions) -> DFResult { + // A concurrent USE can change the session defaults during a catalog lookup. + let state = self.ctx.state(); + let enable_ident_normalization = + state.config_options().sql_parser.enable_ident_normalization; + let (mut rewritten_sql, partition_keys) = + extract_partition_by(sql, enable_ident_normalization)?; + let time_travel_sources = mask_time_travel_sources(&mut rewritten_sql); if let Some(show_partitions) = crate::format_partition_ddl::parse_show_partitions(&rewritten_sql)? { @@ -526,33 +531,60 @@ impl SQLContext { )); } + if !time_travel_sources.is_empty() { + validate_time_travel_sources(&statements[0], &time_travel_sources)?; + } + if let Statement::CreateTable(ct) = &mut statements[0] { + if !partition_keys.is_empty() + && matches!( + ct.hive_distribution, + HiveDistributionStyle::PARTITIONED { .. } + ) + { + return Err(plan_datafusion_err!( + "CREATE TABLE accepts only one PARTITIONED BY clause" + )); + } + if let Some(query) = ct.query.take_if(|_| !ct.temporary) { + return Box::pin(self.handle_create_table_as( + ct, + query, + partition_keys, + state, + options, + &time_travel_sources, + )) + .await; + } + } + if !time_travel_sources.is_empty() + || matches!( + statements[0], + Statement::Query(_) | Statement::Explain { .. } + ) + { + return Box::pin(self.plan_query( + state, + statements.remove(0), + options, + &time_travel_sources, + )) + .await; + } + let rewritten; let stored_definition = matches!(&statements[0], Statement::CreateView(view) if view.temporary || self.is_paimon_catalog_ref(&TableReference::from(view.name.to_string().as_str()))) || matches!(&statements[0], Statement::CreateFunction(_)); let changed = !stored_definition && { - let binary_changed = crate::binary_cast::rewrite(&mut statements[0])?; - let regex_changed = crate::regex_operators::rewrite(&mut statements[0]); - let lateral_changed = crate::lateral_views::rewrite(&mut statements[0])?; - let compat_changed = - crate::expression_compat::rewrite(&mut statements[0], &self.ctx.state())?; - let state = self.ctx.state(); - // Queries and temporary view bodies resolve after SQL function expansion below. - let max_pt_changed = if matches!( - statements[0], - Statement::Query(_) | Statement::Explain { .. } - ) || matches!(&statements[0], Statement::CreateView(view) if view.temporary) - { - false - } else { - Box::pin(crate::partition_functions::rewrite( - &mut statements[0], - &state, - &self.current_catalog_name(), - &state.config_options().catalog.default_schema, - )) - .await? - }; - binary_changed || regex_changed || lateral_changed || compat_changed || max_pt_changed + let expressions_changed = Self::rewrite_expressions(&mut statements[0], &state)?; + let partitions_changed = Box::pin(crate::partition_functions::rewrite( + &mut statements[0], + &state, + &state.config_options().catalog.default_catalog, + &state.config_options().catalog.default_schema, + )) + .await?; + expressions_changed || partitions_changed }; let sql = if changed || vector_changed { rewritten = statements[0].to_string(); @@ -936,127 +968,70 @@ impl SQLContext { )) .await } - Statement::Query(_) | Statement::Explain { .. } => { - let mut statement = statements[0].clone(); - if let Statement::Explain { - statement: inner, .. - } = &mut statement - { - if let Statement::Merge(merge) = inner.as_mut() { - *merge = self.normalize_merge_into(merge).await?; - } - } - let current_catalog = self.current_catalog_name(); - let current_database = self - .ctx - .state() - .config_options() - .catalog - .default_schema - .clone(); - let expanded = crate::sql_function::expand_statement( - &self.ctx.state(), - statement, - &self.catalogs, - ¤t_catalog, - ¤t_database, - ) - .await?; - crate::read_files::sql(&self.ctx, &expanded.to_string(), options).await - } _ => crate::read_files::sql(&self.ctx, sql, options).await, } } - /// Rewrite time-travel references to temporary snapshot providers. - /// The tracker removes registrations after planning. - async fn handle_time_travel_query( + fn rewrite_expressions(statement: &mut Statement, state: &SessionState) -> DFResult { + let binary = crate::binary_cast::rewrite(statement)?; + let regex = crate::regex_operators::rewrite(statement); + let lateral = crate::lateral_views::rewrite(statement)?; + let compat = crate::expression_compat::rewrite(statement, state)?; + Ok(binary || regex || lateral || compat) + } + + async fn plan_query( &self, - sql: &str, - sql_options: SQLOptions, + mut state: SessionState, + mut statement: Statement, + options: SQLOptions, + sources: &[TimeTravelSource], ) -> DFResult { - let mut tracker = crate::merge_into::TempTableTracker::new(self); - - let version_clauses = extract_all_version_as_of(sql); - let timestamp_clauses = extract_all_timestamp_as_of(sql); - - if version_clauses.is_empty() && timestamp_clauses.is_empty() { - return Err(DataFusionError::Plan( - "Failed to parse time-travel clause in SQL".to_string(), - )); - } - - let mut replacements: Vec<((usize, usize), String)> = Vec::new(); - - for info in &version_clauses { - let table_ref: datafusion::common::TableReference = info.table_name.as_str().into(); - let (catalog, catalog_name, identifier) = - self.resolve_table_name_from_ref(&table_ref)?; - let provider = self - .time_travel_provider( - &catalog, - &catalog_name, - &identifier, - TimeTravelClause::Version(info.version.clone()), - ) - .await?; - - let uuid_name = format!("__paimon_tt_{}", uuid::Uuid::new_v4().as_simple()); - self.register_temp_table(uuid_name.as_str(), provider)?; - tracker.register(&uuid_name); - replacements.push((info.clause_range, uuid_name)); + Self::rewrite_expressions(&mut statement, &state)?; + if let Statement::Explain { + statement: inner, .. + } = &mut statement + { + if let Statement::Merge(merge) = inner.as_mut() { + *merge = self.normalize_merge_into(merge).await?; + } } - - for info in ×tamp_clauses { - let table_ref: datafusion::common::TableReference = info.table_name.as_str().into(); + let session_catalog = &state.config_options().catalog; + let mut bindings = HashMap::new(); + for source in sources { + let table = object_name_to_table_reference( + source.table.clone(), + state.config_options().sql_parser.enable_ident_normalization, + )?; let (catalog, catalog_name, identifier) = - self.resolve_table_name_from_ref(&table_ref)?; - let millis = Self::parse_timestamp_to_millis(&info.timestamp)?; + self.resolve_table_reference(&table, session_catalog)?; let provider = self - .time_travel_provider( - &catalog, - &catalog_name, - &identifier, - TimeTravelClause::TimestampMillis(millis), - ) + .time_travel_provider(&catalog, &catalog_name, &identifier, &source.clause) .await?; - - let uuid_name = format!("__paimon_tt_{}", uuid::Uuid::new_v4().as_simple()); - self.register_temp_table(uuid_name.as_str(), provider)?; - tracker.register(&uuid_name); - replacements.push((info.clause_range, uuid_name)); - } - - // Replace from right to left to preserve byte offsets. - replacements.sort_by_key(|r| std::cmp::Reverse(r.0 .0)); - - let mut rewritten_sql = sql.to_string(); - for ((start, end), uuid_name) in &replacements { - rewritten_sql = format!( - "{}{}{}", - &rewritten_sql[..*start], - uuid_name, - &rewritten_sql[*end..] - ); + bindings.insert(source.binding.clone(), (table, provider)); } - - let current_catalog = self.current_catalog_name(); - let current_database = self - .ctx - .state() - .config_options() - .catalog - .default_schema - .clone(); - let expanded = crate::sql_function::expand_sql( - &self.ctx.state(), - &rewritten_sql, + let mut expanded = crate::sql_function::expand_statement( + &state, + statement, &self.catalogs, - ¤t_catalog, - ¤t_database, + &session_catalog.default_catalog, + &session_catalog.default_schema, ) .await?; - crate::read_files::sql(&self.ctx, &expanded, sql_options).await + let plan = if bindings.is_empty() { + crate::read_files::plan_sql(&mut state, &expanded.to_string()).await? + } else { + let snapshots = Arc::new(crate::relation_planner::SnapshotRelationPlanner::try_new( + bindings, + &mut expanded, + session_catalog, + state.config_options().sql_parser.enable_ident_normalization, + )?); + state.register_relation_planner(snapshots.clone())?; + let plan = crate::read_files::plan_sql(&mut state, &expanded.to_string()).await?; + snapshots.restore_output_names(plan)? + }; + crate::read_files::execute_plan(&self.ctx, state, plan, options).await } async fn time_travel_provider( @@ -1064,9 +1039,10 @@ impl SQLContext { catalog: &Arc, catalog_name: &str, identifier: &Identifier, - clause: TimeTravelClause, + clause: &TimeTravelClause, ) -> DFResult> { use crate::catalog::EngineTimeTravel; + use crate::relation_planner::parse_timestamp_to_millis; use paimon::spec::{SCAN_TIMESTAMP_MILLIS_OPTION, SCAN_VERSION_OPTION}; let parsed = identifier @@ -1096,10 +1072,10 @@ impl SQLContext { } let travel = match clause { TimeTravelClause::Version(version) => { - EngineTimeTravel::Snapshot(crate::catalog::parse_engine_snapshot_id(&version)?) + EngineTimeTravel::Snapshot(crate::catalog::parse_engine_snapshot_id(version)?) } - TimeTravelClause::TimestampMillis(millis) => { - EngineTimeTravel::TimestampMillis(millis) + TimeTravelClause::Timestamp(timestamp) => { + EngineTimeTravel::TimestampMillis(parse_timestamp_to_millis(timestamp)?) } }; let provider = self @@ -1126,10 +1102,11 @@ impl SQLContext { let (table, base, system_name) = crate::table_loader::loaded_table_for_read(loaded, identifier).await?; let (option, value) = match clause { - TimeTravelClause::Version(version) => (SCAN_VERSION_OPTION, version), - TimeTravelClause::TimestampMillis(millis) => { - (SCAN_TIMESTAMP_MILLIS_OPTION, millis.to_string()) - } + TimeTravelClause::Version(version) => (SCAN_VERSION_OPTION, version.clone()), + TimeTravelClause::Timestamp(timestamp) => ( + SCAN_TIMESTAMP_MILLIS_OPTION, + parse_timestamp_to_millis(timestamp)?.to_string(), + ), }; let mut options = self.dynamic_options.read().unwrap().clone(); options.insert(option.to_string(), value); @@ -1155,68 +1132,22 @@ impl SQLContext { } } - /// Parse a timestamp string to milliseconds since epoch (using local timezone). - fn parse_timestamp_to_millis(ts: &str) -> DFResult { - use chrono::{Local, NaiveDateTime, TimeZone}; - - let naive = NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").map_err(|e| { - DataFusionError::Plan(format!( - "Cannot parse time travel timestamp '{ts}': {e}. Expected format: YYYY-MM-DD HH:MM:SS" - )) - })?; - let local = Local.from_local_datetime(&naive).single().ok_or_else(|| { - DataFusionError::Plan(format!("Ambiguous or invalid local time: '{ts}'")) - })?; - Ok(local.timestamp_millis()) - } - - /// Resolve a TableReference to (catalog, catalog_name, Identifier). - fn resolve_table_name_from_ref( + fn resolve_table_reference( &self, - table_ref: &datafusion::common::TableReference, + table: &TableReference, + defaults: &CatalogOptions, ) -> DFResult<(Arc, String, Identifier)> { - match table_ref { - datafusion::common::TableReference::Full { - catalog, - schema, - table, - } => { - let catalog_arc = self - .catalogs - .get(catalog.as_ref()) - .ok_or_else(|| DataFusionError::Plan(format!("Unknown catalog '{catalog}'")))?; - Ok(( - catalog_arc.clone(), - catalog.to_string(), - Identifier::new(schema.as_ref(), table.as_ref()), - )) - } - datafusion::common::TableReference::Partial { schema, table } => { - let catalog = self.current_catalog()?; - let catalog_name = self.current_catalog_name(); - Ok(( - catalog, - catalog_name, - Identifier::new(schema.as_ref(), table.as_ref()), - )) - } - datafusion::common::TableReference::Bare { table } => { - let catalog = self.current_catalog()?; - let catalog_name = self.current_catalog_name(); - let default_schema = self - .ctx - .state() - .config_options() - .catalog - .default_schema - .clone(); - Ok(( - catalog, - catalog_name, - Identifier::new(default_schema, table.as_ref()), - )) - } - } + let catalog_name = table.catalog().unwrap_or(&defaults.default_catalog); + let catalog = self + .catalogs + .get(catalog_name) + .ok_or_else(|| plan_datafusion_err!("Unknown catalog '{catalog_name}'"))?; + let database = table.schema().unwrap_or(&defaults.default_schema); + Ok(( + catalog.clone(), + catalog_name.to_string(), + Identifier::new(database, table.table()), + )) } async fn handle_create_table( @@ -1236,73 +1167,14 @@ impl SQLContext { "LOCATION is not supported for Paimon tables. Table path is determined by the catalog warehouse.".to_string(), )); } - if ct.query.is_some() { - return Err(DataFusionError::Plan( - "CREATE TABLE AS SELECT is not yet supported for Paimon tables.".to_string(), - )); - } - let identifier = self.resolve_table_name(&ct.name)?; - - let mut builder = paimon::spec::Schema::builder(); - let mut comments = Vec::new(); - if let Some(comment) = &ct.comment { - comments.push(comment); - } - let options = match &ct.table_options { - CreateTableOptions::With(options) - | CreateTableOptions::Options(options) - | CreateTableOptions::TableProperties(options) - | CreateTableOptions::Plain(options) => options.as_slice(), - CreateTableOptions::None => &[], - }; - for option in options { - if let SqlOption::Comment(comment) = option { - comments.push(comment); - } - } - if comments.len() > 1 { - return Err(DataFusionError::Plan("Duplicate table COMMENT".into())); - } - if let Some(CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment)) = - comments.first().copied() - { - builder = builder.comment(Some(comment.clone())); - } - let table_options = extract_options(&ct.table_options)?; - let column_names: Vec = ct - .columns - .iter() - .map(|column| normalize_schema_identifier(&column.name, enable_ident_normalization)) - .collect(); - - // Columns - for (col, column_name) in ct.columns.iter().zip(&column_names) { - let paimon_type = column_def_to_paimon_type(col)?; - let comment = column_def_comment(col); - builder = builder.column_with_description(column_name.clone(), paimon_type, comment); - } - - builder = builder.primary_key(extract_primary_keys(ct, enable_ident_normalization)?); - - // Partition keys (extracted and validated before parsing) - if !partition_keys.is_empty() { - for pk in &partition_keys { - if !column_names.contains(pk) { - return Err(DataFusionError::Plan(format!( - "PARTITIONED BY column '{pk}' is not defined in the table" - ))); - } - } - builder = builder.partition_keys(partition_keys); - } - - // Table options from WITH ('key' = 'value', ...) - for (k, v) in table_options { - builder = builder.option(k, v); - } - - let schema = builder.build().map_err(to_datafusion_error)?; + let schema = create_table_schema( + ct, + partition_keys, + enable_ident_normalization, + None, + extract_table_properties(&ct.table_options)?, + )?; catalog .create_table(&identifier, schema, ct.if_not_exists) @@ -1751,7 +1623,7 @@ impl SQLContext { ) }); if has_partition_operation { - Self::ensure_partition_command_target(name, "ALTER TABLE")?; + Self::ensure_main_branch_base_table(name, "ALTER TABLE")?; } else { Self::ensure_main_branch_write_target(name, "ALTER TABLE")?; } @@ -2876,7 +2748,7 @@ impl SQLContext { Ok(()) } - pub(crate) fn ensure_partition_command_target( + pub(crate) fn ensure_main_branch_base_table( name: &ObjectName, operation: &str, ) -> DFResult<()> { @@ -2911,6 +2783,71 @@ impl SQLContext { } } +fn create_table_schema( + ct: &CreateTable, + partition_keys: Vec, + enable_ident_normalization: bool, + inferred_schema: Option<&Schema>, + table_options: HashMap, +) -> DFResult { + let mut builder = paimon::spec::Schema::builder(); + let mut table_comment = ct.comment.as_ref(); + for option in table_option_entries(&ct.table_options) { + if let SqlOption::Comment(comment) = option { + if table_comment.replace(comment).is_some() { + return Err(DataFusionError::Plan("Duplicate table COMMENT".into())); + } + } + } + if let Some(CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment)) = table_comment { + builder = builder.comment(Some(comment.clone())); + } + let column_names: Vec = if let Some(schema) = inferred_schema { + for field in schema.fields() { + let data_type = + paimon::arrow::arrow_field_to_paimon_type(field).map_err(to_datafusion_error)?; + builder = builder.column(field.name(), data_type); + } + schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect() + } else { + let names: Vec = ct + .columns + .iter() + .map(|column| normalize_schema_identifier(&column.name, enable_ident_normalization)) + .collect(); + for (col, name) in ct.columns.iter().zip(&names) { + builder = builder.column_with_description( + name.clone(), + column_def_to_paimon_type(col)?, + column_def_comment(col), + ); + } + names + }; + + builder = builder.primary_key(extract_primary_keys(ct, enable_ident_normalization)?); + + if !partition_keys.is_empty() { + for pk in &partition_keys { + if !column_names.contains(pk) { + return Err(DataFusionError::Plan(format!( + "PARTITIONED BY column '{pk}' is not defined in the table" + ))); + } + } + builder = builder.partition_keys(partition_keys); + } + + builder + .options(table_options) + .build() + .map_err(to_datafusion_error) +} + fn typed_view_query(view: &paimon::catalog::View) -> DFResult { let fields = view.schema().fields(); if fields.is_empty() { @@ -3159,6 +3096,7 @@ fn parse_sql_statements(sql: &str) -> DFResult<(Vec, bool)> { let significant = tokens .iter() .enumerate() + .skip_while(|(_, token)| matches!(token.token, Token::Whitespace(_) | Token::SemiColon)) .filter_map(|(index, token)| match &token.token { Token::Whitespace(_) => None, Token::Word(word) => Some((index, word.keyword)), @@ -3201,6 +3139,19 @@ fn parse_sql_statements(sql: &str) -> DFResult<(Vec, bool)> { let (mut statements, vector_changed) = crate::vector_type::parse_statements(tokens) .map_err(|error| DataFusionError::Plan(format!("SQL parse error: {error}")))?; crate::geospatial::quote_cast_types(&mut statements); + // sqlparser can omit OR ALTER and earlier table-options clauses from the AST. + if matches!(statements.first(), Some(Statement::CreateTable(ct)) if !ct.temporary && ct.query.is_some()) + { + if !matches!( + significant.as_slice(), + [(_, Keyword::CREATE), (_, Keyword::TABLE), ..] + ) { + return Err(DataFusionError::NotImplemented( + "CREATE TABLE AS SELECT does not support modifiers before TABLE".into(), + )); + } + validate_ctas_option_clauses(sql)?; + } if create_function_if_not_exists { let Some(Statement::CreateFunction(create_function)) = statements.first_mut() else { return Err(DataFusionError::Plan( @@ -3324,284 +3275,146 @@ fn validate_persistent_create_view(create_view: &CreateView) -> DFResult<()> { Ok(()) } -/// Quick check whether the SQL looks like a CREATE TABLE statement. -/// Skips leading whitespace, `--` line comments, and `/* */` block comments. -fn looks_like_create_table(sql: &str) -> bool { - let bytes = sql.as_bytes(); - let len = bytes.len(); - let mut i = 0; - // Skip leading whitespace and comments - loop { - while i < len && bytes[i].is_ascii_whitespace() { - i += 1; - } - if i + 1 < len && bytes[i] == b'-' && bytes[i + 1] == b'-' { - i += 2; - while i < len && bytes[i] != b'\n' { - i += 1; - } - continue; - } - if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' { - i += 2; - while i + 1 < len { - if bytes[i] == b'*' && bytes[i + 1] == b'/' { - i += 2; - break; - } - i += 1; - } - continue; - } - break; - } - // Match "CREATE" then whitespace then optional "TEMPORARY"/"TEMP" then "TABLE" (all ASCII, byte-safe) - if i + 6 > len || !bytes[i..i + 6].eq_ignore_ascii_case(b"CREATE") { - return false; - } - i += 6; - if i >= len || !bytes[i].is_ascii_whitespace() { - return false; - } - while i < len && bytes[i].is_ascii_whitespace() { - i += 1; - } - // Skip optional TEMPORARY or TEMP keyword - if i + 9 <= len && bytes[i..i + 9].eq_ignore_ascii_case(b"TEMPORARY") { - i += 9; - while i < len && bytes[i].is_ascii_whitespace() { - i += 1; - } - } else if i + 4 <= len && bytes[i..i + 4].eq_ignore_ascii_case(b"TEMP") { - i += 4; - while i < len && bytes[i].is_ascii_whitespace() { - i += 1; - } - } - // After optional TEMPORARY/TEMP, reject CREATE TEMPORARY VIEW / CREATE TEMP VIEW - if i + 4 <= len && bytes[i..i + 4].eq_ignore_ascii_case(b"VIEW") { - return false; - } - i + 5 <= len && bytes[i..i + 5].eq_ignore_ascii_case(b"TABLE") -} - -/// Find `PARTITIONED BY` keyword position, skipping string literals and comments. -fn find_partitioned_by(sql: &str) -> Option<(usize, usize)> { - let bytes = sql.as_bytes(); - let len = bytes.len(); - let mut i = 0; - while i < len { - match bytes[i] { - b'\'' => { - i += 1; - while i < len { - if bytes[i] == b'\'' { - i += 1; - if i < len && bytes[i] == b'\'' { - i += 1; - } else { - break; - } - } else { - i += 1; - } - } - } - b'-' if i + 1 < len && bytes[i + 1] == b'-' => { - i += 2; - while i < len && bytes[i] != b'\n' { - i += 1; - } - } - b'/' if i + 1 < len && bytes[i + 1] == b'*' => { - i += 2; - while i + 1 < len { - if bytes[i] == b'*' && bytes[i + 1] == b'/' { - i += 2; - break; - } - i += 1; - } - } - b if b.is_ascii_alphabetic() && i + 11 <= len => { - if bytes[i..i + 11].eq_ignore_ascii_case(b"PARTITIONED") { - let rest = &bytes[i + 11..]; - let ws = rest.iter().take_while(|b| b.is_ascii_whitespace()).count(); - if ws > 0 - && i + 11 + ws + 2 <= len - && rest[ws..ws + 2].eq_ignore_ascii_case(b"BY") - { - let by_end = i + 11 + ws + 2; - return Some((i, by_end)); - } - } - i += 1; - } - _ => { - i += 1; +fn create_table_parser(sql: &str) -> Option> { + if !matches!( + sql.trim_start().as_bytes().first(), + Some(b'c' | b'C' | b'-' | b'/' | b';') + ) { + return None; + } + let mut parser = Parser::new(&GenericDialect).try_with_sql(sql).ok()?; + while parser.consume_token(&Token::SemiColon) {} + if !parser.parse_keyword(Keyword::CREATE) { + return None; + } + while let Token::Word(word) = parser.next_token().token { + match word.keyword { + Keyword::TABLE => { + let _ = parser.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]); + parser.parse_object_name(false).ok()?; + return Some(parser); } + Keyword::OR + | Keyword::REPLACE + | Keyword::ALTER + | Keyword::TEMP + | Keyword::TEMPORARY + | Keyword::EXTERNAL + | Keyword::GLOBAL + | Keyword::LOCAL + | Keyword::TRANSIENT + | Keyword::VOLATILE + | Keyword::DYNAMIC + | Keyword::ICEBERG + | Keyword::SNAPSHOT => {} + _ => break, } } None } -/// Parse a single partition column token, handling quoted identifiers. -fn parse_partition_column(token: &str, enable_ident_normalization: bool) -> DFResult { - let trimmed = token.trim(); - if trimmed.is_empty() { - return Err(DataFusionError::Plan( - "Empty column name in PARTITIONED BY".to_string(), - )); - } - - let first = trimmed.as_bytes()[0]; - if first == b'"' || first == b'`' { - let mut value = String::new(); - let mut end = None; - let mut chars = trimmed[1..].char_indices().peekable(); - while let Some((idx, ch)) = chars.next() { - if ch == first as char { - if chars.peek().is_some_and(|(_, next)| *next == first as char) { - value.push(ch); - chars.next(); - } else { - end = Some(1 + idx + ch.len_utf8()); - break; +fn validate_ctas_option_clauses(sql: &str) -> DFResult<()> { + let Some(mut parser) = create_table_parser(sql) else { + return Ok(()); + }; + let mut depth = 0; + let mut seen_options = false; + loop { + match parser.next_token().token { + Token::EOF => return Ok(()), + Token::LParen => depth += 1, + Token::RParen => depth -= 1, + Token::Word(word) if depth == 0 => match word.keyword { + Keyword::AS => return Ok(()), + Keyword::WITH | Keyword::TBLPROPERTIES | Keyword::OPTIONS + if parser.peek_token_ref().token == Token::LParen => + { + if seen_options { + return Err(plan_datafusion_err!( + "CREATE TABLE AS SELECT accepts only one table options clause" + )); + } + seen_options = true; } - } else { - value.push(ch); - } - } - if let Some(end) = end { - if trimmed[end..].trim().is_empty() { - return Ok(normalize_schema_identifier( - &Ident::with_quote(first as char, value), - enable_ident_normalization, - )); - } + _ => {} + }, + _ => {} } - return Err(DataFusionError::Plan(format!( - "Invalid quoted identifier in PARTITIONED BY: {trimmed}" - ))); - } - - let parts: Vec<&str> = trimmed.split_whitespace().collect(); - match parts.len() { - 1 => Ok(normalize_schema_identifier( - &Ident::new(parts[0]), - enable_ident_normalization, - )), - _ => Err(DataFusionError::Plan(format!( - "PARTITIONED BY column '{}' should not specify a type. \ - Use column references only, e.g. PARTITIONED BY ({})", - parts[0], parts[0] - ))), } } -fn split_partition_columns(inner: &str) -> DFResult> { - let mut columns = Vec::new(); - let mut start = 0; - let mut quote = None; - let mut chars = inner.char_indices().peekable(); - while let Some((idx, ch)) = chars.next() { - match quote { - Some(q) if ch == q => { - if chars.peek().is_some_and(|(_, next)| *next == q) { - chars.next(); - } else { - quote = None; - } - } - Some(_) => {} - None if ch == '"' || ch == '`' => quote = Some(ch), - None if ch == ',' => { - columns.push(&inner[start..idx]); - start = idx + ch.len_utf8(); - } - None => {} +fn sql_byte_offset(sql: &str, location: Location) -> usize { + let mut offset = 0; + for (index, line) in sql.split_inclusive('\n').enumerate() { + if index + 1 == location.line as usize { + return offset + + line + .char_indices() + .nth(location.column as usize - 1) + .map_or(line.len(), |(index, _)| index); } + offset += line.len(); } - if quote.is_some() { - return Err(DataFusionError::Plan( - "Unterminated quoted identifier in PARTITIONED BY".to_string(), - )); - } - columns.push(&inner[start..]); - Ok(columns) + offset } -/// Extract `PARTITIONED BY (col1, col2, ...)` from SQL before parsing. -/// -/// Paimon only allows column references (no types) in PARTITIONED BY. -/// Since sqlparser's GenericDialect requires types in column definitions, -/// we extract and validate the clause ourselves, then strip it from the SQL -/// so sqlparser can parse the rest. +/// Paimon partition keys refer to output columns. GenericDialect parses the +/// same syntax as Hive column declarations. fn extract_partition_by( sql: &str, enable_ident_normalization: bool, ) -> DFResult<(String, Vec)> { - let Some((kw_start, by_end)) = find_partitioned_by(sql) else { - return Ok((sql.to_string(), vec![])); + let Some(mut parser) = create_table_parser(sql) else { + return Ok((sql.to_owned(), vec![])); }; - - let after_by = sql[by_end..].trim_start(); - let paren_start = by_end + (sql[by_end..].len() - after_by.len()); - - if !after_by.starts_with('(') { - return Err(DataFusionError::Plan( - "Expected '(' after PARTITIONED BY".to_string(), - )); - } - - let inner_start = paren_start + 1; - let mut depth = 1; - let mut paren_end = None; - let mut quote = None; - let mut chars = sql[inner_start..].char_indices().peekable(); - while let Some((i, ch)) = chars.next() { - match quote { - Some(q) if ch == q => { - if chars.peek().is_some_and(|(_, next)| *next == q) { - chars.next(); - } else { - quote = None; - } + let mut depth = 0; + let start = loop { + let token = parser.next_token(); + match token.token { + Token::LParen => depth += 1, + Token::RParen => depth -= 1, + Token::Word(word) if depth == 0 && word.keyword == Keyword::AS => { + return Ok((sql.to_owned(), vec![])); } - Some(_) => {} - None if ch == '"' || ch == '`' => quote = Some(ch), - None if ch == '(' => depth += 1, - None if ch == ')' => { - depth -= 1; - if depth == 0 { - paren_end = Some(inner_start + i); - break; - } + Token::Word(word) + if depth == 0 + && word.keyword == Keyword::PARTITIONED + && parser.parse_keyword(Keyword::BY) => + { + break token.span.start; } - None => {} + Token::EOF => return Ok((sql.to_owned(), vec![])), + _ => {} } + }; + if !parser.consume_token(&Token::LParen) { + return Err(plan_datafusion_err!("Expected '(' after PARTITIONED BY")); } - let paren_end = paren_end.ok_or_else(|| { - DataFusionError::Plan("Unmatched '(' in PARTITIONED BY clause".to_string()) - })?; - - let inner = sql[inner_start..paren_end].trim(); - if inner.is_empty() { - return Err(DataFusionError::Plan( - "PARTITIONED BY must specify at least one column".to_string(), + if parser.peek_token_ref().token == Token::RParen { + return Err(plan_datafusion_err!( + "PARTITIONED BY must specify at least one column" )); } - - let mut partition_keys = Vec::new(); - for token in split_partition_columns(inner)? { - partition_keys.push(parse_partition_column(token, enable_ident_normalization)?); + let keys = parser.parse_comma_separated(Parser::parse_identifier)?; + let end = parser.next_token(); + match end.token { + Token::RParen => {} + Token::EOF => return Err(plan_datafusion_err!("Unmatched '(' in PARTITIONED BY clause")), + other => return Err(plan_datafusion_err!( + "Expected ',' or ')' in PARTITIONED BY, found {other}. Partition columns should not specify a type" + )), } - - let clause_end = paren_end + 1; - let mut rewritten = String::with_capacity(sql.len()); - rewritten.push_str(&sql[..kw_start]); - rewritten.push_str(&sql[clause_end..]); - Ok((rewritten, partition_keys)) + let normalizer = IdentNormalizer::new(enable_ident_normalization); + let keys = keys + .into_iter() + .map(|key| normalizer.normalize(key)) + .collect(); + let mut rewritten = sql.to_owned(); + rewritten.replace_range( + sql_byte_offset(sql, start)..sql_byte_offset(sql, end.span.end), + "", + ); + Ok((rewritten, keys)) } pub(crate) fn normalize_schema_identifier( @@ -4000,28 +3813,30 @@ fn object_name_to_single_identifier( } } -/// Extract key-value pairs from [`CreateTableOptions`]. -fn extract_options(opts: &CreateTableOptions) -> DFResult> { - let sql_options = match opts { +fn table_option_entries(options: &CreateTableOptions) -> &[SqlOption] { + match options { CreateTableOptions::With(options) | CreateTableOptions::Options(options) | CreateTableOptions::TableProperties(options) | CreateTableOptions::Plain(options) => options, - CreateTableOptions::None => return Ok(Vec::new()), - }; - sql_options + CreateTableOptions::None => &[], + } +} + +fn extract_table_properties(options: &CreateTableOptions) -> DFResult> { + table_option_entries(options) .iter() .filter(|option| !matches!(option, SqlOption::Comment(_))) .map(|opt| match opt { SqlOption::KeyValue { key, value } => { - let v = value.to_string(); - // Strip surrounding quotes from the value if present. - let v = v - .strip_prefix('\'') - .and_then(|s| s.strip_suffix('\'')) - .unwrap_or(&v) - .to_string(); - Ok((key.value.clone(), v)) + let value = match value { + SqlExpr::Value(literal) => literal + .clone() + .into_string() + .unwrap_or_else(|| literal.to_string()), + expr => expr.to_string(), + }; + Ok((key.value.clone(), value)) } other => Err(DataFusionError::Plan(format!( "Unsupported table option: {other}" @@ -4439,290 +4254,131 @@ fn datum_to_constant_array( .to_array_of_size(num_rows) } Datum::Time(_) | Datum::Bytes(_) | Datum::Variant { .. } => Err(DataFusionError::Plan( - format!("Unsupported datum type for partition column: {d}"), - )), - }, - } -} - -struct VersionAsOfInfo { - table_name: String, - version: String, - /// Byte range (start, end) covering "table_name VERSION AS OF n" - clause_range: (usize, usize), -} - -struct TimestampAsOfInfo { - table_name: String, - timestamp: String, - /// Byte range (start, end) covering "table_name TIMESTAMP AS OF 'ts'" - clause_range: (usize, usize), -} - -/// A parsed `VERSION AS OF` or `TIMESTAMP AS OF` selector. -enum TimeTravelClause { - Version(String), - TimestampMillis(i64), -} - -/// Locate the table before a time-travel keyword without treating delimiters -/// inside quoted identifiers as boundaries. -fn time_travel_table_before(prefix: &str) -> (usize, &str) { - let prefix = prefix.trim_end(); - let mut quote = None; - for (index, ch) in prefix.char_indices().rev() { - if let Some(delimiter) = quote { - if ch == delimiter { - quote = None; - } - } else if matches!(ch, '"' | '`') { - // Adjacent escaped quotes toggle the quote state twice. - quote = Some(ch); - } else if ch.is_whitespace() || matches!(ch, ',' | '(') { - let start = index + ch.len_utf8(); - return (start, &prefix[start..]); - } - } - (0, prefix) -} - -/// Check for a time-travel keyword outside quoted strings, identifiers, and comments. -fn contains_time_travel_keyword(sql: &str) -> bool { - let bytes = sql.as_bytes(); - let len = bytes.len(); - let mut i = 0; - while i < len { - match bytes[i] { - quote @ (b'\'' | b'"' | b'`') => { - // Skip a quoted string or identifier, including doubled quotes. - i += 1; - while i < len { - if bytes[i] == quote { - i += 1; - if i < len && bytes[i] == quote { - i += 1; // escaped quote - } else { - break; - } - } else { - i += 1; - } - } - } - b'-' if i + 1 < len && bytes[i + 1] == b'-' => { - // Skip line comment - i += 2; - while i < len && bytes[i] != b'\n' { - i += 1; - } - } - b'/' if i + 1 < len && bytes[i + 1] == b'*' => { - // Skip block comment - i += 2; - while i + 1 < len { - if bytes[i] == b'*' && bytes[i + 1] == b'/' { - i += 2; - break; - } - i += 1; - } - } - _ => { - // Check for keywords - if i + 14 <= len && bytes[i..i + 14].eq_ignore_ascii_case(b"version as of ") { - return true; - } - if i + 16 <= len && bytes[i..i + 16].eq_ignore_ascii_case(b"timestamp as of ") { - return true; - } - i += 1; - } - } + format!("Unsupported datum type for partition column: {d}"), + )), + }, } - false } -/// Extract **all** `VERSION AS OF ` or `VERSION AS OF ''` clauses from a -/// SQL string, skipping quoted strings, identifiers, and comments. -fn extract_all_version_as_of(sql: &str) -> Vec { - let bytes = sql.as_bytes(); - let len = bytes.len(); - let mut i = 0; - let mut results = Vec::new(); - - while i < len { - match bytes[i] { - quote @ (b'\'' | b'"' | b'`') => { - // Skip a quoted string or identifier, including doubled quotes. - i += 1; - while i < len { - if bytes[i] == quote { - i += 1; - if i < len && bytes[i] == quote { - i += 1; // escaped quote - } else { - break; - } - } else { - i += 1; - } - } - } - b'-' if i + 1 < len && bytes[i + 1] == b'-' => { - // Skip line comment - i += 2; - while i < len && bytes[i] != b'\n' { - i += 1; - } - } - b'/' if i + 1 < len && bytes[i + 1] == b'*' => { - // Skip block comment - i += 2; - while i + 1 < len { - if bytes[i] == b'*' && bytes[i + 1] == b'/' { - i += 2; - break; - } - i += 1; - } - } - _ => { - if i + 14 <= len && bytes[i..i + 14].eq_ignore_ascii_case(b"version as of ") { - let kw_start = i; - let val_start = i + 14; - let remaining = &sql[val_start..]; - - // Parse either a quoted tag name or a numeric snapshot ID - let version = if let Some(after_quote) = remaining.strip_prefix('\'') { - // Tag name: VERSION AS OF 'tagname' - if let Some(close_quote) = after_quote.find('\'') { - after_quote[..close_quote].to_string() - } else { - i += 1; - continue; - } - } else { - // Numeric snapshot ID: VERSION AS OF 1 - let v: String = remaining - .chars() - .take_while(|c| c.is_ascii_digit()) - .collect(); - if v.is_empty() { - i += 1; - continue; - } - v - }; - - let is_quoted = remaining.starts_with('\''); - let val_end = if is_quoted { - val_start + version.len() + 2 // 2 quotes - } else { - val_start + version.len() - }; - - let (table_start, table_name) = time_travel_table_before(&sql[..kw_start]); - - if !table_name.is_empty() { - results.push(VersionAsOfInfo { - table_name: table_name.to_string(), - version, - clause_range: (table_start, val_end), - }); - } - - i = val_end; - } else { - i += 1; - } - } - } - } +struct TimeTravelSource { + binding: String, + table: ObjectName, + clause: TimeTravelClause, +} - results +#[derive(Debug, PartialEq)] +enum TimeTravelClause { + Version(String), + Timestamp(String), } -/// Extract all time-travel timestamp clauses outside quoted strings, -/// identifiers, and comments. -fn extract_all_timestamp_as_of(sql: &str) -> Vec { - let bytes = sql.as_bytes(); - let len = bytes.len(); - let mut i = 0; - let mut results = Vec::new(); - - while i < len { - match bytes[i] { - quote @ (b'\'' | b'"' | b'`') => { - // Skip a quoted string or identifier, including doubled quotes. - i += 1; - while i < len { - if bytes[i] == quote { - i += 1; - if i < len && bytes[i] == quote { - i += 1; // escaped quote - } else { - break; - } - } else { - i += 1; - } - } +/// Defer snapshot lookups so `IF NOT EXISTS` can skip the source query. +fn mask_time_travel_sources(sql: &mut String) -> Vec { + let lowercase = sql.to_ascii_lowercase(); + if !lowercase.contains("version") && !lowercase.contains("timestamp") { + return Vec::new(); + } + let tokens: Vec<_> = Tokenizer::new(&GenericDialect, sql) + .tokenize_with_location() + .unwrap_or_default() + .into_iter() + .filter(|token| !matches!(token.token, Token::Whitespace(_))) + .collect(); + let mut sources = Vec::new(); + for (index, clause) in tokens.windows(4).enumerate().rev() { + if index == 0 + || !matches!(tokens[index - 1].token, Token::Word(_)) + || !matches!(&clause[1].token, Token::Word(word) if word.keyword == Keyword::AS) + || !matches!(&clause[2].token, Token::Word(word) if word.keyword == Keyword::OF) + { + continue; + } + let Token::Word(word) = &clause[0].token else { + continue; + }; + let selector = match (word.keyword, &clause[3].token) { + (Keyword::VERSION, Token::SingleQuotedString(tag)) => { + TimeTravelClause::Version(tag.clone()) } - b'-' if i + 1 < len && bytes[i + 1] == b'-' => { - // Skip line comment - i += 2; - while i < len && bytes[i] != b'\n' { - i += 1; - } + (Keyword::VERSION, Token::Number(id, false)) + if id.bytes().all(|byte| byte.is_ascii_digit()) => + { + TimeTravelClause::Version(id.clone()) } - b'/' if i + 1 < len && bytes[i + 1] == b'*' => { - // Skip block comment - i += 2; - while i + 1 < len { - if bytes[i] == b'*' && bytes[i + 1] == b'/' { - i += 2; - break; - } - i += 1; - } + (Keyword::TIMESTAMP, Token::SingleQuotedString(timestamp)) => { + TimeTravelClause::Timestamp(timestamp.clone()) } - _ => { - if i + 16 <= len && bytes[i..i + 16].eq_ignore_ascii_case(b"timestamp as of ") { - let kw_start = i; - let val_start = i + 16; - let remaining = &sql[val_start..]; - - // Read the quoted timestamp string - if !remaining.starts_with('\'') { - i += 1; - continue; - } - if let Some(close_quote) = remaining[1..].find('\'') { - let timestamp = remaining[1..close_quote + 1].to_string(); - let val_end = val_start + close_quote + 2; // skip both quotes - - let (table_start, table_name) = time_travel_table_before(&sql[..kw_start]); - - if !table_name.is_empty() { - results.push(TimestampAsOfInfo { - table_name: table_name.to_string(), - timestamp, - clause_range: (table_start, val_end), - }); - } + _ => continue, + }; + let mut start = index - 1; + while start >= 2 + && matches!(tokens[start - 1].token, Token::Period) + && matches!(tokens[start - 2].token, Token::Word(_)) + { + start -= 2; + } + let table_start = sql_byte_offset(sql, tokens[start].span.start); + let identifiers: Vec<_> = tokens[start..index] + .iter() + .filter_map(|token| match &token.token { + Token::Word(word) => Some(word.to_ident(token.span)), + _ => None, + }) + .collect(); + let end = sql_byte_offset(sql, clause[3].span.end); + let binding = format!("__paimon_tt_{}", uuid::Uuid::new_v4().as_simple()); + let separator = if start > 0 && tokens[start - 1].span.end == tokens[start].span.start { + " " + } else { + "" + }; + sql.replace_range(table_start..end, &format!("{separator}TABLE({binding})")); + sources.push(TimeTravelSource { + binding, + table: ObjectName::from(identifiers), + clause: selector, + }); + } + sources.reverse(); + sources +} - i = val_end; - } else { - i += 1; - } - } else { - i += 1; - } +fn validate_time_travel_sources( + statement: &Statement, + sources: &[TimeTravelSource], +) -> DFResult<()> { + use datafusion::sql::sqlparser::ast::{Visit, Visitor}; + use std::ops::ControlFlow; + + struct Bindings<'a>(HashSet<&'a str>); + impl Visitor for Bindings<'_> { + type Break = (); + fn pre_visit_table_factor(&mut self, factor: &TableFactor) -> ControlFlow<()> { + if let TableFactor::TableFunction { + expr: SqlExpr::Identifier(binding), + .. + } = factor + { + self.0.remove(binding.value.as_str()); } + ControlFlow::Continue(()) } } - - results + let mut bindings = Bindings(sources.iter().map(|s| s.binding.as_str()).collect()); + match statement { + Statement::CreateTable(ct) => { + let _ = ct.query.visit(&mut bindings); + } + _ => { + let _ = statement.visit(&mut bindings); + } + } + if !bindings.0.is_empty() { + return Err(DataFusionError::Plan( + "Time travel requires a source table reference".into(), + )); + } + Ok(()) } /// Return an empty DataFrame with a single "result" column containing "OK". @@ -8731,30 +8387,6 @@ mod tests { } } - // ==================== extract_options tests ==================== - - #[test] - fn test_extract_options_none() { - let opts = extract_options(&CreateTableOptions::None).unwrap(); - assert!(opts.is_empty()); - } - - #[test] - fn test_extract_options_with_kv() { - // Parse a CREATE TABLE with WITH options to get a real CreateTableOptions - let dialect = GenericDialect {}; - let stmts = - Parser::parse_sql(&dialect, "CREATE TABLE t (id INT) WITH ('bucket' = '4')").unwrap(); - if let Statement::CreateTable(ct) = &stmts[0] { - let opts = extract_options(&ct.table_options).unwrap(); - assert_eq!(opts.len(), 1); - assert_eq!(opts[0].0, "bucket"); - assert_eq!(opts[0].1, "4"); - } else { - panic!("expected CreateTable"); - } - } - // ==================== SQLContext::sql integration tests ==================== #[tokio::test] @@ -8779,6 +8411,7 @@ mod tests { assert_eq!(identifier.object(), "t1"); assert!(!ignore_if_exists); assert_eq!(schema.primary_keys(), &["id"]); + assert!(schema.options().is_empty()); } else { panic!("expected CreateTable call"); } @@ -8914,23 +8547,57 @@ mod tests { } #[tokio::test] - async fn test_create_table_with_options() { + async fn test_ctas_existing_target_without_catalog_listing() { let catalog = Arc::new(MockCatalog::new()); let sql_context = make_sql_context(catalog.clone()).await; + for table_type in ["table", "iceberg-table"] { + let schema = PaimonSchema::builder() + .column("id", PaimonDataType::Int(IntType::new())) + .option("type", table_type) + .build() + .unwrap(); + *catalog.existing_table.lock().unwrap() = Some(Table::new( + paimon::io::FileIOBuilder::new("memory").build().unwrap(), + Identifier::new("mydb", "t1"), + "memory:/warehouse/mydb.db/t1".to_string(), + paimon::spec::TableSchema::new(0, &schema), + None, + )); + assert!(catalog.list_tables("mydb").await.unwrap().is_empty()); + sql_context + .sql("CREATE TABLE IF NOT EXISTS mydb.t1 AS SELECT missing_function(id) FROM missing_source") + .await + .unwrap() + .collect() + .await + .unwrap(); + let error = sql_context + .sql("CREATE TABLE mydb.t1 AS SELECT missing_function(id) FROM missing_source") + .await + .unwrap_err(); + assert!(error.to_string().contains("already exists"), "{error}"); + assert!(catalog.take_calls().is_empty()); + } + } - sql_context - .sql("CREATE TABLE mydb.t1 (id INT) WITH ('bucket' = '4', 'file.format' = 'parquet')") - .await - .unwrap(); - - let calls = catalog.take_calls(); - assert_eq!(calls.len(), 1); - if let CatalogCall::CreateTable { schema, .. } = &calls[0] { - let opts = schema.options(); - assert_eq!(opts.get("bucket").unwrap(), "4"); - assert_eq!(opts.get("file.format").unwrap(), "parquet"); - } else { - panic!("expected CreateTable call"); + #[tokio::test] + async fn test_create_table_with_options() { + let catalog = Arc::new(MockCatalog::new()); + let sql_context = make_sql_context(catalog.clone()).await; + let expected = HashMap::from([ + ("bucket".into(), "4".into()), + ("file.format".into(), "parquet".into()), + ]); + for clause in ["WITH", "OPTIONS", "TBLPROPERTIES"] { + let sql = format!( + "CREATE TABLE mydb.t1 (id INT) {clause} ('bucket' = '4', 'file.format' = 'parquet')" + ); + sql_context.sql(&sql).await.unwrap(); + let calls = catalog.take_calls(); + let [CatalogCall::CreateTable { schema, .. }] = calls.as_slice() else { + panic!("Expected a single create call for {sql}"); + }; + assert_eq!(schema.options(), &expected, "{clause}"); } } @@ -9580,82 +9247,51 @@ mod tests { } #[test] - fn test_extract_partition_by_rejects_typed_column() { - let err = extract_partition_by( - "CREATE TABLE t (dt STRING) PARTITIONED BY (dt STRING)", - true, - ) - .unwrap_err(); - assert!(err.to_string().contains("should not specify a type")); - } - - #[test] - fn test_extract_partition_by_empty_parens() { - let err = - extract_partition_by("CREATE TABLE t (id INT) PARTITIONED BY ()", true).unwrap_err(); - assert!(err.to_string().contains("at least one column")); - } - - #[test] - fn test_extract_partition_by_unmatched_paren() { - let err = - extract_partition_by("CREATE TABLE t (id INT) PARTITIONED BY (dt", true).unwrap_err(); - assert!(err.to_string().contains("Unmatched")); - } - - #[test] - fn test_extract_partition_by_skips_string_literal() { - let sql = - "CREATE TABLE t (id INT) WITH ('note' = 'PARTITIONED BY (x)') PARTITIONED BY (id)"; - let (rewritten, keys) = extract_partition_by(sql, true).unwrap(); - assert_eq!(keys, vec!["id"]); - assert!(rewritten.contains("WITH")); - assert!(rewritten.contains("'PARTITIONED BY (x)'")); - } - - #[test] - fn test_extract_partition_by_skips_line_comment() { - let sql = "CREATE TABLE t (id INT) -- PARTITIONED BY (x)\nPARTITIONED BY (id)"; - let (_, keys) = extract_partition_by(sql, true).unwrap(); - assert_eq!(keys, vec!["id"]); - } - - #[test] - fn test_extract_partition_by_double_quoted_identifier() { - let (_, keys) = extract_partition_by( - "CREATE TABLE t (\"order\" INT) PARTITIONED BY (\"order\")", - true, - ) - .unwrap(); - assert_eq!(keys, vec!["order"]); - } - - #[test] - fn test_extract_partition_by_double_quoted_identifier_with_escaped_quote_and_comma() { - let (_, keys) = extract_partition_by( - "CREATE TABLE t (\"a\"\"b,c\" INT, `d``e,f` INT) \ - PARTITIONED BY (\"a\"\"b,c\", `d``e,f`)", - true, - ) - .unwrap(); - assert_eq!(keys, vec!["a\"b,c", "d`e,f"]); + fn test_extract_partition_by_rejects_invalid_columns() { + for (columns, expected) in [ + ("(dt STRING)", "should not specify a type"), + ("()", "at least one column"), + ("(dt", "Unmatched '('"), + ("dt", "Expected '('"), + ] { + let sql = format!("CREATE TABLE t (dt STRING) PARTITIONED BY {columns}"); + let error = extract_partition_by(&sql, true).unwrap_err().to_string(); + assert!(error.contains(expected), "{sql}: {error}"); + } } #[test] - fn test_extract_partition_by_backtick_quoted_identifier() { - let (_, keys) = extract_partition_by( - "CREATE TABLE t (`order` INT) PARTITIONED BY (`order`)", - true, - ) - .unwrap(); - assert_eq!(keys, vec!["order"]); + fn test_extract_partition_by_ignores_literals_and_comments() { + for ignored in [ + "WITH ('note' = 'PARTITIONED BY (x)')", + "WITH ('note' = $$PARTITIONED BY (x)$$)", + "WITH ('note' = $tag$PARTITIONED BY (x)$tag$)", + "-- PARTITIONED BY (x)", + "/* PARTITIONED BY (x) */", + "/* outer /* inner */ PARTITIONED BY (x) */", + ] { + let prefix = format!("CREATE TABLE \"中文\" (id INT) {ignored}\n"); + let sql = format!("{prefix}PARTITIONED /* key */ BY (id)"); + let (rewritten, keys) = extract_partition_by(&sql, true).unwrap(); + assert_eq!(keys, ["id"], "{sql}"); + assert_eq!(rewritten, prefix, "{sql}"); + } } #[test] - fn test_extract_partition_by_no_paren_after_by() { - let err = - extract_partition_by("CREATE TABLE t (id INT) PARTITIONED BY dt", true).unwrap_err(); - assert!(err.to_string().contains("Expected '('")); + fn test_extract_partition_by_quoted_identifiers_and_comments() { + for (clause, expected) in [ + (r#"("order")"#, vec!["order"]), + ("(`order`)", vec!["order"]), + ( + "/* layout */ (\"a\"\"b,c\" /* ,) */, -- second key\n `d``e,f`)", + vec!["a\"b,c", "d`e,f"], + ), + ] { + let sql = format!("CREATE TABLE t PARTITIONED BY {clause} AS SELECT 1"); + let (_, keys) = extract_partition_by(&sql, true).unwrap(); + assert_eq!(keys, expected, "{clause}"); + } } #[test] @@ -9667,47 +9303,67 @@ mod tests { } #[test] - fn test_extract_partition_by_skips_block_comment() { - let sql = "CREATE TABLE t (id INT) /* PARTITIONED BY (x) */ PARTITIONED BY (id)"; - let (rewritten, keys) = extract_partition_by(sql, true).unwrap(); - assert_eq!(keys, vec!["id"]); - assert!(rewritten.contains("/* PARTITIONED BY (x) */")); - } - - #[test] - fn test_looks_like_create_table() { - assert!(looks_like_create_table("CREATE TABLE t (id INT)")); - assert!(looks_like_create_table(" create table t (id INT)")); - assert!(looks_like_create_table( + fn test_create_table_parser() { + for sql in [ + "CREATE TABLE t (id INT)", + " create table t (id INT)", "CREATE TABLE IF NOT EXISTS t (id INT)", - )); - assert!(looks_like_create_table( "/* note */ CREATE TABLE t (id INT)", - )); - assert!(looks_like_create_table( "-- comment\nCREATE TABLE t (id INT)", - )); - assert!(looks_like_create_table( "/* a */ /* b */ CREATE TABLE t (id INT)", - )); - assert!(!looks_like_create_table("ALTER TABLE t ADD COLUMN x INT")); - assert!(!looks_like_create_table("SELECT 1")); - assert!(!looks_like_create_table( + "CREATE /* note */ TABLE t AS SELECT 1", + "CREATE TEMP TABLE t AS SELECT 1", + "CREATE TEMPORARY TABLE t AS SELECT 1", + "CREATE OR REPLACE TABLE t AS SELECT * FROM s VERSION AS OF 1", + "CREATE OR ALTER TABLE t AS SELECT * FROM s VERSION AS OF 1", + "CREATE EXTERNAL TABLE t AS SELECT 1", + "CREATE GLOBAL TABLE t AS SELECT 1", + "CREATE TRANSIENT TABLE t AS SELECT 1", + "; CREATE TABLE t AS SELECT 1", + "/* start */ ; ; -- empty statements\n; CREATE TABLE t AS SELECT 1", + "; CREATE OR REPLACE TABLE t AS SELECT * FROM s VERSION AS OF 1", + ] { + assert!(create_table_parser(sql).is_some(), "{sql}"); + } + for sql in [ + "ALTER TABLE t ADD COLUMN x INT", + "SELECT 1", "SELECT aaaaaaaaaaaaaaaaaaaa中文 FROM t", - )); + "CREATE VIEW v AS SELECT 1", + "CREATE TEMP VIEW v AS SELECT 1", + "CREATE TABLE_SUFFIX t (id INT)", + "CREATE \"TABLE\" t (id INT)", + "; ; -- only empty statements\n;", + "; SELECT 1; CREATE TABLE t AS SELECT 1", + ] { + assert!(create_table_parser(sql).is_none(), "{sql}"); + } } // ==================== partition key validation tests ==================== #[tokio::test] - async fn test_create_table_partition_key_not_in_columns() { + async fn test_create_table_rejects_invalid_partition_clauses() { let catalog = Arc::new(MockCatalog::new()); - let sql_context = make_sql_context(catalog).await; - let err = sql_context - .sql("CREATE TABLE mydb.t (id INT, dt STRING) PARTITIONED BY (nonexistent)") - .await - .unwrap_err(); - assert!(err.to_string().contains("is not defined in the table")); + let sql_context = make_sql_context(catalog.clone()).await; + for (clause, expected_error) in [ + ( + "PARTITIONED BY (nonexistent)", + "is not defined in the table", + ), + ( + "PARTITIONED BY (id) PARTITIONED BY (dt STRING)", + "only one PARTITIONED BY clause", + ), + ] { + let sql = format!("CREATE TABLE mydb.t (id INT, dt STRING) {clause}"); + let Err(error) = sql_context.sql(&sql).await else { + panic!("Unexpectedly accepted {sql}"); + }; + let error = error.to_string(); + assert!(error.contains(expected_error), "{sql}: {error}"); + } + assert!(catalog.take_calls().is_empty()); } #[tokio::test] @@ -9715,7 +9371,7 @@ mod tests { let catalog = Arc::new(MockCatalog::new()); let sql_context = make_sql_context(catalog.clone()).await; sql_context - .sql("CREATE TABLE mydb.t (id INT, dt STRING) PARTITIONED BY (dt)") + .sql("CREATE TABLE mydb.as (id INT, dt STRING) PARTITIONED BY (dt)") .await .unwrap(); let calls = catalog.take_calls(); @@ -10718,212 +10374,81 @@ mod tests { } #[test] - fn test_extract_version_as_of() { - let sql = "SELECT id, name FROM paimon.default.time_travel_table VERSION AS OF 1"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.version, "1"); - assert_eq!(info.table_name, "paimon.default.time_travel_table"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT id, name FROM __uuid"); - } - - #[test] - fn test_extract_version_as_of_multi_digit() { - let sql = "SELECT * FROM mydb.t VERSION AS OF 42"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.version, "42"); - assert_eq!(info.table_name, "mydb.t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT * FROM __uuid"); - } - - #[test] - fn test_extract_version_as_of_case_insensitive() { - let sql = "SELECT * FROM t version as of 5"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.version, "5"); - assert_eq!(info.table_name, "t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT * FROM __uuid"); - } - - #[test] - fn test_extract_version_as_of_not_present() { - let sql = "SELECT * FROM t"; - assert!(extract_all_version_as_of(sql).is_empty()); - } - - #[test] - fn test_extract_version_as_of_tag() { - let sql = "SELECT id, name FROM paimon.default.t VERSION AS OF 'snapshot1'"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.version, "snapshot1"); - assert_eq!(info.table_name, "paimon.default.t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT id, name FROM __uuid"); - } - - #[test] - fn test_extract_version_as_of_tag_case_insensitive() { - let sql = "SELECT * FROM t version as of 'my_tag'"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.version, "my_tag"); - assert_eq!(info.table_name, "t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT * FROM __uuid"); - } - - #[test] - fn test_extract_version_as_of_numeric_still_works() { - let sql = "SELECT * FROM t VERSION AS OF 123"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 1); - assert_eq!(infos[0].version, "123"); - assert_eq!(infos[0].table_name, "t"); - } - - #[test] - fn test_extract_version_as_of_multiple() { - // JOIN two time-travel tables - let sql = "SELECT * FROM t1 VERSION AS OF 1 JOIN t2 VERSION AS OF 2 ON t1.id = t2.id"; - let infos = extract_all_version_as_of(sql); - assert_eq!(infos.len(), 2); - assert_eq!(infos[0].version, "1"); - assert_eq!(infos[0].table_name, "t1"); - assert_eq!(infos[1].version, "2"); - assert_eq!(infos[1].table_name, "t2"); - } - - #[test] - fn test_extract_version_as_of_skips_string_literal() { - let sql = "SELECT * FROM t WHERE note = 'version as of 1'"; - let infos = extract_all_version_as_of(sql); - assert!(infos.is_empty()); - } - - #[test] - fn test_extract_version_as_of_skips_comment() { - let sql = "SELECT * FROM t -- version as of 1\n WHERE id > 0"; - let infos = extract_all_version_as_of(sql); - assert!(infos.is_empty()); + fn test_mask_time_travel_sources() { + use TimeTravelClause::{Timestamp, Version}; + + for (selector, expected) in [ + ("VERSION AS OF 1", Version("1".into())), + ("version as of 123", Version("123".into())), + ("VERSION AS OF 'my_tag'", Version("my_tag".into())), + ("VERSION AS OF 'tag''quoted'", Version("tag'quoted".into())), + ( + "/* table */ VERSION\nAS /* selector */ OF 42", + Version("42".into()), + ), + ( + "timestamp as of '2024-01-15 10:30:00'", + Timestamp("2024-01-15 10:30:00".into()), + ), + ( + "/* table */ TIMESTAMP\nAS /* selector */ OF '2024-01-15'", + Timestamp("2024-01-15".into()), + ), + ] { + let mut sql = format!( + r#"SELECT 'İ' FROM paimon."my db"."with ""quote"", (space" {selector} AS s"# + ); + let sources = mask_time_travel_sources(&mut sql); + assert_eq!(sources.len(), 1, "{selector}"); + assert_eq!(sources[0].clause, expected); + assert_eq!( + sources[0].table.to_string(), + r#"paimon."my db"."with ""quote"", (space""# + ); + assert_eq!( + sql, + format!("SELECT 'İ' FROM TABLE({}) AS s", sources[0].binding) + ); + } } #[test] - fn test_time_travel_keeps_quoted_table_reference() { - let table = r#"paimon."my db"."with ""quote"", (space""#; - let version_sql = format!("SELECT 'İ' FROM {table} VERSION AS OF 1"); - let versions = extract_all_version_as_of(&version_sql); - assert_eq!(versions.len(), 1); - assert_eq!(versions[0].table_name, table); - assert_eq!( - &version_sql[versions[0].clause_range.0..versions[0].clause_range.1], - format!("{table} VERSION AS OF 1") - ); - - let timestamp_sql = format!("SELECT 'İ' FROM {table} TIMESTAMP AS OF '2024-01-01'"); - let timestamps = extract_all_timestamp_as_of(×tamp_sql); - assert_eq!(timestamps.len(), 1); - assert_eq!(timestamps[0].table_name, table); + fn test_mask_multiple_time_travel_sources() { + let mut sql = + "SELECT * FROM t1 VERSION AS OF 1 JOIN t2 VERSION AS OF 2 ON t1.id = t2.id".to_string(); + let sources = mask_time_travel_sources(&mut sql); + assert_eq!(sources.len(), 2); + assert_eq!(sources[0].table.to_string(), "t1"); + assert_eq!(sources[0].clause, TimeTravelClause::Version("1".into())); + assert_eq!(sources[1].table.to_string(), "t2"); + assert_eq!(sources[1].clause, TimeTravelClause::Version("2".into())); assert_eq!( - ×tamp_sql[timestamps[0].clause_range.0..timestamps[0].clause_range.1], - format!("{table} TIMESTAMP AS OF '2024-01-01'") - ); - } - - #[test] - fn test_contains_time_travel_keyword() { - assert!(contains_time_travel_keyword( - "SELECT * FROM t VERSION AS OF 1" - )); - assert!(contains_time_travel_keyword( - "SELECT * FROM t TIMESTAMP AS OF '2024-01-01 00:00:00'" - )); - // Inside string literal — should NOT match - assert!(!contains_time_travel_keyword( - "SELECT * FROM t WHERE note = 'version as of 1'" - )); - // Inside comment — should NOT match - assert!(!contains_time_travel_keyword( - "SELECT * FROM t -- version as of 1" - )); - assert!(!contains_time_travel_keyword( - "SELECT * FROM t /* timestamp as of now */ WHERE id > 0" - )); - assert!(!contains_time_travel_keyword( - r#"SELECT * FROM "version as of 1""# - )); - assert!(!contains_time_travel_keyword( - "SELECT * FROM `timestamp as of now`" - )); - // No keyword at all - assert!(!contains_time_travel_keyword("SELECT * FROM t")); - } - - #[test] - fn test_extract_timestamp_as_of() { - let sql = "SELECT * FROM paimon.default.t TIMESTAMP AS OF '2024-01-15 10:30:00'"; - let infos = extract_all_timestamp_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.timestamp, "2024-01-15 10:30:00"); - assert_eq!(info.table_name, "paimon.default.t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] - ); - assert_eq!(rewritten, "SELECT * FROM __uuid"); - } - - #[test] - fn test_extract_timestamp_as_of_case_insensitive() { - let sql = "SELECT * FROM t timestamp as of '2024-06-01 00:00:00'"; - let infos = extract_all_timestamp_as_of(sql); - assert_eq!(infos.len(), 1); - let info = &infos[0]; - assert_eq!(info.timestamp, "2024-06-01 00:00:00"); - assert_eq!(info.table_name, "t"); - let rewritten = format!( - "{}__uuid{}", - &sql[..info.clause_range.0], - &sql[info.clause_range.1..] + sql, + format!( + "SELECT * FROM TABLE({}) JOIN TABLE({}) ON t1.id = t2.id", + sources[0].binding, sources[1].binding + ) ); - assert_eq!(rewritten, "SELECT * FROM __uuid"); } #[test] - fn test_extract_timestamp_as_of_not_present() { - let sql = "SELECT * FROM t"; - assert!(extract_all_timestamp_as_of(sql).is_empty()); + fn test_time_travel_ignores_literals_comments_and_aliases() { + for sql in [ + "SELECT * FROM t", + "SELECT * FROM t WHERE note = 'version as of 1'", + "SELECT $$source VERSION AS OF 1$$ FROM t", + "SELECT $tag$source TIMESTAMP AS OF '2024-01-01'$tag$ FROM t", + "SELECT * FROM t -- version as of 1", + "SELECT * FROM t /* timestamp as of now */ WHERE id > 0", + "SELECT * FROM t /* outer /* inner */ source VERSION AS OF 1 */", + r#"SELECT * FROM "version as of 1""#, + "SELECT * FROM `timestamp as of now`", + "SELECT conversion AS of_value FROM t", + "SELECT version AS of FROM t", + ] { + let mut masked = sql.to_string(); + assert!(mask_time_travel_sources(&mut masked).is_empty(), "{sql}"); + assert_eq!(masked, sql); + } } } diff --git a/crates/integrations/datafusion/src/sql_context/ctas.rs b/crates/integrations/datafusion/src/sql_context/ctas.rs new file mode 100644 index 000000000..4cd450083 --- /dev/null +++ b/crates/integrations/datafusion/src/sql_context/ctas.rs @@ -0,0 +1,347 @@ +// 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::ops::ControlFlow; +use std::sync::Arc; + +use datafusion::arrow::datatypes::SchemaRef; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::error::{DataFusionError, Result as DFResult}; +use datafusion::execution::context::SQLOptions; +use datafusion::execution::session_state::SessionState; +use datafusion::execution::TaskContext; +use datafusion::logical_expr::{Expr, LogicalPlan}; +use datafusion::physical_plan::{execute_stream, ExecutionPlan}; +use datafusion::prelude::DataFrame; +use datafusion::sql::planner::object_name_to_table_reference; +use datafusion::sql::sqlparser::ast::helpers::stmt_create_table::CreateTableBuilder; +use datafusion::sql::sqlparser::ast::{ + CreateTable, CreateTableOptions, Query, Select, SqlOption, Statement, Visit, Visitor, +}; +use futures::StreamExt; +use paimon::spec::{CoreOptions, DataType as PaimonDataType, TableType}; +use paimon::table::Table; + +use super::{ + create_table_schema, extract_table_properties, ok_result, SQLContext, TimeTravelSource, +}; +use crate::error::to_datafusion_error; +use crate::physical_plan::cast_batch_to_schema; + +impl SQLContext { + pub(super) async fn handle_create_table_as( + &self, + ct: &CreateTable, + query: Box, + partition_keys: Vec, + state: SessionState, + options: SQLOptions, + time_travel_sources: &[TimeTravelSource], + ) -> DFResult { + validate_create_table_as(ct, &query)?; + Self::ensure_main_branch_base_table(&ct.name, "CREATE TABLE AS SELECT")?; + let enable_ident_normalization = + state.config_options().sql_parser.enable_ident_normalization; + let target = object_name_to_table_reference(ct.name.clone(), enable_ident_normalization)?; + let (catalog, catalog_name, identifier) = + self.resolve_table_reference(&target, &state.config_options().catalog)?; + + match catalog.check_table_exists(&identifier).await { + Ok(()) if ct.if_not_exists => return ok_result(&self.ctx), + Ok(()) => { + return Err(to_datafusion_error(paimon::Error::TableAlreadyExist { + full_name: identifier.full_name(), + })); + } + Err(paimon::Error::TableNotExist { .. }) => {} + Err(error) => return Err(to_datafusion_error(error)), + } + + let table_options = extract_table_properties(&ct.table_options)?; + let table_type = CoreOptions::new(&table_options) + .table_type() + .map_err(to_datafusion_error)?; + if table_type != TableType::Table { + return Err(DataFusionError::NotImplemented(format!( + "CREATE TABLE AS SELECT only supports native Paimon tables, got '{table_type}'" + ))); + } + + let df = + Box::pin(self.plan_query(state, Statement::Query(query), options, time_travel_sources)) + .await?; + let (state, source) = df.into_parts(); + let task_ctx = state.task_ctx(); + // Optimization can narrow nullability beyond the query's declared schema. + let analyzed = + state + .analyzer() + .execute_and_check(source, state.config_options(), |_, _| {})?; + validate_lateral_correlations(&analyzed)?; + let schema = create_table_schema( + ct, + partition_keys, + enable_ident_normalization, + Some(analyzed.schema().as_arrow()), + table_options, + )?; + if schema.fields().is_empty() { + return Err(DataFusionError::Plan( + "CREATE TABLE AS SELECT requires at least one output column".into(), + )); + } + for field in schema.fields() { + validate_time_precision(field.data_type())?; + } + let write_schema = paimon::arrow::build_target_arrow_schema(schema.fields()) + .map_err(to_datafusion_error)?; + let optimized = state.optimizer().optimize(analyzed, &state, |_, _| {})?; + let plan = state + .query_planner() + .create_physical_plan(&optimized, &state) + .await?; + if !has_bounded_output(plan.as_ref()) { + return Err(DataFusionError::NotImplemented( + "CREATE TABLE AS SELECT requires a bounded query".into(), + )); + } + + match catalog.create_table_exclusive(&identifier, schema).await { + Ok(()) => {} + Err(paimon::Error::TableAlreadyExist { .. }) if ct.if_not_exists => { + return ok_result(&self.ctx); + } + Err(error) => return Err(to_datafusion_error(error)), + } + let name = format!("{catalog_name}.{}", identifier.full_name()); + let table = catalog.get_table(&identifier).await.map_err(|error| { + DataFusionError::Context( + format!("Failed to load newly created table '{name}' for CREATE TABLE AS SELECT"), + Box::new(to_datafusion_error(error)), + ) + })?; + let (mut response, outcome) = tokio::sync::oneshot::channel(); + // Keep the writer alive to clean up or finish an in-flight commit after cancellation. + tokio::spawn(async move { + let result = populate_table(table, plan, task_ctx, write_schema, &mut response) + .await + .map_err(|error| { + DataFusionError::Context( + format!( + "CREATE TABLE AS SELECT failed for '{name}'. \ + Inspect the target table before retrying." + ), + Box::new(error), + ) + }); + if let Err(Err(error)) = response.send(result) { + log::warn!("Cancelled CREATE TABLE AS SELECT for '{name}': {error}"); + } + }); + outcome.await.map_err(|error| { + DataFusionError::Execution(format!("CREATE TABLE AS SELECT worker stopped: {error}")) + })??; + ok_result(&self.ctx) + } +} + +fn validate_lateral_correlations(plan: &LogicalPlan) -> DFResult<()> { + // DataFusion can turn a reference to an enclosing query into a local + // column when it decorrelates an inner LATERAL join. + plan.apply_with_subqueries(|outer| { + outer.apply_subqueries(|query| { + let enclosing_inputs = outer.inputs(); + query.apply_with_subqueries(|node| { + let LogicalPlan::Join(join) = node else { + return Ok(TreeNodeRecursion::Continue); + }; + let right = match join.right.as_ref() { + LogicalPlan::SubqueryAlias(alias) => alias.input.as_ref(), + right => right, + }; + let LogicalPlan::Subquery(lateral) = right else { + return Ok(TreeNodeRecursion::Continue); + }; + let columns = lateral.outer_ref_columns.iter().filter_map(|expr| match expr { + Expr::OuterReferenceColumn(_, column) => Some(column), + _ => None, + }); + for column in columns { + if !join.left.schema().has_column(column) + && enclosing_inputs + .iter() + .any(|input| input.schema().has_column(column)) + { + return Err(DataFusionError::NotImplemented(format!( + "CREATE TABLE AS SELECT cannot materialize a LATERAL source referencing enclosing query column '{column}'" + ))); + } + } + Ok(TreeNodeRecursion::Continue) + }) + }) + })?; + Ok(()) +} + +fn has_bounded_output(plan: &dyn ExecutionPlan) -> bool { + if !plan.properties().boundedness.is_unbounded() || plan.fetch().is_some() { + return true; + } + + // A pushed-down LIMIT can leave the scan and its ancestors marked unbounded. + let inputs = plan.children(); + inputs + .iter() + .any(|input| input.properties().boundedness.is_unbounded()) + && inputs + .into_iter() + .all(|input| has_bounded_output(input.as_ref())) +} + +async fn populate_table( + table: Table, + plan: Arc, + task_ctx: Arc, + write_schema: SchemaRef, + response: &mut tokio::sync::oneshot::Sender>, +) -> DFResult<()> { + let resources = crate::memory::writer_resources(&task_ctx).map_err(to_datafusion_error)?; + let builder = table.new_write_builder().with_resources(resources); + let commit = builder.try_new_commit().map_err(to_datafusion_error)?; + let mut writer = builder.new_write().map_err(to_datafusion_error)?; + let prepared = async { + let mut input = execute_stream(plan, task_ctx)?; + loop { + let next = tokio::select! { + biased; + _ = response.closed() => return Ok(None), + batch = input.next() => batch, + }; + let Some(batch) = next else { + break; + }; + let batch = cast_batch_to_schema(batch?, &write_schema)?; + writer + .write_arrow_batch(&batch) + .await + .map_err(to_datafusion_error)?; + } + writer + .prepare_commit() + .await + .map(Some) + .map_err(to_datafusion_error) + } + .await; + writer.close().await; + let messages = prepared.map_err(|error| { + DataFusionError::Context("no commit was attempted".into(), Box::new(error)) + })?; + let Some(messages) = messages else { + return Ok(()); + }; + if response.is_closed() { + commit.abort(&messages).await.map_err(to_datafusion_error)?; + return Ok(()); + } + // A lost response can follow successful publication, so keep the files on commit errors. + Box::pin(commit.commit(messages)).await.map_err(|error| { + DataFusionError::Context( + "publication may have succeeded".into(), + Box::new(to_datafusion_error(error)), + ) + }) +} + +fn validate_time_precision(data_type: &PaimonDataType) -> DFResult<()> { + match data_type { + PaimonDataType::Time(time) if time.precision() > 3 => { + Err(DataFusionError::NotImplemented(format!( + "CREATE TABLE AS SELECT cannot preserve TIME({}); Paimon stores TIME with millisecond precision", + time.precision() + ))) + } + PaimonDataType::Array(array) => validate_time_precision(array.element_type()), + PaimonDataType::Vector(vector) => validate_time_precision(vector.element_type()), + PaimonDataType::Multiset(multiset) => validate_time_precision(multiset.element_type()), + PaimonDataType::Map(map) => { + validate_time_precision(map.key_type())?; + validate_time_precision(map.value_type()) + } + PaimonDataType::Row(row) => row + .fields() + .iter() + .try_for_each(|field| validate_time_precision(field.data_type())), + _ => Ok(()), + } +} + +fn validate_create_table_as(ct: &CreateTable, query: &Query) -> DFResult<()> { + struct ReadOnlyQuery; + impl Visitor for ReadOnlyQuery { + type Break = (); + + fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<()> { + if matches!(statement, Statement::Query(_)) { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(()) + } + } + + fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<()> { + if select.into.is_some() { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + } + } + if let ControlFlow::Break(()) = query.visit(&mut ReadOnlyQuery) { + return Err(DataFusionError::NotImplemented( + "CREATE TABLE AS SELECT requires a read-only query".into(), + )); + } + if !ct.columns.is_empty() { + return Err(DataFusionError::NotImplemented( + "CREATE TABLE AS SELECT with explicit column declarations is not supported".into(), + )); + } + if let CreateTableOptions::Plain(options) = &ct.table_options { + if let Some(option) = options + .iter() + .find(|option| !matches!(option, SqlOption::Comment(_))) + { + return Err(DataFusionError::NotImplemented(format!( + "Unsupported CREATE TABLE AS SELECT option: {option}" + ))); + } + } + // Reject unhandled AST fields, including modifiers added by parser upgrades. + let mut supported = CreateTableBuilder::new(ct.name.clone()) + .if_not_exists(ct.if_not_exists) + .table_options(ct.table_options.clone()) + .build(); + supported.comment = ct.comment.clone(); + if ct != &supported { + return Err(DataFusionError::NotImplemented( + "Unsupported CREATE TABLE AS SELECT modifiers; only IF NOT EXISTS, PARTITIONED BY, table options and COMMENT are supported".into(), + )); + } + Ok(()) +} diff --git a/crates/integrations/datafusion/tests/create_table_as.rs b/crates/integrations/datafusion/tests/create_table_as.rs new file mode 100644 index 000000000..17b0e0016 --- /dev/null +++ b/crates/integrations/datafusion/tests/create_table_as.rs @@ -0,0 +1,1011 @@ +// 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. + +mod common; +#[path = "create_table_as/execution.rs"] +mod execution; +#[path = "../../../paimon/tests/mock_server.rs"] +mod mock_server; + +use std::collections::HashMap; +use std::sync::Arc; + +use arrow_array::{Array, Int32Array, Int64Array, RecordBatch}; +use arrow_schema::{DataType as ArrowType, Field, Schema as ArrowSchema}; +use common::{assert_sql_error, create_sql_context, create_test_env, exec, row_count}; +use datafusion::datasource::MemTable; +use paimon::catalog::{Catalog, Identifier, RESTCatalog}; +use paimon::spec::{BigIntType, DataType, IntType, Schema, TableType}; +use paimon::{CatalogOptions, Options}; +use paimon_datafusion::SQLContext; + +async fn query_ids(ctx: &SQLContext, sql: &str) -> Vec { + let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap(); + let mut ids = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + }) + .map(Option::unwrap) + .collect::>(); + ids.sort_unstable(); + ids +} + +#[tokio::test] +async fn inferred_schema_options_partitioning_and_persistence() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + let source = Arc::new(ArrowSchema::new(vec![ + Field::new("id", ArrowType::Int32, false), + Field::new("part", ArrowType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + source.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(arrow_array::StringArray::from(vec![ + Some("a"), + None, + Some("b"), + ])), + ], + ) + .unwrap(); + let partitions = vec![vec![batch.slice(0, 2)], vec![batch.slice(2, 1)]]; + ctx.register_temp_table( + "source", + Arc::new(MemTable::try_new(source, partitions).unwrap()), + ) + .unwrap(); + exec( + &ctx, + "/* start */ ; ; -- empty statements + ; CREATE TABLE result PARTITIONED BY (part) + WITH ('bucket' = '-1', 'file.format' = 'parquet', 'partition.default-name' = 'it''s null') + AS SELECT id + 10 AS id, part FROM source WHERE id > 1", + ) + .await; + let table = catalog + .get_table(&Identifier::new("default", "result")) + .await + .unwrap(); + let schema = table.schema(); + assert_eq!( + schema.fields()[0].data_type(), + &DataType::BigInt(BigIntType::with_nullable(false)) + ); + assert!(schema.fields()[1].data_type().is_nullable()); + assert_eq!(schema.partition_keys(), &["part"]); + assert_eq!( + schema.options(), + &HashMap::from([ + ("bucket".into(), "-1".into()), + ("file.format".into(), "parquet".into()), + ("partition.default-name".into(), "it's null".into()), + ]), + "CTAS must preserve the supplied options without adding internal metadata" + ); + let definitions = ctx + .sql("SHOW CREATE TABLE result") + .await + .unwrap() + .collect() + .await + .unwrap(); + let definition = definitions[0] + .column(3) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + exec(&ctx, &definition.replace("\"result\"", "\"result_copy\"")).await; + exec( + &ctx, + "CREATE TABLE non_null AS WITH selected AS (SELECT part FROM source) SELECT part FROM selected WHERE part IS NOT NULL", + ) + .await; + let non_null = catalog + .get_table(&Identifier::new("default", "non_null")) + .await + .unwrap(); + assert!(non_null.schema().fields()[0].data_type().is_nullable()); + assert_eq!(row_count(&ctx, "SELECT * FROM non_null").await, 2); + exec( + &ctx, + "CREATE TABLE keyed + TBLPROPERTIES ('bucket' = '2', 'partition' = 'part', 'primary-key' = 'part,id') + AS SELECT CAST(id AS BIGINT) AS id, part FROM source WHERE part IS NOT NULL", + ) + .await; + let keyed = catalog + .get_table(&Identifier::new("default", "keyed")) + .await + .unwrap(); + assert_eq!(keyed.schema().partition_keys(), &["part"]); + assert_eq!(keyed.schema().primary_keys(), &["part", "id"]); + let fresh = create_sql_context(catalog).await; + assert_eq!(query_ids(&fresh, "SELECT id FROM keyed").await, [1, 3]); + let rows = fresh + .sql("SELECT id, part FROM result ORDER BY id") + .await + .unwrap() + .collect() + .await + .unwrap(); + datafusion::assert_batches_eq!( + [ + "+----+------+", + "| id | part |", + "+----+------+", + "| 12 | |", + "| 13 | b |", + "+----+------+" + ], + &rows + ); +} + +#[tokio::test] +async fn empty_results_preserve_schema_and_partitioning() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + exec( + &ctx, + "CREATE TABLE IF NOT EXISTS paimon.default.as PARTITIONED BY (id) COMMENT 'query result' + AS SELECT CAST(NULL AS INT) AS id, CAST(1.25 AS DECIMAL(8, 2)) AS amount WHERE false", + ) + .await; + let schema = catalog + .get_table(&Identifier::new("default", "as")) + .await + .unwrap() + .schema() + .clone(); + assert_eq!(schema.fields().len(), 2); + assert_eq!(schema.partition_keys(), &["id"]); + assert_eq!(schema.comment(), Some("query result")); + assert_eq!(schema.fields()[0].name(), "id"); + assert_eq!( + schema.fields()[0].data_type(), + &DataType::Int(IntType::new()) + ); + assert_eq!(schema.fields()[1].name(), "amount"); + let DataType::Decimal(amount) = schema.fields()[1].data_type() else { + panic!("expected a decimal output"); + }; + assert_eq!((amount.precision(), amount.scale()), (8, 2)); + assert_eq!(row_count(&ctx, "SELECT * FROM paimon.default.as").await, 0); +} + +#[tokio::test] +async fn time_precision_loss_is_rejected_before_table_creation() { + use arrow_array::types::Int32Type; + use arrow_array::{DictionaryArray, Time64MicrosecondArray, Time64NanosecondArray}; + + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + let nanos = Arc::new(Time64NanosecondArray::from(vec![ + Some(45_296_123_456_789), + None, + ])); + let columns: Vec = vec![ + Arc::new(Time64MicrosecondArray::from(vec![ + Some(45_296_123_456), + None, + ])), + nanos.clone(), + Arc::new( + DictionaryArray::::try_new(Int32Array::from(vec![Some(0), None]), nanos) + .unwrap(), + ), + ]; + let schema = Arc::new(ArrowSchema::new( + ["micros", "nanos", "encoded"] + .into_iter() + .zip(&columns) + .map(|(name, column)| Field::new(name, column.data_type().clone(), true)) + .collect::>(), + )); + let batch = RecordBatch::try_new(schema.clone(), columns).unwrap(); + ctx.register_temp_table( + "time_source", + Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()), + ) + .unwrap(); + for (index, (query, precision)) in [ + ("SELECT CAST('12:34:56.123456789' AS TIME) AS value", 9), + ("SELECT micros FROM time_source", 6), + ("SELECT nanos FROM time_source", 9), + ("SELECT encoded FROM time_source", 9), + ( + "SELECT named_struct('value', nanos) AS value FROM time_source", + 9, + ), + ("SELECT ARRAY[micros] AS value FROM time_source", 6), + ( + "SELECT MAP(ARRAY[1], ARRAY[nanos]) AS value FROM time_source", + 9, + ), + ( + "SELECT MAP(ARRAY[micros], ARRAY[1]) AS value FROM time_source", + 6, + ), + ( + "SELECT named_struct('values', ARRAY[encoded]) AS value FROM time_source", + 9, + ), + ("SELECT nanos FROM time_source WHERE false", 9), + ] + .iter() + .enumerate() + { + let target = format!("rejected_time_{index}"); + assert_sql_error( + &ctx, + &format!("CREATE TABLE {target} AS {query}"), + &format!("cannot preserve TIME({precision})"), + ) + .await; + assert!( + matches!( + catalog + .get_table(&Identifier::new("default", &target)) + .await, + Err(paimon::Error::TableNotExist { .. }) + ), + "{query}" + ); + } +} + +#[tokio::test] +async fn supported_time_outputs_preserve_values_and_nulls() { + use arrow_array::{Time32MillisecondArray, Time32SecondArray}; + + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + let columns: Vec = vec![ + Arc::new(Time32SecondArray::from(vec![Some(45_296), None])), + Arc::new(Time32MillisecondArray::from(vec![Some(45_296_123), None])), + ]; + let schema = Arc::new(ArrowSchema::new( + ["seconds", "millis"] + .into_iter() + .zip(&columns) + .map(|(name, column)| Field::new(name, column.data_type().clone(), true)) + .collect::>(), + )); + let batch = RecordBatch::try_new(schema.clone(), columns).unwrap(); + ctx.register_temp_table( + "time_source", + Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()), + ) + .unwrap(); + exec(&ctx, "CREATE TABLE supported_times AS SELECT seconds, millis, named_struct('value', millis) AS nested, ARRAY[seconds] AS items FROM time_source").await; + exec(&ctx, "CREATE TABLE time_text AS SELECT CAST(CAST('12:34:56.123456789' AS TIME) AS VARCHAR) AS value").await; + let fresh = create_sql_context(catalog).await; + let rows = fresh.sql("SELECT seconds, millis, nested.value, items[1] FROM supported_times ORDER BY seconds NULLS LAST") + .await.unwrap().collect().await.unwrap(); + for (index, expected) in [45_296_000, 45_296_123, 45_296_123, 45_296_000] + .into_iter() + .enumerate() + { + let values = rows + .iter() + .flat_map(|batch| { + batch + .column(index) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + }) + .collect::>(); + assert_eq!(values, vec![Some(expected), None]); + } + let rows = fresh + .sql("SELECT value FROM time_text") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + common::string_value(rows[0].column(0).as_ref(), 0), + "12:34:56.123456789" + ); +} + +#[tokio::test] +async fn quoted_names_and_cross_catalog_target_keep_the_session_source() { + let (_src, source) = create_test_env(); + let (_dst, destination) = create_test_env(); + let mut ctx = create_sql_context(source).await; + ctx.register_catalog("Other", destination.clone()) + .await + .unwrap(); + exec(&ctx, "CREATE DATABASE paimon.current_db").await; + exec(&ctx, "CREATE DATABASE \"Other\".\"TargetDb\"").await; + exec(&ctx, "USE paimon.current_db").await; + exec( + &ctx, + "CREATE TABLE \"Source.Table\" AS SELECT 7 AS \"Mixed.Id\"", + ) + .await; + exec( + &ctx, + "CREATE TABLE \"Other\".\"TargetDb\".\"Source.Table\" AS SELECT 99 AS \"Mixed.Id\"", + ) + .await; + exec( + &ctx, + r#"CREATE TABLE "Other"."TargetDb"."Result.Table" PARTITIONED BY ("Mixed.Id") + AS SELECT "Mixed.Id" FROM "Source.Table""#, + ) + .await; + assert_eq!( + query_ids( + &ctx, + r#"SELECT "Mixed.Id" FROM "Other"."TargetDb"."Result.Table""# + ) + .await, + [7] + ); + let result = destination + .get_table(&Identifier::new("TargetDb", "Result.Table")) + .await + .unwrap(); + assert_eq!(result.schema().partition_keys(), &["Mixed.Id"]); + exec( + &ctx, + r#"CREATE TABLE "PARTITIONED BY (id)" AS SELECT 2 AS version"#, + ) + .await; + exec( + &ctx, + r#"CREATE TABLE UPPER_TARGET AS SELECT version AS OF, $$PARTITIONED BY (id)$$ AS value + FROM "PARTITIONED BY (id)""#, + ) + .await; + assert_eq!( + row_count( + &ctx, + "SELECT * FROM upper_target WHERE of = 2 AND value = 'PARTITIONED BY (id)'" + ) + .await, + 1 + ); + exec( + &ctx, + "SET datafusion.sql_parser.enable_ident_normalization = false", + ) + .await; + exec( + &ctx, + "CREATE TABLE Other.TargetDb.CaseTarget PARTITIONED BY (Part) AS SELECT 8 AS Part", + ) + .await; + let table = destination + .get_table(&Identifier::new("TargetDb", "CaseTarget")) + .await + .unwrap(); + assert_eq!(table.schema().partition_keys(), &["Part"]); + assert_eq!( + row_count( + &ctx, + "SELECT Part FROM Other.TargetDb.CaseTarget WHERE Part = 8" + ) + .await, + 1 + ); + for (index, selector) in ["VERSION AS OF 1", "TIMESTAMP AS OF '2099-01-01 00:00:00'"] + .iter() + .enumerate() + { + exec( + &ctx, + &format!("CREATE TABLE Other.TargetDb.History{index} AS SELECT Part FROM Other.TargetDb.CaseTarget {selector}"), + ) + .await; + assert_eq!( + row_count( + &ctx, + &format!("SELECT Part FROM Other.TargetDb.History{index} WHERE Part = 8") + ) + .await, + 1 + ); + } +} + +#[tokio::test] +async fn time_travel_source_is_materialized_as_a_persistent_table() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + exec(&ctx, "CREATE TABLE \"源表.db.rel.data\" AS SELECT 1 AS id").await; + catalog + .create_tag( + &Identifier::new("default", "源表.db.rel.data"), + "base", + Some(1), + false, + ) + .await + .unwrap(); + exec(&ctx, "INSERT INTO \"源表.db.rel.data\" VALUES (2)").await; + let fresh = create_sql_context(catalog.clone()).await; + for (table, selector, expected) in [ + ("historical", "VERSION AS OF 1", vec![1]), + ("tagged", "VERSION AS OF 'base'", vec![1]), + ( + "at_timestamp", + "TIMESTAMP AS OF '2099-01-01 00:00:00'", + vec![1, 2], + ), + ] { + exec( + &ctx, + &format!("; CREATE TABLE {table} PARTITIONED BY (id) AS SELECT \"源表.db.rel.data\".id FROM \"源表.db.rel.data\" {selector}"), + ) + .await; + let target = catalog + .get_table(&Identifier::new("default", table)) + .await + .unwrap(); + assert_eq!(target.schema().partition_keys(), &["id"]); + assert_eq!( + query_ids(&fresh, &format!("SELECT * FROM {table}")).await, + expected + ); + } + assert_eq!( + row_count(&fresh, "SELECT * FROM \"源表.db.rel.data\"").await, + 2 + ); + exec( + &ctx, + r#"CREATE TABLE joined AS + SELECT s1.id, $tag$source VERSION AS OF 99$tag$ AS note + FROM"源表.db.rel.data" VERSION AS /* tag */ OF 'base' AS s1 + JOIN "源表.db.rel.data" TIMESTAMP AS OF '2099-01-01 00:00:00' AS s2 ON s1.id = s2.id"#, + ) + .await; + assert_eq!( + query_ids( + &fresh, + "SELECT id FROM joined WHERE note = 'source VERSION AS OF 99'" + ) + .await, + [1] + ); + exec( + &ctx, + r#"CREATE TABLE live_join AS + SELECT "源表.db.rel.data".id + FROM "源表.db.rel.data" VERSION AS OF 1 + CROSS JOIN paimon.default."源表.db.rel.data" + WHERE "源表.db.rel.data".id = 2"#, + ) + .await; + assert_eq!(query_ids(&fresh, "SELECT id FROM live_join").await, [2]); + let query = "AS SELECT id FROM 源表.db.rel.data VERSION AS OF 1"; + assert_sql_error( + &ctx, + &format!("CREATE TABLE invalid_name {query}"), + "Expected 1, 2 or 3 parts, got 4", + ) + .await; + assert!(matches!( + catalog + .get_table(&Identifier::new("default", "invalid_name")) + .await, + Err(paimon::Error::TableNotExist { .. }) + )); + exec( + &ctx, + &format!("CREATE TABLE IF NOT EXISTS historical {query}"), + ) + .await; + exec(&ctx, "CREATE DATABASE db2").await; + exec(&ctx, "CREATE TABLE db2.src AS SELECT 10 AS id").await; + exec(&ctx, "CREATE TABLE src AS SELECT 12 AS id").await; + for (table, query) in [ + ("current_join", "SELECT paimon.default.src.id AS a, db2.src.id AS b FROM paimon.default.src CROSS JOIN db2.src"), + ("historical_join", "SELECT paimon.default.src.id AS a, db2.src.id AS b FROM paimon.default.src VERSION AS OF 1 CROSS JOIN db2.src VERSION AS OF 1"), + ("qualified_history", "SELECT src.id AS a, paimon.db2.src.id AS b FROM db2.src VERSION AS OF 1 CROSS JOIN src"), + ("aliased_join", "SELECT a.id AS a, b.id AS b FROM paimon.default.src VERSION AS OF 1 AS a CROSS JOIN db2.src VERSION AS OF 1 AS b"), + ] { + exec(&ctx, &format!("CREATE TABLE {table} AS {query}")).await; + assert_eq!( + row_count(&fresh, &format!("SELECT * FROM {table} WHERE a = 12 AND b = 10")).await, + 1, + "{table} from {query}" + ); + } + exec( + &ctx, + "CREATE TABLE totals AS SELECT paimon.default.src.id + src.id + FROM paimon.default.src VERSION AS OF 1 CROSS JOIN db2.src VERSION AS OF 1 AS src", + ) + .await; + assert_eq!( + query_ids( + &fresh, + r#"SELECT "paimon.default.src.id + src.id" FROM totals"# + ) + .await, + [22] + ); + ctx.ctx().register_catalog( + "analytics", + Arc::new(datafusion::catalog::MemoryCatalogProvider::new()), + ); + exec(&ctx, "SET datafusion.catalog.default_catalog = 'analytics'").await; + exec( + &ctx, + "CREATE TABLE paimon.db2.history AS SELECT id FROM paimon.default.src VERSION AS OF 1", + ) + .await; + assert_eq!(query_ids(&fresh, "SELECT * FROM db2.history").await, [12]); +} + +#[tokio::test] +async fn inferred_nested_types_and_repeated_source_field_ids() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + exec( + &ctx, + "CREATE TABLE source AS + SELECT named_struct('x', 1, 'text', 'hello') AS item, ARRAY[1, 2] AS items, + MAP(ARRAY['key'], ARRAY[3]) AS entries, CAST(1.25 AS DECIMAL(8, 2)) AS amount, + TIMESTAMP '2026-11-17 01:02:03' AS ts", + ) + .await; + exec( + &ctx, + "CREATE TABLE copied AS SELECT item AS first, item AS second, items, entries, amount, ts FROM source", + ) + .await; + let schema = catalog + .get_table(&Identifier::new("default", "copied")) + .await + .unwrap() + .schema() + .clone(); + assert_ne!(schema.fields()[0].id(), schema.fields()[1].id()); + if let (DataType::Row(first), DataType::Row(second)) = ( + schema.fields()[0].data_type(), + schema.fields()[1].data_type(), + ) { + assert_ne!(first.fields()[0].id(), second.fields()[0].id()); + } else { + panic!("expected nested ROW types"); + } + let rows = row_count( + &ctx, + "SELECT * FROM copied WHERE first.x = 1 AND second.text = 'hello' AND items[1] = 1 + AND entries['key'] = 3 AND amount = 1.25 AND ts = TIMESTAMP '2026-11-17 01:02:03'", + ) + .await; + assert_eq!(rows, 1); +} + +#[tokio::test] +async fn inferred_geospatial_types_preserve_crs_and_algorithm() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + let wkb = "decode('0101000000000000000000F03F0000000000000040', 'hex')"; + for (name, predicate, expected_rows) in [("shapes", "true", 1), ("empty_shapes", "false", 0)] { + exec( + &ctx, + &format!( + "CREATE TABLE {name} AS SELECT + CAST({wkb} AS GEOMETRY('EPSG:3857')) AS geom, + CAST({wkb} AS GEOGRAPHY('OGC:CRS84', karney)) AS geog + WHERE {predicate}" + ), + ) + .await; + let table = catalog + .get_table(&Identifier::new("default", name)) + .await + .unwrap(); + assert!(matches!( + table.schema().fields()[0].data_type(), + DataType::Geometry(geometry) if geometry.crs() == "EPSG:3857" + )); + assert!(matches!( + table.schema().fields()[1].data_type(), + DataType::Geography(geography) + if geography.crs() == "OGC:CRS84" && geography.algorithm().to_string() == "karney" + )); + assert_eq!( + row_count( + &ctx, + &format!("SELECT * FROM {name} WHERE geom = {wkb} AND geog = {wkb}") + ) + .await, + expected_rows + ); + } +} + +#[tokio::test] +async fn arrow_layouts_are_normalized_for_scalar_and_nested_outputs() { + use arrow_array::builder::StringDictionaryBuilder; + use arrow_array::types::Int32Type; + use arrow_array::LargeStringArray; + + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + let mut dictionary = StringDictionaryBuilder::::new(); + dictionary.append("encoded").unwrap(); + dictionary.append_null(); + let columns: Vec = vec![ + Arc::new(dictionary.finish()), + Arc::new(LargeStringArray::from(vec![Some("large"), None])), + ]; + let schema = Arc::new(ArrowSchema::new(vec![ + Field::new("encoded", columns[0].data_type().clone(), true), + Field::new("large", ArrowType::LargeUtf8, true), + ])); + let batch = RecordBatch::try_new(schema.clone(), columns).unwrap(); + ctx.register_temp_table( + "source", + Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()), + ) + .unwrap(); + exec(&ctx, "CREATE TABLE decoded AS SELECT *, named_struct('encoded', encoded, 'large', large) AS nested, ARRAY[large] AS items FROM source").await; + assert_eq!( + row_count( + &ctx, + "SELECT * FROM decoded WHERE encoded = 'encoded' AND large = 'large' AND nested.encoded = 'encoded' AND nested.large = 'large' AND items[1] = 'large'" + ) + .await, + 1 + ); + assert_eq!( + row_count( + &ctx, + "SELECT * FROM decoded WHERE encoded IS NULL AND large IS NULL AND nested.encoded IS NULL AND nested.large IS NULL AND items[1] IS NULL" + ) + .await, + 1 + ); + use arrow_array::builder::{Int64Builder, MapBuilder, MapFieldNames, StringBuilder}; + use arrow_array::MapArray; + let names = MapFieldNames { + entry: "entries".into(), + key: "key".into(), + value: "value".into(), + }; + let mut map = MapBuilder::new(Some(names), StringBuilder::new(), Int64Builder::new()); + map.keys().append_value("discarded"); + map.values().append_value(0); + map.append(true).unwrap(); + map.keys().append_value("key"); + map.values().append_value(9); + map.append(true).unwrap(); + map.append(false).unwrap(); + let (field, offsets, entries, nulls, _) = map.finish().into_parts(); + for sorted in [false, true] { + let map = MapArray::new( + field.clone(), + offsets.clone(), + entries.clone(), + nulls.clone(), + sorted, + ) + .slice(1, 2); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "m", + map.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(map)]).unwrap(); + ctx.register_temp_table( + format!("maps_{sorted}"), + Arc::new(MemTable::try_new(schema, vec![vec![batch]]).unwrap()), + ) + .unwrap(); + exec(&ctx, &format!("CREATE TABLE map_copy_{sorted} AS SELECT m, named_struct('m', m) AS nested, ARRAY[m] AS items FROM maps_{sorted}")).await; + assert_eq!(row_count(&ctx, &format!("SELECT * FROM map_copy_{sorted} WHERE m['key'] = 9 AND nested.m['key'] = 9 AND items[1]['key'] = 9")).await, 1); + assert_eq!(row_count(&ctx, &format!("SELECT * FROM map_copy_{sorted} WHERE m IS NULL AND nested.m IS NULL AND items[1] IS NULL")).await, 1); + } +} + +#[tokio::test] +async fn existing_target_is_a_noop_without_source_planning_or_execution() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + exec(&ctx, "CREATE TABLE existing AS SELECT 9 AS id").await; + catalog + .create_table( + &Identifier::new("default", "external_target"), + Schema::builder() + .column("id", DataType::Int(IntType::new())) + .option("type", TableType::IcebergTable.as_str()) + .build() + .unwrap(), + false, + ) + .await + .unwrap(); + exec( + &ctx, + "CREATE TABLE object_target (id INT) WITH ('type' = 'object-table', 'path' = 'oss://bucket/objects')", + ) + .await; + for target in ["existing", "external_target", "object_target"] { + let identifier = Identifier::new("default", target); + let original = catalog.fetch_table_schema(&identifier).await.unwrap(); + for source in [ + "SELECT missing_function(id) FROM missing_source", + "SELECT * FROM missing_source VERSION AS OF 1", + "SELECT * FROM missing_source TIMESTAMP AS OF '2099-01-01 00:00:00'", + ] { + exec( + &ctx, + &format!("; CREATE TABLE IF NOT EXISTS {target} AS {source}"), + ) + .await; + } + assert_sql_error( + &ctx, + &format!("CREATE TABLE {target} AS SELECT * FROM missing_source"), + "already exists", + ) + .await; + assert_eq!( + catalog.fetch_table_schema(&identifier).await.unwrap(), + original + ); + } + assert_eq!(query_ids(&ctx, "SELECT * FROM existing").await, [9]); +} + +#[tokio::test] +async fn filesystem_target_lookup_errors_precede_source_planning() { + let (warehouse, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + exec(&ctx, "CREATE TABLE broken (id INT)").await; + std::fs::write( + warehouse.path().join("default.db/broken/schema/schema-0"), + b"invalid JSON", + ) + .unwrap(); + + for (target, expected_error) in [ + ("broken", "Failed to parse schema file"), + ("missing_db.target", "Database missing_db does not exist"), + ] { + for clause in ["", "IF NOT EXISTS "] { + assert_sql_error( + &ctx, + &format!("CREATE TABLE {clause}{target} AS SELECT * FROM missing_source"), + expected_error, + ) + .await; + } + } +} + +#[tokio::test] +async fn invalid_ctas_preserves_catalog_and_source_data() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + exec(&ctx, "CREATE TABLE source AS SELECT 1 AS id").await; + ctx.register_temp_table( + "empty_columns", + Arc::new(MemTable::try_new(Arc::new(ArrowSchema::empty()), vec![vec![]]).unwrap()), + ) + .unwrap(); + for sql in [ + "CREATE TABLE bad AUTO_INCREMENT = 42 AS SELECT 1 AS id", + "CREATE TABLE bad DEFAULT CHARSET = utf8mb4 AS SELECT 1 AS id", + "CREATE TABLE bad COLLATE = utf8mb4_bin AS SELECT 1 AS id", + "CREATE TABLE bad WITH ('type' = 'iceberg-table') TBLPROPERTIES ('bucket' = '-1') AS SELECT 1 AS id", + "CREATE TABLE bad WITH ('bucket' = '0') OPTIONS ('file.format' = 'parquet') AS SELECT 1 AS id", + "CREATE TABLE bad WITH () OPTIONS ('bucket' = '-1') AS SELECT 1 AS id", + "CREATE TABLE bad AS SELECT * FROM empty_columns", + "CREATE TABLE bad AS SELECT NULL AS value", + "CREATE TABLE bad AS SELECT 1 AS id, 2 AS id", + "CREATE TABLE bad AS SELECT 1 AS \"_KEY_id\"", + "CREATE TABLE bad AS SELECT 1 AS alias VERSION AS OF 1", + "CREATE TABLE bad PARTITIONED BY (missing) AS SELECT 1 AS id", + r#"CREATE TABLE bad PARTITIONED BY (s.id) AS SELECT 1 AS "s.id""#, + "CREATE TABLE bad AS SELECT 1 AS id PARTITIONED BY (id)", + "CREATE TABLE bad WITH ('bucket' = '0') AS SELECT 1 AS id", + "CREATE EXTERNAL TABLE bad AS SELECT 1 AS id", + "CREATE TRANSIENT TABLE bad AS SELECT 1 AS id", + "CREATE GLOBAL TABLE bad AS SELECT 1 AS id", + "CREATE TABLE bad LOCATION '/tmp/not-a-ctas-table' AS SELECT 1 AS id", + "CREATE TABLE bad WITH ('type' = 'iceberg-table') AS SELECT 1 AS id", + "CREATE TABLE bad WITH ('type' = 'format-table') AS SELECT 1 AS id", + "CREATE TABLE bad (PRIMARY KEY (id)) AS SELECT 1 AS id", + ] { + assert!(ctx.sql(sql).await.is_err(), "{sql}"); + } + for (statement, expected_error) in [ + ( + "CREATE TABLE IF NOT EXISTS source PARTITIONED BY (id) PARTITIONED BY (other) AS SELECT * FROM missing_source", + "only one PARTITIONED BY clause", + ), + ( + "CREATE TABLE bad COMMENT 'first' COMMENT 'second' AS SELECT 1 AS id", + "Duplicate table COMMENT", + ), + ( + r#"CREATE TABLE IF NOT EXISTS "source$branch_dev" AS SELECT * FROM missing_source"#, + "on Paimon branch 'dev' is not supported", + ), + ( + r#"CREATE TABLE "source$snapshots" AS SELECT * FROM missing_source"#, + "on Paimon system table 'snapshots' is not supported", + ), + ( + "CREATE OR REPLACE TABLE source AS SELECT 2 AS id", + "does not support modifiers before TABLE", + ), + ( + "CREATE OR REPLACE TABLE source PARTITIONED BY (id) AS SELECT * FROM missing_source VERSION AS OF 1", + "does not support modifiers before TABLE", + ), + ( + "CREATE OR ALTER TABLE source AS SELECT * FROM source TIMESTAMP AS OF '2099-01-01 00:00:00'", + "does not support modifiers before TABLE", + ), + ( + "CREATE TABLE source (id BIGINT) AS SELECT * FROM source VERSION AS OF 1", + "explicit column declarations", + ), + ( + "CREATE TABLE bad AS SELECT * FROM source VERSION AS OF 1; DROP TABLE source", + "Expected exactly one SQL statement", + ), + ] { + assert_sql_error(&ctx, &format!("/* start */ ; ; {statement}"), expected_error).await; + } + for sql in [ + "; CREATE TABLE bad AS SELECT id INTO side_effect FROM source VERSION AS OF 1", + "CREATE TABLE bad AS WITH changed AS (SELECT id INTO side_effect FROM source) SELECT * FROM changed", + "CREATE TABLE bad AS SELECT id FROM source UNION ALL SELECT id INTO side_effect FROM source", + "CREATE TABLE bad AS INSERT INTO source VALUES (2)", + "CREATE TABLE bad AS UPDATE source SET id = 2", + "CREATE TABLE bad AS DELETE FROM source", + "CREATE TABLE bad AS MERGE INTO source t USING (SELECT 1 AS id) s ON t.id = s.id WHEN MATCHED THEN DELETE", + "CREATE TABLE bad AS WITH changed AS (INSERT INTO source VALUES (2) RETURNING id) SELECT * FROM changed", + ] { + assert_sql_error(&ctx, sql, "requires a read-only query").await; + } + for missing in ["bad", "side_effect"] { + assert!(matches!( + catalog + .get_table(&Identifier::new("default", missing)) + .await, + Err(paimon::Error::TableNotExist { .. }) + )); + } + assert_eq!(query_ids(&ctx, "SELECT id FROM source").await, [1]); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rest_ctas_resolves_the_source_only_after_checking_the_target() { + let tmp = tempfile::tempdir().unwrap(); + let server = mock_server::start_mock_server( + "ctas".into(), + tmp.path().to_string_lossy().into_owned(), + paimon::api::ConfigResponse::new(HashMap::from([( + CatalogOptions::PREFIX.to_string(), + "mock-test".into(), + )])), + vec!["source_db".into(), "default".into()], + ) + .await; + let mut options = Options::new(); + options.set(CatalogOptions::URI, server.url().unwrap()); + options.set(CatalogOptions::WAREHOUSE, "ctas"); + options.set(CatalogOptions::TOKEN_PROVIDER, "bear"); + options.set(CatalogOptions::TOKEN, "test-token"); + let source = Arc::new(RESTCatalog::new(options, true).await.unwrap()); + let (_dest, destination) = create_test_env(); + let mut ctx = SQLContext::new(); + ctx.register_catalog("source", source).await.unwrap(); + ctx.register_catalog("dest", destination).await.unwrap(); + exec(&ctx, "USE source.source_db").await; + exec( + &ctx, + "CREATE FUNCTION plus_one(x BIGINT) RETURNS BIGINT RETURN x + 1", + ) + .await; + exec(&ctx, "CREATE TABLE inputs AS SELECT 8 AS id").await; + let query = "SELECT plus_one(id) AS id FROM inputs"; + server.add_table_with_schema( + "default", + "objects", + Schema::builder() + .column("id", DataType::Int(IntType::new())) + .option("type", TableType::ObjectTable.as_str()) + .build() + .unwrap(), + "oss://bucket/objects", + ); + exec( + &ctx, + "CREATE TABLE IF NOT EXISTS source.default.objects AS SELECT * FROM missing_source", + ) + .await; + assert_sql_error( + &ctx, + "CREATE TABLE source.default.objects AS SELECT * FROM missing_source", + "already exists", + ) + .await; + assert_eq!( + server.table_get_call_count("source_db", "missing_source"), + 0 + ); + server.add_no_permission_table("default", "forbidden"); + for (target, expected_error) in [ + ( + "source.missing_db.result", + "Database missing_db does not exist", + ), + ("source.default.forbidden", "No Permission"), + ( + "source.default.\".\"", + "table name must not be a dot path segment", + ), + ( + "source.\"..\".result", + "database name must not be a dot path segment", + ), + ] { + let before = server.table_get_call_count("source_db", "inputs"); + for clause in ["", "IF NOT EXISTS "] { + assert_sql_error( + &ctx, + &format!("CREATE TABLE {clause}{target} AS {query}"), + expected_error, + ) + .await; + } + assert_eq!(server.table_get_call_count("source_db", "inputs"), before); + } + for target in ["dest.default.result", "source.default.result"] { + let before = server.table_get_call_count("source_db", "inputs"); + exec( + &ctx, + &format!("CREATE TABLE {target} WITH ('commit.max-retries' = '0') AS {query}"), + ) + .await; + assert_eq!( + server.table_get_call_count("source_db", "inputs") - before, + 1 + ); + assert_eq!( + query_ids(&ctx, &format!("SELECT * FROM {target}")).await, + [9] + ); + } +} diff --git a/crates/integrations/datafusion/tests/create_table_as/execution.rs b/crates/integrations/datafusion/tests/create_table_as/execution.rs new file mode 100644 index 000000000..9529bb565 --- /dev/null +++ b/crates/integrations/datafusion/tests/create_table_as/execution.rs @@ -0,0 +1,786 @@ +// 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 super::*; +use async_trait::async_trait; +use bytes::Bytes; +use datafusion::catalog::streaming::StreamingTable; +use datafusion::catalog::Session; +use datafusion::datasource::{TableProvider, TableType as DFTableType}; +use datafusion::error::{DataFusionError, Result as DFResult}; +use datafusion::execution::{SendableRecordBatchStream, TaskContext}; +use datafusion::logical_expr::{create_udf, ColumnarValue, Expr, Volatility}; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::streaming::{PartitionStream, StreamingTableExec}; +use datafusion::physical_plan::ExecutionPlan; +use futures::StreamExt; +use paimon::catalog::Database; +use paimon::io::{FileIOBuilder, FileIOProvider}; +use paimon::spec::SchemaChange; +use paimon::table::Table; +use paimon::FileSystemCatalog; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; +use tokio::sync::Notify; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Fault { + None, + Lookup, + PauseLookup, + Create, + LostCreateResponse, + Race, + LoadAfterCreate, + Write, + WriteAfterOutput, + BeforePublication, + LostResponse, + PausePublication, +} + +#[derive(Debug)] +struct InjectedIO { + operator: opendal::Operator, + fault: Fault, + published: AtomicBool, + data_paths: std::sync::Mutex>, + reached: Notify, + resume: Notify, +} + +fn injected_error(message: &str) -> paimon::Error { + paimon::Error::UnexpectedError { + message: message.into(), + source: None, + } +} + +fn relative(path: &str) -> &str { + path.trim_start_matches("file://").trim_start_matches('/') +} + +#[async_trait] +impl FileIOProvider for InjectedIO { + async fn create(&self, path: &str) -> paimon::Result<(opendal::Operator, String)> { + if path.ends_with(".parquet") { + let mut paths = self.data_paths.lock().unwrap(); + let index = paths + .iter() + .position(|entry| entry == path) + .unwrap_or_else(|| { + paths.push(path.into()); + paths.len() - 1 + }); + if self.fault == Fault::Write || self.fault == Fault::WriteAfterOutput && index == 1 { + return Err(injected_error("injected data write failure")); + } + } + if self.published.load(Ordering::SeqCst) + && self.fault == Fault::LostResponse + && path.contains("/snapshot/") + { + return Err(injected_error("injected snapshot read failure")); + } + Ok((self.operator.clone(), relative(path).into())) + } + + async fn write_atomic_if_not_exists( + &self, + path: &str, + bytes: Bytes, + ) -> paimon::Result> { + if path.contains("/snapshot/snapshot-") { + if self.fault == Fault::PausePublication { + self.reached.notify_one(); + self.resume.notified().await; + self.operator.write(relative(path), bytes).await.unwrap(); + self.published.store(true, Ordering::SeqCst); + return Ok(Some(true)); + } + if self.fault == Fault::BeforePublication { + return Err(injected_error("injected publication failure")); + } + if self.fault == Fault::LostResponse { + self.operator.write(relative(path), bytes).await.unwrap(); + self.published.store(true, Ordering::SeqCst); + return Err(injected_error("injected lost commit response")); + } + } + Ok(None) + } +} + +#[derive(Debug)] +struct TestCatalog { + inner: Arc, + fault: Fault, + creates: AtomicUsize, + drops: AtomicUsize, + io: Option>, + lookup_started: Notify, + resume_lookup: Notify, +} + +impl TestCatalog { + fn new(inner: Arc, fault: Fault) -> Arc { + let io = matches!( + fault, + Fault::Write + | Fault::WriteAfterOutput + | Fault::BeforePublication + | Fault::LostResponse + | Fault::PausePublication + ) + .then(|| { + Arc::new(InjectedIO { + operator: + opendal::Operator::from_config(opendal::services::MemoryConfig::default()) + .unwrap(), + fault, + published: AtomicBool::new(false), + data_paths: std::sync::Mutex::new(Vec::new()), + reached: Notify::new(), + resume: Notify::new(), + }) + }); + Arc::new(Self { + inner, + fault, + creates: AtomicUsize::new(0), + drops: AtomicUsize::new(0), + io, + lookup_started: Notify::new(), + resume_lookup: Notify::new(), + }) + } +} + +async fn append(table: &Table, value: i64) { + let builder = table.new_write_builder(); + let mut writer = builder.new_write().unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "id", + ArrowType::Int64, + false, + )])); + writer + .write_arrow_batch( + &RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(vec![value]))]).unwrap(), + ) + .await + .unwrap(); + let messages = writer.prepare_commit().await.unwrap(); + builder.new_commit().commit(messages).await.unwrap(); +} + +#[async_trait] +impl Catalog for TestCatalog { + async fn list_databases(&self) -> paimon::Result> { + self.inner.list_databases().await + } + async fn create_database( + &self, + name: &str, + ignore: bool, + properties: HashMap, + ) -> paimon::Result<()> { + self.inner.create_database(name, ignore, properties).await + } + async fn get_database(&self, name: &str) -> paimon::Result { + self.inner.get_database(name).await + } + async fn drop_database(&self, name: &str, ignore: bool, cascade: bool) -> paimon::Result<()> { + self.inner.drop_database(name, ignore, cascade).await + } + async fn check_table_exists(&self, id: &Identifier) -> paimon::Result<()> { + if self.fault == Fault::Lookup { + return Err(injected_error("injected forbidden lookup")); + } + if self.fault == Fault::PauseLookup + && id.object() == "target" + && self.creates.load(Ordering::SeqCst) == 0 + { + self.lookup_started.notify_one(); + self.resume_lookup.notified().await; + } + self.inner.check_table_exists(id).await + } + async fn get_table(&self, id: &Identifier) -> paimon::Result { + if self.fault == Fault::LoadAfterCreate && self.creates.load(Ordering::SeqCst) > 0 { + return Err(injected_error("injected table load failure")); + } + let table = self.inner.get_table(id).await?; + if let Some(io) = &self.io { + let schema_path = format!("{}/schema/schema-0", table.location()); + if !io.operator.exists(relative(&schema_path)).await.unwrap() { + io.operator + .write( + relative(&schema_path), + serde_json::to_vec(table.schema()).unwrap(), + ) + .await + .unwrap(); + } + Ok(Table::new( + FileIOBuilder::new("memory") + .with_provider(io.clone()) + .build()?, + id.clone(), + table.location().to_string(), + table.schema().clone(), + None, + )) + } else { + Ok(table) + } + } + async fn list_tables(&self, db: &str) -> paimon::Result> { + self.inner.list_tables(db).await + } + async fn create_table( + &self, + id: &Identifier, + schema: Schema, + ignore: bool, + ) -> paimon::Result<()> { + self.inner.create_table(id, schema, ignore).await + } + async fn create_table_exclusive(&self, id: &Identifier, schema: Schema) -> paimon::Result<()> { + self.creates.fetch_add(1, Ordering::SeqCst); + if self.fault == Fault::Create { + return Err(injected_error("injected table creation failure")); + } + if self.fault == Fault::Race { + self.inner.create_table(id, schema.clone(), false).await?; + append(&self.inner.get_table(id).await?, 77).await; + } + self.inner.create_table_exclusive(id, schema).await?; + if self.fault == Fault::LostCreateResponse { + return Err(injected_error("injected lost create response")); + } + Ok(()) + } + async fn drop_table(&self, id: &Identifier, ignore: bool) -> paimon::Result<()> { + self.drops.fetch_add(1, Ordering::SeqCst); + self.inner.drop_table(id, ignore).await + } + async fn rename_table( + &self, + from: &Identifier, + to: &Identifier, + ignore: bool, + ) -> paimon::Result<()> { + self.inner.rename_table(from, to, ignore).await + } + async fn alter_table( + &self, + id: &Identifier, + changes: Vec, + ignore: bool, + ) -> paimon::Result<()> { + self.inner.alter_table(id, changes, ignore).await + } +} + +#[derive(Debug)] +struct ProbeSource { + schema: Arc, + scans: AtomicUsize, + executions: Arc, + fail: bool, + concurrent_writer: Option>, +} +impl ProbeSource { + fn new(fail: bool, concurrent_writer: Option>) -> Arc { + Arc::new(Self { + schema: Arc::new(ArrowSchema::new(vec![Field::new( + "id", + ArrowType::Int64, + false, + )])), + scans: AtomicUsize::new(0), + executions: Arc::new(AtomicUsize::new(0)), + fail, + concurrent_writer, + }) + } +} +#[derive(Debug)] +struct ProbePartition { + schema: Arc, + executions: Arc, + fail: bool, + concurrent_writer: Option>, +} +impl PartitionStream for ProbePartition { + fn schema(&self) -> &Arc { + &self.schema + } + fn execute(&self, _: Arc) -> SendableRecordBatchStream { + self.executions.fetch_add(1, Ordering::SeqCst); + let first = RecordBatch::try_new( + self.schema.clone(), + vec![Arc::new(Int64Array::from(vec![11]))], + ) + .unwrap(); + let concurrent_writer = self.concurrent_writer.clone(); + let fail = self.fail; + let schema = self.schema.clone(); + let stream = + futures::stream::once(async { Ok(first) }).chain(futures::stream::once(async move { + if let Some(catalog) = concurrent_writer { + let table = catalog + .get_table(&Identifier::new("default", "target")) + .await + .unwrap(); + append(&table, 88).await; + } + if fail { + Err(DataFusionError::Execution("injected source failure".into())) + } else { + Ok(RecordBatch::try_new( + schema, + vec![Arc::new(Int64Array::from(vec![12]))], + )?) + } + })); + Box::pin(RecordBatchStreamAdapter::new(self.schema.clone(), stream)) + } +} +#[async_trait] +impl TableProvider for ProbeSource { + fn schema(&self) -> Arc { + self.schema.clone() + } + fn table_type(&self) -> DFTableType { + DFTableType::Base + } + async fn scan( + &self, + _: &dyn Session, + projection: Option<&Vec>, + _: &[Expr], + limit: Option, + ) -> DFResult> { + self.scans.fetch_add(1, Ordering::SeqCst); + Ok(Arc::new(StreamingTableExec::try_new( + self.schema.clone(), + vec![Arc::new(ProbePartition { + schema: self.schema.clone(), + executions: self.executions.clone(), + fail: self.fail, + concurrent_writer: self.concurrent_writer.clone(), + })], + projection, + [], + false, + limit, + )?)) + } +} + +async fn context(catalog: Arc, source: Arc) -> SQLContext { + let mut ctx = SQLContext::new(); + ctx.register_catalog("paimon", catalog).await.unwrap(); + ctx.register_temp_table("source", source).unwrap(); + ctx +} + +#[tokio::test] +async fn inference_and_population_use_one_plan_in_the_statement_namespace() { + let (_tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner, Fault::PauseLookup); + let source = ProbeSource::new(false, None); + let ctx = context(catalog.clone(), source.clone()).await; + exec(&ctx, "CREATE DATABASE other").await; + ctx.register_temp_table("other.source", ProbeSource::new(true, None)) + .unwrap(); + let observed_rows = Arc::new(AtomicUsize::new(0)); + let counter = observed_rows.clone(); + ctx.ctx().register_udf(create_udf( + "observe", + vec![ArrowType::Int64], + ArrowType::Int64, + Volatility::Volatile, + Arc::new(move |args| { + let ColumnarValue::Array(ids) = &args[0] else { + panic!("expected the source column"); + }; + counter.fetch_add(ids.len(), Ordering::SeqCst); + Ok(args[0].clone()) + }), + )); + let query = "SELECT observe(id) AS id FROM source"; + let sql = format!("CREATE TABLE target AS {query}"); + tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(exec(&ctx, &sql), async { + catalog.lookup_started.notified().await; + ctx.set_current_database("other").await.unwrap(); + catalog.resume_lookup.notify_one(); + }); + }) + .await + .unwrap(); + assert_eq!(source.scans.load(Ordering::SeqCst), 1); + assert_eq!(source.executions.load(Ordering::SeqCst), 1); + assert_eq!( + query_ids(&ctx, "SELECT * FROM default.target").await, + [11, 12] + ); + assert_eq!(catalog.creates.load(Ordering::SeqCst), 1); + exec( + &ctx, + &format!("CREATE TABLE IF NOT EXISTS default.target AS {query}"), + ) + .await; + assert_eq!(source.scans.load(Ordering::SeqCst), 1); + assert_eq!(source.executions.load(Ordering::SeqCst), 1); + assert_eq!(observed_rows.load(Ordering::SeqCst), 2); + assert_eq!(catalog.creates.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn create_race_never_populates_or_drops_the_winner() { + for if_not_exists in [false, true] { + let (_tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner.clone(), Fault::Race); + let source = ProbeSource::new(false, None); + let ctx = context(catalog.clone(), source.clone()).await; + let clause = if if_not_exists { "IF NOT EXISTS " } else { "" }; + let result = ctx + .sql(&format!( + "CREATE TABLE {clause}target AS SELECT * FROM source" + )) + .await; + assert_eq!(result.is_ok(), if_not_exists); + if let Err(error) = result { + assert!(error.to_string().contains("already exists"), "{error}"); + } + assert_eq!(catalog.creates.load(Ordering::SeqCst), 1); + assert_eq!(source.executions.load(Ordering::SeqCst), 0); + assert_eq!(catalog.drops.load(Ordering::SeqCst), 0); + assert_eq!(query_ids(&ctx, "SELECT * FROM target").await, [77]); + } +} + +#[tokio::test] +async fn catalog_failures_do_not_execute_the_source_or_drop_the_target() { + for (fault, expected_error) in [ + (Fault::Lookup, "injected forbidden lookup"), + (Fault::Create, "injected table creation failure"), + (Fault::LostCreateResponse, "injected lost create response"), + (Fault::LoadAfterCreate, "injected table load failure"), + ] { + for if_not_exists in [false, true] { + let (_tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner.clone(), fault); + let source = ProbeSource::new(false, None); + let ctx = context(catalog.clone(), source.clone()).await; + let clause = if if_not_exists { "IF NOT EXISTS " } else { "" }; + let sql = format!("CREATE TABLE {clause}target AS SELECT * FROM source"); + let error = ctx.sql(&sql).await.unwrap_err().to_string(); + assert!(error.contains(expected_error), "{error}"); + if fault == Fault::LoadAfterCreate { + assert!( + error.contains("Failed to load newly created table 'paimon.default.target'"), + "{error}" + ); + } + let planned = usize::from(fault != Fault::Lookup); + assert_eq!(catalog.creates.load(Ordering::SeqCst), planned); + assert_eq!(source.scans.load(Ordering::SeqCst), planned); + assert_eq!(source.executions.load(Ordering::SeqCst), 0); + assert_eq!(catalog.drops.load(Ordering::SeqCst), 0); + let target = inner.get_table(&Identifier::new("default", "target")).await; + if matches!(fault, Fault::LostCreateResponse | Fault::LoadAfterCreate) { + assert!(target + .unwrap() + .snapshot_manager() + .get_latest_snapshot() + .await + .unwrap() + .is_none()); + } else { + assert!(matches!(target, Err(paimon::Error::TableNotExist { .. }))); + } + } + } +} + +#[tokio::test] +async fn population_preserves_concurrent_rows_and_cleans_failed_output() { + for (fail, concurrent) in [(true, false), (true, true), (false, true)] { + let (tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner.clone(), Fault::None); + let source = ProbeSource::new(fail, concurrent.then_some(inner)); + let ctx = context(catalog.clone(), source.clone()).await; + let sql = "CREATE TABLE target WITH ('target-file-size' = '1 b') AS SELECT * FROM source"; + if fail { + assert_sql_error(&ctx, sql, "injected source failure").await; + } else { + exec(&ctx, sql).await; + } + assert_eq!(catalog.drops.load(Ordering::SeqCst), 0); + let mut expected = if fail { vec![] } else { vec![11, 12] }; + if concurrent { + expected.push(88); + } + assert_eq!(query_ids(&ctx, "SELECT * FROM target").await, expected); + let data_files = common::files_under(tmp.path()) + .iter() + .filter(|path| path.extension().is_some_and(|ext| ext == "parquet")) + .count(); + assert_eq!( + data_files, + expected.len(), + "only committed output should remain: fail={fail}, concurrent={concurrent}" + ); + exec( + &ctx, + "CREATE TABLE IF NOT EXISTS target AS SELECT * FROM source", + ) + .await; + assert_eq!(catalog.creates.load(Ordering::SeqCst), 1); + assert_eq!(source.executions.load(Ordering::SeqCst), 1); + } +} + +#[tokio::test] +async fn write_and_publication_failures_keep_the_table_and_uncertain_files() { + for fault in [ + Fault::Write, + Fault::WriteAfterOutput, + Fault::BeforePublication, + Fault::LostResponse, + ] { + let (_tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner, fault); + let source = ProbeSource::new(false, None); + let ctx = context(catalog.clone(), source.clone()).await; + let error = ctx + .sql("CREATE TABLE target WITH ('target-file-size' = '1 b', 'commit.max-retries' = '0') AS SELECT * FROM source") + .await + .expect_err("injected failure") + .to_string(); + assert!(error.contains("injected"), "{fault:?}: {error}"); + assert_eq!(catalog.drops.load(Ordering::SeqCst), 0); + catalog + .inner + .get_table(&Identifier::new("default", "target")) + .await + .unwrap(); + let io = catalog.io.as_ref().unwrap(); + let entries = io.operator.list_with("/").recursive(true).await.unwrap(); + let data = entries + .iter() + .filter(|entry| entry.path().ends_with(".parquet")) + .count(); + if matches!(fault, Fault::Write | Fault::WriteAfterOutput) { + assert_eq!(data, 0); + assert_eq!( + io.data_paths.lock().unwrap().len(), + if fault == Fault::Write { 1 } else { 2 } + ); + assert!(error.contains("no commit was attempted"), "{error}"); + } else { + assert!( + data > 0, + "prepared files must survive uncertain publication" + ); + assert!(error.contains("publication may have succeeded"), "{error}"); + } + assert_eq!( + io.published.load(Ordering::SeqCst), + fault == Fault::LostResponse + ); + exec( + &ctx, + "CREATE TABLE IF NOT EXISTS target AS SELECT * FROM source", + ) + .await; + assert_eq!(catalog.creates.load(Ordering::SeqCst), 1); + assert_eq!(source.executions.load(Ordering::SeqCst), 1); + if fault == Fault::LostResponse { + io.published.store(false, Ordering::SeqCst); + assert_eq!(query_ids(&ctx, "SELECT * FROM target").await, [11, 12]); + } + } +} + +#[derive(Debug)] +struct PausedSource(RecordBatch); + +impl PausedSource { + fn table(rows: usize, infinite: bool) -> StreamingTable { + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "id", + ArrowType::Int64, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(vec![12; rows]))], + ) + .unwrap(); + StreamingTable::try_new(schema, vec![Arc::new(Self(batch))]) + .unwrap() + .with_infinite_table(infinite) + } +} + +impl PartitionStream for PausedSource { + fn schema(&self) -> &Arc { + self.0.schema_ref() + } + fn execute(&self, _: Arc) -> SendableRecordBatchStream { + let input = futures::stream::iter([Ok(self.0.clone())]).chain(futures::stream::pending()); + Box::pin(RecordBatchStreamAdapter::new(self.0.schema(), input)) + } +} + +#[tokio::test] +async fn output_must_be_bounded_before_creation() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + ctx.register_temp_table("probe", Arc::new(PausedSource::table(1, true))) + .unwrap(); + + for (target, source) in [ + ("unbounded", "SELECT id FROM probe"), + ( + "mixed", + "SELECT id FROM (SELECT id FROM probe LIMIT 1) AS limited_input + UNION ALL SELECT id FROM probe", + ), + ] { + let sql = format!("CREATE TABLE {target} AS {source}"); + tokio::time::timeout( + Duration::from_secs(10), + assert_sql_error(&ctx, &sql, "requires a bounded query"), + ) + .await + .unwrap(); + assert!(matches!( + catalog.get_table(&Identifier::new("default", target)).await, + Err(paimon::Error::TableNotExist { .. }) + )); + } + + for (target, source, expected) in [ + ("limited", "SELECT id FROM probe LIMIT 1", vec![12]), + ( + "projected", + "SELECT id + 1 AS id FROM (SELECT id FROM probe LIMIT 1) AS limited_input", + vec![13], + ), + ( + "expanded", + "SELECT unnest(ARRAY[id, id + 1]) AS id FROM (SELECT id FROM probe LIMIT 1) AS limited_input", + vec![12, 13], + ), + ] { + let sql = format!("CREATE TABLE {target} AS {source}"); + tokio::time::timeout(Duration::from_secs(10), exec(&ctx, &sql)) + .await + .unwrap(); + assert_eq!( + query_ids(&ctx, &format!("SELECT id FROM {target}")).await, + expected + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancellation_discards_uncommitted_output() { + let (tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog.clone()).await; + ctx.register_temp_table("probe", Arc::new(PausedSource::table(24_576, false))) + .unwrap(); + let statement = tokio::spawn(async move { + ctx.sql("CREATE TABLE result WITH ('target-file-size' = '1 b') AS SELECT id FROM probe") + .await + .map(|_| ()) + }); + let outputs = || { + common::files_under(tmp.path()) + .into_iter() + .filter(|p| p.extension().is_some_and(|e| e == "parquet")) + .collect::>() + }; + tokio::time::timeout(Duration::from_secs(10), async { + while !outputs() + .iter() + .any(|path| path.metadata().is_ok_and(|metadata| metadata.len() > 0)) + { + tokio::time::sleep(Duration::from_millis(15)).await; + } + }) + .await + .unwrap(); + statement.abort(); + assert!(statement.await.unwrap_err().is_cancelled()); + tokio::time::timeout(Duration::from_secs(10), async { + while !outputs().is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(outputs().is_empty(), "orphan files: {:?}", outputs()); + let table = catalog + .get_table(&Identifier::new("default", "result")) + .await + .unwrap(); + assert!(table + .snapshot_manager() + .get_latest_snapshot() + .await + .unwrap() + .is_none()); + let fresh = create_sql_context(catalog).await; + assert_eq!(row_count(&fresh, "SELECT * FROM result").await, 0); +} + +#[tokio::test] +async fn cancellation_finishes_started_publication() { + let (_tmp, inner) = create_test_env(); + let catalog = TestCatalog::new(inner, Fault::PausePublication); + let ctx = Arc::new(context(catalog.clone(), ProbeSource::new(false, None)).await); + let writer_ctx = ctx.clone(); + let statement = tokio::spawn(async move { + writer_ctx + .sql("CREATE TABLE target AS SELECT * FROM source") + .await + .map(|_| ()) + }); + let io = catalog.io.as_ref().unwrap(); + tokio::time::timeout(Duration::from_secs(10), io.reached.notified()) + .await + .unwrap(); + statement.abort(); + assert!(statement.await.unwrap_err().is_cancelled()); + io.resume.notify_one(); + tokio::time::timeout(Duration::from_secs(10), async { + while !io.published.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(query_ids(&ctx, "SELECT id FROM target").await, [11, 12]); +} diff --git a/crates/integrations/datafusion/tests/read_files_behavior.rs b/crates/integrations/datafusion/tests/read_files_behavior.rs index 6cba4097c..c4f9c16da 100644 --- a/crates/integrations/datafusion/tests/read_files_behavior.rs +++ b/crates/integrations/datafusion/tests/read_files_behavior.rs @@ -291,10 +291,15 @@ async fn wildcard_replacements_preserve_aliases_for_outer_queries_and_ctas() { ) .await .unwrap(); - ctx.sql("CREATE TEMPORARY TABLE replaced AS SELECT * REPLACE (upper(value) AS value) FROM read_files('memory://files/data.txt')").await.unwrap(); - assert_eq!(columns(&ctx, "SELECT * FROM replaced").await, ["value"]); - let values = rows(&ctx, "SELECT value FROM replaced").await; - assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO")); + for (modifier, table) in [("TEMPORARY ", "temp_replaced"), ("", "replaced")] { + ctx.sql(&format!("CREATE {modifier}TABLE {table} AS SELECT * REPLACE (upper(value) AS value) FROM read_files('memory://files/data.txt')")).await.unwrap(); + assert_eq!( + columns(&ctx, &format!("SELECT * FROM {table}")).await, + ["value"] + ); + let values = rows(&ctx, &format!("SELECT value FROM {table}")).await; + assert_eq!(values[0][0].try_as_str().flatten(), Some("HELLO")); + } } #[tokio::test] diff --git a/crates/integrations/datafusion/tests/time_travel_schema_tests.rs b/crates/integrations/datafusion/tests/time_travel_schema_tests.rs index defd15b08..bc9b10dc1 100644 --- a/crates/integrations/datafusion/tests/time_travel_schema_tests.rs +++ b/crates/integrations/datafusion/tests/time_travel_schema_tests.rs @@ -191,6 +191,359 @@ async fn test_version_as_of_uses_snapshot_schema() { assert_eq!(total_rows(&batches), 5); } +#[tokio::test] +async fn prepared_statement_keeps_its_snapshot_in_the_original_session() { + use datafusion::arrow::array::Int32Array; + + let (_tmp, ctx) = setup_evolved_table().await; + ctx.sql( + "PREPARE historical(INT) AS SELECT paimon.default.t.id + t.id + FROM paimon.default.t VERSION AS OF 1 + JOIN t VERSION AS OF 2 AS t ON paimon.default.t.id = t.id + WHERE t.id >= $1", + ) + .await + .unwrap(); + let batches = ctx + .sql("EXECUTE historical(3)") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(total_rows(&batches), 1); + assert_eq!(column_names(&batches), ["paimon.default.t.id + t.id"]); + assert_eq!( + batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 6 + ); + ctx.sql("DEALLOCATE historical").await.unwrap(); +} + +#[tokio::test] +async fn snapshot_join_qualifiers_follow_sql_scope() { + use datafusion::arrow::array::Int64Array; + + let (warehouse, mut ctx) = setup_evolved_table().await; + let other_warehouse = TempDir::new().unwrap(); + let mut options = Options::new(); + options.set( + CatalogOptions::WAREHOUSE, + format!("file://{}", other_warehouse.path().display()), + ); + ctx.register_catalog("other", Arc::new(FileSystemCatalog::new(options).unwrap())) + .await + .unwrap(); + for sql in [ + "CREATE TABLE other.default.t (id INT, t STRUCT)", + "INSERT INTO other.default.t VALUES (5, named_struct('field', 7))", + ] { + ctx.sql(sql).await.unwrap().collect().await.unwrap(); + } + let sums = "SELECT paimon.default.t.id + t.id FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN t VERSION AS OF 2 AS t WHERE t.id = 5"; + let column = r#""paimon.default.t.id + t.id""#; + let derived = format!("({sums}) s WHERE s.{column} = 8"); + let cte = + format!("(WITH pairs AS ({sums}) SELECT pairs.{column} FROM pairs) s WHERE s.{column} = 8"); + for (from, expected) in [ + ("t VERSION AS OF 1 JOIN t VERSION AS OF 2 USING (id)", 3), + ( + "t VERSION AS OF 1 JOIN paimon.default.t VERSION AS OF 2 USING (id)", + 3, + ), + ( + "t VERSION AS OF 1 CROSS JOIN t VERSION AS OF 2 AS t WHERE t.id = 5", + 3, + ), + ( + "paimon.default.t VERSION AS OF 1 CROSS JOIN t VERSION AS OF 2 AS t + WHERE paimon.default.t.id = 1 AND t.id = 5", + 1, + ), + ("t VERSION AS OF 1 CROSS JOIN t WHERE t.id = 5", 3), + ("t VERSION AS OF 1 CROSS JOIN default.t WHERE t.id = 5", 3), + ( + "default.t VERSION AS OF 1 CROSS JOIN paimon.default.t WHERE default.t.id = 5", + 3, + ), + ( + "default.t VERSION AS OF 1 CROSS JOIN t WHERE default.t.id = 5", + 3, + ), + ( + "paimon.default.t VERSION AS OF 1 CROSS JOIN t WHERE paimon.default.t.id = 5", + 3, + ), + ( + "(t VERSION AS OF 1 JOIN (SELECT 1 AS minimum) x ON t.id >= x.minimum) + RIGHT ANTI JOIN t VERSION AS OF 2 USING (id) WHERE t.id >= 4", + 2, + ), + ( + "(SELECT t.* FROM t VERSION AS OF 1 RIGHT ANTI JOIN t VERSION AS OF 2 USING (id)) s + WHERE s.id = 5", + 1, + ), + ( + "paimon.default.t VERSION AS OF 1 LEFT SEMI JOIN other.default.t VERSION AS OF 1 + ON paimon.default.t.id + 4 = other.default.t.id + JOIN (SELECT 1 AS id) x ON t.id = x.id", + 1, + ), + ( + "(t VERSION AS OF 1 JOIN (SELECT 1 AS minimum) x ON t.id >= x.minimum) + JOIN t VERSION AS OF 2 AS t USING (id)", + 3, + ), + ( + "t VERSION AS OF 1 JOIN (SELECT 1 AS minimum) x ON t.id >= x.minimum + JOIN t VERSION AS OF 2 AS t USING (id)", + 3, + ), + ( + "(SELECT paimon.default.t.* FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN t VERSION AS OF 2 AS t WHERE t.id = 5 + ORDER BY paimon.default.t.id DESC LIMIT 1) s WHERE s.id = 3", + 1, + ), + ( + "(SELECT COUNT(paimon.default.t.*) AS n FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN t AS t WHERE t.id = 5) s WHERE s.n = 3", + 1, + ), + (derived.as_str(), 1), + (cte.as_str(), 1), + ( + "(WITH t AS (SELECT 5 AS id) + SELECT paimon.default.t.id FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN t WHERE paimon.default.t.id = 1 AND t.id = 5) s", + 1, + ), + ( + "(WITH t AS ( + SELECT paimon.default.t.id FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN t WHERE paimon.default.t.id = 5 + ) SELECT * FROM t) s", + 3, + ), + ( + "(SELECT t.id FROM t VERSION AS OF 1) a + JOIN (SELECT t.id FROM t VERSION AS OF 2) b USING (id)", + 3, + ), + ( + "paimon.default.t VERSION AS OF 1 CROSS JOIN other.default.t VERSION AS OF 1 + WHERE other.default.t.id = 5", + 3, + ), + ( + "paimon.default.t VERSION AS OF 1 JOIN (SELECT 1 AS id) minimum + ON default.t.id = minimum.id + CROSS JOIN other.default.t VERSION AS OF 1", + 1, + ), + ( + "paimon.default.t VERSION AS OF 1 JOIN (SELECT 1 AS id) minimum + ON t.id = minimum.id CROSS JOIN other.default.t", + 1, + ), + ( + "other.default.t AS t WHERE EXISTS ( + SELECT 1 FROM (SELECT 5 AS id) x JOIN (SELECT 5 AS id) y + ON x.id = y.id AND t.id = x.id + CROSS JOIN paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 + )", + 1, + ), + ( + "other.default.t AS t WHERE EXISTS ( + SELECT 1 FROM ((SELECT 5 AS id) x JOIN (SELECT 5 AS id) y + ON x.id = y.id AND t.id = x.id) early_join + CROSS JOIN paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 + )", + 1, + ), + ( + "paimon.default.t VERSION AS OF 1 CROSS JOIN other.default.t WHERE EXISTS ( + SELECT 1 FROM (SELECT 1 AS id) x JOIN (SELECT 1 AS id) y + ON x.id = y.id AND paimon.default.t.id = x.id + CROSS JOIN paimon.default.t VERSION AS OF 1 + )", + 1, + ), + ] { + let batches = ctx + .sql(&format!("SELECT COUNT(*) FROM {from}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + let count = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(count, expected, "{from}"); + } + + for (target, query, expected) in [ + ( + "snapshot_and_live_join", + "SELECT COUNT(*) AS n FROM t VERSION AS OF 1 + CROSS JOIN paimon.default.t WHERE t.id = 5", + 3, + ), + ( + "full_live_join", + "SELECT COUNT(*) AS n FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t WHERE t.id = 5 AND paimon.default.t.id >= 1", + 3, + ), + ( + "partial_live_join", + "SELECT COUNT(*) AS n FROM default.t VERSION AS OF 1 + CROSS JOIN other.default.t WHERE t.id = 5 AND paimon.default.t.id >= 1", + 3, + ), + ( + "right_anti", + "SELECT CAST(t.id AS BIGINT) AS n FROM paimon.default.t VERSION AS OF 1 + RIGHT ANTI JOIN other.default.t VERSION AS OF 1 USING (id)", + 5, + ), + ( + "nested_field", + "SELECT CAST(t.field AS BIGINT) AS n FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 WHERE paimon.default.t.id = 1", + 7, + ), + ( + "correlated_derived_source", + "SELECT COUNT(*) AS n FROM other.default.t AS t WHERE EXISTS ( + SELECT 1 FROM (SELECT 1 AS id WHERE t.id = 5) matched + CROSS JOIN paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 + )", + 1, + ), + ( + "lateral_join_source", + "SELECT COUNT(*) AS n FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN LATERAL (SELECT 1 AS id WHERE t.id = 1) matched + CROSS JOIN other.default.t", + 1, + ), + ( + "lateral_from_source", + "SELECT COUNT(*) AS n FROM paimon.default.t VERSION AS OF 1, + LATERAL (SELECT 1 AS id WHERE t.id = 1) matched, other.default.t", + 1, + ), + ( + "local_lateral_in_correlated_subquery", + "SELECT COUNT(*) AS n FROM other.default.t AS outer_t WHERE EXISTS ( + SELECT 1 FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN LATERAL (SELECT 1 AS id WHERE t.id = 5) matched + CROSS JOIN other.default.t WHERE outer_t.id = 5 + )", + 0, + ), + ] { + ctx.sql(&format!("CREATE TABLE {target} AS {query}")) + .await + .unwrap_or_else(|error| panic!("{query}: {error}")); + let batches = ctx + .sql(&format!("SELECT n FROM {target}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(total_rows(&batches), 1, "{query}"); + let value = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + assert_eq!(value, expected, "{query}"); + } + + for sql in [ + "SELECT t.id FROM t VERSION AS OF 1 CROSS JOIN t VERSION AS OF 2", + "SELECT t.id FROM t VERSION AS OF 1 CROSS JOIN paimon.default.t VERSION AS OF 2", + "SELECT paimon.default.t.id FROM t VERSION AS OF 1 + CROSS JOIN paimon.default.t VERSION AS OF 2", + "SELECT default.t.id FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN default.t VERSION AS OF 2", + "SELECT COUNT(*) FROM t VERSION AS OF 1 + RIGHT ANTI JOIN t VERSION AS OF 2 ON t.id = t.id", + "CREATE TABLE ambiguous_snapshots AS + SELECT t.id FROM t VERSION AS OF 1 CROSS JOIN paimon.default.t VERSION AS OF 2", + "SELECT paimon.default.t.* FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN paimon.default.t VERSION AS OF 2", + "SELECT COUNT(*) FROM paimon.default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 WHERE default.t.id = 5", + "SELECT COUNT(*) FROM default.t VERSION AS OF 1 + CROSS JOIN other.default.t VERSION AS OF 1 WHERE default.t.id = 5", + ] { + let Err(error) = ctx.sql(sql).await else { + panic!("Unexpectedly planned {sql}"); + }; + let error = error.to_string(); + assert!(error.contains("Ambiguous snapshot qualifier"), "{error}"); + } + assert!(!warehouse + .path() + .join("default.db/ambiguous_snapshots/schema/schema-0") + .exists()); + + for (target, inputs) in [ + ( + "correlated_lateral_live", + "(SELECT id FROM paimon.default.t WHERE id <= 3) AS t CROSS JOIN other.default.t", + ), + ( + "correlated_lateral_snapshots", + "paimon.default.t VERSION AS OF 1 CROSS JOIN other.default.t VERSION AS OF 1", + ), + ] { + let sql = format!( + "CREATE TABLE {target} AS SELECT COUNT(*) AS n FROM other.default.t AS t WHERE EXISTS ( + SELECT 1 FROM (SELECT 1 AS id) seed + CROSS JOIN LATERAL (SELECT 1 AS id WHERE t.id = 5) matched + CROSS JOIN {inputs} + )" + ); + let error = ctx.sql(&sql).await.unwrap_err().to_string(); + assert!( + error.contains("LATERAL source referencing enclosing query column 't.id'"), + "{sql}: {error}" + ); + assert!(!warehouse + .path() + .join(format!("default.db/{target}")) + .exists()); + } + + ctx.sql( + "CREATE TABLE IF NOT EXISTS t AS + SELECT t.id FROM t VERSION AS OF 1 CROSS JOIN t VERSION AS OF 2", + ) + .await + .unwrap(); +} + #[tokio::test] async fn test_version_as_of_java_watermark_prefix() { let temp_dir = TempDir::new().expect("Failed to create temp dir"); diff --git a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv index 072862f1f..905f74725 100644 --- a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv +++ b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv @@ -13,17 +13,17 @@ approx@0.5.1 X arc-swap@1.9.2 X X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-compression@0.4.42 X X async-stream@0.3.6 X @@ -260,7 +260,7 @@ paimon-ftindex-core@0.2.0 X paimon-mosaic-core@0.3.0 X paimon-rest-server@0.6.0 X paimon-vindex-core@0.6.0 X -parquet@59.3.2 X +parquet@59.3.3 X paste@1.0.15 X X percent-encoding@2.3.2 X X phf@0.12.1 X diff --git a/crates/paimon/Cargo.toml b/crates/paimon/Cargo.toml index c15cbbf12..8c4546b6a 100644 --- a/crates/paimon/Cargo.toml +++ b/crates/paimon/Cargo.toml @@ -55,11 +55,13 @@ storage-oss = [ "dep:opendal-http-transport-reqwest", "dep:opendal-layer-retry", "dep:opendal-service-oss", + "dep:reqwest-opendal", ] storage-s3 = [ "dep:opendal-http-transport-reqwest", "dep:opendal-service-s3", "dep:opendal-layer-retry", + "dep:reqwest-opendal", ] storage-cos = ["dep:opendal-http-transport-reqwest", "dep:opendal-service-cos"] storage-azdls = [ @@ -67,7 +69,11 @@ storage-azdls = [ "dep:opendal-service-azdls", ] storage-obs = ["dep:opendal-http-transport-reqwest", "dep:opendal-service-obs"] -storage-gcs = ["dep:opendal-http-transport-reqwest", "dep:opendal-service-gcs"] +storage-gcs = [ + "dep:opendal-http-transport-reqwest", + "dep:opendal-service-gcs", + "dep:reqwest-opendal", +] storage-hdfs = ["dep:opendal-service-hdfs-native"] storage-jindo = ["storage-oss"] storage-oss-cpp = ["storage-oss"] @@ -145,6 +151,7 @@ parquet = { workspace = true, features = ["async", "zstd", "lz4", "snap"] } orc-rust = "0.9.0" async-stream = "0.3.6" reqwest = { version = "0.12", features = ["json", "gzip", "deflate"] } +reqwest-opendal = { package = "reqwest", version = "0.13.4", default-features = false, optional = true } # Already in the tree via `reqwest`; direct dep for the object storage User-Agent transport. http = "1" # DLF authentication dependencies diff --git a/crates/paimon/DEPENDENCIES.rust.tsv b/crates/paimon/DEPENDENCIES.rust.tsv index e2c4570f1..9bccf39cd 100644 --- a/crates/paimon/DEPENDENCIES.rust.tsv +++ b/crates/paimon/DEPENDENCIES.rust.tsv @@ -17,17 +17,17 @@ arc-swap@1.9.2 X X arcref@0.2.0 X arrow@59.3.2 X arrow-arith@59.3.2 X -arrow-array@59.3.2 X X -arrow-buffer@59.3.2 X +arrow-array@59.3.3 X X +arrow-buffer@59.3.3 X arrow-cast@59.3.2 X arrow-csv@59.3.2 X -arrow-data@59.3.2 X -arrow-ipc@59.3.2 X +arrow-data@59.3.3 X +arrow-ipc@59.3.3 X arrow-json@59.3.2 X arrow-ord@59.3.2 X arrow-row@59.3.2 X -arrow-schema@59.3.2 X -arrow-select@59.3.2 X +arrow-schema@59.3.3 X +arrow-select@59.3.3 X arrow-string@59.3.2 X async-channel@2.5.0 X X async-compression@0.4.42 X X @@ -350,7 +350,7 @@ paimon-vindex-core@0.6.0 X parking@2.2.1 X X parking_lot@0.12.5 X X parking_lot_core@0.9.12 X X -parquet@59.3.2 X +parquet@59.3.3 X parquet-variant@59.3.2 X parquet-variant-compute@59.3.2 X parquet-variant-json@59.3.2 X diff --git a/crates/paimon/src/api/rest_api.rs b/crates/paimon/src/api/rest_api.rs index 9b8ae2ebe..c78861488 100644 --- a/crates/paimon/src/api/rest_api.rs +++ b/crates/paimon/src/api/rest_api.rs @@ -382,7 +382,7 @@ impl RESTApi { identifier: &Identifier, schema: Schema, ) -> Result { - validate_non_empty_multi(&[ + validate_resource_path(&[ (identifier.database(), "database name"), (identifier.object(), "table name"), ])?; @@ -398,6 +398,16 @@ impl RESTApi { Ok(()) } + pub(crate) async fn create_table_exclusive( + &self, + identifier: &Identifier, + schema: Schema, + ) -> Result<()> { + let request = Self::prepare_create_table(identifier, schema)?; + let path = self.resource_paths.tables(Some(identifier.database())); + self.client.post_for_exclusive_create(&path, &request).await + } + /// Alter a table's schema by applying a list of schema changes. pub async fn alter_table( &self, @@ -415,11 +425,23 @@ impl RESTApi { /// Get table information. pub async fn get_table(&self, identifier: &Identifier) -> Result { + let path = self.table_metadata_path(identifier)?; + self.client.get(&path, None::<&[(&str, &str)]>).await + } + + pub(crate) async fn get_table_for_existence_check( + &self, + identifier: &Identifier, + ) -> Result { + let path = self.table_metadata_path(identifier)?; + self.client.get_with_confirmed_not_found(&path).await + } + + fn table_metadata_path(&self, identifier: &Identifier) -> Result { let database = identifier.database(); let table = identifier.object(); - validate_non_empty_multi(&[(database, "database name"), (table, "table name")])?; - let path = self.resource_paths.table(database, table); - self.client.get(&path, None::<&[(&str, &str)]>).await + validate_resource_path(&[(database, "database name"), (table, "table name")])?; + Ok(self.resource_paths.table(database, table)) } /// Load the latest snapshot and statistics from the catalog. diff --git a/crates/paimon/src/api/rest_client.rs b/crates/paimon/src/api/rest_client.rs index 6968a36fd..32b6ed9ee 100644 --- a/crates/paimon/src/api/rest_client.rs +++ b/crates/paimon/src/api/rest_client.rs @@ -24,13 +24,17 @@ use crate::Error; use crate::Result; use rand::Rng; use reqwest::header::{HeaderMap, HeaderValue, RETRY_AFTER}; +use reqwest::StatusCode; use serde::de::DeserializeOwned; use std::collections::HashMap; use std::time::Duration; +use tokio::sync::OnceCell; /// Asynchronous HTTP client for REST API calls. pub struct HttpClient { client: reqwest::Client, + exclusive_create_client: OnceCell, + user_agent: HeaderValue, base_url: String, auth_function: Option, } @@ -58,8 +62,11 @@ impl HttpClient { auth_function: Option, agent: &str, ) -> Result { + let user_agent = Self::user_agent_header(agent); Ok(HttpClient { - client: Self::build_client(agent)?, + client: Self::build_client(&user_agent, false)?, + exclusive_create_client: OnceCell::new(), + user_agent, base_url: Self::normalize_uri(base_url)?, auth_function, }) @@ -67,26 +74,38 @@ impl HttpClient { /// Replace the default User-Agent, e.g. after options are merged with the server config. pub(crate) fn set_user_agent(&mut self, agent: &str) -> Result<()> { - self.client = Self::build_client(agent)?; + let user_agent = Self::user_agent_header(agent); + self.client = Self::build_client(&user_agent, false)?; + self.user_agent = user_agent; + self.exclusive_create_client = OnceCell::new(); Ok(()) } - fn build_client(agent: &str) -> Result { - let agent = HeaderValue::from_str(agent).unwrap_or_else(|_| { + fn user_agent_header(agent: &str) -> HeaderValue { + HeaderValue::from_str(agent).unwrap_or_else(|_| { log::warn!("Invalid REST User-Agent {agent:?}, using the default"); HeaderValue::from_str(&user_agent::default_rest_user_agent()) .expect("the default User-Agent is visible ASCII") - }); - reqwest::Client::builder() + }) + } + + fn build_client(agent: &HeaderValue, exclusive_create: bool) -> Result { + let builder = reqwest::Client::builder() // Java and PyPaimon allow three minutes for connection and response // reads. A short total deadline aborts otherwise valid REST calls. .connect_timeout(Duration::from_secs(180)) .read_timeout(Duration::from_secs(180)) - .user_agent(agent) - .build() - .map_err(|e| Error::ConfigInvalid { - message: format!("Failed to create HTTP client: {e}"), - }) + .user_agent(agent.clone()); + let builder = if exclusive_create { + builder + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + } else { + builder + }; + builder.build().map_err(|error| Error::ConfigInvalid { + message: format!("Failed to create HTTP client: {error}"), + }) } /// Normalize and validate a URI. @@ -129,6 +148,47 @@ impl HttpClient { path: &str, params: Option<&[(impl AsRef, impl AsRef)]>, ) -> Result { + self.parse_response(self.send_get(path, params).await?) + .await + } + + pub(crate) async fn get_with_confirmed_not_found( + &self, + path: &str, + ) -> Result { + let response = self.send_get(path, None::<&[(&str, &str)]>).await?; + let status = response.status(); + if status == StatusCode::NOT_FOUND + && reqwest::Url::parse(&self.request_url(path)).as_ref() != Ok(response.url()) + { + return Err(Error::UnexpectedError { + message: + "REST table lookup returned HTTP 404 from a different URL after a redirect" + .to_string(), + source: None, + }); + } + match self.parse_response(response).await { + Err(Error::RestApi { + source: RestError::NoSuchResource { message, .. }, + }) if status != StatusCode::NOT_FOUND => { + let error = super::ErrorResponse::new( + None, + None, + Some(message), + Some(i32::from(status.as_u16())), + ); + Err(RestError::from_error_response(error).into()) + } + result => result, + } + } + + async fn send_get( + &self, + path: &str, + params: Option<&[(impl AsRef, impl AsRef)]>, + ) -> Result { let url = self.request_url(path); let params_map: HashMap = match params { @@ -182,7 +242,7 @@ impl HttpClient { } }; if attempt == 5 || !matches!(response.status().as_u16(), 429 | 503) { - return self.parse_response(response).await; + return Ok(response); } let retry_after = response .headers() @@ -230,7 +290,8 @@ impl HttpClient { path: &str, body: &B, ) -> Result { - self.parse_response(self.send_post(path, body).await?).await + self.parse_response(self.send_post(&self.client, path, body).await?) + .await } /// Send a mutation whose successful response has no defined payload. @@ -239,12 +300,54 @@ impl HttpClient { path: &str, body: &B, ) -> Result<()> { - Self::response_text(self.send_post(path, body).await?).await?; + Self::response_text(self.send_post(&self.client, path, body).await?).await?; Ok(()) } + pub(crate) async fn post_for_exclusive_create( + &self, + path: &str, + body: &B, + ) -> Result<()> { + let client = self + .exclusive_create_client + .get_or_try_init(|| async { Self::build_client(&self.user_agent, true) }) + .await?; + let response = self.send_post(client, path, body).await?; + let status = response.status(); + if matches!( + status, + StatusCode::OK | StatusCode::CREATED | StatusCode::NO_CONTENT + ) { + return Ok(()); + } + let unknown_outcome = || Error::UnexpectedError { + message: format!( + "REST create returned HTTP {}. The publication outcome is unknown", + status.as_u16() + ), + source: None, + }; + if status.is_redirection() || status.is_success() { + return Err(unknown_outcome()); + } + let result = Self::response_text(response).await; + if status != StatusCode::CONFLICT + && matches!( + result, + Err(Error::RestApi { + source: RestError::AlreadyExists { .. }, + }) + ) + { + return Err(unknown_outcome()); + } + result.map(|_| ()) + } + async fn send_post( &self, + client: &reqwest::Client, path: &str, body: &B, ) -> Result { @@ -253,7 +356,7 @@ impl HttpClient { let headers = self .build_auth_headers("POST", path, body_str.as_deref(), HashMap::new()) .await?; - let request = self.client.post(&url).json(body); + let request = client.post(&url).json(body); let request = Self::apply_headers(request, &headers)?; request.send().await.map_err(|e| Error::UnexpectedError { message: "http post failed".to_string(), diff --git a/crates/paimon/src/catalog/filesystem.rs b/crates/paimon/src/catalog/filesystem.rs index 826d341bc..b2cc65d59 100644 --- a/crates/paimon/src/catalog/filesystem.rs +++ b/crates/paimon/src/catalog/filesystem.rs @@ -26,7 +26,7 @@ use crate::catalog::{Catalog, Database, Identifier, DB_LOCATION_PROP, DB_SUFFIX} use crate::common::{CatalogOptions, Options}; use crate::error::{ConfigInvalidSnafu, Error, Result}; use crate::io::cache::{create_local_cache, LocalCache}; -use crate::io::FileIO; +use crate::io::{AtomicPublication, FileIO}; use crate::spec::{ CoreOptions, Schema, Snapshot, TableSchema, TableType, INDEX_FILE_IN_DATA_FILE_DIR_OPTION, PRIMARY_KEY_NULLABLE_OPTION, TABLE_TYPE_OPTION, @@ -47,6 +47,15 @@ fn make_path(parent: &str, child: &str) -> String { format!("{parent}/{child}") } +fn serialize_table_schema(schema: &TableSchema) -> Result { + serde_json::to_vec(schema) + .map(Bytes::from) + .map_err(|error| Error::DataInvalid { + message: format!("Failed to serialize schema: {error}"), + source: Some(Box::new(error)), + }) +} + /// Filesystem catalog implementation. /// /// This catalog stores metadata on a filesystem with the following structure: @@ -259,14 +268,62 @@ impl FileSystemCatalog { self.file_io.mkdirs(&schema_dir).await?; let schema_path = self.schema_file_path(table_path, schema.id()); let output_file = self.file_io.new_output(&schema_path)?; - let content = - Bytes::from( - serde_json::to_string(schema).map_err(|e| Error::DataInvalid { - message: format!("Failed to serialize schema: {e}"), - source: Some(Box::new(e)), - })?, - ); - output_file.write(content).await?; + output_file.write(serialize_table_schema(schema)?).await + } + + async fn create_table_with_publication( + &self, + identifier: &Identifier, + creation: Schema, + ignore_if_exists: bool, + publication: AtomicPublication, + ) -> Result<()> { + identifier.validate()?; + let declared = CoreOptions::new(creation.options()).table_type()?; + + let table_path = self.table_path(identifier); + let object_schema = if declared == TableType::ObjectTable { + Some(ObjectTable::normalize_creation(&creation, &table_path)?) + } else { + None + }; + let table_exists = self.table_exists(identifier).await?; + + if !ignore_if_exists && table_exists { + return Err(Error::TableAlreadyExist { + full_name: identifier.full_name(), + }); + } + + if !self.database_exists(identifier.database()).await? { + return Err(Error::DatabaseNotExist { + database: identifier.database().to_string(), + }); + } + + if !table_exists { + creation.validate_fields_for_create()?; + // Another catalog may have dropped a table at this path with cached schema or snapshots. + self.file_io.invalidate_directory_cache(&table_path).await?; + self.file_io + .mkdirs(&self.schema_dir_path(&table_path)) + .await?; + let table_schema = TableSchema::new(0, object_schema.as_ref().unwrap_or(&creation)); + let created = self + .file_io + .publish_new_file( + &self.schema_file_path(&table_path, 0), + serialize_table_schema(&table_schema)?, + publication, + ) + .await?; + if !created && !ignore_if_exists { + return Err(Error::TableAlreadyExist { + full_name: identifier.full_name(), + }); + } + } + Ok(()) } @@ -379,6 +436,17 @@ impl Catalog for FileSystemCatalog { Ok(()) } + async fn check_table_exists(&self, identifier: &Identifier) -> Result<()> { + match self.fetch_table_schema(identifier).await { + Ok(_) => Ok(()), + Err(error @ Error::TableNotExist { .. }) => { + self.get_database(identifier.database()).await?; + Err(error) + } + Err(error) => Err(error), + } + } + async fn get_table(&self, identifier: &Identifier) -> Result
{ let (table_path, schema) = self.fetch_table_schema(identifier).await?; self.build_table(identifier, table_path, schema) @@ -440,39 +508,22 @@ impl Catalog for FileSystemCatalog { creation: Schema, ignore_if_exists: bool, ) -> Result<()> { - identifier.validate()?; - // Never persist a type nothing can load. - let declared = CoreOptions::new(creation.options()).table_type()?; - - let table_path = self.table_path(identifier); - let object_schema = if declared == TableType::ObjectTable { - Some(ObjectTable::normalize_creation(&creation, &table_path)?) - } else { - None - }; - let table_exists = self.table_exists(identifier).await?; - - if !ignore_if_exists && table_exists { - return Err(Error::TableAlreadyExist { - full_name: identifier.full_name(), - }); - } - - if !self.database_exists(identifier.database()).await? { - return Err(Error::DatabaseNotExist { - database: identifier.database().to_string(), - }); - } - - // todo: consider with lock - if !table_exists { - creation.validate_fields_for_create()?; - self.file_io.mkdirs(&table_path).await?; - let table_schema = TableSchema::new(0, object_schema.as_ref().unwrap_or(&creation)); - self.save_table_schema(&table_path, &table_schema).await?; - } + self.create_table_with_publication( + identifier, + creation, + ignore_if_exists, + AtomicPublication::IfSupported, + ) + .await + } - Ok(()) + async fn create_table_exclusive( + &self, + identifier: &Identifier, + creation: Schema, + ) -> Result<()> { + self.create_table_with_publication(identifier, creation, false, AtomicPublication::Required) + .await } async fn drop_table(&self, identifier: &Identifier, ignore_if_not_exists: bool) -> Result<()> { @@ -859,19 +910,50 @@ mod tests { FileSystemCatalog::new(options).unwrap() } - #[test] - fn test_filesystem_catalog_builds_local_cache_from_catalog_options() { - let warehouse = TempDir::new().unwrap(); + #[tokio::test] + async fn test_cached_catalog_reads_the_recreated_table_schema() { + let (warehouse, other) = create_test_catalog(); + let cache_dir = TempDir::new().unwrap(); let mut options = Options::new(); options.set( CatalogOptions::WAREHOUSE, warehouse.path().to_string_lossy(), ); options.set(CatalogOptions::LOCAL_CACHE_ENABLED, "true"); + options.set( + CatalogOptions::LOCAL_CACHE_DIR, + cache_dir.path().to_string_lossy(), + ); let catalog = FileSystemCatalog::new(options).unwrap(); - assert!(catalog.file_io().has_local_cache()); + let id = Identifier::new("db", "t"); + other + .create_database("db", false, HashMap::new()) + .await + .unwrap(); + other + .create_table(&id, testing_schema(), false) + .await + .unwrap(); + assert_eq!( + catalog.get_table(&id).await.unwrap().schema().fields()[0].name(), + "id" + ); + + other.drop_table(&id, false).await.unwrap(); + let schema = Schema::builder() + .column( + "replacement", + crate::spec::DataType::Int(crate::spec::IntType::new()), + ) + .build() + .unwrap(); + catalog.create_table_exclusive(&id, schema).await.unwrap(); + assert_eq!( + catalog.get_table(&id).await.unwrap().schema().fields()[0].name(), + "replacement" + ); } #[test] @@ -1754,6 +1836,205 @@ mod tests { ); } + #[cfg(feature = "storage-fs")] + #[tokio::test] + async fn test_table_creation_without_atomic_publication() { + use futures::TryStreamExt; + + let (temp, mut catalog) = create_test_catalog(); + let mut config = opendal_service_fs::FsConfig::default(); + config.root = Some("/".into()); + let operator = opendal::Operator::from_config(config).unwrap().layer( + opendal::layers::CapabilityOverrideLayer::new(|mut cap| { + cap.rename_with_if_not_exists = false; + cap.write_with_if_not_exists = false; + cap + }), + ); + catalog.file_io = crate::io::FileIOBuilder::new("file") + .with_fs_operator(operator) + .build() + .unwrap(); + catalog + .create_database("db", false, HashMap::new()) + .await + .unwrap(); + + let data = temp.path().join("existing"); + std::fs::create_dir(&data).unwrap(); + let batch = arrow_array::record_batch!(("id", Int32, [42])).unwrap(); + let file = std::fs::File::create(data.join("part.parquet")).unwrap(); + let mut writer = parquet::arrow::ArrowWriter::try_new(file, batch.schema(), None).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + + let identifier = Identifier::new("db", "registered"); + assert!(matches!( + catalog + .create_table_exclusive(&identifier, testing_schema()) + .await, + Err(Error::IoUnsupported { .. }) + )); + assert!(matches!( + catalog.get_table(&identifier).await, + Err(Error::TableNotExist { .. }) + )); + let schema = Schema::builder() + .column("id", DataType::Int(IntType::new())) + .option("type", "format-table") + .option("file.format", "parquet") + .option("path", data.to_str().unwrap()) + .build() + .unwrap(); + catalog + .create_table(&identifier, schema, false) + .await + .unwrap(); + catalog + .create_table(&identifier, testing_schema(), true) + .await + .unwrap(); + assert!(matches!( + catalog.create_table(&identifier, testing_schema(), false).await, + Err(Error::TableAlreadyExist { full_name }) if full_name == identifier.full_name() + )); + let table = catalog.get_table(&identifier).await.unwrap(); + let builder = table.new_read_builder(); + let plan = builder.new_scan().plan().await.unwrap(); + let batches = builder + .new_read() + .unwrap() + .to_arrow(plan.splits()) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].columns(), batch.columns()); + + assert!(matches!( + catalog.create_table_exclusive(&identifier, testing_schema()).await, + Err(Error::TableAlreadyExist { full_name }) if full_name == identifier.full_name() + )); + } + + #[tokio::test] + async fn test_create_table_propagates_a_failed_conditional_rename() { + let (_warehouse, mut catalog) = create_test_catalog(); + let operator = opendal::Operator::from_config(opendal::services::MemoryConfig::default()) + .unwrap() + .layer(opendal::layers::CapabilityOverrideLayer::new(|mut cap| { + cap.rename = true; + cap.rename_with_if_not_exists = true; + cap + })); + catalog.file_io = crate::io::FileIOBuilder::new("file") + .with_fs_operator(operator) + .build() + .unwrap(); + catalog + .create_database("db", false, HashMap::new()) + .await + .unwrap(); + let id = Identifier::new("db", "t"); + let schema_dir = catalog.schema_dir_path(&catalog.table_path(&id)); + let other_staged_schema = format!("{schema_dir}/schema-0.tmp-other"); + catalog + .file_io + .new_output(&other_staged_schema) + .unwrap() + .write(Bytes::from_static(b"other creator")) + .await + .unwrap(); + for create in [ + catalog.create_table(&id, testing_schema(), false), + catalog.create_table(&id, testing_schema(), true), + catalog.create_table_exclusive(&id, testing_schema()), + ] { + let error = create.await.unwrap_err(); + assert!( + matches!(error, Error::IoUnexpected { ref source, .. } if source.kind() == opendal::ErrorKind::Unsupported) + ); + assert!(matches!( + catalog.get_table(&id).await, + Err(Error::TableNotExist { .. }) + )); + let files = catalog.file_io.list_status(&schema_dir).await.unwrap(); + assert_eq!( + files.iter().map(|file| &file.path).collect::>(), + [&other_staged_schema] + ); + } + } + + #[tokio::test] + async fn test_create_table_atomically_rejects_a_raced_creator() { + #[derive(Debug)] + struct SharedMemoryStorage { + operator: opendal::Operator, + publication: tokio::sync::Barrier, + } + + #[async_trait] + impl crate::io::FileIOProvider for SharedMemoryStorage { + async fn create(&self, path: &str) -> Result<(opendal::Operator, String)> { + Ok(( + self.operator.clone(), + path.trim_start_matches("memory:/").into(), + )) + } + + async fn write_atomic_if_not_exists( + &self, + _path: &str, + _bytes: Bytes, + ) -> Result> { + self.publication.wait().await; + Ok(None) + } + } + + for ignore_if_exists in [false, true] { + let storage = std::sync::Arc::new(SharedMemoryStorage { + operator: + opendal::Operator::from_config(opendal::services::MemoryConfig::default()) + .unwrap(), + publication: tokio::sync::Barrier::new(2), + }); + let mut first = create_memory_catalog(); + let mut second = create_memory_catalog(); + first.file_io = first.file_io.clone().with_provider(storage.clone()); + second.file_io = second.file_io.clone().with_provider(storage); + first + .create_database("db", false, HashMap::new()) + .await + .unwrap(); + let identifier = Identifier::new("db", "raced"); + let schema = |name: &str| { + Schema::builder() + .column(name, DataType::Int(IntType::new())) + .build() + .unwrap() + }; + let (a, b) = tokio::time::timeout(std::time::Duration::from_secs(10), async { + tokio::join!( + first.create_table_exclusive(&identifier, schema("first")), + second.create_table(&identifier, schema("second"), ignore_if_exists), + ) + }) + .await + .unwrap(); + let winner = match (a, b) { + (Ok(()), Ok(())) if ignore_if_exists => "first", + (Ok(()), Err(Error::TableAlreadyExist { .. })) if !ignore_if_exists => "first", + (Err(Error::TableAlreadyExist { .. }), Ok(())) => "second", + results => panic!("unexpected creation results: {results:?}"), + }; + let table = first.get_table(&identifier).await.unwrap(); + assert_eq!(table.schema().fields()[0].name(), winner); + } + } + #[tokio::test] async fn test_create_table_rejects_an_unknown_type() { let (_temp_dir, catalog) = create_test_catalog(); diff --git a/crates/paimon/src/catalog/mod.rs b/crates/paimon/src/catalog/mod.rs index 72c936e33..e0841d349 100644 --- a/crates/paimon/src/catalog/mod.rs +++ b/crates/paimon/src/catalog/mod.rs @@ -415,6 +415,17 @@ pub trait Catalog: Send + Sync { // ======================= table methods =============================== + /// Check that a base table exists. + /// + /// The default preserves [`Catalog::load_table`] lookup behavior. Override + /// with a metadata lookup to avoid initializing table storage. + /// + /// # Errors + /// Returns [`Error::TableNotExist`] for an absent table and propagates lookup errors. + async fn check_table_exists(&self, identifier: &Identifier) -> Result<()> { + self.load_table(identifier).await.map(|_| ()) + } + /// Get table metadata for the given identifier. /// /// # Errors @@ -481,6 +492,21 @@ pub trait Catalog: Send + Sync { ignore_if_exists: bool, ) -> Result<()>; + /// Atomically create a table for immediate population. + /// + /// Return [`Error::TableAlreadyExist`] only for a definite conflict. If + /// publication may have succeeded, propagate the failure to the caller. + /// Catalogs without atomic creation return [`Error::Unsupported`]. + async fn create_table_exclusive( + &self, + _identifier: &Identifier, + _creation: Schema, + ) -> Result<()> { + Err(Error::Unsupported { + message: "This catalog does not support exclusive table creation".to_string(), + }) + } + /// Drop a table. System tables cannot be dropped. /// /// # Errors diff --git a/crates/paimon/src/catalog/rest/rest_catalog.rs b/crates/paimon/src/catalog/rest/rest_catalog.rs index 9f517fdda..929e438e9 100644 --- a/crates/paimon/src/catalog/rest/rest_catalog.rs +++ b/crates/paimon/src/catalog/rest/rest_catalog.rs @@ -29,7 +29,7 @@ use crate::api::rest_api::RESTApi; use crate::api::rest_error::RestError; use crate::api::{ DataPolicy, GetTagResponse, ListPermissionsRequest, ListPoliciesRequest, PagedList, - PermissionAssignment, PermissionResource, PolicyType, + PermissionAssignment, PermissionResource, PolicyType, ResourceType, }; use crate::catalog::{ list_partitions_from_file_system, Catalog, Database, Identifier, DB_LOCATION_PROP, @@ -279,6 +279,10 @@ impl Catalog for RESTCatalog { // ======================= table methods =============================== + async fn check_table_exists(&self, identifier: &Identifier) -> Result<()> { + RESTEnv::check_table_exists(identifier, &self.api).await + } + async fn get_table(&self, identifier: &Identifier) -> Result
{ RESTEnv::load_table( identifier, @@ -370,12 +374,23 @@ impl Catalog for RESTCatalog { .api .send_create_table(&request) .await - .map_err(|e| map_rest_error_for_table(e, identifier)); + .map_err(|e| map_table_metadata_error(e, identifier, ResourceType::Database)); ignore_error_if(result, |e| { ignore_if_exists && matches!(e, Error::TableAlreadyExist { .. }) }) } + async fn create_table_exclusive( + &self, + identifier: &Identifier, + creation: Schema, + ) -> Result<()> { + self.api + .create_table_exclusive(identifier, creation) + .await + .map_err(|error| map_table_metadata_error(error, identifier, ResourceType::Database)) + } + async fn drop_table(&self, identifier: &Identifier, ignore_if_not_exists: bool) -> Result<()> { let result = self .api @@ -940,6 +955,57 @@ fn map_rest_error_for_table(err: Error, identifier: &Identifier) -> Error { } } +/// Default an untyped 404 to a missing table on GET or a missing database on CREATE. +pub(crate) fn map_table_metadata_error( + error: Error, + identifier: &Identifier, + missing_resource: ResourceType, +) -> Error { + let (resource, resource_name) = match &error { + Error::RestApi { + source: + RestError::NoSuchResource { + resource_type, + resource_name, + .. + }, + } => ( + resource_type + .as_deref() + .unwrap_or(missing_resource.as_str()), + resource_name.as_deref(), + ), + Error::RestApi { + source: + RestError::AlreadyExists { + resource_type, + resource_name, + .. + }, + } => ( + resource_type.as_deref().unwrap_or("table"), + resource_name.as_deref(), + ), + _ => return error, + }; + if resource.eq_ignore_ascii_case("table") + && resource_name.is_some_and(|name| { + !name.is_empty() + && !name.eq_ignore_ascii_case(identifier.object()) + && !name.eq_ignore_ascii_case(&identifier.full_name()) + }) + { + return error; + } + if resource.eq_ignore_ascii_case("database") { + map_rest_error_for_database(error, identifier.database()) + } else if resource.eq_ignore_ascii_case("table") || resource.eq_ignore_ascii_case("column") { + map_rest_error_for_table(error, identifier) + } else { + error + } +} + fn map_table_not_exist(error: Error, identifier: &Identifier) -> Error { match error { Error::RestApi { @@ -1477,7 +1543,7 @@ mod tests { } #[test] - fn test_column_error_mapping() { + fn test_table_error_mapping_preserves_the_resource_type() { let identifier = Identifier::new("db", "table"); let not_exist = Error::RestApi { @@ -1510,9 +1576,7 @@ mod tests { other => panic!("expected ColumnAlreadyExist, got {other:?}"), } - // A table-level 404 (no `column` resource type) must still map to - // `TableNotExist`, not a column error. - let table_missing = Error::RestApi { + let untyped_missing = || Error::RestApi { source: RestError::NoSuchResource { resource_type: None, resource_name: None, @@ -1520,8 +1584,25 @@ mod tests { }, }; assert!(matches!( - map_rest_error_for_table(table_missing, &identifier), - Error::TableNotExist { .. } + map_table_metadata_error(untyped_missing(), &identifier, ResourceType::Table), + Error::TableNotExist { full_name } if full_name == identifier.full_name() + )); + assert!(matches!( + map_table_metadata_error(untyped_missing(), &identifier, ResourceType::Database), + Error::DatabaseNotExist { database } if database == identifier.database() + )); + let policy_conflict = Error::RestApi { + source: RestError::AlreadyExists { + resource_type: Some("POLICY".into()), + resource_name: Some("readers".into()), + message: "policy already exists".into(), + }, + }; + assert!(matches!( + map_table_metadata_error(policy_conflict, &identifier, ResourceType::Database), + Error::RestApi { + source: RestError::AlreadyExists { .. } + } )); } } diff --git a/crates/paimon/src/io/file_io.rs b/crates/paimon/src/io/file_io.rs index 9a717d16a..0c196d377 100644 --- a/crates/paimon/src/io/file_io.rs +++ b/crates/paimon/src/io/file_io.rs @@ -19,6 +19,7 @@ use crate::common::options::{parse_memory_size, CatalogOptions}; use crate::error::*; use lru::LruCache; use std::any::Any; +use std::cell::Cell; use std::collections::HashMap; use std::future::Future; use std::num::NonZeroUsize; @@ -32,6 +33,7 @@ use bytes::Bytes; use chrono::{DateTime, Utc}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; +use http::StatusCode; use opendal::raw::{new_std_io_error, normalize_path, normalize_root}; use opendal::Operator; use sha2::{Digest, Sha256}; @@ -93,6 +95,8 @@ pub trait FileIOProvider: std::fmt::Debug + Send + Sync + 'static { /// Return `None` only if no publication was attempted; FileIO then uses the /// resolved operator's safe publication primitives. An error may have an /// unknown outcome and is propagated without falling back to another write. + /// If that operator's retry layer hides earlier attempts, a persistent + /// conflict also has an unknown outcome. async fn write_atomic_if_not_exists( &self, _path: &str, @@ -118,6 +122,73 @@ enum FileIOBackend { Provider(Arc), } +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum AtomicPublication { + Required, + /// Allow a plain write when conditional publication is definitively unsupported. + IfSupported, +} + +#[derive(Clone, Copy, Default)] +struct PublicationAttempt { + replayed: bool, + response_status: Option, +} + +tokio::task_local! { + static PUBLICATION_ATTEMPT: Cell; +} + +#[cfg(all(test, feature = "storage-fs"))] +tokio::task_local! { + static TEST_LOCAL_PERSIST: fn(tempfile::NamedTempFile, &std::path::Path) -> std::io::Result<()>; +} + +#[cfg(any( + feature = "storage-s3", + feature = "storage-oss", + feature = "storage-gcs" +))] +pub(super) fn is_conditional_publication() -> bool { + PUBLICATION_ATTEMPT.try_with(|_| ()).is_ok() +} + +#[cfg(any( + feature = "storage-s3", + feature = "storage-oss", + feature = "storage-gcs" +))] +pub(super) fn record_publication_replay() { + let _ = PUBLICATION_ATTEMPT.try_with(|state| { + state.update(|mut attempt| { + attempt.replayed = true; + attempt + }); + }); +} + +#[cfg(any( + feature = "storage-s3", + feature = "storage-oss", + feature = "storage-gcs" +))] +pub(super) fn record_publication_status(status: StatusCode) { + let _ = PUBLICATION_ATTEMPT.try_with(|state| { + state.update(|mut attempt| { + attempt.response_status = Some(status); + attempt + }); + }); +} + +#[cfg(any(feature = "storage-s3", feature = "storage-oss"))] +pub(super) fn observe_retry(event: opendal_layer_retry::RetryEvent<'_>) { + use opendal_layer_retry::{DefaultRetryInterceptor, RetryInterceptor}; + + record_publication_replay(); + DefaultRetryInterceptor.intercept(event); +} + #[derive(Clone)] pub struct FileIO { backend: FileIOBackend, @@ -874,6 +945,10 @@ impl FileIO { self.file_format_metadata_cache .invalidate_row_sidecar_size(cache_path); } + self.invalidate_cached_blocks(path, cache_path).await + } + + async fn invalidate_cached_blocks(&self, path: &str, cache_path: Option) -> Result<()> { if let (Some(cache), Some(cache_path)) = ( self.cache.as_ref().filter(|cache| cache.is_cacheable(path)), cache_path, @@ -903,14 +978,31 @@ impl FileIO { format!("Failed to delete directory '{path}'"), ) })?; - if let Some(ref cache_path) = cache_path { + self.invalidate_cached_prefix(cache_path.as_deref()).await + } + + pub(crate) async fn invalidate_directory_cache(&self, path: &str) -> Result<()> { + if self.cache.is_none() + && self + .file_format_metadata_cache + .row_sidecar_sizes + .get() + .is_none() + { + return Ok(()); + } + let (_, _, cache_path) = self.create_with_cache_path(path).await?; + self.invalidate_cached_prefix(cache_path.as_deref()).await + } + + async fn invalidate_cached_prefix(&self, cache_path: Option<&str>) -> Result<()> { + if let Some(cache_path) = cache_path { self.file_format_metadata_cache .invalidate_row_sidecar_prefix(cache_path); + if let Some(cache) = &self.cache { + cache.invalidate_prefix(cache_path).await?; + } } - if let (Some(cache), Some(cache_path)) = (&self.cache, cache_path) { - cache.invalidate_prefix(&cache_path).await?; - } - Ok(()) } @@ -948,6 +1040,16 @@ impl FileIO { &self, path: &str, bytes: Bytes, + ) -> Result { + self.publish_new_file(path, bytes, AtomicPublication::Required) + .await + } + + pub(crate) async fn publish_new_file( + &self, + path: &str, + bytes: Bytes, + publication: AtomicPublication, ) -> Result { if let FileIOBackend::Provider(provider) = &self.backend { if let Some(published) = provider @@ -958,89 +1060,168 @@ impl FileIO { } } let source = self.file_source(path)?; - let (op, relative_path, _) = source.resolve(path).await?; + let (op, relative_path, cache_path) = source.resolve(path).await?; #[cfg(feature = "storage-fs")] if matches!(source, FileSource::Static { local_fs: true, .. }) { - return Self::write_local_atomic_if_not_exists(path, &op, &relative_path, bytes).await; + if let Some(published) = + Self::publish_local_file(path, &op, &relative_path, bytes.clone(), publication) + .await? + { + return Ok(published); + } } let info = op.info(); let capability = info.capability(); - let result = if capability.rename_with_if_not_exists { + if capability.rename_with_if_not_exists { let staging_path = format!("{relative_path}.tmp-{}", uuid::Uuid::new_v4()); - op.write(&staging_path, bytes).await?; - let result = op - .rename_with(&staging_path, &relative_path) - .if_not_exists(true) - .await; - if result.as_ref().is_err_and(|error| { - matches!( - error.kind(), - opendal::ErrorKind::AlreadyExists | opendal::ErrorKind::ConditionNotMatch + let discard_staging = || async { + if let Err(error) = op.delete(&staging_path).await { + log::warn!( + "Failed to delete staging file '{staging_path}' for '{path}': {error}" + ); + } + }; + if let Err(error) = op.write(&staging_path, bytes).await { + discard_staging().await; + return Err(Error::from_opendal_with_context( + error, + format!("Failed to stage '{path}'"), + )); + } + let result = self + .conditional_publication( + path, + op.rename_with(&staging_path, &relative_path) + .if_not_exists(true), ) - }) { - let _ = op.delete(&staging_path).await; + .await; + if !matches!(result, Ok(true)) { + discard_staging().await; } - result - } else if capability.write_with_if_not_exists + return result; + } + if capability.write_with_if_not_exists // Only known whole-object publishers are safe here: position // writers can expose incomplete files, and COS ignores conditional // puts on buckets that have ever enabled versioning. OSS requires // the bucket's default, never-enabled versioning configuration. && matches!(info.scheme(), "memory" | "s3" | "oss" | "gcs") { - op.write_with(&relative_path, bytes) - .if_not_exists(true) - .await - .map(|_| ()) + let result = self + .conditional_publication( + path, + op.write_with(&relative_path, bytes.clone()) + .if_not_exists(true), + ) + .await; + if publication == AtomicPublication::Required + || !matches!(result, Err(Error::IoUnsupported { .. })) + { + return result; + } + } + if publication == AtomicPublication::IfSupported { + op.write(&relative_path, bytes).await.map_err(|error| { + Error::from_opendal_with_context(error, format!("Failed to write '{path}'")) + })?; + self.invalidate_cached_blocks(path, cache_path).await?; + Ok(true) } else { - return Err(Error::IoUnsupported { + Err(Error::IoUnsupported { message: format!( - "Storage '{}' cannot atomically publish a complete snapshot without overwriting '{path}'; use a catalog SnapshotCommit with concurrency control", + "Storage '{}' cannot atomically publish '{path}' without overwriting it. \ + Use storage or a FileIOProvider with atomic publication support. \ + For snapshots, a catalog SnapshotCommit can also coordinate publication.", info.scheme() ), + }) + } + } + + async fn conditional_publication( + &self, + path: &str, + publish: impl std::future::IntoFuture>, + ) -> Result { + let (result, attempt) = PUBLICATION_ATTEMPT + .scope(Cell::new(PublicationAttempt::default()), async { + (publish.await, PUBLICATION_ATTEMPT.with(Cell::get)) + }) + .await; + let Err(error) = result else { return Ok(true) }; + // OpenDAL's RetryLayer marks its final error persistent even on the + // first attempt. Only built-in operators install our retry observer. + let built_in = matches!(&self.backend, FileIOBackend::Storage(storage) + if !matches!(storage.as_ref(), Storage::CustomFs { .. })); + // OpenDAL can classify an error from the response body even if the status disagrees. + let status_allows_conflict = attempt.response_status.is_none_or(|status| { + matches!( + status, + StatusCode::CONFLICT | StatusCode::PRECONDITION_FAILED + ) + }); + if !attempt.replayed + && (built_in || !error.is_persistent()) + && status_allows_conflict + && matches!( + error.kind(), + opendal::ErrorKind::AlreadyExists | opendal::ErrorKind::ConditionNotMatch + ) + { + return Ok(false); + } + #[cfg(feature = "storage-s3")] + if !attempt.replayed + && built_in + && std::error::Error::source(&error).is_some_and(|source| { + source.is::() + }) + { + return Err(Error::IoUnsupported { + message: format!("S3 storage cannot atomically publish '{path}': {error}"), }); - }; - match result { - Ok(()) => Ok(true), - Err(error) - if matches!( - error.kind(), - opendal::ErrorKind::AlreadyExists | opendal::ErrorKind::ConditionNotMatch - ) => - { - Ok(false) - } - Err(error) => Err(Error::from_opendal_with_context( - error, - format!("Failed to publish '{path}'"), - )), } + Err(Error::from_opendal_with_context( + error, + format!("Failed to publish '{path}': publication outcome is unknown"), + )) } + /// Returns `None` when optional native publication is explicitly unsupported. #[cfg(feature = "storage-fs")] - async fn write_local_atomic_if_not_exists( + async fn publish_local_file( path: &str, op: &Operator, relative_path: &str, bytes: Bytes, - ) -> Result { - // OpenDAL's filesystem conditional write exposes the target before - // its contents are complete. Stage locally, then publish without - // replacing another process's snapshot. + publication: AtomicPublication, + ) -> Result> { + // OpenDAL's filesystem conditional write can expose incomplete contents. let relative = normalize_path(relative_path); if std::path::Path::new(&relative) .components() .any(|component| matches!(component, std::path::Component::ParentDir)) { return Err(Error::IoUnsupported { - message: format!("Cannot publish a snapshot through a parent path: '{path}'"), + message: format!("Cannot atomically publish '{path}' through a parent path"), }); } let target = std::path::Path::new(&op.info().root()).join(relative); - tokio::task::spawn_blocking(move || -> opendal::Result { - use std::io::Write; + let persist = |staged: tempfile::NamedTempFile, target: &std::path::Path| { + staged + .persist_noclobber(target) + .map(|_| ()) + .map_err(|error| error.error) + }; + #[cfg(test)] + let persist = TEST_LOCAL_PERSIST + .try_with(|persist| *persist) + .unwrap_or(persist); + + tokio::task::spawn_blocking(move || -> opendal::Result> { + use std::io::{ErrorKind, Write}; let parent = target.parent().ok_or_else(|| { opendal::Error::new(opendal::ErrorKind::IsADirectory, "target has no parent") @@ -1056,10 +1237,17 @@ impl FileIO { let mut staged = builder.tempfile_in(parent).map_err(new_std_io_error)?; staged.write_all(&bytes).map_err(new_std_io_error)?; staged.as_file().sync_all().map_err(new_std_io_error)?; - match staged.persist_noclobber(target) { - Ok(_) => Ok(true), - Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => Ok(false), - Err(error) => Err(new_std_io_error(error.error)), + match persist(staged, &target) { + Ok(()) => Ok(Some(true)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => Ok(Some(false)), + // Mounts can support writes while rejecting both no-replace rename and hard links. + Err(error) + if publication == AtomicPublication::IfSupported + && error.kind() == ErrorKind::Unsupported => + { + Ok(None) + } + Err(error) => Err(new_std_io_error(error)), } }) .await @@ -2025,6 +2213,16 @@ impl OutputFile { } } +#[cfg(test)] +fn local_file_path(path: &std::path::Path) -> String { + let normalized = path.to_string_lossy().replace('\\', "/"); + if normalized.starts_with('/') { + format!("file:{normalized}") + } else { + format!("file:/{normalized}") + } +} + #[cfg(test)] mod file_action_test { use std::collections::BTreeSet; @@ -2322,15 +2520,6 @@ mod file_action_test { FileIOBuilder::new("file").build().unwrap() } - fn local_file_path(path: &std::path::Path) -> String { - let normalized = path.to_string_lossy().replace('\\', "/"); - if normalized.starts_with('/') { - format!("file:{normalized}") - } else { - format!("file:/{normalized}") - } - } - async fn common_test_get_status(file_io: &FileIO, path: &str) { let output = file_io.new_output(path).unwrap(); let mut writer = output.writer().await.unwrap(); @@ -4532,20 +4721,106 @@ mod input_output_test { ); } + #[cfg(feature = "storage-fs")] + #[tokio::test] + async fn test_native_publication_unsupported_allows_only_optional_fallback() { + let directory = tempfile::tempdir().unwrap(); + let path = local_file_path(&directory.path().join("schema-0")); + let io = FileIOBuilder::new("file").build().unwrap(); + let schema = Bytes::from_static(b"table schema"); + let unsupported = |_, _: &std::path::Path| Err(std::io::ErrorKind::Unsupported.into()); + + let error = TEST_LOCAL_PERSIST + .scope( + unsupported, + io.write_atomic_if_not_exists(&path, schema.clone()), + ) + .await + .unwrap_err(); + assert!(matches!( + error, + Error::IoUnexpected { source, .. } if source.kind() == opendal::ErrorKind::Unsupported + )); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0); + + assert!(TEST_LOCAL_PERSIST + .scope( + unsupported, + io.publish_new_file(&path, schema.clone(), AtomicPublication::IfSupported), + ) + .await + .unwrap()); + assert!(!io + .publish_new_file( + &path, + Bytes::from_static(b"competing table schema"), + AtomicPublication::IfSupported, + ) + .await + .unwrap()); + let file = directory.path().join("schema-0"); + assert_eq!(std::fs::read(&file).unwrap(), schema.as_ref()); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); + } + + #[cfg(feature = "storage-fs")] + #[tokio::test] + async fn test_native_publication_propagates_uncertain_outcome() { + let directory = tempfile::tempdir().unwrap(); + let path = local_file_path(&directory.path().join("schema-0")); + let io = FileIOBuilder::new("file").build().unwrap(); + let schema = Bytes::from_static(b"table schema"); + let timed_out = |staged: tempfile::NamedTempFile, target: &std::path::Path| { + staged + .persist_noclobber(target) + .map_err(|error| error.error)?; + Err(std::io::ErrorKind::TimedOut.into()) + }; + + let error = TEST_LOCAL_PERSIST + .scope( + timed_out, + io.publish_new_file(&path, schema.clone(), AtomicPublication::IfSupported), + ) + .await + .unwrap_err(); + assert!(matches!( + error, + Error::IoUnexpected { message, .. } if message.contains("Failed to publish") + )); + assert_eq!( + std::fs::read(directory.path().join("schema-0")).unwrap(), + schema.as_ref(), + ); + } + #[cfg(feature = "storage-oss")] #[tokio::test] async fn test_atomic_publication_oss_has_one_winner() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use axum::body::Body; - use axum::http::{HeaderMap, Response, StatusCode, Uri}; + use axum::http::{header::LOCATION, HeaderMap, Response, StatusCode, Uri}; + use axum::routing::get; use axum::Router; use opendal::Configurator; let objects = Arc::new(Mutex::new(HashMap::::new())); let stored = objects.clone(); + let redirected_gets = Arc::new(AtomicUsize::new(0)); + let counted_gets = redirected_gets.clone(); // An OSS bucket with default versioning atomically enforces this header. let app = Router::new().fallback(move |uri: Uri, headers: HeaderMap, body: Bytes| { let stored = stored.clone(); async move { + if uri.path() == "/bucket/table/schema/schema-0" { + assert_eq!(headers["x-oss-forbid-overwrite"], "true"); + return Response::builder() + .status(StatusCode::SEE_OTHER) + .header(LOCATION, "/publication-status") + .body(Body::empty()) + .unwrap(); + } let mut objects = stored.lock().unwrap(); if headers.get("x-oss-forbid-overwrite").is_some_and(|value| value == "true") && objects.contains_key(uri.path()) @@ -4561,7 +4836,13 @@ mod input_output_test { .body(Body::empty()) .unwrap() } - }); + }).route("/publication-status", get(move || async move { + counted_gets.fetch_add(1, Ordering::SeqCst); + Response::builder() + .header("etag", "\"mock-etag\"") + .body(Body::empty()) + .unwrap() + })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = format!("http://{}", listener.local_addr().unwrap()); let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); @@ -4584,7 +4865,6 @@ mod input_output_test { io.write_atomic_if_not_exists(path, first.clone()), io.write_atomic_if_not_exists(path, second.clone()) ); - server.abort(); let (a, b) = (a.unwrap(), b.unwrap()); assert_ne!(a, b, "exactly one conditional OSS PUT must win"); assert_eq!( @@ -4594,5 +4874,12 @@ mod input_output_test { .get("/bucket/table/snapshot/snapshot-1"), Some(if a { &first } else { &second }) ); + let error = io + .write_atomic_if_not_exists("/table/schema/schema-0", first) + .await + .expect_err("a redirected GET cannot confirm publication"); + assert!(error.to_string().contains("outcome is unknown"), "{error}"); + assert_eq!(redirected_gets.load(Ordering::SeqCst), 0); + server.abort(); } } diff --git a/crates/paimon/src/io/file_io/fuse.rs b/crates/paimon/src/io/file_io/fuse.rs index 27c039635..de87b1705 100644 --- a/crates/paimon/src/io/file_io/fuse.rs +++ b/crates/paimon/src/io/file_io/fuse.rs @@ -43,9 +43,14 @@ impl FileIOProvider for FuseFileIO { if let Some(relative) = self.relative_path(path) { // Require the mount to implement no-replace publication. An // unsupported hard link must never fall back to copy or rename. - FileIO::write_local_atomic_if_not_exists(path, &self.mounted, relative, bytes) - .await - .map(Some) + FileIO::publish_local_file( + path, + &self.mounted, + relative, + bytes, + AtomicPublication::Required, + ) + .await } else { self.fallback .write_atomic_if_not_exists(path, bytes) diff --git a/crates/paimon/src/io/mod.rs b/crates/paimon/src/io/mod.rs index 7b3023d21..5c067ae0b 100644 --- a/crates/paimon/src/io/mod.rs +++ b/crates/paimon/src/io/mod.rs @@ -29,13 +29,12 @@ pub use storage::*; feature = "storage-cos", feature = "storage-gcs", feature = "storage-obs", - feature = "storage-oss", - feature = "storage-s3" + feature = "storage-oss" ))] fn with_http_transport(op: opendal::Operator, user_agent: &str) -> opendal::Operator { use opendal::{HttpTransporter, OperationContext}; - let transport = HttpTransporter::new(user_agent::UserAgentTransport::new(user_agent)); + let transport = HttpTransporter::new(user_agent::StorageHttpTransport::new(user_agent)); op.with_context(OperationContext::new().with_http_transport(transport)) } diff --git a/crates/paimon/src/io/storage_oss.rs b/crates/paimon/src/io/storage_oss.rs index 17b99bea7..1e63b57b2 100644 --- a/crates/paimon/src/io/storage_oss.rs +++ b/crates/paimon/src/io/storage_oss.rs @@ -140,6 +140,7 @@ pub(crate) fn oss_config_build(cfg: &OssStorageConfig, path: &str) -> Result Result Operator { + let transport = HttpTransporter::new(S3HttpTransport(StorageHttpTransport::new(user_agent))); + op.with_context(OperationContext::new().with_http_transport(transport)) +} + +#[derive(Debug, snafu::Snafu)] +#[snafu(display("S3 endpoint returned HTTP 501 for conditional PUT"))] +pub(super) struct ConditionalPutNotImplemented; + +struct S3HttpTransport(StorageHttpTransport); + +impl HttpTransport for S3HttpTransport { + async fn fetch(&self, request: Request) -> opendal::Result> { + let conditional_put = request.method() == Method::PUT + && request + .headers() + .get(IF_NONE_MATCH) + .is_some_and(|value| value == "*"); + let response = self.0.fetch(request).await?; + if conditional_put && response.status() == StatusCode::NOT_IMPLEMENTED { + return Err(opendal::Error::new( + opendal::ErrorKind::Unsupported, + "S3 conditional PUT is unsupported", + ) + .set_source(ConditionalPutNotImplemented)); + } + Ok(response) + } } #[cfg(test)] @@ -549,6 +584,248 @@ mod tests { assert_eq!(attempts.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn conditional_put_conflict_after_a_retry_has_an_unknown_outcome() { + use axum::routing::put; + use bytes::Bytes; + + let object = Arc::new(Mutex::new(None)); + let attempts = Arc::new(AtomicUsize::new(0)); + let app = Router::new().route( + "/bucket/table/schema/schema-0", + put({ + let object = object.clone(); + let attempts = attempts.clone(); + move |headers: HeaderMap, body: Bytes| { + let object = object.clone(); + let attempts = attempts.clone(); + async move { + assert_eq!(headers[header::IF_NONE_MATCH], "*"); + attempts.fetch_add(1, Ordering::SeqCst); + let mut stored = object.lock().unwrap(); + if stored.is_none() { + *stored = Some(body); + return temporary_failure(); + } + Response::builder() + .status(StatusCode::PRECONDITION_FAILED) + .body(Body::from("PreconditionFailed")) + .unwrap() + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let properties = [ + (S3_ENDPOINT, endpoint.as_str()), + (S3_REGION, "us-east-1"), + (S3_PATH_STYLE_ACCESS, "true"), + ("s3.anonymous", "true"), + (S3_RETRY_COUNT, "1"), + (S3_RETRY_INTERVAL_MILLIS, "1"), + ]; + let io = crate::io::FileIOBuilder::new("s3") + .with_props(properties) + .build() + .unwrap(); + let path = "s3://bucket/table/schema/schema-0"; + let schema = Bytes::from_static(b"schema"); + let error = io + .write_atomic_if_not_exists(path, schema.clone()) + .await + .unwrap_err(); + assert!(error.to_string().contains("outcome is unknown"), "{error}"); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + assert_eq!(object.lock().unwrap().as_ref(), Some(&schema)); + + assert!(!io + .write_atomic_if_not_exists(path, schema.clone()) + .await + .unwrap()); + assert_eq!(attempts.load(Ordering::SeqCst), 3); + + *object.lock().unwrap() = None; + let cfg = s3_config_parse(make_props(&properties)).unwrap(); + let op = Operator::new(cfg.service.into_builder().bucket("bucket")).unwrap(); + let op = with_s3_http_transport(op, &cfg.user_agent).layer( + RetryLayer::default() + .with_max_times(1) + .with_min_delay(Duration::from_millis(1)), + ); + let custom = crate::io::FileIOBuilder::new("file") + .with_fs_operator(op) + .build() + .unwrap(); + let error = custom + .write_atomic_if_not_exists("/table/schema/schema-0", schema.clone()) + .await + .unwrap_err(); + assert!(error.to_string().contains("outcome is unknown"), "{error}"); + assert_eq!(attempts.load(Ordering::SeqCst), 5); + assert_eq!(object.lock().unwrap().as_ref(), Some(&schema)); + server.abort(); + } + + #[tokio::test] + async fn create_table_falls_back_only_after_definite_s3_conditional_put_rejection() { + use axum::extract::{Path, Query}; + use axum::routing::{head, put}; + use bytes::Bytes; + + use crate::catalog::{Catalog, FileSystemCatalog, Identifier}; + use crate::common::{CatalogOptions, Options}; + use crate::spec::{DataType, IntType, Schema}; + + let writes = Arc::new(Mutex::new(Vec::<(String, bool, Bytes)>::new())); + let redirected_requests = Arc::new(AtomicUsize::new(0)); + let app = Router::new() + .route( + "/publication-status", + get({ + let redirected_requests = redirected_requests.clone(); + move || async move { + redirected_requests.fetch_add(1, Ordering::SeqCst); + StatusCode::NOT_IMPLEMENTED + } + }) + .put({ + let redirected_requests = redirected_requests.clone(); + move || async move { + redirected_requests.fetch_add(1, Ordering::SeqCst); + StatusCode::OK + } + }), + ) + .route( + "/bucket", + get(|Query(query): Query>| async move { + if query.get("prefix").is_some_and(|p| p == "warehouse/db.db/") { + "false\ + warehouse/db.db/0\ + 2026-01-01T00:00:00Z\ + " + } else { + "" + } + }), + ) + .route( + "/bucket/warehouse/db.db/:table/schema/", + put(|| async { StatusCode::OK }), + ) + .route( + "/bucket/warehouse/db.db/:table/schema/schema-0", + head(|| async { StatusCode::NOT_FOUND }).put({ + let writes = writes.clone(); + move |Path(table): Path, headers: HeaderMap, body: Bytes| { + let writes = writes.clone(); + async move { + let mut writes = writes.lock().unwrap(); + let first = !writes.iter().any(|(name, _, _)| name == &table); + let conditional = headers.contains_key(header::IF_NONE_MATCH); + writes.push((table.clone(), conditional, body)); + if !conditional { + return Response::new(Body::empty()); + } + assert_eq!(headers[header::IF_NONE_MATCH], "*"); + if table == "uncertain" && first { + return temporary_failure(); + } + if table == "mislabeled_conflict" { + return Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Body::from( + "PreconditionFailed", + )) + .unwrap(); + } + let redirect = match table.as_str() { + "redirected" => Some(StatusCode::SEE_OTHER), + "misdirected" => Some(StatusCode::TEMPORARY_REDIRECT), + _ => None, + }; + if let Some(status) = redirect { + return Response::builder() + .status(status) + .header(header::LOCATION, "/publication-status") + .body(Body::empty()) + .unwrap(); + } + Response::builder() + .status(StatusCode::NOT_IMPLEMENTED) + .body(Body::from("NotImplemented")) + .unwrap() + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut options = Options::new(); + for (key, value) in [ + (CatalogOptions::WAREHOUSE, "s3://bucket/warehouse"), + (S3_ENDPOINT, endpoint.as_str()), + (S3_REGION, "us-east-1"), + (S3_PATH_STYLE_ACCESS, "true"), + ("s3.anonymous", "true"), + (S3_RETRY_COUNT, "1"), + (S3_RETRY_INTERVAL_MILLIS, "1"), + ] { + options.set(key, value); + } + let catalog = FileSystemCatalog::new(options).unwrap(); + let schema = Schema::builder() + .column("id", DataType::Int(IntType::new())) + .build() + .unwrap(); + let id = Identifier::new("db", "plain"); + let error = catalog + .create_table_exclusive(&id, schema.clone()) + .await + .unwrap_err(); + assert!(matches!(error, Error::IoUnsupported { .. }), "{error:?}"); + catalog + .create_table(&id, schema.clone(), false) + .await + .unwrap(); + for table in ["uncertain", "redirected", "mislabeled_conflict"] { + let error = catalog + .create_table(&Identifier::new("db", table), schema.clone(), true) + .await + .unwrap_err(); + assert!(error.to_string().contains("outcome is unknown"), "{error}"); + } + let error = catalog + .create_table_exclusive(&Identifier::new("db", "misdirected"), schema) + .await + .expect_err("a successful write to a different object cannot confirm table creation"); + assert!(error.to_string().contains("outcome is unknown"), "{error}"); + + let writes = writes.lock().unwrap(); + assert_eq!( + writes + .iter() + .map(|(table, conditional, _)| (table.as_str(), *conditional)) + .collect::>(), + [ + ("plain", true), + ("plain", true), + ("plain", false), + ("uncertain", true), + ("uncertain", true), + ("redirected", true), + ("mislabeled_conflict", true), + ("misdirected", true), + ] + ); + assert_eq!(writes[1].2, writes[2].2); + assert_eq!(redirected_requests.load(Ordering::SeqCst), 0); + server.abort(); + } + #[tokio::test] async fn test_s3_retry_count_is_additional_attempts() { let attempts = Arc::new(AtomicUsize::new(0)); diff --git a/crates/paimon/src/io/user_agent.rs b/crates/paimon/src/io/user_agent.rs index 8bb21e2c8..1092f3388 100644 --- a/crates/paimon/src/io/user_agent.rs +++ b/crates/paimon/src/io/user_agent.rs @@ -25,6 +25,37 @@ use http::{Request, Response}; use opendal::{Buffer, HttpBody, HttpTransport}; use opendal_http_transport_reqwest::ReqwestTransport; +#[cfg(any( + feature = "storage-s3", + feature = "storage-oss", + feature = "storage-gcs" +))] +static PUBLICATION_TRANSPORT: std::sync::LazyLock< + std::result::Result, +> = std::sync::LazyLock::new(|| { + use http::StatusCode; + use reqwest_opendal::redirect::Policy; + + let default_policy = Policy::default(); + let policy = Policy::custom(move |attempt| { + super::file_io::record_publication_replay(); + // A redirected GET can return metadata without publishing the object. + if matches!( + attempt.status(), + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER + ) { + attempt.stop() + } else { + default_policy.redirect(attempt) + } + }); + reqwest_opendal::Client::builder() + .redirect(policy) + .retry(reqwest_opendal::retry::never()) + .build() + .map(ReqwestTransport::new) +}); + /// Replaces the default `paimon-rust/` module; shared with REST requests. pub(crate) const USER_AGENT_MODULE: &str = "user-agent.module"; @@ -106,15 +137,15 @@ fn build_user_agent(props: &HashMap, overrides: Option<[&str; 3] user_agent } -/// Sends every request through the shared reqwest client with a User-Agent, unless one is set. +/// Adds the configured User-Agent and preserves conditional publication semantics. #[derive(Clone)] -pub(crate) struct UserAgentTransport { +pub(crate) struct StorageHttpTransport { user_agent: HeaderValue, inner: ReqwestTransport, } -impl UserAgentTransport { - pub(crate) fn new(user_agent: &str) -> Self { +impl StorageHttpTransport { + pub(super) fn new(user_agent: &str) -> Self { let user_agent = HeaderValue::from_bytes(user_agent.as_bytes()).unwrap_or_else(|_| { log::warn!("Invalid object storage User-Agent {user_agent:?}, using the default"); HeaderValue::from_str(&default_user_agent()) @@ -133,9 +164,25 @@ impl UserAgentTransport { } } -impl HttpTransport for UserAgentTransport { +impl HttpTransport for StorageHttpTransport { async fn fetch(&self, mut req: Request) -> opendal::Result> { self.apply(&mut req); + #[cfg(any( + feature = "storage-s3", + feature = "storage-oss", + feature = "storage-gcs" + ))] + if !req.method().is_safe() && super::file_io::is_conditional_publication() { + let transport = PUBLICATION_TRANSPORT.as_ref().map_err(|error| { + opendal::Error::new( + opendal::ErrorKind::Unexpected, + format!("Failed to initialize the publication HTTP transport: {error}"), + ) + })?; + let response = transport.fetch(req).await?; + super::file_io::record_publication_status(response.status()); + return Ok(response); + } self.inner.fetch(req).await } } @@ -269,7 +316,7 @@ mod tests { #[test] fn test_existing_user_agent_is_kept() { - let transport = UserAgentTransport::new("paimon-rust/test"); + let transport = StorageHttpTransport::new("paimon-rust/test"); let mut req = Request::new(Buffer::new()); transport.apply(&mut req); @@ -285,7 +332,7 @@ mod tests { #[test] fn test_invalid_user_agent_falls_back_to_default() { - let transport = UserAgentTransport::new("bad\nagent"); + let transport = StorageHttpTransport::new("bad\nagent"); assert_eq!(transport.user_agent, default_user_agent().as_str()); } } diff --git a/crates/paimon/src/table/data_file_writer.rs b/crates/paimon/src/table/data_file_writer.rs index a97ebea26..8a18f3317 100644 --- a/crates/paimon/src/table/data_file_writer.rs +++ b/crates/paimon/src/table/data_file_writer.rs @@ -40,6 +40,12 @@ use std::collections::HashMap; use std::sync::Arc; use tokio::task::JoinSet; +pub(super) async fn discard_uncommitted_file(file_io: &FileIO, path: &str) { + if let Err(error) = file_io.delete_file(path).await { + log::warn!("Failed to discard uncommitted file '{path}': {error}"); + } +} + /// Low-level writer that produces Parquet data files for a single (partition, bucket). /// /// Batches are accumulated into a single `FormatFileWriter` that streams directly @@ -573,7 +579,7 @@ impl DataFileWriter { while self.in_flight_closes.join_next().await.is_some() {} for path in self.created_paths.drain(..) { if self.delete_file_upon_abort { - let _ = self.file_io.delete_file(&path).await; + discard_uncommitted_file(&self.file_io, &path).await; } } self.written_files.clear(); @@ -585,7 +591,7 @@ impl DataFileWriter { } for file in files { for path in file.collect_files(self.bucket_dir()) { - let _ = self.file_io.delete_file(&path).await; + discard_uncommitted_file(&self.file_io, &path).await; } } } diff --git a/crates/paimon/src/table/kv_data_file_writer.rs b/crates/paimon/src/table/kv_data_file_writer.rs index e8d56dbac..f0c3e755c 100644 --- a/crates/paimon/src/table/kv_data_file_writer.rs +++ b/crates/paimon/src/table/kv_data_file_writer.rs @@ -20,6 +20,7 @@ use super::data_file_index_writer::{DataFileIndexWriter, FileIndexOptions}; use super::data_file_path_factory::{DataFilePath, DataFilePathFactory}; +use super::data_file_writer::discard_uncommitted_file; use super::managed_blob_reference::ManagedBlobReferences; use crate::arrow::format::{ create_format_writer_factory, with_write_resources, FormatFileWriter, FormatWriterFactory, @@ -207,7 +208,7 @@ impl<'a> KeyValueFileOptions<'a> { let writer = match factory.create_writer(&output, self.file_compression).await { Ok(writer) => with_write_resources(writer, self.resources), Err(error) => { - let _ = self.file_io.delete_file(&location.path).await; + discard_uncommitted_file(self.file_io, &location.path).await; return Err(error); } }; @@ -418,14 +419,14 @@ impl KeyValueDataFileWriter<'_> { if let Some(writer) = self.writer.take() { let _ = writer.close().await; } - let _ = self.options.file_io.delete_file(&self.location.path).await; + discard_uncommitted_file(self.options.file_io, &self.location.path).await; if self.options.index_options.is_some() && !self.options.is_changelog { let path = format!( "{}/{}", self.location.parent(), data_file_to_file_index_file_name(&self.name) ); - let _ = self.options.file_io.delete_file(&path).await; + discard_uncommitted_file(self.options.file_io, &path).await; } } } @@ -535,7 +536,7 @@ impl<'a> KeyValueRollingWriter<'a> { } for file in self.files.drain(..) { for path in file.collect_files(self.options.paths.bucket_path()) { - let _ = self.options.file_io.delete_file(&path).await; + discard_uncommitted_file(self.options.file_io, &path).await; } } } diff --git a/crates/paimon/src/table/rest_env.rs b/crates/paimon/src/table/rest_env.rs index bec6e0a48..f8efe0715 100644 --- a/crates/paimon/src/table/rest_env.rs +++ b/crates/paimon/src/table/rest_env.rs @@ -19,9 +19,10 @@ use crate::api::rest_api::RESTApi; use crate::api::rest_error::RestError; -use crate::api::GetTableResponse; +use crate::api::{GetTableResponse, ResourceType}; use crate::catalog::{ - FusePathResolver, Identifier, RESTToken, RESTTokenFileIO, DEFAULT_MAIN_BRANCH, + map_table_metadata_error, FusePathResolver, Identifier, RESTToken, RESTTokenFileIO, + DEFAULT_MAIN_BRANCH, }; use crate::common::{CatalogOptions, Options}; use crate::error::Error; @@ -330,7 +331,15 @@ impl RESTEnv { ) -> Result { api.get_table(identifier) .await - .map_err(|e| map_rest_error_for_table(e, identifier)) + .map_err(|e| map_table_metadata_error(e, identifier, ResourceType::Table)) + } + + pub(crate) async fn check_table_exists(identifier: &Identifier, api: &RESTApi) -> Result<()> { + let response = api + .get_table_for_existence_check(identifier) + .await + .map_err(|error| map_table_metadata_error(error, identifier, ResourceType::Table))?; + response_identifier(identifier, &response).map(|_| ()) } #[allow(clippy::too_many_arguments)] diff --git a/crates/paimon/src/table/table_commit.rs b/crates/paimon/src/table/table_commit.rs index 7171b9777..0d2a669f1 100644 --- a/crates/paimon/src/table/table_commit.rs +++ b/crates/paimon/src/table/table_commit.rs @@ -1099,7 +1099,9 @@ impl TableCommit { .abort(commit_messages) .await; } - self.delete_new_files(commit_messages).await?; + for failure in self.delete_new_files(commit_messages).await? { + log::warn!("Failed to discard uncommitted file: {failure}"); + } Ok(()) } diff --git a/crates/paimon/tests/mock_server.rs b/crates/paimon/tests/mock_server.rs index 6503331bf..6b7954c2b 100644 --- a/crates/paimon/tests/mock_server.rs +++ b/crates/paimon/tests/mock_server.rs @@ -36,13 +36,14 @@ use tokio::task::JoinHandle; use paimon::api::{ AlterDatabaseRequest, AlterTableRequest, AuditRESTResponse, AuthTableQueryResponse, ConfigResponse, CreateBranchRequest, CreateFunctionRequest, CreatePartitionsRequest, - CreateTagRequest, CreateViewRequest, DataPolicy, DropPartitionsRequest, DropPolicyRequest, - ErrorResponse, GetDatabaseResponse, GetFunctionResponse, GetTableResponse, GetTagResponse, - GetViewResponse, ListBranchesResponse, ListDatabasesResponse, ListFunctionsResponse, - ListPartitionsByFilterRequest, ListPartitionsByNamesRequest, ListPartitionsResponse, - ListPermissionsResponse, ListPoliciesResponse, ListTablesResponse, ListViewsResponse, - PermissionAssignment, PermissionResource, PolicyRequest, PolicyType, RESTUtil, - RenameTableRequest, ResourcePaths, ResourceType, RevokePermissionRequest, RollbackTableRequest, + CreateTableRequest, CreateTagRequest, CreateViewRequest, DataPolicy, DropPartitionsRequest, + DropPolicyRequest, ErrorResponse, GetDatabaseResponse, GetFunctionResponse, GetTableResponse, + GetTagResponse, GetViewResponse, ListBranchesResponse, ListDatabasesResponse, + ListFunctionsResponse, ListPartitionsByFilterRequest, ListPartitionsByNamesRequest, + ListPartitionsResponse, ListPermissionsResponse, ListPoliciesResponse, ListTablesResponse, + ListViewsResponse, PermissionAssignment, PermissionResource, PolicyRequest, PolicyType, + RESTUtil, RenameTableRequest, ResourcePaths, ResourceType, RevokePermissionRequest, + RollbackTableRequest, }; use paimon::catalog::{Function, Identifier}; use paimon::spec::{CommitKind, Partition, Snapshot}; @@ -220,7 +221,7 @@ fn paginate( #[derive(Clone)] pub struct RESTServer { warehouse: String, - _data_path: String, + data_path: String, config: ConfigResponse, inner: Arc>, resource_paths: ResourcePaths, @@ -233,7 +234,7 @@ impl RESTServer { /// Create a new RESTServer with initial databases. pub fn new( warehouse: String, - _data_path: String, + data_path: String, config: ConfigResponse, initial_dbs: Vec, ) -> Self { @@ -255,7 +256,7 @@ impl RESTServer { .collect(); RESTServer { - _data_path, + data_path, config, warehouse, inner: Arc::new(Mutex::new(MockState { @@ -784,26 +785,14 @@ impl RESTServer { Extension(state): Extension>, Json(payload): Json, ) -> impl IntoResponse { - // Extract table name from payload - let table_name = payload - .get("identifier") - .and_then(|id| id.get("object")) - .and_then(|o| o.as_str()) - .map(|s| s.to_string()); - - let table_name = match table_name { - Some(name) => name, - None => { - let err = ErrorResponse::new( - None, - None, - Some("Missing table name in identifier".to_string()), - Some(400), - ); + let request = match serde_json::from_value::(payload) { + Ok(request) => request, + Err(error) => { + let err = ErrorResponse::new(None, None, Some(error.to_string()), Some(400)); return (StatusCode::BAD_REQUEST, Json(err)).into_response(); } }; - + let table_name = request.identifier.object().to_string(); let mut s = state.inner.lock().unwrap(); // Check database exists @@ -828,15 +817,15 @@ impl RESTServer { return (StatusCode::CONFLICT, Json(err)).into_response(); } - // Create table response + let path = format!("{}/{db}.db/{table_name}", state.data_path); let response = GetTableResponse::new( - Some(table_name.clone()), + Some(uuid::Uuid::new_v4().to_string()), Some(db.clone()), Some(table_name), - None, + Some(path), Some(true), - None, - None, + Some(0), + Some(request.schema), AuditRESTResponse::new(None, None, None, None, None), ); s.tables.insert(key, response); diff --git a/crates/paimon/tests/rest_catalog_test.rs b/crates/paimon/tests/rest_catalog_test.rs index 7e33ca73a..ff0cdb19b 100644 --- a/crates/paimon/tests/rest_catalog_test.rs +++ b/crates/paimon/tests/rest_catalog_test.rs @@ -1926,34 +1926,300 @@ async fn test_catalog_get_table_propagates_oss_options_in_else_branch() { #[tokio::test] async fn test_catalog_create_table() { let ctx = setup_catalog(vec!["default"]).await; - - let schema = test_schema(); let identifier = Identifier::new("default", "new_table"); - - let result = ctx.catalog.create_table(&identifier, schema, false).await; - assert!(result.is_ok(), "failed to create table: {result:?}"); - - // Verify table exists - let tables = ctx.catalog.list_tables("default").await.unwrap(); - assert!(tables.contains(&"new_table".to_string())); + ctx.catalog + .create_table(&identifier, test_schema(), false) + .await + .unwrap(); + for result in [ + ctx.catalog + .create_table(&identifier, test_schema(), false) + .await, + ctx.catalog + .create_table_exclusive(&identifier, test_schema()) + .await, + ] { + assert!(matches!( + result, + Err(paimon::Error::TableAlreadyExist { full_name }) if full_name == identifier.full_name() + )); + } + ctx.catalog + .create_table(&identifier, test_schema(), true) + .await + .unwrap(); + assert_eq!( + ctx.catalog.list_tables("default").await.unwrap(), + ["new_table"] + ); + let missing = Identifier::new("missing_db", "new_table"); + assert!(matches!( + ctx.catalog.create_table_exclusive(&missing, test_schema()).await, + Err(paimon::Error::DatabaseNotExist { database }) if database == missing.database() + )); } #[tokio::test] -async fn test_catalog_create_table_already_exists() { - let ctx = setup_catalog(vec!["default"]).await; - - // Add a table first - ctx.server.add_table("default", "existing_table"); +async fn rest_ctas_validates_target_lookup_and_creation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; - let schema = test_schema(); - let identifier = Identifier::new("default", "existing_table"); + use axum::body::{Body, Bytes}; + use axum::extract::Path; + use axum::http::Method; + use axum::response::{IntoResponse, Redirect}; + use axum::routing::{any, get, post}; + use axum::{Json, Router}; + use futures::{stream, StreamExt}; + use paimon::api::CreateTableRequest; + use serde_json::json; - // Create with ignore_if_exists=false should fail - let result = ctx.catalog.create_table(&identifier, schema, false).await; + let followed = Arc::new(AtomicUsize::new(0)); + let app = Router::new() + .route( + "/v1/config", + get(|| async { Json(ConfigResponse::new(HashMap::new())) }), + ) + .route( + "/v1/databases/default/tables", + post(|Json(request): Json| async move { + let conflict = |resource_name: &str| { + ( + StatusCode::CONFLICT, + Json(json!({ + "resourceType": "TABLE", + "resourceName": resource_name, + "code": 409, + "message": "Already exists", + })), + ) + .into_response() + }; + match request.identifier.object() { + "created" => (StatusCode::OK, "Created").into_response(), + "created_without_body" => StatusCode::NO_CONTENT.into_response(), + "created_with_pending_body" => { + let body = stream::iter([Ok::<_, std::io::Error>(Bytes::from_static( + b"Created", + ))]) + .chain(stream::pending()); + (StatusCode::CREATED, Body::from_stream(body)).into_response() + } + "bare_conflict" => StatusCode::CONFLICT.into_response(), + "qualified_conflict" => conflict("DEFAULT.Qualified_Conflict"), + "different_conflict" => conflict("other"), + "see_other" => Redirect::to("/result").into_response(), + "temporary_redirect" => Redirect::temporary("/result").into_response(), + "accepted" => (StatusCode::ACCEPTED, Json(json!(null))).into_response(), + "multi_status" => StatusCode::MULTI_STATUS.into_response(), + "unavailable" => ( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({"resourceType": "TABLE", "code": 409, "message": "Already exists"})), + ) + .into_response(), + other => panic!("unexpected create target {other}"), + } + }), + ) + .route( + "/v1/databases/default/tables/:table", + get(|Path(table): Path| async move { + let lookup_error = |status, resource_name: Option<&str>| { + ( + status, + Json(json!({ + "resourceType": "TABLE", + "resourceName": resource_name, + "code": 404, + "message": "Table lookup failed", + })), + ) + .into_response() + }; + let metadata = match table.as_str() { + "canonical.name" => json!({"database": "DEFAULT", "name": "Canonical.Name"}), + "different_table" => json!({"database": "default", "name": "other"}), + "missing_name" => json!({}), + "bare_missing" => return StatusCode::NOT_FOUND.into_response(), + "missing" => return lookup_error(StatusCode::NOT_FOUND, None), + "named_missing" => { + return lookup_error(StatusCode::NOT_FOUND, Some("DEFAULT.Named_Missing")); + } + "different_missing" => return lookup_error(StatusCode::NOT_FOUND, Some("other")), + "redirected_missing" => return Redirect::temporary("/missing").into_response(), + "denied" => return lookup_error(StatusCode::FORBIDDEN, None), + other => panic!("unexpected lookup target {other}"), + }; + Json(metadata).into_response() + }), + ) + .route("/missing", get(|| async { StatusCode::NOT_FOUND })) + .route( + "/result", + any({ + let followed = followed.clone(); + move |method: Method| async move { + followed.fetch_add(1, Ordering::SeqCst); + if method == Method::GET { + Json(json!(null)).into_response() + } else { + StatusCode::CONFLICT.into_response() + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut options = Options::new(); + options.set( + CatalogOptions::URI, + format!("http://{}", listener.local_addr().unwrap()), + ); + options.set(CatalogOptions::WAREHOUSE, "test_warehouse"); + options.set(CatalogOptions::TOKEN_PROVIDER, "bear"); + options.set(CatalogOptions::TOKEN, "test_token"); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let catalog = RESTCatalog::new(options, true).await.unwrap(); + for (identifier, field) in [ + (Identifier::new("default", "."), "table"), + (Identifier::new("default", ".."), "table"), + (Identifier::new(".", "created"), "database"), + (Identifier::new("..", "created"), "database"), + ] { + let expected = format!("{field} name must not be a dot path segment"); + for result in [ + catalog.check_table_exists(&identifier).await, + catalog + .create_table_exclusive(&identifier, test_schema()) + .await, + ] { + let error = result.unwrap_err(); + assert!( + matches!(&error, paimon::Error::ConfigInvalid { message } if *message == expected), + "{}: {error}", + identifier.full_name() + ); + } + } + catalog + .check_table_exists(&Identifier::new("default", "canonical.name")) + .await + .unwrap(); + for (table, expected) in [ + ("different_table", "does not match requested identifier"), + ("missing_name", "missing name"), + ] { + let error = catalog + .check_table_exists(&Identifier::new("default", table)) + .await + .unwrap_err(); + assert!( + matches!(error, paimon::Error::DataInvalid { ref message, .. } + if message.contains(expected)), + "{table}: {error}" + ); + } + for table in ["bare_missing", "missing", "named_missing"] { + let identifier = Identifier::new("default", table); + assert!(matches!( + catalog.check_table_exists(&identifier).await, + Err(paimon::Error::TableNotExist { full_name }) if full_name == identifier.full_name() + )); + } + let error = catalog + .check_table_exists(&Identifier::new("default", "different_missing")) + .await + .unwrap_err(); assert!( - result.is_err(), - "creating duplicate table should fail when ignore_if_exists=false" + matches!(&error, paimon::Error::RestApi { + source: paimon::api::RestError::NoSuchResource { resource_name: Some(name), .. } + } if name == "other"), + "{error}" ); + let error = catalog + .check_table_exists(&Identifier::new("default", "redirected_missing")) + .await + .unwrap_err(); + assert!( + matches!(&error, paimon::Error::UnexpectedError { message, .. } + if message.contains("HTTP 404 from a different URL")), + "{error}" + ); + let error = catalog + .check_table_exists(&Identifier::new("default", "denied")) + .await + .unwrap_err(); + assert!( + matches!( + error, + paimon::Error::RestApi { + source: paimon::api::rest_error::RestError::Forbidden { .. }, + } + ), + "{error}" + ); + for table in [ + "created", + "created_without_body", + "created_with_pending_body", + ] { + tokio::time::timeout( + Duration::from_secs(5), + catalog.create_table_exclusive(&Identifier::new("default", table), test_schema()), + ) + .await + .expect("exclusive create should complete from the HTTP status") + .unwrap(); + } + for table in ["bare_conflict", "qualified_conflict"] { + let identifier = Identifier::new("default", table); + assert!(matches!( + catalog.create_table_exclusive(&identifier, test_schema()).await, + Err(paimon::Error::TableAlreadyExist { full_name }) if full_name == identifier.full_name() + )); + } + let identifier = Identifier::new("default", "different_conflict"); + for result in [ + catalog + .create_table_exclusive(&identifier, test_schema()) + .await, + catalog.create_table(&identifier, test_schema(), true).await, + ] { + let error = result.unwrap_err(); + assert!( + matches!(&error, paimon::Error::RestApi { + source: paimon::api::RestError::AlreadyExists { resource_name: Some(name), .. } + } if name == "other"), + "{error}" + ); + } + for (table, status) in [ + ("see_other", 303), + ("temporary_redirect", 307), + ("accepted", 202), + ("multi_status", 207), + ("unavailable", 503), + ] { + let result = catalog + .create_table_exclusive(&Identifier::new("default", table), test_schema()) + .await; + let error = result.expect_err(table); + assert!( + matches!(error, paimon::Error::UnexpectedError { ref message, .. } + if message.contains(&format!("HTTP {status}")) && message.contains("outcome is unknown")), + "{table}: {error}" + ); + } + assert_eq!(followed.load(Ordering::SeqCst), 0); + catalog + .create_table( + &Identifier::new("default", "see_other"), + test_schema(), + false, + ) + .await + .unwrap(); + assert_eq!(followed.load(Ordering::SeqCst), 1); + server.abort(); } #[tokio::test] diff --git a/docs/src/sql.md b/docs/src/sql.md index 0becd44de..a179e0681 100644 --- a/docs/src/sql.md +++ b/docs/src/sql.md @@ -43,7 +43,7 @@ SQL support has two layers: - DataFusion provides the parser, query planner, optimizer, execution engine, expressions, scalar functions, aggregate functions, and window functions. SQL statements that `SQLContext` does not intercept are delegated to DataFusion. This includes the DataFusion SQL surface for `SELECT` queries, CTEs (including recursive CTEs), subqueries, joins including `LATERAL` joins, SQL lambda functions, grouping, `HAVING`, window clauses, `QUALIFY`, set operations, `ORDER BY`, `LIMIT`/`OFFSET`, `EXPLAIN`, information-schema commands such as `SHOW TABLES`, `DESCRIBE`, `COPY`, and ordinary `INSERT`. - Paimon-specific table management and row-level writes are implemented by `SQLContext`. This includes Paimon `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, `CREATE TEMPORARY TABLE`, `CREATE TEMPORARY VIEW`, REST Catalog persistent `CREATE VIEW`, `DROP VIEW`, `CREATE FUNCTION`, and `DROP FUNCTION`, `DROP TEMPORARY TABLE` / `VIEW`, `INSERT OVERWRITE ... PARTITION`, `UPDATE`, `DELETE`, `TRUNCATE TABLE`, `ALTER TABLE ... ADD PARTITION`, `ALTER TABLE ... DROP PARTITION`, `SHOW PARTITIONS`, `MSCK REPAIR TABLE`, `ANALYZE TABLE`, `CALL sys.*`, Paimon time travel, and `SET` / `RESET 'paimon.*'`. `MERGE INTO` uses DataFusion's native planner and the Paimon table provider for execution. -Not every DataFusion DDL/DML statement maps to a Paimon table operation. For Paimon catalogs, `CREATE EXTERNAL TABLE`, `LOCATION`, `CREATE MATERIALIZED VIEW`, and persistent `CREATE TABLE AS SELECT` are rejected or not implemented. Persistent `CREATE FUNCTION` is supported only for the REST Catalog SQL scalar form documented below. DataFusion `COPY` can export query results to files; it does not create or commit Paimon table files. +Not every DataFusion DDL/DML statement maps to a Paimon table operation. For Paimon catalogs, `CREATE EXTERNAL TABLE`, `LOCATION`, `CREATE MATERIALIZED VIEW`, and `CREATE OR REPLACE TABLE ... AS SELECT` are rejected or not implemented. Persistent `CREATE FUNCTION` is supported only for the REST Catalog SQL scalar form documented below. DataFusion `COPY` can export query results to files; it does not create or commit Paimon table files. For the exact delegated SQL grammar, see the [DataFusion SQL Reference](https://datafusion.apache.org/user-guide/sql/index.html). @@ -913,7 +913,88 @@ mixed-case or uppercase field when normalization is enabled. Unsupported syntax (will return an error): - `CREATE EXTERNAL TABLE` - `LOCATION` -- `CREATE TABLE AS SELECT` + +### CREATE TABLE AS SELECT + +Use a bounded, read-only query to create and populate a persistent native +Paimon table. + +```sql +CREATE TABLE paimon.my_db.query_result +PARTITIONED BY (region) +WITH ('bucket' = '-1') +AS SELECT id, region FROM source WHERE id > 10; +``` + +The analyzed query supplies column names, types and nullability, including for +empty results. Use aliases and casts to choose names and types. Geospatial +outputs retain their type, CRS and edge algorithm. + +CTAS validates table options, comments and keys as in ordinary `CREATE TABLE`. +Use one options clause (`WITH`, `TBLPROPERTIES` or `OPTIONS`) and use the +`'primary-key'` option for a keyed table. Specify partition keys with +`PARTITIONED BY` or the `'partition'` option. List unqualified output names and +quote names containing dots, as in `PARTITIONED BY ("event.day")`. +CTAS rejects explicit column declarations and unsupported modifiers such as +`OR REPLACE` and `AUTO_INCREMENT`. + +The query must produce a finite result. A `LIMIT` can bound a stream when the +query plan can stop after collecting enough rows. CTEs and set operations must +also be read-only. `TIME` output must have at most millisecond precision, +including inside nested values and dictionaries. DataFusion's +`CAST(... AS TIME)` produces nanosecond time. Cast to `VARCHAR` to retain finer +precision as text. + +The same query plan supplies the schema and the rows. Unqualified source +tables and REST catalog SQL functions resolve in the session catalog and +database at statement start. Identifier normalization follows the session +setting. Each source in a join can use `VERSION AS OF` or `TIMESTAMP AS OF`. +When a live table and an unaliased snapshot share a qualifier, that qualifier +refers to the live table, including in joins across catalogs. A qualifier that +matches only snapshots is ambiguous for a qualified column or wildcard if it +matches multiple visible scans. Struct field access still works when no matching +relation has the named column. Each `ON` clause sees both join inputs and +enclosing query scopes. A `LATERAL` source sees preceding `FROM` inputs. In an +expression subquery such as `EXISTS`, CTAS rejects `LATERAL` references to +enclosing query columns outside the join inputs because DataFusion can bind +them to an inner relation during optimization. A semi or anti join exposes +only its retained side to later joins and query clauses. Use catalog-qualified +names to distinguish tables in different catalogs and distinct aliases for +multiple snapshots of the same table. + +`IF NOT EXISTS` skips source planning and execution for an existing target, +including an external table. Filesystem and REST catalogs check target +metadata without opening its data backend. REST verifies that the metadata +identifies the requested table and requires HTTP 404 from the requested table URL +to treat it as absent. +Catalog lookup errors propagate. REST also propagates errors that name another +table during lookup or creation. +If a concurrent creator wins, `IF NOT EXISTS` skips the target and strict +creation reports a conflict. CTAS returns an error even with `IF NOT EXISTS` +if ownership is uncertain, including after a lost create response. +REST CTAS relies on the server to enforce exclusive creation. A direct HTTP +200, 201 or 204 confirms completion regardless of the response body. A redirect +or a different 2xx status leaves the outcome uncertain. + +Filesystem CTAS requires atomic, no-overwrite publication of the initial +schema. Conditional object uploads reject redirects that would turn the +upload into a metadata request. A built-in object store reports a definite +conflict only when the HTTP status and storage error agree. For OSS, use a +bucket that has never had versioning enabled. Ordinary `CREATE TABLE` can fall +back to a plain write when conditional publication is unsupported, including on +HDFS-native, writable filesystem mounts that reject atomic publication, and S3 +endpoints that reject the first conditional PUT with HTTP 501. An uncertain +outcome still returns an error. Coordinate concurrent ordinary creates of the +same name on those backends. + +**A population failure retains the created table.** Other clients can write +to it as soon as it is created. Coordinate `DROP`, `RENAME` and replacement +with active writers as for an ordinary `INSERT`. Before commit, the writer +finishes an in-progress write and attempts to remove its own uncommitted files +on failure or cancellation. After commit starts, publication continues through +caller cancellation. A commit error retains prepared files that a published +snapshot may reference. Inspect the table and snapshots before retrying an +uncertain create or commit. `IF NOT EXISTS` skips a retained table. ### Partitioned Tables