This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 7712fafc [datafusion] Support SQL DELETE on deduplicate primary-key
tables (#1392)
7712fafc is described below
commit 7712fafc6b3b515d92b6e75b1e0fa223e2c45be3
Author: Nicholas Jiang <[email protected]>
AuthorDate: Mon Nov 16 21:32:12 2026 +0800
[datafusion] Support SQL DELETE on deduplicate primary-key tables (#1392)
---
crates/integrations/datafusion/src/delete.rs | 248 +++++-
crates/integrations/datafusion/src/delete/tests.rs | 581 +++++++++++++++
.../datafusion/src/physical_plan/sink.rs | 5 +-
crates/integrations/datafusion/src/table/mod.rs | 11 +
.../integrations/datafusion/tests/delete_tests.rs | 26 -
.../datafusion/tests/pk_delete_tests.rs | 829 +++++++++++++++++++++
crates/integrations/datafusion/tests/pk_tables.rs | 58 --
docs/src/sql.md | 45 +-
8 files changed, 1711 insertions(+), 92 deletions(-)
diff --git a/crates/integrations/datafusion/src/delete.rs
b/crates/integrations/datafusion/src/delete.rs
index bad2c812..40eb282a 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;
@@ -33,7 +44,9 @@ use crate::merge_into::{
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.
///
@@ -64,12 +77,239 @@ 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_live_target = |provider: &PaimonTableProvider| {
+ let source = provider.table();
+ source.identifier() == table.identifier()
+ && source.location() == table.location()
+ && source.branch() == table.branch()
+ && !source.is_time_traveled()
+ && !source.schema().core_options().has_time_travel_selector()
+ && !source
+ .schema()
+ .options()
+ .contains_key("incremental-between-timestamp")
+ };
+ // 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 or uses
historical/incremental read options"
+ .into(),
+ )
+ };
+ let LogicalPlan::TableScan(scan) = source else {
+ return Err(target_changed());
+ };
+ let provider = source_as_provider(&scan.source)?;
+ let Some(provider) = provider.downcast_ref::<PaimonTableProvider>() else {
+ return Err(target_changed());
+ };
+ if !is_live_target(provider) {
+ return Err(target_changed());
+ }
+ validate_primary_key_delete_read_options(provider.table(), table)?;
+ let Some(snapshot) = snapshot else {
+ return Ok(None);
+ };
+ // Pin live self-references; preserve explicit historical and incremental
reads.
+ 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_live_target(provider) {
+ validate_primary_key_delete_read_options(provider.table(),
table)?;
+ scan.source = provider_as_source(Arc::new(
+
provider.clone().with_primary_key_delete_snapshot(&snapshot),
+ ));
+ return Ok(Transformed::yes(LogicalPlan::TableScan(scan)));
+ }
+ }
+ Ok(Transformed::no(LogicalPlan::TableScan(scan)))
+ })?
+ .data;
+ Ok(Some(DataFrame::new(ctx.ctx().state(), plan)))
+}
+
+fn validate_primary_key_delete_read_options(source: &Table, target: &Table) ->
DFResult<()> {
+ let source_schema = source.schema();
+ let target_schema = target.schema();
+ let source = source_schema.core_options();
+ let target = target_schema.core_options();
+ if source.merge_engine().map_err(to_datafusion_error)?
+ != target.merge_engine().map_err(to_datafusion_error)?
+ || source.sequence_fields() != target.sequence_fields()
+ || source.sequence_field_sort_order_is_ascending()
+ != target.sequence_field_sort_order_is_ascending()
+ || source.bucket() != target.bucket()
+ || source.bucket_function_type().map_err(to_datafusion_error)?
+ != target.bucket_function_type().map_err(to_datafusion_error)?
+ || source
+ .bucket_key()
+ .unwrap_or_else(|| source_schema.trimmed_primary_keys())
+ != target
+ .bucket_key()
+ .unwrap_or_else(|| target_schema.trimmed_primary_keys())
+ || source.deletion_vectors_enabled() !=
target.deletion_vectors_enabled()
+ || source.data_evolution_enabled() != target.data_evolution_enabled()
+ || source.ignore_delete() != target.ignore_delete()
+ || source.rowkind_field() != target.rowkind_field()
+ || source.query_auth_enabled() != target.query_auth_enabled()
+ {
+ return Err(DataFusionError::Plan(
+ "Primary-key DELETE requires read options to match the target's
merge engine, \
+ sequence ordering, buckets, deletion vectors, data evolution, row
kinds and query authorization"
+ .into(),
+ ));
+ }
+ Ok(())
}
/// 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..c9830a5e
--- /dev/null
+++ b/crates/integrations/datafusion/src/delete/tests.rs
@@ -0,0 +1,581 @@
+// 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::collections::BTreeSet;
+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};
+use tokio::sync::oneshot;
+
+#[derive(Clone, Copy, Debug)]
+enum PublicationFault {
+ Conflict,
+ RepeatedConflict,
+ LostReply,
+ LostReplyAndReadFailure,
+}
+
+#[derive(Debug)]
+struct PublicationBarrier {
+ entered: oneshot::Sender<()>,
+ resume: oneshot::Receiver<()>,
+}
+
+#[derive(Debug)]
+struct FaultProvider {
+ operator: Operator,
+ publication_fault: Mutex<Option<PublicationFault>>,
+ publication_barrier: Mutex<Option<PublicationBarrier>>,
+ 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::RepeatedConflict)) {
+ *self.publication_fault.lock().unwrap() = fault;
+ return Ok(Some(false));
+ }
+ if matches!(fault, Some(PublicationFault::Conflict)) {
+ let barrier =
self.publication_barrier.lock().unwrap().take().unwrap();
+ barrier.entered.send(()).unwrap();
+ barrier.resume.await.unwrap();
+ }
+ 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 matches!(
+ fault,
+ Some(PublicationFault::LostReply |
PublicationFault::LostReplyAndReadFailure)
+ ) {
+ 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),
+ publication_barrier: 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("sequence.field", "v")
+ .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 stored_files(provider: &FaultProvider) -> BTreeSet<String> {
+ provider
+ .operator
+ .list_with("table/")
+ .recursive(true)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| entry.path().to_string())
+ .collect()
+}
+
+async fn assert_table_state(
+ ctx: &SQLContext,
+ table: &Table,
+ snapshot_id: i64,
+ expected_ids: &[i32],
+) {
+ assert_eq!(
+ table
+ .snapshot_manager()
+ .get_latest_snapshot_id()
+ .await
+ .unwrap(),
+ Some(snapshot_id)
+ );
+ let batches = ctx
+ .ctx()
+ .sql("SELECT id FROM target ORDER BY id")
+ .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, expected_ids);
+}
+
+#[tokio::test]
+async fn
delete_input_pins_live_self_references_and_preserves_historical_views() {
+ for predicate in [
+ None,
+ Some("id IN (SELECT id FROM target WHERE v = 11)"),
+ Some("v = (SELECT MIN(v) FROM target)"),
+ Some("EXISTS (SELECT 1 FROM target other WHERE other.id = target.id
AND other.v = 11)"),
+ Some("id IN (SELECT id FROM target_view WHERE v = 11)"),
+ Some("id IN (SELECT id FROM target_history WHERE v = 10)"),
+ ] {
+ let (ctx, table, _, _) = setup().await;
+ let historical_snapshot =
table.resolve_read_snapshot().await.unwrap().unwrap();
+ ctx.ctx()
+ .register_table(
+ "target_history",
+ Arc::new(
+ PaimonTableProvider::try_new(
+
table.copy_with_pinned_snapshot(Some(&historical_snapshot)),
+ )
+ .unwrap(),
+ ),
+ )
+ .unwrap();
+ ctx.ctx()
+ .sql("INSERT INTO target VALUES (1, 11)")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ let view = ctx
+ .ctx()
+ .sql("SELECT * FROM target")
+ .await
+ .unwrap()
+ .into_view();
+ ctx.ctx().register_table("target_view", view).unwrap();
+ let sql = match predicate {
+ Some(predicate) => format!("DELETE FROM target WHERE {predicate}"),
+ None => "DELETE FROM target".to_string(),
+ };
+ let input = plan_primary_key_delete_input(&ctx, &parse_delete(&sql),
&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 mut 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<_>>();
+ rows.sort_unstable();
+ let expected = if predicate.is_some() {
+ vec![(1, 11)]
+ } else {
+ vec![(1, 11), (2, 20)]
+ };
+ assert_eq!(rows, expected, "{sql}");
+ }
+}
+
+#[tokio::test]
+async fn failed_tombstone_staging_does_not_publish_or_leave_files() {
+ let (ctx, table, provider, calls) = setup().await;
+ let before_files = stored_files(&provider).await;
+ 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)
+ );
+ assert_eq!(stored_files(&provider).await, before_files);
+ execute_counted_delete(&ctx, &table).await.unwrap();
+ assert_table_state(&ctx, &table, 2, &[2]).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);
+ let (entered, wait_for_publication) = oneshot::channel();
+ let (resume, wait_for_upsert) = oneshot::channel();
+ if matches!(fault, PublicationFault::Conflict) {
+ *provider.publication_barrier.lock().unwrap() =
Some(PublicationBarrier {
+ entered,
+ resume: wait_for_upsert,
+ });
+ }
+ *provider.publication_fault.lock().unwrap() = Some(fault);
+ let (result, ()) = tokio::try_join!(execute_counted_delete(&ctx,
&table), async {
+ if matches!(fault, PublicationFault::Conflict) {
+ wait_for_publication.await.unwrap();
+ ctx.ctx()
+ .sql("INSERT INTO target VALUES (1, 30), (3, 5)")
+ .await?
+ .collect()
+ .await?;
+ resume.send(()).unwrap();
+ }
+ Ok(())
+ })
+ .unwrap();
+ let result = result.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)
{
+ 3
+ } else {
+ 1
+ };
+ assert_eq!(
+ provider.publication_attempts.load(Ordering::SeqCst) - before,
+ expected_attempts
+ );
+ if matches!(fault, PublicationFault::Conflict) {
+ assert_table_state(&ctx, &table, 3, &[1, 2, 3]).await;
+ } else {
+ assert_table_state(&ctx, &table, 2, &[2]).await;
+ }
+ }
+}
+
+#[tokio::test]
+async fn publication_errors_keep_prepared_tombstones_without_rescanning() {
+ for fault in [
+ PublicationFault::RepeatedConflict,
+ PublicationFault::LostReplyAndReadFailure,
+ ] {
+ let (ctx, table, provider, calls) = setup().await;
+ let before_files = stored_files(&provider).await;
+ let before_attempts =
provider.publication_attempts.load(Ordering::SeqCst);
+ *provider.publication_fault.lock().unwrap() = Some(fault);
+ 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_eq!(calls.load(Ordering::SeqCst), 1);
+ let after_files = stored_files(&provider).await;
+ assert!(before_files.is_subset(&after_files), "{fault:?}");
+ assert_eq!(
+ after_files
+ .difference(&before_files)
+ .filter(|path| path.ends_with(".parquet"))
+ .count(),
+ 1,
+ "{fault:?} must retain the prepared tombstone file"
+ );
+ provider.fail_snapshot_access.store(false, Ordering::SeqCst);
+ let snapshot = table.resolve_read_snapshot().await.unwrap().unwrap();
+ if matches!(fault, PublicationFault::RepeatedConflict) {
+ assert!(source.to_string().contains("with 2 retries"), "{source}");
+ assert_eq!(snapshot.id(), 1);
+ assert_eq!(
+ provider.publication_attempts.load(Ordering::SeqCst) -
before_attempts,
+ 3
+ );
+ } else {
+ assert!(source.to_string().contains("unknown"), "{source}");
+ assert!(
+ context.contains(&format!("commit_user={}",
snapshot.commit_user())),
+ "the failure must identify the published commit: {context}"
+ );
+ assert_table_state(&ctx, &table, 2, &[2]).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"),
+ ("first-row.ignore-delete", "true", "ignore-delete"),
+ ("deduplicate.ignore-delete", "true", "ignore-delete"),
+ ("partial-update.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 overridden =
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, &overridden)
+ .await
+ .expect_err("DELETE unexpectedly succeeded");
+ assert!(error.to_string().contains(expected_error), "{error}");
+ ctx.ctx().deregister_table("target").unwrap();
+ ctx.ctx()
+ .register_table(
+ "target",
+ Arc::new(PaimonTableProvider::try_new(overridden).unwrap()),
+ )
+ .unwrap();
+ let error = execute_counted_delete(&ctx, &table)
+ .await
+ .expect_err("DELETE unexpectedly succeeded with overridden read
options");
+ assert!(error.to_string().contains("read options"), "{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)),
+ table.copy_with_options(std::collections::HashMap::from([(
+ "scan.snapshot-id".into(),
+ snapshot.id().to_string(),
+ )])),
+ ] {
+
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/src/table/mod.rs
b/crates/integrations/datafusion/src/table/mod.rs
index 6d9219d1..01115719 100644
--- a/crates/integrations/datafusion/src/table/mod.rs
+++ b/crates/integrations/datafusion/src/table/mod.rs
@@ -17,6 +17,7 @@
//! Paimon table provider for DataFusion.
+use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::Arc;
@@ -200,6 +201,16 @@ impl PaimonTableProvider {
self.table = self.table.copy_with_pinned_snapshot(Some(snapshot));
self
}
+
+ pub(crate) fn with_primary_key_delete_snapshot(mut self, snapshot:
&Snapshot) -> Self {
+ // Merge L0 versions before evaluating DELETE predicates, even when
+ // ordinary deletion-vector reads are compacted-only.
+ self.table = self.table.copy_with_options(HashMap::from([(
+ "deletion-vectors.merge-on-read".to_string(),
+ "true".to_string(),
+ )]));
+ self.with_pinned_snapshot(snapshot)
+ }
}
/// Build a `CREATE TABLE` DDL string for a Paimon table.
diff --git a/crates/integrations/datafusion/tests/delete_tests.rs
b/crates/integrations/datafusion/tests/delete_tests.rs
index 2c0d62ba..7e0a3b74 100644
--- a/crates/integrations/datafusion/tests/delete_tests.rs
+++ b/crates/integrations/datafusion/tests/delete_tests.rs
@@ -519,32 +519,6 @@ async fn test_delete_with_order_by_and_limit() {
// ======================= 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..3ed412e5
--- /dev/null
+++ b/crates/integrations/datafusion/tests/pk_delete_tests.rs
@@ -0,0 +1,829 @@
+// 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, CatalogOptions, FileSystemCatalog, Options};
+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()
+}
+
+async fn setup_dv_with_uncompacted_upsert(
+ merge_on_read: Option<bool>,
+) -> (tempfile::TempDir, Arc<FileSystemCatalog>, SQLContext) {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let mut options = Options::new();
+ options.set(
+ CatalogOptions::WAREHOUSE,
+ format!("file://{}", tmp.path().join("warehouse").display()),
+ );
+ options.set("local-cache.enabled", "true");
+ options.set(
+ "local-cache.dir",
+ tmp.path().join("cache").to_str().unwrap(),
+ );
+ let catalog = Arc::new(FileSystemCatalog::new(options).unwrap());
+ let ctx = create_sql_context(Arc::clone(&catalog)).await;
+ exec(&ctx, "CREATE SCHEMA paimon.test_db").await;
+ let merge_on_read = merge_on_read
+ .map(|enabled| format!(", 'deletion-vectors.merge-on-read' =
'{enabled}'"))
+ .unwrap_or_default();
+ exec(
+ &ctx,
+ &format!(
+ "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, PRIMARY
KEY (id)) \
+ WITH ('bucket' = '2', 'write-only' = 'true', \
+ 'deletion-vectors.enabled' = 'true'{merge_on_read})"
+ ),
+ )
+ .await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 30)").await;
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10)), (2, Some(30))]);
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 20), (3, 40)").await;
+ (tmp, catalog, ctx)
+}
+
+#[tokio::test]
+async fn primary_key_delete_merges_uncompacted_dv_versions() {
+ for merge_on_read in [None, Some(false), Some(true)] {
+ let (_tmp, catalog, ctx) =
setup_dv_with_uncompacted_upsert(merge_on_read).await;
+ let before_rows = if merge_on_read.unwrap_or(false) {
+ vec![(1, Some(20)), (2, Some(30)), (3, Some(40))]
+ } else {
+ vec![(1, Some(10)), (2, Some(30))]
+ };
+ assert_eq!(rows(&ctx).await, before_rows);
+ let before = snapshot(&catalog).await;
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE v = 10").await,
+ 0,
+ "merge_on_read={merge_on_read:?}"
+ );
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(rows(&ctx).await, before_rows);
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert_eq!(
+ rows(&ctx).await,
+ vec![(1, Some(20)), (2, Some(30)), (3, Some(40))]
+ );
+
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 50), (4,
60)").await;
+ let delete = "DELETE FROM paimon.test_db.t WHERE v >= 40";
+ assert_eq!(dml_count(&ctx, delete).await, 3);
+ let before = snapshot(&catalog).await;
+ assert_eq!(dml_count(&ctx, delete).await, 0);
+ assert_eq!(snapshot(&catalog).await, before);
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert_eq!(rows(&ctx).await, vec![(2, Some(30))]);
+
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (5, 70)").await;
+ assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 2);
+ let before = snapshot(&catalog).await;
+ assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 0);
+ assert_eq!(snapshot(&catalog).await, before);
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert!(rows(&ctx).await.is_empty());
+ }
+}
+
+#[tokio::test]
+async fn primary_key_delete_subqueries_merge_uncompacted_dv_versions() {
+ let (_tmp, catalog, ctx) = setup_dv_with_uncompacted_upsert(None).await;
+ exec(
+ &ctx,
+ "CREATE TEMPORARY VIEW target_view AS SELECT * FROM paimon.test_db.t",
+ )
+ .await;
+ let before = snapshot(&catalog).await;
+ let historical_view = ctx
+ .sql(&format!(
+ "SELECT * FROM paimon.test_db.t VERSION AS OF {}",
+ before.unwrap()
+ ))
+ .await
+ .unwrap();
+ ctx.register_temp_table("target_history", historical_view.into_view())
+ .unwrap();
+ assert_eq!(
+ common::row_count(&ctx, "SELECT * FROM target_history WHERE id = 1 AND
v = 10").await,
+ 1
+ );
+ for predicate in [
+ "id IN (SELECT id FROM paimon.test_db.t WHERE v = 10)",
+ "id = 1 AND 10 = (SELECT v FROM paimon.test_db.t WHERE id = 1)",
+ "EXISTS (SELECT 1 FROM paimon.test_db.t other WHERE other.id = t.id
AND other.v = 10)",
+ "id IN (SELECT id FROM target_view WHERE v = 10)",
+ ] {
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("DELETE FROM paimon.test_db.t WHERE {predicate}")
+ )
+ .await,
+ 0,
+ "{predicate}"
+ );
+ assert_eq!(snapshot(&catalog).await, before);
+ }
+ let delete = "DELETE FROM paimon.test_db.t WHERE id IN \
+ (SELECT id FROM target_view WHERE v = 20)";
+ assert_eq!(dml_count(&ctx, delete).await, 1);
+ assert_eq!(dml_count(&ctx, delete).await, 0);
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert_eq!(rows(&ctx).await, vec![(2, Some(30)), (3, Some(40))]);
+ assert_eq!(
+ common::row_count(&ctx, "SELECT * FROM target_history WHERE id = 1 AND
v = 10").await,
+ 1
+ );
+ assert_eq!(
+ dml_count(
+ &ctx,
+ "DELETE FROM paimon.test_db.t WHERE id = 2 AND \
+ EXISTS (SELECT 1 FROM target_history WHERE id = 1 AND v = 10)"
+ )
+ .await,
+ 1
+ );
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ assert_eq!(rows(&ctx).await, vec![(3, Some(40))]);
+}
+
+#[tokio::test]
+async fn primary_key_delete_reads_latest_versions_and_counts_logical_rows() {
+ let (tmp, catalog, ctx) = setup(", 'read.batch-size' = '1'").await;
+ exec(&ctx, "SET datafusion.execution.batch_size = 1").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.t VALUES (1, 10), (2, 20), (3, NULL), (4,
40)",
+ )
+ .await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 11)").await;
+ let before = snapshot(&catalog).await;
+ let before_files = files_under(tmp.path());
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE v = 10").await,
+ 0
+ );
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(files_under(tmp.path()), before_files);
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE t.v <> 11").await,
+ 2
+ );
+ 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;
+ let before_files = files_under(tmp.path());
+ assert_eq!(dml_count(&ctx, "DELETE FROM paimon.test_db.t").await, 0);
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(files_under(tmp.path()), before_files);
+}
+
+#[tokio::test]
+async fn primary_key_delete_on_never_written_table_is_a_noop() {
+ let (tmp, catalog, ctx) = setup("").await;
+ let before_files = files_under(tmp.path());
+ 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_eq!(files_under(tmp.path()), before_files);
+ }
+ assert_sql_error(
+ &ctx,
+ "DELETE FROM paimon.test_db.t WHERE missing_column = 1",
+ "missing_column",
+ )
+ .await;
+ assert_eq!(snapshot(&catalog).await, None);
+ assert_eq!(files_under(tmp.path()), before_files);
+}
+
+#[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;
+ let before = snapshot(&catalog).await;
+ let before_files = files_under(tmp.path());
+ exec(&ctx, "SET 'paimon.incremental-between-timestamp' = '0,1'").await;
+ exec(
+ &ctx,
+ "CREATE TEMPORARY VIEW target_changes AS SELECT * FROM
paimon.test_db.t",
+ )
+ .await;
+ exec(&ctx, "RESET 'paimon.incremental-between-timestamp'").await;
+ assert_eq!(
+ common::row_count(&ctx, "SELECT * FROM target_changes").await,
+ 0
+ );
+ for predicate in [
+ "id IN (SELECT id FROM paimon.test_db.t WHERE v = 999)",
+ "id = (SELECT id FROM paimon.test_db.t WHERE v = 999)",
+ "v = (SELECT CAST(NULL AS INT))",
+ "id NOT IN (SELECT CAST(NULL AS INT))",
+ "id IN (SELECT id FROM target_changes)",
+ ] {
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("DELETE FROM paimon.test_db.t WHERE {predicate}")
+ )
+ .await,
+ 0,
+ "{predicate}"
+ );
+ assert_eq!(snapshot(&catalog).await, before, "{predicate}");
+ assert_eq!(files_under(tmp.path()), before_files, "{predicate}");
+ }
+ 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_rejects_inconsistent_read_options() {
+ for (table_options, option, value) in [
+ ("", "sequence.field", "v"),
+ (
+ ", 'sequence.field' = 'v', 'sequence.field.sort-order' =
'descending'",
+ "sequence.field.sort-order",
+ "ascending",
+ ),
+ ("", "deletion-vectors.enabled", "true"),
+ ("", "data-evolution.enabled", "true"),
+ ("", "bucket", "-1"),
+ ("", "bucket-key", "v"),
+ ("", "bucket-function.type", "mod"),
+ ] {
+ let (tmp, catalog, ctx) = setup(table_options).await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 20), (2,
30)").await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10)").await;
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10)), (2, Some(30))]);
+ let before = snapshot(&catalog).await;
+ let before_files = files_under(tmp.path());
+ exec(&ctx, &format!("SET 'paimon.{option}' = '{value}'")).await;
+ if option.starts_with("sequence.field") {
+ assert_eq!(rows(&ctx).await, vec![(1, Some(20)), (2, Some(30))]);
+ }
+ assert_sql_error(
+ &ctx,
+ "DELETE FROM paimon.test_db.t WHERE id = 1",
+ "read options",
+ )
+ .await;
+ exec(
+ &ctx,
+ "CREATE TEMPORARY VIEW target_view AS SELECT * FROM
paimon.test_db.t",
+ )
+ .await;
+ exec(&ctx, &format!("RESET 'paimon.{option}'")).await;
+ assert_sql_error(
+ &ctx,
+ "DELETE FROM paimon.test_db.t WHERE id IN (SELECT id FROM
target_view WHERE id = 1)",
+ "read options",
+ )
+ .await;
+ assert_eq!(snapshot(&catalog).await, before, "{option}");
+ assert_eq!(files_under(tmp.path()), before_files, "{option}");
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10)), (2, Some(30))]);
+ exec(&ctx, "SET 'paimon.read.batch-size' = '1'").await;
+ exec(&ctx, "SET 'paimon.bucket-key' = ' id, '").await;
+ exec(&ctx, "SET 'paimon.bucket-function.type' = 'DEFAULT'").await;
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE v = 10").await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(2, Some(30))]);
+ }
+}
+
+#[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() {
+ for (nullable, key, predicate) in [(false, "'a'", "name = 'a'"), (true,
"NULL", "name IS NULL")]
+ {
+ 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, name STRING,
pt INT NOT NULL, v INT, PRIMARY KEY (id, name, pt)) \
+ PARTITIONED BY (pt) WITH ('bucket' = '2',
'primary-key.nullable' = '{nullable}')"
+ ),
+ )
+ .await;
+ exec(
+ &ctx,
+ &format!(
+ "INSERT INTO paimon.test_db.t VALUES (1, {key}, 1, 10), (1,
'b', 1, 11), (1, {key}, 2, 20), (2, {key}, 1, 30)"
+ ),
+ )
+ .await;
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("DELETE FROM paimon.test_db.t WHERE pt = 1 AND id = 1
AND {predicate}")
+ )
+ .await,
+ 1,
+ "nullable={nullable}"
+ );
+ assert_eq!(
+ rows(&ctx).await,
+ vec![(1, Some(11)), (1, Some(20)), (2, Some(30))]
+ );
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE pt = 1 AND v >
20").await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(1, Some(11)), (1, Some(20))]);
+ }
+}
+
+#[tokio::test]
+async fn
primary_key_delete_preserves_sequence_fields_and_allows_later_upserts() {
+ for (order, older, newer) in [("ascending", 99, 101), ("descending", 101,
99)] {
+ let (_tmp, _catalog, ctx) = setup(&format!(
+ ", 'sequence.field' = 'v', '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 ({order})"
+ );
+ exec(
+ &ctx,
+ &format!("INSERT INTO paimon.test_db.t VALUES (1, {newer})"),
+ )
+ .await;
+ assert_eq!(rows(&ctx).await, vec![(1, Some(newer))], "{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",
+ "()",
+ "WITH (NOLOCK)",
+ "WITH ORDINALITY",
+ "PARTITION (p0)",
+ ] {
+ 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;
+ exec(&ctx, "SET 'paimon.incremental-between-timestamp' = '0,1'").await;
+ assert_sql_error(&ctx, "DELETE FROM paimon.test_db.t", "target
changed").await;
+ exec(&ctx, "RESET 'paimon.incremental-between-timestamp'").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",
+ "first-row.ignore-delete",
+ "deduplicate.ignore-delete",
+ "partial-update.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', 'first-row.ignore-delete' = 'true', \
+ 'deduplicate.ignore-delete' = 'true', 'partial-update.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 04afc253..9191f64c 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,46 @@ 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` targets every row in the captured read
+snapshot. A delete with no matches returns zero without publishing a snapshot.
+
+The target and its live self-references, including those through views, use one
+captured snapshot and merge uncompacted primary-key versions before applying
+predicates. On deletion-vector tables this applies even when
+`deletion-vectors.merge-on-read` is disabled. Ordinary queries retain their
+configured read behavior. Explicitly historical and incremental views retain
+their selected snapshots or timestamp windows and configured read behavior.
+DELETE targets cannot use time-travel or incremental read options.
+
+The target and its live self-references must use the table's configured merge
+engine, sequence fields, sort order, bucket count, bucket keys and bucket
+function. Conflicting session options or options captured by a view are
rejected
+before scanning, as are overrides that enable or disable deletion vectors or
+data evolution, or change row-kind handling or query authorization. Read tuning
+options, such as `read.batch-size`, remain supported.
+
+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. Prepared files are retained
+on publication errors; the error identifies the table and commit user for
+investigating an uncertain outcome.
+
+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