This is an automated email from the ASF dual-hosted git repository. SteNicholas pushed a commit to branch PAIMON-1379 in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
commit b7fd8ff2631392ce0127d33aef54ef74e1655b71 Author: Nicholas Jiang <[email protected]> AuthorDate: Thu Nov 12 15:37:09 2026 +0800 [datafusion] Support SQL DELETE on deduplicate primary-key tables Stream matching logical rows as DELETE records through TableWrite and the existing commit path, preserving primary keys, partition columns and configured sequence values. Return the matched-row count and skip publication when no rows match. Pin target scans and predicate self-references to one snapshot and validate the direct target provider. Apply normal primary-key merge rules to concurrent upserts. Reuse prepared files for publication retries without rescanning. Close writers and discard unprepared output on scan or staging failures. Retain prepared files on publication errors and report the table and commit user so uncertain outcomes can be investigated. Reject unsupported merge engines, table options and DELETE clauses before scanning or writing. Test deletion semantics, sequence ordering, concurrent writes and failure recovery, and document the SQL behavior. Closes #1379. --- crates/integrations/datafusion/src/delete.rs | 202 +++++++- crates/integrations/datafusion/src/delete/tests.rs | 471 +++++++++++++++++ .../datafusion/src/physical_plan/sink.rs | 5 +- .../integrations/datafusion/tests/delete_tests.rs | 26 - .../datafusion/tests/pk_delete_tests.rs | 568 +++++++++++++++++++++ crates/integrations/datafusion/tests/pk_tables.rs | 58 --- docs/src/sql.md | 29 +- 7 files changed, 1267 insertions(+), 92 deletions(-) diff --git a/crates/integrations/datafusion/src/delete.rs b/crates/integrations/datafusion/src/delete.rs index 11a14c02..adae3bc2 100644 --- a/crates/integrations/datafusion/src/delete.rs +++ b/crates/integrations/datafusion/src/delete.rs @@ -17,13 +17,24 @@ //! DELETE execution for Paimon tables. //! -//! Supports copy-on-write file rewriting for append-only tables (no PK, no deletion vectors). +//! Supports primary-key tombstones, append copy-on-write, and Data Evolution deletion vectors. +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use datafusion::arrow::array::{Int8Array, RecordBatch}; +use datafusion::arrow::datatypes::{DataType, Field, Schema}; +use datafusion::common::tree_node::Transformed; +use datafusion::datasource::{provider_as_source, source_as_provider}; use datafusion::error::{DataFusionError, Result as DFResult}; +use datafusion::logical_expr::LogicalPlan; use datafusion::prelude::{DataFrame, SessionContext}; use datafusion::sql::sqlparser::ast::{Delete, FromTable, TableFactor}; +use futures::StreamExt; -use paimon::spec::CoreOptions; +use paimon::spec::{CoreOptions, MergeEngine, RowKind, VALUE_KIND_FIELD_NAME}; use paimon::table::{CopyOnWriteMergeWriter, Table}; use crate::error::to_datafusion_error; @@ -32,7 +43,9 @@ use crate::merge_into::{ build_partition_set_from_where, extract_tracking_columns, is_delete_conflict, is_row_id_conflict, ok_result, register_cow_target_table, retry_on_conflict, }; +use crate::physical_plan::sink::to_paimon_batch; use crate::sql_context::SQLContext; +use crate::table::PaimonTableProvider; /// Execute a DELETE statement on a Paimon table. /// @@ -63,12 +76,193 @@ pub(crate) async fn execute_delete( return execute_data_evolution_delete(ctx, delete, &table, table_ref).await; } if !schema.trimmed_primary_keys().is_empty() { + return execute_primary_key_delete(ctx, delete, &table, table_ref).await; + } + + execute_cow_delete(ctx, delete, &table, table_ref).await +} + +async fn execute_primary_key_delete( + ctx: &SQLContext, + delete: &Delete, + table: &Table, + table_ref: &str, +) -> DFResult<DataFrame> { + let options = table.schema().core_options(); + if options.merge_engine().map_err(to_datafusion_error)? != MergeEngine::Deduplicate { return Err(DataFusionError::Plan( - "DELETE on primary-key tables is not yet supported".to_string(), + "DELETE on primary-key tables requires merge-engine=deduplicate".into(), + )); + } + if options.ignore_delete() { + return Err(DataFusionError::NotImplemented( + "DELETE on primary-key tables requires ignore-delete=false".into(), + )); + } + // A masked key or sequence value cannot safely identify a tombstone target. + if options.query_auth_enabled() { + return Err(DataFusionError::NotImplemented( + "DELETE on query-authorized primary-key tables is not supported".into(), + )); + } + if options.rowkind_field().is_some() { + return Err(DataFusionError::NotImplemented( + "DELETE on primary-key tables with rowkind.field is not supported".into(), + )); + } + let from = match &delete.from { + FromTable::WithFromKeyword(tables) | FromTable::WithoutKeyword(tables) => tables, + }; + if from.len() != 1 + || !from[0].joins.is_empty() + || !delete.tables.is_empty() + || delete.using.is_some() + || delete.returning.is_some() + || delete.output.is_some() + || !delete.order_by.is_empty() + || delete.limit.is_some() + || !matches!(&from[0].relation, + TableFactor::Table { + args: None, version: None, with_ordinality: false, + json_path: None, sample: None, with_hints, partitions, index_hints, .. + } if with_hints.is_empty() && partitions.is_empty() && index_hints.is_empty()) + { + return Err(DataFusionError::NotImplemented( + "Primary-key DELETE supports a single target with an optional WHERE clause".into(), )); } - execute_cow_delete(ctx, delete, &table, table_ref).await + let resources = + crate::memory::writer_resources(&ctx.ctx().task_ctx()).map_err(to_datafusion_error)?; + let write_builder = table.new_write_builder().with_resources(resources); + let commit = write_builder + .try_new_commit() + .map_err(to_datafusion_error)?; + let Some(input) = plan_primary_key_delete_input(ctx, delete, table, table_ref).await? else { + return ok_result(ctx.ctx(), 0); + }; + let mut writer = write_builder.new_write().map_err(to_datafusion_error)?; + + let staged = async { + let mut stream = input.execute_stream().await?; + let mut matched_rows = 0; + while let Some(batch) = stream.next().await { + let batch = to_paimon_batch(batch?, false)?; + matched_rows += batch.num_rows() as u64; + let schema = batch.schema(); + let mut fields = schema.fields().to_vec(); + let mut columns = batch.columns().to_vec(); + fields.push(Arc::new(Field::new( + VALUE_KIND_FIELD_NAME, + DataType::Int8, + false, + ))); + columns.push(Arc::new(Int8Array::from(vec![ + RowKind::Delete.to_value(); + batch.num_rows() + ]))); + let batch = RecordBatch::try_new( + Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())), + columns, + )?; + writer + .write_arrow_batch(&batch) + .await + .map_err(to_datafusion_error)?; + } + let messages = writer.prepare_commit().await.map_err(to_datafusion_error)?; + Ok::<_, DataFusionError>((matched_rows, messages)) + } + .await; + // Close unprepared output even on scan failure; prepared files are caller-owned. + writer.close().await; + let (matched_rows, messages) = staged?; + if !messages.is_empty() { + // Publication may have succeeded even on error. Keep prepared files for recovery. + commit.commit(messages).await.map_err(|error| { + let context = format!( + "Primary-key DELETE commit failed for table '{}' (commit_user={}, matched_rows={matched_rows}); prepared files retained", + table.identifier(), + write_builder.commit_user(), + ); + log::warn!("{context}: {error}"); + to_datafusion_error(error).context(context) + })?; + } + ok_result(ctx.ctx(), matched_rows) +} + +async fn plan_primary_key_delete_input( + ctx: &SQLContext, + delete: &Delete, + table: &Table, + table_ref: &str, +) -> DFResult<Option<DataFrame>> { + let snapshot = table + .resolve_read_snapshot() + .await + .map_err(to_datafusion_error)?; + let where_clause = delete + .selection + .as_ref() + .map(|predicate| format!(" WHERE {predicate}")) + .unwrap_or_default(); + let matched = ctx + .ctx() + .sql(&format!("SELECT * FROM {table_ref}{where_clause}")) + .await?; + let is_target = |provider: &PaimonTableProvider| { + let source = provider.table(); + source.identifier() == table.identifier() + && source.location() == table.location() + && source.branch() == table.branch() + && !source.is_time_traveled() + }; + // Validate the direct FROM source: a view can synthesize keys or hide scans. + let source = match matched.logical_plan() { + LogicalPlan::Projection(projection) => projection.input.as_ref(), + plan => plan, + }; + let source = match source { + LogicalPlan::Filter(filter) => filter.input.as_ref(), + plan => plan, + }; + let target_changed = || DataFusionError::Plan("DELETE target changed during planning".into()); + let LogicalPlan::TableScan(scan) = source else { + return Err(target_changed()); + }; + let provider = source_as_provider(&scan.source)?; + if !provider + .downcast_ref::<PaimonTableProvider>() + .is_some_and(is_target) + { + return Err(target_changed()); + } + let Some(snapshot) = snapshot else { + return Ok(None); + }; + // Self-references in predicates must use the captured target snapshot too. + let plan = matched + .into_unoptimized_plan() + .transform_up_with_subqueries(|plan| { + let LogicalPlan::TableScan(mut scan) = plan else { + return Ok(Transformed::no(plan)); + }; + let Ok(provider) = source_as_provider(&scan.source) else { + return Ok(Transformed::no(LogicalPlan::TableScan(scan))); + }; + if let Some(provider) = provider.downcast_ref::<PaimonTableProvider>() { + if is_target(provider) { + scan.source = provider_as_source(Arc::new( + provider.clone().with_pinned_snapshot(&snapshot), + )); + return Ok(Transformed::yes(LogicalPlan::TableScan(scan))); + } + } + Ok(Transformed::no(LogicalPlan::TableScan(scan))) + })? + .data; + Ok(Some(DataFrame::new(ctx.ctx().state(), plan))) } /// Execute DELETE on a data-evolution table with retry on row ID conflict. diff --git a/crates/integrations/datafusion/src/delete/tests.rs b/crates/integrations/datafusion/src/delete/tests.rs new file mode 100644 index 00000000..43d2cfd3 --- /dev/null +++ b/crates/integrations/datafusion/src/delete/tests.rs @@ -0,0 +1,471 @@ +// 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 std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Mutex; + +use bytes::Bytes; +use datafusion::arrow::array::{Int32Array, UInt64Array}; +use datafusion::arrow::datatypes::DataType as ArrowType; +use datafusion::logical_expr::{create_udf, Volatility}; +use datafusion::sql::sqlparser::{ast::Statement, dialect::GenericDialect, parser::Parser}; +use opendal::{services::Memory, Operator}; +use paimon::catalog::Identifier; +use paimon::io::{FileIOBuilder, FileIOProvider}; +use paimon::spec::{DataType as PaimonType, IntType, Schema as PaimonSchema, TableSchema}; + +#[derive(Clone, Copy, Debug)] +enum PublicationFault { + Conflict, + LostReply, + LostReplyAndReadFailure, +} + +#[derive(Debug)] +struct FaultProvider { + operator: Operator, + publication_fault: Mutex<Option<PublicationFault>>, + fail_next_data_output: AtomicBool, + fail_snapshot_access: AtomicBool, + publication_attempts: AtomicUsize, +} + +#[async_trait::async_trait] +impl FileIOProvider for FaultProvider { + async fn create(&self, path: &str) -> paimon::Result<(Operator, String)> { + let relative_path = path.strip_prefix("memory:/").unwrap(); + if path.ends_with(".parquet") + && self.fail_next_data_output.load(Ordering::SeqCst) + && !self.operator.exists(relative_path).await? + && self.fail_next_data_output.swap(false, Ordering::SeqCst) + { + return Err(opendal::Error::new( + opendal::ErrorKind::Unexpected, + "injected tombstone output failure", + ) + .into()); + } + if self.fail_snapshot_access.load(Ordering::SeqCst) && path.contains("/snapshot/") { + return Err(opendal::Error::new( + opendal::ErrorKind::Unexpected, + "injected snapshot read failure", + ) + .into()); + } + Ok((self.operator.clone(), relative_path.to_string())) + } + + async fn write_atomic_if_not_exists( + &self, + path: &str, + bytes: Bytes, + ) -> paimon::Result<Option<bool>> { + self.publication_attempts.fetch_add(1, Ordering::SeqCst); + let fault = self.publication_fault.lock().unwrap().take(); + if matches!(fault, Some(PublicationFault::Conflict)) { + return Ok(Some(false)); + } + match self + .operator + .write_with(path.strip_prefix("memory:/").unwrap(), bytes) + .if_not_exists(true) + .await + { + Ok(_) => {} + Err(error) if error.kind() == opendal::ErrorKind::AlreadyExists => { + return Ok(Some(false)) + } + Err(error) => return Err(error.into()), + } + if matches!(fault, Some(PublicationFault::LostReplyAndReadFailure)) { + self.fail_snapshot_access.store(true, Ordering::SeqCst); + } + if fault.is_some() { + return Err(opendal::Error::new( + opendal::ErrorKind::Unexpected, + "injected lost publication reply", + ) + .into()); + } + Ok(Some(true)) + } +} + +async fn setup() -> (SQLContext, Table, Arc<FaultProvider>, Arc<AtomicUsize>) { + let provider = Arc::new(FaultProvider { + operator: Operator::new(Memory::default()).unwrap(), + publication_fault: Mutex::new(None), + fail_next_data_output: AtomicBool::new(false), + fail_snapshot_access: AtomicBool::new(false), + publication_attempts: AtomicUsize::new(0), + }); + let io = FileIOBuilder::new("memory") + .with_provider(provider.clone()) + .build() + .unwrap(); + let schema = PaimonSchema::builder() + .column("id", PaimonType::Int(IntType::new())) + .column("v", PaimonType::Int(IntType::new())) + .primary_key(["id"]) + .option("bucket", "1") + .option("write-only", "true") + .option("commit.max-retries", "2") + .build() + .unwrap(); + let table = Table::new( + io.clone(), + Identifier::new("default", "target"), + "memory:/table".into(), + TableSchema::new(0, &schema), + None, + ); + io.new_output(&table.schema_manager().schema_path(0)) + .unwrap() + .write(serde_json::to_vec(table.schema()).unwrap().into()) + .await + .unwrap(); + let ctx = SQLContext::new(); + ctx.ctx() + .register_table( + "target", + Arc::new(PaimonTableProvider::try_new(table.clone()).unwrap()), + ) + .unwrap(); + ctx.ctx() + .sql("INSERT INTO target VALUES (1, 10), (2, 20)") + .await + .unwrap() + .collect() + .await + .unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + ctx.ctx().register_udf(create_udf( + "count_scan", + vec![ArrowType::Int32], + ArrowType::Int32, + Volatility::Volatile, + Arc::new(move |args| { + counted.fetch_add(1, Ordering::SeqCst); + Ok(args[0].clone()) + }), + )); + (ctx, table, provider, calls) +} + +fn parse_delete(sql: &str) -> Delete { + let Statement::Delete(delete) = Parser::parse_sql(&GenericDialect {}, sql) + .unwrap() + .pop() + .unwrap() + else { + unreachable!() + }; + delete +} + +async fn execute_counted_delete(ctx: &SQLContext, table: &Table) -> DFResult<DataFrame> { + execute_primary_key_delete( + ctx, + &parse_delete("DELETE FROM target WHERE count_scan(id) = 1"), + table, + "target", + ) + .await +} + +async fn assert_committed_delete(ctx: &SQLContext, table: &Table) { + assert_eq!( + table + .snapshot_manager() + .get_latest_snapshot_id() + .await + .unwrap(), + Some(2) + ); + let batches = ctx + .ctx() + .sql("SELECT id FROM target") + .await + .unwrap() + .collect() + .await + .unwrap(); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::<Int32Array>() + .unwrap() + .values() + .iter() + .copied() + }) + .collect::<Vec<_>>(); + assert_eq!(ids, vec![2]); +} + +#[tokio::test] +async fn target_and_self_references_read_the_captured_snapshot() { + for predicate in [ + "id IN (SELECT id FROM target WHERE v = 10)", + "v = (SELECT MIN(v) FROM target)", + "EXISTS (SELECT 1 FROM target other WHERE other.id = target.id AND other.v = 10)", + "id IN (SELECT id FROM target_view WHERE v = 10)", + ] { + let (ctx, table, _, _) = setup().await; + let view = ctx + .ctx() + .sql("SELECT * FROM target") + .await + .unwrap() + .into_view(); + ctx.ctx().register_table("target_view", view).unwrap(); + let input = plan_primary_key_delete_input( + &ctx, + &parse_delete(&format!("DELETE FROM target WHERE {predicate}")), + &table, + "target", + ) + .await + .unwrap() + .unwrap(); + ctx.ctx() + .sql("INSERT INTO target VALUES (1, 30), (3, 5)") + .await + .unwrap() + .collect() + .await + .unwrap(); + let batches = input.collect().await.unwrap(); + let rows = batches + .iter() + .flat_map(|batch| { + let ids = batch + .column(0) + .as_any() + .downcast_ref::<Int32Array>() + .unwrap(); + let values = batch + .column(1) + .as_any() + .downcast_ref::<Int32Array>() + .unwrap(); + (0..batch.num_rows()).map(move |row| (ids.value(row), values.value(row))) + }) + .collect::<Vec<_>>(); + assert_eq!(rows, vec![(1, 10)], "{predicate}"); + } +} + +#[tokio::test] +async fn failed_tombstone_staging_does_not_publish_or_leave_files() { + let (ctx, table, provider, calls) = setup().await; + let before_files = provider + .operator + .list_with("table/") + .recursive(true) + .await + .unwrap(); + let before_attempts = provider.publication_attempts.load(Ordering::SeqCst); + provider.fail_next_data_output.store(true, Ordering::SeqCst); + let error = execute_counted_delete(&ctx, &table) + .await + .expect_err("DELETE unexpectedly succeeded"); + assert!( + error + .to_string() + .contains("injected tombstone output failure"), + "{error}" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!( + provider.publication_attempts.load(Ordering::SeqCst), + before_attempts + ); + assert_eq!( + table + .snapshot_manager() + .get_latest_snapshot_id() + .await + .unwrap(), + Some(1) + ); + let after_files = provider + .operator + .list_with("table/") + .recursive(true) + .await + .unwrap(); + let paths = |entries: Vec<opendal::Entry>| { + entries + .into_iter() + .map(|entry| entry.path().to_string()) + .collect::<std::collections::BTreeSet<_>>() + }; + assert_eq!(paths(after_files), paths(before_files)); + execute_counted_delete(&ctx, &table).await.unwrap(); + assert_committed_delete(&ctx, &table).await; +} + +#[tokio::test] +async fn publication_retries_do_not_repeat_the_delete_scan() { + for fault in [PublicationFault::Conflict, PublicationFault::LostReply] { + let (ctx, table, provider, calls) = setup().await; + let before = provider.publication_attempts.load(Ordering::SeqCst); + *provider.publication_fault.lock().unwrap() = Some(fault); + let result = execute_counted_delete(&ctx, &table) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + result[0] + .column(0) + .as_any() + .downcast_ref::<UInt64Array>() + .unwrap() + .value(0), + 1 + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + let expected_attempts = if matches!(fault, PublicationFault::Conflict) { + 2 + } else { + 1 + }; + assert_eq!( + provider.publication_attempts.load(Ordering::SeqCst) - before, + expected_attempts + ); + assert_committed_delete(&ctx, &table).await; + } +} + +#[tokio::test] +async fn uncertain_publication_keeps_committed_tombstones() { + let (ctx, table, provider, calls) = setup().await; + *provider.publication_fault.lock().unwrap() = Some(PublicationFault::LostReplyAndReadFailure); + let error = execute_counted_delete(&ctx, &table) + .await + .expect_err("DELETE unexpectedly succeeded"); + let DataFusionError::Context(context, source) = error else { + panic!("expected commit failure context, got {error}"); + }; + assert!(context.contains("table 'default.target'"), "{context}"); + assert!(context.contains("matched_rows=1"), "{context}"); + assert!(context.contains("prepared files retained"), "{context}"); + assert!(source.to_string().contains("unknown"), "{source}"); + provider.fail_snapshot_access.store(false, Ordering::SeqCst); + let snapshot = table.resolve_read_snapshot().await.unwrap().unwrap(); + assert!( + context.contains(&format!("commit_user={}", snapshot.commit_user())), + "the failure must identify the published commit: {context}" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_committed_delete(&ctx, &table).await; +} + +#[tokio::test] +async fn unsupported_primary_key_delete_options_are_rejected_before_scanning() { + for (option, value, expected_error) in [ + ("query-auth.enabled", "true", "query-authorized"), + ("ignore-delete", "true", "ignore-delete"), + ("deduplicate.ignore-delete", "true", "ignore-delete"), + ("rowkind.field", "v", "rowkind.field"), + ( + "merge-engine", + "partial-update", + "requires merge-engine=deduplicate", + ), + ( + "merge-engine", + "aggregation", + "requires merge-engine=deduplicate", + ), + ( + "merge-engine", + "first-row", + "requires merge-engine=deduplicate", + ), + ] { + let (ctx, table, provider, calls) = setup().await; + let table = table.copy_with_options(std::collections::HashMap::from([( + option.into(), + value.into(), + )])); + let before = provider.publication_attempts.load(Ordering::SeqCst); + let error = execute_counted_delete(&ctx, &table) + .await + .expect_err("DELETE unexpectedly succeeded"); + assert!(error.to_string().contains(expected_error), "{error}"); + assert_eq!(calls.load(Ordering::SeqCst), 0, "{option}"); + assert_eq!( + provider.publication_attempts.load(Ordering::SeqCst), + before, + "{option}" + ); + } +} + +#[tokio::test] +async fn replaced_target_cannot_supply_delete_keys() { + let (ctx, table, provider, calls) = setup().await; + let mut replacements = Vec::new(); + for sql in [ + "SELECT CAST(1 AS INT) AS id, CAST(10 AS INT) AS v", + "SELECT CAST(id - 1 AS INT) AS id, v FROM target", + ] { + replacements.push(ctx.ctx().sql(sql).await.unwrap().into_view()); + } + let snapshot = table.resolve_read_snapshot().await.unwrap().unwrap(); + for replacement in [ + Table::new( + table.file_io().clone(), + table.identifier().clone(), + "memory:/replacement".into(), + table.schema().clone(), + None, + ), + table.copy_with_pinned_snapshot(Some(&snapshot)), + ] { + replacements.push(Arc::new(PaimonTableProvider::try_new(replacement).unwrap())); + } + let before = provider.publication_attempts.load(Ordering::SeqCst); + for replacement in replacements { + ctx.ctx().deregister_table("target").unwrap(); + ctx.ctx().register_table("target", replacement).unwrap(); + let error = execute_counted_delete(&ctx, &table) + .await + .expect_err("DELETE unexpectedly succeeded"); + assert!(error.to_string().contains("target changed"), "{error}"); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(provider.publication_attempts.load(Ordering::SeqCst), before); + assert_eq!( + table + .snapshot_manager() + .get_latest_snapshot_id() + .await + .unwrap(), + Some(1) + ); + } +} diff --git a/crates/integrations/datafusion/src/physical_plan/sink.rs b/crates/integrations/datafusion/src/physical_plan/sink.rs index 72957c5d..437e52d9 100644 --- a/crates/integrations/datafusion/src/physical_plan/sink.rs +++ b/crates/integrations/datafusion/src/physical_plan/sink.rs @@ -37,7 +37,10 @@ use paimon::table::Table; use crate::error::to_datafusion_error; -fn to_paimon_batch(batch: RecordBatch, strip_internal_row_id: bool) -> DFResult<RecordBatch> { +pub(crate) fn to_paimon_batch( + batch: RecordBatch, + strip_internal_row_id: bool, +) -> DFResult<RecordBatch> { let input_schema = batch.schema(); let row_id_index = strip_internal_row_id.then(|| { input_schema diff --git a/crates/integrations/datafusion/tests/delete_tests.rs b/crates/integrations/datafusion/tests/delete_tests.rs index aa247afb..402298e8 100644 --- a/crates/integrations/datafusion/tests/delete_tests.rs +++ b/crates/integrations/datafusion/tests/delete_tests.rs @@ -454,32 +454,6 @@ async fn test_delete_multiple_rows_from_single_commit() { // ======================= Unsupported cases ======================= -#[tokio::test] -async fn test_delete_rejects_primary_key_table() { - let (tmp, catalog) = create_test_env(); - let sql_context = create_sql_context(catalog).await; - sql_context - .sql("CREATE SCHEMA paimon.test_db") - .await - .unwrap(); - sql_context - .sql( - "CREATE TABLE paimon.test_db.pk_t (\ - id INT NOT NULL, name VARCHAR, PRIMARY KEY (id)\ - ) WITH ('bucket' = '1')", - ) - .await - .unwrap(); - - assert_sql_error( - &sql_context, - "DELETE FROM paimon.test_db.pk_t WHERE id = 1", - "DELETE on primary-key tables is not yet supported", - ) - .await; - drop(tmp); -} - #[tokio::test] async fn test_delete_rejects_data_evolution_table_without_deletion_vectors() { let (tmp, catalog) = create_test_env(); diff --git a/crates/integrations/datafusion/tests/pk_delete_tests.rs b/crates/integrations/datafusion/tests/pk_delete_tests.rs new file mode 100644 index 00000000..b18238ee --- /dev/null +++ b/crates/integrations/datafusion/tests/pk_delete_tests.rs @@ -0,0 +1,568 @@ +// 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; + +use common::{assert_sql_error, create_sql_context, create_test_env, dml_count, exec}; +use paimon::catalog::Identifier; +use paimon::{Catalog, FileSystemCatalog}; +use paimon_datafusion::SQLContext; +use std::sync::Arc; + +async fn setup(options: &str) -> (tempfile::TempDir, Arc<FileSystemCatalog>, SQLContext) { + let (tmp, catalog) = create_test_env(); + let ctx = create_sql_context(Arc::clone(&catalog)).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec( + &ctx, + &format!( + "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, PRIMARY KEY (id)) \ + WITH ('bucket' = '2', 'write-only' = 'true'{options})" + ), + ) + .await; + (tmp, catalog, ctx) +} + +async fn rows(ctx: &SQLContext) -> Vec<(i32, Option<i32>)> { + use datafusion::arrow::array::{Array, Int32Array}; + let batches = ctx + .sql("SELECT id, v FROM paimon.test_db.t") + .await + .unwrap() + .collect() + .await + .unwrap(); + let mut rows = Vec::new(); + for batch in batches { + let ids = batch + .column(0) + .as_any() + .downcast_ref::<Int32Array>() + .unwrap(); + let values = batch + .column(1) + .as_any() + .downcast_ref::<Int32Array>() + .unwrap(); + rows.extend((0..batch.num_rows()).map(|row| { + ( + ids.value(row), + values.is_valid(row).then(|| values.value(row)), + ) + })); + } + rows.sort_unstable(); + rows +} + +async fn snapshot(catalog: &FileSystemCatalog) -> Option<i64> { + catalog + .get_table(&Identifier::new("test_db", "t")) + .await + .unwrap() + .snapshot_manager() + .get_latest_snapshot_id() + .await + .unwrap() +} + +#[tokio::test] +async fn primary_key_delete_reads_latest_versions_and_counts_logical_rows() { + let (_tmp, catalog, ctx) = setup("").await; + exec( + &ctx, + "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 20), (3, NULL)", + ) + .await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 11)").await; + let before = snapshot(&catalog).await; + assert_eq!( + dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE v = 10").await, + 0 + ); + assert_eq!(snapshot(&catalog).await, before); + assert_eq!( + dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE t.v <> 11").await, + 1 + ); + assert_eq!(rows(&ctx).await, vec![(1, Some(11)), (3, None)]); + assert_eq!( + common::row_count(&ctx, "SELECT id FROM paimon.test_db.t WHERE v IS NULL").await, + 1 + ); + assert_eq!( + dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE v IS NULL").await, + 1 + ); + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 1); + assert!(rows(&ctx).await.is_empty()); + let before = snapshot(&catalog).await; + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 0); + assert_eq!(snapshot(&catalog).await, before); +} + +#[tokio::test] +async fn primary_key_delete_on_never_written_table_is_a_noop() { + let (_tmp, catalog, ctx) = setup("").await; + for sql in [ + "DELETE FROM paimon.test_db.t WHERE id = 1", + "DELETE FROM paimon.test_db.t", + ] { + assert_eq!(dml_count(&ctx, sql).await, 0); + assert_eq!(snapshot(&catalog).await, None); + } + assert_sql_error( + &ctx, + "DELETE FROM paimon.test_db.t WHERE missing_column = 1", + "missing_column", + ) + .await; + assert_eq!(snapshot(&catalog).await, None); +} + +#[tokio::test] +async fn primary_key_delete_supports_subqueries() { + let (_tmp, _catalog, ctx) = setup("").await; + exec( + &ctx, + "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 20), (3, 30)", + ) + .await; + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE id IN (SELECT id FROM paimon.test_db.t WHERE v = 20)").await, 1); + assert_eq!(rows(&ctx).await, vec![(1, Some(10)), (3, Some(30))]); + exec(&ctx, "CREATE TEMPORARY VIEW selected_ids AS SELECT 3 AS id").await; + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE EXISTS (SELECT 1 FROM selected_ids s WHERE s.id = t.id)").await, 1); + assert_eq!(rows(&ctx).await, vec![(1, Some(10))]); + assert_eq!( + dml_count( + &ctx, + "DELETE FROM paimon.test_db.t WHERE v = (SELECT MAX(v) FROM paimon.test_db.t)" + ) + .await, + 1 + ); + assert!(rows(&ctx).await.is_empty()); +} + +#[tokio::test] +async fn primary_key_delete_handles_dynamic_buckets() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec(&ctx, "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, PRIMARY KEY (id)) WITH ('bucket' = '-1', 'write-only' = 'true')").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 20)").await; + assert_eq!( + dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE id = 1").await, + 1 + ); + assert_eq!(rows(&ctx).await, vec![(2, Some(20))]); + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 30)").await; + assert_eq!(rows(&ctx).await, vec![(1, Some(30)), (2, Some(20))]); +} + +#[tokio::test] +async fn primary_key_delete_preserves_partition_and_composite_key() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec(&ctx, "CREATE TABLE paimon.test_db.t (id INT NOT NULL, name STRING NOT NULL, pt INT NOT NULL, v INT, PRIMARY KEY (id, name, pt)) PARTITIONED BY (pt) WITH ('bucket' = '2')").await; + exec( + &ctx, + "INSERT INTO paimon.test_db.t VALUES (1, 'a', 1, 10), (1, 'b', 1, 11), (1, 'a', 2, 20), (2, 'a', 1, 30)", + ) + .await; + assert_eq!( + dml_count( + &ctx, + "DELETE FROM paimon.test_db.t WHERE pt = 1 AND id = 1 AND name = 'a'" + ) + .await, + 1 + ); + assert_eq!( + rows(&ctx).await, + vec![(1, Some(11)), (1, Some(20)), (2, Some(30))] + ); +} + +#[tokio::test] +async fn primary_key_delete_preserves_sequence_fields_and_allows_later_upserts() { + for (fields, order, older, newer) in [ + ("v", "ascending", 99, 101), + ("v", "descending", 101, 99), + ("id,v", "ascending", 99, 101), + ("id,v", "descending", 101, 99), + ] { + let (_tmp, _catalog, ctx) = setup(&format!( + ", 'sequence.field' = '{fields}', 'sequence.field.sort-order' = '{order}'" + )) + .await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 100)").await; + assert_eq!( + dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE id = 1").await, + 1 + ); + exec( + &ctx, + &format!("INSERT INTO paimon.test_db.t VALUES (1, {older})"), + ) + .await; + assert!( + rows(&ctx).await.is_empty(), + "an older sequence must not resurrect the row ({fields}, {order})" + ); + exec( + &ctx, + &format!("INSERT INTO paimon.test_db.t VALUES (1, {newer})"), + ) + .await; + assert_eq!( + rows(&ctx).await, + vec![(1, Some(newer))], + "{fields}, {order}" + ); + } +} + +#[tokio::test] +async fn primary_key_delete_preserves_lexicographic_sequence_order() { + for (order, sequences) in [ + ("ascending", [(9, 99), (10, 19), (11, 0), (10, 21)]), + ("descending", [(11, 0), (10, 21), (9, 99), (10, 19)]), + ] { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec( + &ctx, + &format!( + "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, seq_major INT, seq_minor INT, PRIMARY KEY (id)) \ + WITH ('bucket' = '2', 'write-only' = 'true', 'sequence.field' = 'seq_major,seq_minor', 'sequence.field.sort-order' = '{order}')" + ), + ) + .await; + exec( + &ctx, + "INSERT INTO paimon.test_db.t VALUES (1, 10, 10, 20), (2, 20, 10, 20), (3, 30, 10, 20), (4, 40, 10, 20)", + ) + .await; + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 4); + assert!(rows(&ctx).await.is_empty(), "{order}"); + + let values = sequences + .iter() + .enumerate() + .map(|(index, (major, minor))| { + let id = index + 1; + format!("({id}, {}, {major}, {minor})", id * 10) + }) + .collect::<Vec<_>>() + .join(", "); + exec( + &ctx, + &format!("INSERT INTO paimon.test_db.t VALUES {values}"), + ) + .await; + assert_eq!( + rows(&ctx).await, + vec![(3, Some(30)), (4, Some(40))], + "only newer sequence tuples may resurrect deleted rows ({order})" + ); + } +} + +#[tokio::test] +async fn primary_key_delete_rejects_other_merge_engines() { + for engine in ["partial-update", "aggregation", "first-row"] { + let aggregation = if engine == "aggregation" { + ", 'fields.v.aggregate-function' = 'sum'" + } else { + "" + }; + let (_tmp, catalog, ctx) = + setup(&format!(", 'merge-engine' = '{engine}'{aggregation}")).await; + for (insert_rows, sql) in [ + (false, "DELETE FROM paimon.test_db.t"), + (true, "DELETE FROM paimon.test_db.t WHERE id = 1"), + ] { + if insert_rows { + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 20)").await; + } + let before = snapshot(&catalog).await; + let before_rows = rows(&ctx).await; + assert_sql_error(&ctx, sql, "requires merge-engine=deduplicate").await; + assert_eq!(snapshot(&catalog).await, before, "{engine}: {sql}"); + assert_eq!(rows(&ctx).await, before_rows, "{engine}: {sql}"); + } + } +} + +#[tokio::test] +async fn primary_key_delete_rejects_extended_syntax() { + let (_tmp, catalog, ctx) = setup("").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + let before = snapshot(&catalog).await; + for suffix in [ + "RETURNING id", + "USING paimon.test_db.t other WHERE t.id = other.id", + "ORDER BY id LIMIT 1", + "LIMIT 1", + "JOIN paimon.test_db.t other ON t.id = other.id", + ", paimon.test_db.t", + "TABLESAMPLE BERNOULLI (50)", + "OUTPUT deleted.id", + ] { + assert_sql_error( + &ctx, + &format!("DELETE FROM paimon.test_db.t {suffix}"), + "optional WHERE", + ) + .await; + assert_eq!(snapshot(&catalog).await, before, "{suffix}"); + assert_eq!(rows(&ctx).await, vec![(1, Some(10))]); + } + assert_sql_error( + &ctx, + "DELETE FROM paimon.test_db.t AS x WHERE x.id = 1", + "alias", + ) + .await; + assert_eq!(snapshot(&catalog).await, before); + assert_eq!(rows(&ctx).await, vec![(1, Some(10))]); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn primary_key_delete_pins_snapshot_and_respects_concurrent_upsert_sequence() { + use datafusion::arrow::datatypes::DataType; + use datafusion::logical_expr::{create_udf, Volatility}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + for (options, expected) in [ + ("", vec![(2, Some(10))]), + ( + ", 'sequence.field' = 'v'", + vec![(1, Some(20)), (2, Some(10))], + ), + ( + ", 'sequence.field' = 'v', 'sequence.field.sort-order' = 'descending'", + vec![(2, Some(10))], + ), + ] { + let (_tmp, _catalog, ctx) = setup(options).await; + let ctx = Arc::new(ctx); + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + let weak = Arc::downgrade(&ctx); + ctx.ctx().register_udf(create_udf( + "interfere", + vec![DataType::Int32], + DataType::Int32, + Volatility::Volatile, + Arc::new(move |args| { + if counted.fetch_add(1, Ordering::SeqCst) == 0 { + let ctx = weak.upgrade().unwrap(); + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(async { + ctx.sql("INSERT INTO paimon.test_db.t VALUES (1, 20), (2, 10)") + .await? + .collect() + .await + }) + })?; + } + Ok(args[0].clone()) + }), + )); + let sql = "DELETE FROM paimon.test_db.t WHERE interfere(v) = 10"; + assert_eq!(dml_count(&ctx, sql).await, 1); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "the statement must not re-scan" + ); + assert_eq!(rows(&ctx).await, expected); + + assert_eq!(dml_count(&ctx, sql).await, 1); + assert!( + calls.load(Ordering::SeqCst) > 1, + "re-executing DELETE must scan a new snapshot" + ); + assert_eq!( + rows(&ctx).await, + expected + .into_iter() + .filter(|(id, _)| *id != 2) + .collect::<Vec<_>>() + ); + } +} + +fn files_under(path: &std::path::Path) -> std::collections::BTreeSet<std::path::PathBuf> { + let mut files = std::collections::BTreeSet::new(); + for entry in std::fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files.extend(files_under(&path)); + } else { + files.insert(path); + } + } + files +} + +#[tokio::test] +async fn primary_key_delete_preserves_quoted_names_and_string_values() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(catalog).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec(&ctx, "CREATE TABLE paimon.test_db.\"odd.name\" (\"Key.Id\" INT NOT NULL, name STRING, PRIMARY KEY (\"Key.Id\")) WITH ('bucket' = '1')").await; + exec( + &ctx, + "INSERT INTO paimon.test_db.\"odd.name\" VALUES (1, 'delete'), (2, 'keep')", + ) + .await; + assert_eq!( + dml_count( + &ctx, + "DELETE FROM paimon.test_db.\"odd.name\" WHERE \"Key.Id\" = 1 AND name = 'delete'" + ) + .await, + 1 + ); + assert_eq!( + common::collect_id_name( + &ctx, + "SELECT \"Key.Id\" AS id, name FROM paimon.test_db.\"odd.name\"" + ) + .await, + vec![(2, "keep".into())] + ); +} + +#[tokio::test] +async fn primary_key_delete_keeps_existing_target_guards() { + let (_tmp, _catalog, ctx) = setup("").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + exec( + &ctx, + "CREATE TEMPORARY VIEW paimon.test_db.t AS SELECT 99 AS id", + ) + .await; + assert_sql_error(&ctx, "DELETE FROM paimon.test_db.t", "temporary").await; + exec(&ctx, "DROP TEMPORARY VIEW paimon.test_db.t").await; + assert_sql_error(&ctx, "DELETE FROM paimon.test_db.t$branch_dev", "branch").await; + exec(&ctx, "SET 'paimon.scan.snapshot-id' = '1'").await; + assert_sql_error(&ctx, "DELETE FROM paimon.test_db.t", "time-travel option").await; + exec(&ctx, "RESET 'paimon.scan.snapshot-id'").await; + assert_eq!(rows(&ctx).await, vec![(1, Some(10))]); +} + +#[tokio::test] +async fn primary_key_delete_rejects_rowkind_field() { + let (_tmp, catalog) = create_test_env(); + let ctx = create_sql_context(Arc::clone(&catalog)).await; + exec(&ctx, "CREATE SCHEMA paimon.test_db").await; + exec(&ctx, "CREATE TABLE paimon.test_db.t (id INT NOT NULL, kind STRING, PRIMARY KEY (id)) WITH ('bucket' = '1', 'rowkind.field' = 'kind')").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, '+I')").await; + let before = snapshot(&catalog).await; + assert_sql_error(&ctx, "DELETE FROM paimon.test_db.t", "rowkind.field").await; + assert_eq!(snapshot(&catalog).await, before); + assert_eq!( + common::row_count(&ctx, "SELECT id FROM paimon.test_db.t").await, + 1 + ); +} + +#[tokio::test] +async fn primary_key_delete_requires_delete_records_to_be_enabled() { + for option in ["ignore-delete", "deduplicate.ignore-delete"] { + let (_tmp, catalog, ctx) = setup(&format!(", '{option}' = 'true'")).await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + let before = snapshot(&catalog).await; + assert_sql_error( + &ctx, + "DELETE FROM paimon.test_db.t WHERE id = 1", + "ignore-delete", + ) + .await; + assert_eq!(snapshot(&catalog).await, before, "{option}"); + assert_eq!(rows(&ctx).await, vec![(1, Some(10))], "{option}"); + } + + let (_tmp, _catalog, ctx) = setup( + ", 'ignore-delete' = 'false', 'deduplicate.ignore-delete' = 'true', 'ignore-update-before' = 'true'", + ) + .await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 1); + assert!(rows(&ctx).await.is_empty()); +} + +#[tokio::test] +async fn primary_key_delete_discards_partial_output_when_scan_fails() { + use datafusion::arrow::datatypes::DataType; + use datafusion::error::DataFusionError; + use datafusion::logical_expr::{create_udf, Volatility}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let (tmp, catalog, ctx) = + setup(", 'read.batch-size' = '1', 'write.parquet-buffer-size' = '1'").await; + exec(&ctx, "SET datafusion.execution.target_partitions = 1").await; + exec(&ctx, "SET datafusion.execution.batch_size = 1").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await; + exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (2, 20)").await; + let before = files_under(tmp.path()); + let before_snapshot = snapshot(&catalog).await; + let root = tmp.path().to_path_buf(); + let initial_files = before.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let counted = calls.clone(); + ctx.ctx().register_udf(create_udf( + "fail_after_batch", + vec![DataType::Int32], + DataType::Int32, + Volatility::Volatile, + Arc::new(move |args| { + if counted.fetch_add(1, Ordering::SeqCst) > 0 { + assert!( + files_under(&root) + .difference(&initial_files) + .any(|path| path.extension().is_some_and(|ext| ext == "parquet")), + "the first batch must have staged a data file before the injected error" + ); + return Err(DataFusionError::Execution("injected scan failure".into())); + } + Ok(args[0].clone()) + }), + )); + assert_sql_error( + &ctx, + "DELETE FROM paimon.test_db.t WHERE fail_after_batch(id) > 0", + "injected scan failure", + ) + .await; + assert!(calls.load(Ordering::SeqCst) >= 2); + assert_eq!(snapshot(&catalog).await, before_snapshot); + assert_eq!( + files_under(tmp.path()), + before, + "uncommitted files must be removed" + ); + assert_eq!(rows(&ctx).await, vec![(1, Some(10)), (2, Some(20))]); +} diff --git a/crates/integrations/datafusion/tests/pk_tables.rs b/crates/integrations/datafusion/tests/pk_tables.rs index b06f90f5..af1d927b 100644 --- a/crates/integrations/datafusion/tests/pk_tables.rs +++ b/crates/integrations/datafusion/tests/pk_tables.rs @@ -2780,64 +2780,6 @@ async fn test_pk_aggregation_sequence_field_forced_last_value() { assert_eq!(ts.value(0), 250); // forced last_value over default sum } -/// Aggregation without ignore-retract must reject a DELETE/UPDATE row. -#[tokio::test] -async fn test_pk_aggregation_rejects_delete() { - let (_tmp, sql_context) = setup_sql_context().await; - - sql_context - .sql( - "CREATE TABLE paimon.test_db.t_agg_del ( - id INT NOT NULL, amount INT, - PRIMARY KEY (id) - ) WITH ( - 'bucket' = '1', - 'merge-engine' = 'aggregation', - 'fields.amount.aggregate-function' = 'sum' - )", - ) - .await - .unwrap(); - - sql_context - .sql("INSERT INTO paimon.test_db.t_agg_del VALUES (1, 10), (2, 20)") - .await - .unwrap() - .collect() - .await - .unwrap(); - - // DELETE may either fail at planning or surface Unsupported at execution. - // Either way the error must mention the aggregation engine refusing the - // retract row; we explicitly assert both branches so a future parser - // change cannot silently turn this into a no-op pass. - let plan_result = sql_context - .sql("DELETE FROM paimon.test_db.t_agg_del WHERE id = 1") - .await; - match plan_result { - Ok(df) => { - let exec = df.collect().await; - assert!(exec.is_err(), "DELETE on aggregation table should fail"); - let msg = format!("{:?}", exec.err().unwrap()); - assert!( - msg.contains("aggregation") - || msg.contains("DELETE") - || msg.contains("UPDATE_BEFORE"), - "expected aggregation engine to reject DELETE at execution, got {msg}" - ); - } - Err(e) => { - let msg = format!("{e:?}"); - assert!( - msg.contains("aggregation") - || msg.contains("DELETE") - || msg.contains("Unsupported"), - "expected aggregation engine to reject DELETE at planning, got {msg}" - ); - } - } -} - /// `merge-engine=aggregation` with no per-field nor default aggregate-function /// should still work: each value column falls back to `last_non_null_value`, /// matching Java `AggregateMergeFunction#getAggFuncName`. diff --git a/docs/src/sql.md b/docs/src/sql.md index 713dd370..6139577b 100644 --- a/docs/src/sql.md +++ b/docs/src/sql.md @@ -918,10 +918,10 @@ The table type determines which row-level DML operations are supported: | `TRUNCATE TABLE` | Supported | Supported | Supported | | `ALTER TABLE ... DROP PARTITION` | Supported for partitioned tables | Supported for partitioned tables | Supported for partitioned tables | | `UPDATE` | Supported via Copy-on-Write | Not supported | Supported via row-id update | -| `DELETE` | Supported via Copy-on-Write | Not supported | Supported when deletion vectors are enabled | +| `DELETE` | Supported via Copy-on-Write | Supported for [eligible `deduplicate` tables](#delete) | Supported when deletion vectors are enabled | | `MERGE INTO` | Supported via Copy-on-Write | Not supported | Supported for matched `UPDATE`, matched `DELETE` with deletion vectors, and not-matched `INSERT` | -A data-evolution row-tracking table must have both `'data-evolution.enabled' = 'true'` and `'row-tracking.enabled' = 'true'`, and must not have primary keys. `DELETE` and matched `DELETE` in `MERGE INTO` additionally require `'deletion-vectors.enabled' = 'true'`. Primary-key row-level `UPDATE`, `DELETE`, and `MERGE INTO` are not supported even when data evolution is enabled. +A data-evolution row-tracking table must have both `'data-evolution.enabled' = 'true'` and `'row-tracking.enabled' = 'true'`, and must not have primary keys. `DELETE` and matched `DELETE` in `MERGE INTO` additionally require `'deletion-vectors.enabled' = 'true'`. Primary-key row-level `UPDATE` and `MERGE INTO` are not supported. ### INSERT INTO @@ -1008,7 +1008,30 @@ DELETE FROM paimon.my_db.t WHERE name = 'b'; For data-evolution row-tracking tables without primary keys, deletes are executed via deletion vectors and require `'deletion-vectors.enabled' = 'true'`. -`DELETE` is not supported on primary-key tables. +Primary-key tables using `merge-engine=deduplicate` with data evolution disabled +support `DELETE` by writing tombstones for the logical rows matching the +predicate. `DELETE` without `WHERE` deletes every row in the captured read +snapshot. A delete with no matches returns zero without publishing a snapshot. + +Scans of the target table, including predicate self-references, use one captured +snapshot. Tombstones preserve configured sequence values and sort order, so +concurrent upserts follow the normal primary-key merge rules. With the default +ascending order, a higher-sequence upsert survives; without a sequence field, +normal write ordering applies. This does not provide serializable predicate +deletion. + +The affected-row count reports logical rows matching the predicate in the +captured snapshot. It includes keys whose concurrent upserts survive under the +merge rules above. + +Publication retries reuse prepared files without rescanning. Repeating the SQL +statement scans a new snapshot and is a new operation. A commit error does not +necessarily mean that the deletion was rolled back. + +Other primary-key merge engines, `ignore-delete=true` (including its fallback +options), `rowkind.field`, query-authorized primary-key tables, aliases, +multi-target/join deletes, `USING`, `RETURNING`, `ORDER BY`, `LIMIT`, `OUTPUT`, and +target table modifiers are not supported by this path. ### MERGE INTO
