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 3e8a5dfd [datafusion] Support SQL UPDATE on deduplicate primary-key
tables (#1433)
3e8a5dfd is described below
commit 3e8a5dfd58a402fced6e50395449eb38edcb486b
Author: Nicholas Jiang <[email protected]>
AuthorDate: Tue Nov 17 14:52:15 2026 +0800
[datafusion] Support SQL UPDATE on deduplicate primary-key tables (#1433)
---
crates/integrations/datafusion/src/delete.rs | 223 +------
crates/integrations/datafusion/src/delete/tests.rs | 581 -----------------
crates/integrations/datafusion/src/lib.rs | 1 +
.../integrations/datafusion/src/primary_key_dml.rs | 244 +++++++
.../datafusion/src/primary_key_dml/tests.rs | 724 +++++++++++++++++++++
crates/integrations/datafusion/src/table/mod.rs | 10 +-
crates/integrations/datafusion/src/update.rs | 131 ++--
crates/integrations/datafusion/tests/common/mod.rs | 14 +
.../datafusion/tests/pk_delete_tests.rs | 15 +-
.../datafusion/tests/pk_update_tests.rs | 684 +++++++++++++++++++
.../integrations/datafusion/tests/update_tests.rs | 26 -
docs/src/sql.md | 28 +-
12 files changed, 1802 insertions(+), 879 deletions(-)
diff --git a/crates/integrations/datafusion/src/delete.rs
b/crates/integrations/datafusion/src/delete.rs
index 40eb282a..49037501 100644
--- a/crates/integrations/datafusion/src/delete.rs
+++ b/crates/integrations/datafusion/src/delete.rs
@@ -19,22 +19,11 @@
//!
//! 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, MergeEngine, RowKind, VALUE_KIND_FIELD_NAME};
+use paimon::spec::{CoreOptions, RowKind};
use paimon::table::{CopyOnWriteMergeWriter, Table};
use crate::error::to_datafusion_error;
@@ -44,9 +33,8 @@ 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::primary_key_dml;
use crate::sql_context::SQLContext;
-use crate::table::PaimonTableProvider;
/// Execute a DELETE statement on a Paimon table.
///
@@ -89,28 +77,12 @@ async fn execute_primary_key_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 requires
merge-engine=deduplicate".into(),
- ));
- }
- if options.ignore_delete() {
+ primary_key_dml::validate_table(table, "DELETE")?;
+ if table.schema().core_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,
};
@@ -133,183 +105,16 @@ async fn execute_primary_key_delete(
));
}
- 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(())
+ let input = primary_key_dml::plan_input(
+ ctx,
+ table,
+ table_ref,
+ "*",
+ delete.selection.as_ref(),
+ "DELETE",
+ )
+ .await?;
+ primary_key_dml::write_rows(ctx, table, input, RowKind::Delete,
"DELETE").await
}
/// 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
deleted file mode 100644
index c9830a5e..00000000
--- a/crates/integrations/datafusion/src/delete/tests.rs
+++ /dev/null
@@ -1,581 +0,0 @@
-// 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/lib.rs
b/crates/integrations/datafusion/src/lib.rs
index 0ec0c65f..dd4967db 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -65,6 +65,7 @@ mod merge_condition;
mod merge_into;
mod partition_count_pushdown;
mod physical_plan;
+mod primary_key_dml;
mod procedures;
mod regex_operators;
mod relation_planner;
diff --git a/crates/integrations/datafusion/src/primary_key_dml.rs
b/crates/integrations/datafusion/src/primary_key_dml.rs
new file mode 100644
index 00000000..ac16564b
--- /dev/null
+++ b/crates/integrations/datafusion/src/primary_key_dml.rs
@@ -0,0 +1,244 @@
+// 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.
+
+//! Shared snapshot planning and writes for deduplicate primary-key mutations.
+
+#[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;
+use futures::StreamExt;
+
+use paimon::spec::{MergeEngine, RowKind, VALUE_KIND_FIELD_NAME};
+use paimon::table::Table;
+
+use crate::error::to_datafusion_error;
+use crate::merge_into::ok_result;
+use crate::physical_plan::sink::to_paimon_batch;
+use crate::sql_context::SQLContext;
+use crate::table::PaimonTableProvider;
+
+pub(crate) fn validate_table(table: &Table, operation: &str) -> DFResult<()> {
+ let options = table.schema().core_options();
+ if options.merge_engine().map_err(to_datafusion_error)? !=
MergeEngine::Deduplicate {
+ return Err(DataFusionError::Plan(format!(
+ "{operation} on primary-key tables requires
merge-engine=deduplicate"
+ )));
+ }
+ // Masked values cannot safely identify the keys or preserve unassigned
fields.
+ if options.query_auth_enabled() {
+ return Err(DataFusionError::NotImplemented(format!(
+ "{operation} on query-authorized primary-key tables is not
supported"
+ )));
+ }
+ if options.rowkind_field().is_some() {
+ return Err(DataFusionError::NotImplemented(format!(
+ "{operation} on primary-key tables with rowkind.field is not
supported"
+ )));
+ }
+ Ok(())
+}
+
+pub(crate) async fn write_rows(
+ ctx: &SQLContext,
+ table: &Table,
+ input: DataFrame,
+ kind: RowKind,
+ operation: &str,
+) -> DFResult<DataFrame> {
+ 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 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![
+ kind.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 {operation} 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)
+}
+
+pub(crate) async fn plan_input(
+ ctx: &SQLContext,
+ table: &Table,
+ table_ref: &str,
+ projection: &str,
+ selection: Option<&datafusion::sql::sqlparser::ast::Expr>,
+ operation: &str,
+) -> DFResult<DataFrame> {
+ let snapshot = table
+ .resolve_read_snapshot()
+ .await
+ .map_err(to_datafusion_error)?;
+ let where_clause = selection
+ .map(|predicate| format!(" WHERE {predicate}"))
+ .unwrap_or_default();
+ let matched = ctx
+ .ctx()
+ .sql(&format!(
+ "SELECT {projection} 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(format!(
+ "{operation} target changed during planning or uses
historical/incremental read options"
+ ))
+ };
+ 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_read_options(provider.table(), table, operation)?;
+ // 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_read_options(provider.table(), table, operation)?;
+ scan.source = provider_as_source(Arc::new(
+ provider
+ .clone()
+
.with_primary_key_mutation_snapshot(snapshot.as_ref()),
+ ));
+ return Ok(Transformed::yes(LogicalPlan::TableScan(scan)));
+ }
+ }
+ Ok(Transformed::no(LogicalPlan::TableScan(scan)))
+ })?
+ .data;
+ Ok(DataFrame::new(ctx.ctx().state(), plan))
+}
+
+fn validate_read_options(source: &Table, target: &Table, operation: &str) ->
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(format!(
+ "Primary-key {operation} requires read options to match the
target's merge engine, \
+ sequence ordering, buckets, deletion vectors, data evolution, row
kinds and query authorization"
+ )));
+ }
+ Ok(())
+}
diff --git a/crates/integrations/datafusion/src/primary_key_dml/tests.rs
b/crates/integrations/datafusion/src/primary_key_dml/tests.rs
new file mode 100644
index 00000000..952baa2f
--- /dev/null
+++ b/crates/integrations/datafusion/src/primary_key_dml/tests.rs
@@ -0,0 +1,724 @@
+// 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 crate::delete::execute_delete;
+use datafusion::sql::sqlparser::ast::Delete;
+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 mutation 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_delete(
+ ctx,
+ &parse_delete("DELETE FROM target WHERE count_scan(id) = 1"),
+ table.clone(),
+ "target",
+ )
+ .await
+}
+
+#[derive(Clone, Copy, Debug)]
+enum Mutation {
+ Delete,
+ Update,
+}
+
+impl Mutation {
+ async fn execute(self, ctx: &SQLContext, table: &Table) ->
DFResult<DataFrame> {
+ match self {
+ Self::Delete => execute_counted_delete(ctx, table).await,
+ Self::Update => {
+ let Statement::Update(update) = Parser::parse_sql(
+ &GenericDialect {},
+ "UPDATE target SET v = v + 1 WHERE count_scan(id) = 1",
+ )
+ .unwrap()
+ .pop()
+ .unwrap() else {
+ unreachable!()
+ };
+ crate::update::execute_update(ctx, &update, table.clone(),
true).await
+ }
+ }
+ }
+
+ async fn assert_committed(self, ctx: &SQLContext, table: &Table) {
+ match self {
+ Self::Delete => assert_table_state(ctx, table, 2, &[(2,
20)]).await,
+ Self::Update => assert_table_state(ctx, table, 2, &[(1, 11), (2,
20)]).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_rows: &[(i32, i32)],
+) {
+ assert_eq!(
+ table
+ .snapshot_manager()
+ .get_latest_snapshot_id()
+ .await
+ .unwrap(),
+ Some(snapshot_id)
+ );
+ let input = ctx
+ .ctx()
+ .sql("SELECT id, v FROM target ORDER BY id")
+ .await
+ .unwrap();
+ assert_eq!(collect_rows(input).await, expected_rows);
+}
+
+async fn collect_rows(input: DataFrame) -> Vec<(i32, i32)> {
+ 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();
+ rows
+}
+
+#[tokio::test]
+async fn
mutation_input_pins_live_self_references_and_preserves_selected_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();
+ for (name, view) in [
+ ("target_empty", table.copy_with_pinned_snapshot(None)),
+ (
+ "target_incremental",
+ table.copy_with_options(std::collections::HashMap::from([(
+ "incremental-between-timestamp".into(),
+ "0,1".into(),
+ )])),
+ ),
+ ] {
+ ctx.ctx()
+ .register_table(name,
Arc::new(PaimonTableProvider::try_new(view).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 delete = parse_delete(&sql);
+ let mut inputs = Vec::new();
+ for (operation, projection, increment) in [
+ ("DELETE", "*", 0),
+ ("UPDATE", "id, v + (SELECT MIN(v) FROM target) AS v", 11),
+ (
+ "UPDATE",
+ "id, v + (SELECT MIN(v) FROM target_view) AS v",
+ 11,
+ ),
+ (
+ "UPDATE",
+ "id, v + (SELECT MIN(v) FROM target_history) AS v",
+ 10,
+ ),
+ (
+ "UPDATE",
+ "id, v + COALESCE((SELECT MIN(v) FROM target_empty), CAST(0 AS
INT)) AS v",
+ 0,
+ ),
+ (
+ "UPDATE",
+ "id, v + COALESCE((SELECT MIN(v) FROM target_incremental),
CAST(0 AS INT)) AS v",
+ 0,
+ ),
+ ] {
+ let input = plan_input(
+ &ctx,
+ &table,
+ "target",
+ projection,
+ delete.selection.as_ref(),
+ operation,
+ )
+ .await
+ .unwrap();
+ inputs.push((input, projection, increment));
+ }
+ ctx.ctx()
+ .sql("INSERT INTO target VALUES (1, 30), (3, 5)")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for (input, projection, increment) in inputs {
+ let expected = if predicate.is_some() {
+ vec![(1, 11 + increment)]
+ } else {
+ vec![(1, 11 + increment), (2, 20 + increment)]
+ };
+ assert_eq!(collect_rows(input).await, expected, "{sql}:
{projection}");
+ }
+ }
+}
+
+#[tokio::test]
+async fn failed_mutation_staging_does_not_publish_or_leave_files() {
+ for mutation in [Mutation::Delete, Mutation::Update] {
+ 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 = mutation
+ .execute(&ctx, &table)
+ .await
+ .expect_err("mutation unexpectedly succeeded");
+ assert!(
+ error
+ .to_string()
+ .contains("injected mutation 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);
+ mutation.execute(&ctx, &table).await.unwrap();
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ mutation.assert_committed(&ctx, &table).await;
+ }
+}
+
+#[tokio::test]
+async fn publication_retries_do_not_repeat_the_mutation_scan() {
+ for mutation in [Mutation::Delete, Mutation::Update] {
+ 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!(mutation.execute(&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, 30), (2, 20), (3,
5)]).await;
+ } else {
+ mutation.assert_committed(&ctx, &table).await;
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn publication_errors_keep_prepared_mutations_without_rescanning() {
+ for mutation in [Mutation::Delete, Mutation::Update] {
+ 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 = mutation
+ .execute(&ctx, &table)
+ .await
+ .expect_err("mutation 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 mutation 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}"
+ );
+ mutation.assert_committed(&ctx, &table).await;
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn
unsupported_primary_key_mutation_options_are_rejected_before_scanning() {
+ for mutation in [Mutation::Delete, Mutation::Update] {
+ let mut options = vec![
+ ("query-auth.enabled", "true", "query-authorized"),
+ ("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",
+ ),
+ ];
+ if matches!(mutation, Mutation::Delete) {
+ options.extend([
+ ("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"),
+ ]);
+ }
+ for (option, value, expected_error) in options {
+ 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 = mutation
+ .execute(&ctx, &overridden)
+ .await
+ .expect_err("mutation unexpectedly succeeded");
+ assert!(
+ error.to_string().contains(expected_error),
+ "{mutation:?}, {option}: {error}"
+ );
+ ctx.ctx().deregister_table("target").unwrap();
+ ctx.ctx()
+ .register_table(
+ "target",
+
Arc::new(PaimonTableProvider::try_new(overridden).unwrap()),
+ )
+ .unwrap();
+ let error = mutation
+ .execute(&ctx, &table)
+ .await
+ .expect_err("mutation unexpectedly succeeded with overridden
read options");
+ assert!(
+ error.to_string().contains("read options"),
+ "{mutation:?}, {option}: {error}"
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 0, "{mutation:?},
{option}");
+ assert_eq!(
+ provider.publication_attempts.load(Ordering::SeqCst),
+ before,
+ "{mutation:?}, {option}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn replaced_target_cannot_supply_mutation_rows() {
+ 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();
+ for mutation in [Mutation::Delete, Mutation::Update] {
+ let error = mutation
+ .execute(&ctx, &table)
+ .await
+ .expect_err("mutation 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)
+ );
+ }
+}
+
+#[tokio::test]
+async fn mutation_input_preserves_a_captured_empty_snapshot() {
+ let (ctx, table, _, _) = setup().await;
+ let empty = Table::new(
+ table.file_io().clone(),
+ Identifier::new("default", "empty"),
+ "memory:/empty".into(),
+ table.schema().clone(),
+ None,
+ );
+ empty
+ .file_io()
+ .new_output(&empty.schema_manager().schema_path(0))
+ .unwrap()
+ .write(serde_json::to_vec(empty.schema()).unwrap().into())
+ .await
+ .unwrap();
+ ctx.ctx()
+ .register_table(
+ "empty",
+ Arc::new(PaimonTableProvider::try_new(empty.clone()).unwrap()),
+ )
+ .unwrap();
+ let mut inputs = Vec::new();
+ for (operation, projection) in [("DELETE", "*"), ("UPDATE", "id, v + 1 AS
v")] {
+ inputs.push(
+ plan_input(&ctx, &empty, "empty", projection, None, operation)
+ .await
+ .unwrap(),
+ );
+ }
+ ctx.ctx()
+ .sql("INSERT INTO empty VALUES (1, 10)")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for input in inputs {
+ assert!(collect_rows(input).await.is_empty());
+ }
+}
diff --git a/crates/integrations/datafusion/src/table/mod.rs
b/crates/integrations/datafusion/src/table/mod.rs
index 2c14da87..ab991897 100644
--- a/crates/integrations/datafusion/src/table/mod.rs
+++ b/crates/integrations/datafusion/src/table/mod.rs
@@ -202,14 +202,18 @@ impl PaimonTableProvider {
self
}
- pub(crate) fn with_primary_key_delete_snapshot(mut self, snapshot:
&Snapshot) -> Self {
- // Merge L0 versions before evaluating DELETE predicates, even when
+ pub(crate) fn with_primary_key_mutation_snapshot(
+ mut self,
+ snapshot: Option<&Snapshot>,
+ ) -> Self {
+ // Merge L0 versions before evaluating mutations, 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)
+ self.table = self.table.copy_with_pinned_snapshot(snapshot);
+ self
}
}
diff --git a/crates/integrations/datafusion/src/update.rs
b/crates/integrations/datafusion/src/update.rs
index f672081e..b5fdc6dc 100644
--- a/crates/integrations/datafusion/src/update.rs
+++ b/crates/integrations/datafusion/src/update.rs
@@ -17,7 +17,8 @@
//! UPDATE execution for Paimon tables.
//!
-//! Supports two execution paths:
+//! Supports three execution paths:
+//! - **Deduplicate primary-key tables**: complete-row upserts via the normal
writer.
//! - **Data evolution tables**: partial-column writes via
[`paimon::table::DataEvolutionWriter`].
//! - **Append-only tables** (no PK, no deletion vectors): copy-on-write file
rewriting
//! via [`paimon::table::CopyOnWriteMergeWriter`].
@@ -26,11 +27,13 @@ use std::sync::Arc;
use datafusion::arrow::array::{Array, RecordBatch};
use datafusion::arrow::datatypes::{Field, Schema};
+use datafusion::common::Column;
use datafusion::error::{DataFusionError, Result as DFResult};
+use datafusion::logical_expr::{Expr, ExprSchemable};
use datafusion::prelude::{DataFrame, SessionContext};
use datafusion::sql::sqlparser::ast::{AssignmentTarget, TableFactor, Update};
-use paimon::spec::CoreOptions;
+use paimon::spec::{CoreOptions, RowKind};
use paimon::table::{CopyOnWriteMergeWriter, Table};
use crate::error::to_datafusion_error;
@@ -40,6 +43,7 @@ use crate::merge_into::{
project_update_columns, quote_identifier, register_cow_target_table,
retry_on_conflict,
validate_update_columns, TempTableTracker,
};
+use crate::primary_key_dml;
use crate::sql_context::{normalize_schema_identifier, SQLContext};
/// Execute an UPDATE statement on a Paimon table.
@@ -64,12 +68,89 @@ pub(crate) async fn execute_update(
} else if schema.trimmed_primary_keys().is_empty() {
execute_cow_update(ctx, update, &table,
enable_ident_normalization).await
} else {
- Err(DataFusionError::Plan(
- "UPDATE on primary-key tables without data-evolution is not
supported".to_string(),
- ))
+ execute_primary_key_update(ctx, update, &table,
enable_ident_normalization).await
}
}
+async fn execute_primary_key_update(
+ ctx: &SQLContext,
+ update: &Update,
+ table: &Table,
+ enable_ident_normalization: bool,
+) -> DFResult<DataFrame> {
+ primary_key_dml::validate_table(table, "UPDATE")?;
+ if !update.table.joins.is_empty()
+ || update.from.is_some()
+ || update.returning.is_some()
+ || update.output.is_some()
+ || update.or.is_some()
+ || !update.optimizer_hints.is_empty()
+ || !update.order_by.is_empty()
+ || update.limit.is_some()
+ || !matches!(&update.table.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 UPDATE supports a single target, SET assignments and
an optional WHERE clause".into(),
+ ));
+ }
+ if update.assignments.iter().any(|assignment| {
+ !matches!(&assignment.target, AssignmentTarget::ColumnName(name) if
name.0.len() == 1)
+ }) {
+ return Err(DataFusionError::NotImplemented(
+ "Primary-key UPDATE requires unqualified, top-level SET
columns".into(),
+ ));
+ }
+ let schema = table.schema();
+ let (columns, expressions) = extract_set_assignments(update,
enable_ident_normalization)?;
+ validate_update_columns(&columns, schema.fields())?;
+ for column in &columns {
+ if schema.primary_keys().contains(column) ||
schema.partition_keys().contains(column) {
+ return Err(DataFusionError::Plan(format!(
+ "Primary-key UPDATE cannot modify primary-key or partition
column '{column}'"
+ )));
+ }
+ }
+ // All assignments share the original row, including references to other
SET columns.
+ let projection = schema
+ .fields()
+ .iter()
+ .map(|field| {
+ let name = quote_identifier(field.name());
+ match columns.iter().position(|column| column == field.name()) {
+ Some(index) => format!("({}) AS {name}", expressions[index]),
+ None => name,
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ let input = primary_key_dml::plan_input(
+ ctx,
+ table,
+ &update.table.to_string(),
+ &projection,
+ update.selection.as_ref(),
+ "UPDATE",
+ )
+ .await?;
+ let target_schema =
+
paimon::arrow::build_target_arrow_schema(schema.fields()).map_err(to_datafusion_error)?;
+ let projection = target_schema
+ .fields()
+ .iter()
+ .map(|field| {
+ Expr::Column(Column::from_name(field.name()))
+ .cast_to(field.data_type(), input.schema())
+ .map(|expr| expr.alias(field.name()))
+ })
+ .collect::<DFResult<Vec<_>>>()?;
+ let input = input.select(projection)?;
+ primary_key_dml::write_rows(ctx, table, input, RowKind::UpdateAfter,
"UPDATE").await
+}
+
// ---------------------------------------------------------------------------
// Data evolution path
// ---------------------------------------------------------------------------
@@ -338,8 +419,6 @@ mod tests {
use datafusion::sql::sqlparser::dialect::GenericDialect;
use datafusion::sql::sqlparser::parser::Parser;
use paimon::catalog::{Catalog, Identifier};
- use paimon::io::FileIOBuilder;
- use paimon::spec::{DataType, IntType, Schema as PaimonSchema, TableSchema};
use paimon::{CatalogOptions, FileSystemCatalog, Options};
use tempfile::TempDir;
@@ -626,44 +705,6 @@ mod tests {
assert_eq!(before, after);
}
- #[tokio::test]
- async fn test_update_rejects_pk_table_without_data_evolution() {
- let file_io = FileIOBuilder::new("memory").build().unwrap();
- let table_path = "memory:/test_update_reject";
- file_io
- .mkdirs(&format!("{table_path}/snapshot/"))
- .await
- .unwrap();
- file_io
- .mkdirs(&format!("{table_path}/manifest/"))
- .await
- .unwrap();
-
- let schema = PaimonSchema::builder()
- .column("id", DataType::Int(IntType::new()))
- .primary_key(["id"])
- .option("bucket", "1")
- .build()
- .unwrap();
- let table_schema = TableSchema::new(0, &schema);
- let table = Table::new(
- file_io,
- Identifier::new("default", "t"),
- table_path.to_string(),
- table_schema,
- None,
- );
-
- let sql_context = SQLContext::new();
- let update = parse_update("UPDATE t SET id = 1");
- let result = execute_update(&sql_context, &update, table, true).await;
- assert!(result.is_err());
- assert!(result
- .unwrap_err()
- .to_string()
- .contains("primary-key tables without data-evolution"));
- }
-
// -----------------------------------------------------------------------
// CoW UPDATE tests (append-only tables)
// -----------------------------------------------------------------------
diff --git a/crates/integrations/datafusion/tests/common/mod.rs
b/crates/integrations/datafusion/tests/common/mod.rs
index 23d9fb9c..5aa36463 100644
--- a/crates/integrations/datafusion/tests/common/mod.rs
+++ b/crates/integrations/datafusion/tests/common/mod.rs
@@ -48,6 +48,20 @@ pub fn create_test_env() -> (TempDir,
Arc<FileSystemCatalog>) {
(temp_dir, Arc::new(catalog))
}
+#[allow(dead_code)]
+pub 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
+}
+
pub async fn create_sql_context(catalog: Arc<FileSystemCatalog>) -> SQLContext
{
let mut ctx = SQLContext::new();
ctx.register_catalog("paimon", catalog).await.unwrap();
diff --git a/crates/integrations/datafusion/tests/pk_delete_tests.rs
b/crates/integrations/datafusion/tests/pk_delete_tests.rs
index 3ed412e5..42733223 100644
--- a/crates/integrations/datafusion/tests/pk_delete_tests.rs
+++ b/crates/integrations/datafusion/tests/pk_delete_tests.rs
@@ -17,7 +17,7 @@
mod common;
-use common::{assert_sql_error, create_sql_context, create_test_env, dml_count,
exec};
+use common::{assert_sql_error, create_sql_context, create_test_env, dml_count,
exec, files_under};
use paimon::catalog::Identifier;
use paimon::{Catalog, CatalogOptions, FileSystemCatalog, Options};
use paimon_datafusion::SQLContext;
@@ -664,19 +664,6 @@ async fn
primary_key_delete_pins_snapshot_and_respects_concurrent_upsert_sequenc
}
}
-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();
diff --git a/crates/integrations/datafusion/tests/pk_update_tests.rs
b/crates/integrations/datafusion/tests/pk_update_tests.rs
new file mode 100644
index 00000000..8856d9b9
--- /dev/null
+++ b/crates/integrations/datafusion/tests/pk_update_tests.rs
@@ -0,0 +1,684 @@
+// 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, files_under};
+use datafusion::arrow::array::{Array, Int32Array};
+use paimon::catalog::Identifier;
+use paimon::{Catalog, FileSystemCatalog};
+use paimon_datafusion::SQLContext;
+use std::sync::Arc;
+
+async fn setup(
+ bucket: i32,
+ options: &str,
+) -> (tempfile::TempDir, Arc<FileSystemCatalog>, SQLContext) {
+ let (tmp, catalog) = create_test_env();
+ let ctx = create_sql_context(catalog.clone()).await;
+ exec(&ctx, "CREATE SCHEMA paimon.test_db").await;
+ exec(
+ &ctx,
+ &format!(
+ "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, w INT,
PRIMARY KEY (id)) \
+ WITH ('bucket' = '{bucket}', 'write-only' = 'true'{options})"
+ ),
+ )
+ .await;
+ (tmp, catalog, ctx)
+}
+
+async fn rows(ctx: &SQLContext) -> Vec<(i32, Option<i32>, Option<i32>)> {
+ let batches = ctx
+ .sql("SELECT id, v, w 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();
+ let other = batch
+ .column(2)
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .unwrap();
+ rows.extend((0..batch.num_rows()).map(|i| {
+ (
+ ids.value(i),
+ values.is_valid(i).then(|| values.value(i)),
+ other.is_valid(i).then(|| other.value(i)),
+ )
+ }));
+ }
+ 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_update_uses_logical_rows_and_original_assignment_values()
{
+ for bucket in [2, -1] {
+ let (_tmp, catalog, ctx) = setup(bucket, "").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.t VALUES (1, 10, 100), (2, 20, 200),
(3, NULL, 300), (4, 40, 400)",
+ )
+ .await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 11, 101)").await;
+ assert_eq!(
+ dml_count(&ctx, "DELETE FROM paimon.test_db.t WHERE id = 4").await,
+ 1
+ );
+ let before = snapshot(&catalog).await;
+ for predicate in ["v = 10", "id = 4"] {
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("UPDATE paimon.test_db.t SET w = 0 WHERE
{predicate}")
+ )
+ .await,
+ 0
+ );
+ assert_eq!(snapshot(&catalog).await, before);
+ }
+ assert_eq!(
+ dml_count(
+ &ctx,
+ "UPDATE paimon.test_db.t SET v = v + 1, w = v WHERE t.v <> 11"
+ )
+ .await,
+ 1
+ );
+ assert_eq!(
+ rows(&ctx).await,
+ vec![
+ (1, Some(11), Some(101)),
+ (2, Some(21), Some(20)),
+ (3, None, Some(300))
+ ]
+ );
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET v = 5 WHERE v IS
NULL").await,
+ 1
+ );
+ for expected in [
+ vec![
+ (1, Some(101), Some(11)),
+ (2, Some(20), Some(21)),
+ (3, Some(300), Some(5)),
+ ],
+ vec![
+ (1, Some(11), Some(101)),
+ (2, Some(21), Some(20)),
+ (3, Some(5), Some(300)),
+ ],
+ ] {
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET v = w, w =
v").await,
+ 3
+ );
+ assert_eq!(rows(&ctx).await, expected);
+ }
+ let before_rows = rows(&ctx).await;
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET v = v").await,
+ 3
+ );
+ assert_eq!(rows(&ctx).await, before_rows);
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_validates_assignments_before_writing() {
+ let (tmp, catalog, ctx) = setup(2, "").await;
+ let before_files = files_under(tmp.path());
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET v = 1").await,
+ 0
+ );
+ assert_eq!(snapshot(&catalog).await, None);
+ assert_eq!(files_under(tmp.path()), before_files);
+ for populated in [false, true] {
+ if populated {
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10,
100)").await;
+ }
+ let before = snapshot(&catalog).await;
+ let before_rows = rows(&ctx).await;
+ let before_files = files_under(tmp.path());
+ for (sql, error) in [
+ ("UPDATE paimon.test_db.t SET missing = 1", "Unknown column"),
+ ("UPDATE paimon.test_db.t SET \"V\" = 1", "Unknown column"),
+ (
+ "UPDATE paimon.test_db.t SET v = v, V = 1",
+ "Duplicate column",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET v = no_such_column",
+ "no_such_column",
+ ),
+ ] {
+ assert_sql_error(&ctx, sql, error).await;
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(rows(&ctx).await, before_rows);
+ assert_eq!(files_under(tmp.path()), before_files);
+ }
+ }
+}
+
+#[tokio::test]
+async fn
primary_key_update_preserves_partition_composite_key_and_quoted_strings() {
+ 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, \"Key.Part\" STRING NOT NULL, pt INT NOT NULL, \"Value.Name\" STRING,
untouched STRING, PRIMARY KEY (\"Key.Id\", \"Key.Part\", pt)) PARTITIONED BY
(pt) WITH ('bucket' = '2')").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.\"odd.name\" VALUES (1, 'a', 1, 'first',
'keep-first'), (1, 'b', 1, 'second', 'keep-second'), (1, 'a', 2, 'third',
'keep-third'), (2, 'a', 1, 'fourth', 'keep-fourth')",
+ )
+ .await;
+ assert_eq!(dml_count(&ctx, "UPDATE paimon.test_db.\"odd.name\" SET
\"Value.Name\" = concat(\"Value.Name\", '_new') WHERE \"Key.Id\" = 1 AND
\"Key.Part\" = 'a' AND pt = 1").await, 1);
+ assert_eq!(
+ common::collect_id_name(
+ &ctx,
+ "SELECT \"Key.Id\" AS id, concat(\"Key.Part\", ':', pt, ':',
\"Value.Name\", ':', untouched) AS name FROM paimon.test_db.\"odd.name\" ORDER
BY id, name"
+ )
+ .await,
+ vec![
+ (1, "a:1:first_new:keep-first".into()),
+ (1, "a:2:third:keep-third".into()),
+ (1, "b:1:second:keep-second".into()),
+ (2, "a:1:fourth:keep-fourth".into()),
+ ]
+ );
+ for sql in [
+ "UPDATE paimon.test_db.\"odd.name\" SET \"Key.Id\" = 3",
+ "UPDATE paimon.test_db.\"odd.name\" SET \"Key.Part\" = 'c'",
+ "UPDATE paimon.test_db.\"odd.name\" SET pt = 3",
+ ] {
+ assert_sql_error(&ctx, sql, "cannot modify primary-key or partition
column").await;
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_supports_predicate_and_assignment_subqueries() {
+ let (_tmp, _catalog, ctx) = setup(2, "").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.t VALUES (1, 10, 100), (2, 20, 200), (3,
30, 300)",
+ )
+ .await;
+ assert_eq!(dml_count(&ctx, "UPDATE paimon.test_db.t SET w = (SELECT MAX(v)
FROM paimon.test_db.t) WHERE id IN (SELECT id FROM paimon.test_db.t WHERE v =
20)").await, 1);
+ exec(&ctx, "CREATE TEMPORARY VIEW selected_ids AS SELECT 3 AS id").await;
+ assert_eq!(dml_count(&ctx, "UPDATE paimon.test_db.t SET w = w + 1 WHERE
EXISTS (SELECT 1 FROM selected_ids s WHERE s.id = t.id)").await, 1);
+ assert_eq!(
+ rows(&ctx).await,
+ vec![
+ (1, Some(10), Some(100)),
+ (2, Some(20), Some(30)),
+ (3, Some(30), Some(301))
+ ]
+ );
+}
+
+#[tokio::test]
+async fn primary_key_update_preserves_and_assigns_sequence_fields() {
+ for (options, losing, winning) in [
+ (", 'sequence.field' = 'v'", 99, 101),
+ (
+ ", 'sequence.field' = 'v', 'sequence.field.sort-order' =
'descending'",
+ 101,
+ 99,
+ ),
+ ] {
+ let (_tmp, _catalog, ctx) = setup(2, options).await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 100, 10)").await;
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET w = 11").await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(1, Some(100), Some(11))]);
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("UPDATE paimon.test_db.t SET v = {losing}, w = 12")
+ )
+ .await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(1, Some(100), Some(11))]);
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!("UPDATE paimon.test_db.t SET v = {winning}, w = 13")
+ )
+ .await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(1, Some(winning), Some(13))]);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn primary_key_update_pins_snapshot_and_respects_concurrent_upserts() {
+ use datafusion::arrow::datatypes::DataType;
+ use datafusion::logical_expr::{create_udf, Volatility};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ for (options, expected) in [
+ ("", (Some(10), Some(101))),
+ (", 'sequence.field' = 'v'", (Some(20), Some(200))),
+ (
+ ", 'sequence.field' = 'v', 'sequence.field.sort-order' =
'descending'",
+ (Some(10), Some(101)),
+ ),
+ ] {
+ let (_tmp, _catalog, ctx) = setup(2, options).await;
+ let ctx = Arc::new(ctx);
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10, 100)").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, 200), (2, 10, 10)")
+ .await?
+ .collect()
+ .await
+ })
+ })?;
+ }
+ Ok(args[0].clone())
+ }),
+ ));
+ let sql = "UPDATE paimon.test_db.t SET w = interfere(w) + 1";
+ assert_eq!(dml_count(&ctx, sql).await, 1);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ rows(&ctx).await,
+ vec![(1, expected.0, expected.1), (2, Some(10), Some(10))]
+ );
+ assert_eq!(dml_count(&ctx, sql).await, 2);
+ assert!(calls.load(Ordering::SeqCst) > 1);
+ assert_eq!(
+ rows(&ctx).await,
+ vec![
+ (1, expected.0, expected.1.map(|value| value + 1)),
+ (2, Some(10), Some(11)),
+ ]
+ );
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_rejects_unsupported_targets_and_syntax() {
+ for engine in ["partial-update", "aggregation", "first-row"] {
+ let (_tmp, _catalog, ctx) = setup(2, &format!(", 'merge-engine' =
'{engine}'")).await;
+ assert_sql_error(
+ &ctx,
+ "UPDATE paimon.test_db.t SET v = 1",
+ "requires merge-engine=deduplicate",
+ )
+ .await;
+ }
+ let (_tmp, catalog, ctx) = setup(2, "").await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10, 100)").await;
+ let before = snapshot(&catalog).await;
+ for (sql, error) in [
+ ("UPDATE paimon.test_db.t SET id = 2", "cannot modify"),
+ (
+ "UPDATE paimon.test_db.t SET t.v = 2",
+ "top-level SET columns",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET (v, w) = (1, 2)",
+ "top-level SET columns",
+ ),
+ ("UPDATE paimon.test_db.t AS x SET v = 1", "alias"),
+ (
+ "UPDATE paimon.test_db.t SET v = 1 RETURNING id",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET v = 1 FROM paimon.test_db.t other
WHERE t.id = other.id",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t JOIN paimon.test_db.t other ON t.id =
other.id SET v = 1",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET v = 1 OUTPUT inserted.id",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE OR IGNORE paimon.test_db.t SET v = 1",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t WITH (NOLOCK) SET v = 1",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET v = 1 ORDER BY id LIMIT 1",
+ "optional WHERE",
+ ),
+ (
+ "UPDATE paimon.test_db.t SET v = 1 LIMIT 1",
+ "optional WHERE",
+ ),
+ ] {
+ assert_sql_error(&ctx, sql, error).await;
+ }
+ exec(
+ &ctx,
+ "CREATE TEMPORARY VIEW paimon.test_db.t AS SELECT 99 AS id",
+ )
+ .await;
+ assert_sql_error(&ctx, "UPDATE paimon.test_db.t SET v = 1",
"temporary").await;
+ exec(&ctx, "DROP TEMPORARY VIEW paimon.test_db.t").await;
+ assert_sql_error(
+ &ctx,
+ "UPDATE paimon.test_db.t$branch_dev SET v = 1",
+ "branch",
+ )
+ .await;
+ exec(&ctx, "SET 'paimon.scan.snapshot-id' = '1'").await;
+ assert_sql_error(
+ &ctx,
+ "UPDATE paimon.test_db.t SET v = 1",
+ "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,
+ "UPDATE paimon.test_db.t SET v = 1",
+ "historical/incremental read options",
+ )
+ .await;
+ exec(&ctx, "RESET 'paimon.incremental-between-timestamp'").await;
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10), Some(100))]);
+}
+
+#[tokio::test]
+async fn primary_key_update_rejects_overridden_read_semantics() {
+ for (option, value) in [
+ ("sequence.field", "v"),
+ ("bucket", "-1"),
+ ("deletion-vectors.enabled", "true"),
+ ] {
+ let (_tmp, catalog, ctx) = setup(2, "").await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 20, 100)").await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10, 100)").await;
+ let before = snapshot(&catalog).await;
+ exec(&ctx, &format!("SET 'paimon.{option}' = '{value}'")).await;
+ assert_sql_error(&ctx, "UPDATE paimon.test_db.t SET w = 1", "read
options").await;
+ exec(
+ &ctx,
+ "CREATE TEMPORARY VIEW captured_target AS SELECT * FROM
paimon.test_db.t",
+ )
+ .await;
+ exec(&ctx, &format!("RESET 'paimon.{option}'")).await;
+ assert_sql_error(
+ &ctx,
+ "UPDATE paimon.test_db.t SET w = (SELECT MIN(w) FROM
captured_target)",
+ "read options",
+ )
+ .await;
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10), Some(100))]);
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_discards_partial_output_when_an_expression_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(
+ 2,
+ ", '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, 100)").await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (2, 20, 200)").await;
+ let before_files = files_under(tmp.path());
+ let before_snapshot = snapshot(&catalog).await;
+ let root = tmp.path().to_path_buf();
+ let initial_files = before_files.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")));
+ return Err(DataFusionError::Execution("injected SET
failure".into()));
+ }
+ Ok(args[0].clone())
+ }),
+ ));
+ assert_sql_error(
+ &ctx,
+ "UPDATE paimon.test_db.t SET w = fail_after_batch(w) + 1",
+ "injected SET failure",
+ )
+ .await;
+ assert!(calls.load(Ordering::SeqCst) >= 2);
+ assert_eq!(snapshot(&catalog).await, before_snapshot);
+ assert_eq!(files_under(tmp.path()), before_files);
+ assert_eq!(
+ rows(&ctx).await,
+ vec![(1, Some(10), Some(100)), (2, Some(20), Some(200))]
+ );
+}
+
+#[tokio::test]
+async fn primary_key_update_writes_update_after_and_coerces_assignments() {
+ for options in [
+ ", 'changelog-producer' = 'input'",
+ ", 'ignore-delete' = 'true'",
+ ] {
+ let (_tmp, _catalog, ctx) = setup(2, options).await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10, 100)").await;
+ assert_eq!(
+ dml_count(
+ &ctx,
+ "UPDATE paimon.test_db.t SET v = CAST(12 AS BIGINT), w = NULL"
+ )
+ .await,
+ 1
+ );
+ assert_eq!(rows(&ctx).await, vec![(1, Some(12), None)]);
+ assert_eq!(
+ common::collect_id_name(
+ &ctx,
+ "SELECT id, rowkind AS name FROM paimon.test_db.t$audit_log"
+ )
+ .await,
+ vec![(1, "+U".into())]
+ );
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_merges_uncompacted_deletion_vector_versions() {
+ use paimon::{CatalogOptions, Options};
+ for merge_on_read in [false, true] {
+ 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(catalog.clone()).await;
+ exec(&ctx, "CREATE SCHEMA paimon.test_db").await;
+ exec(&ctx, &format!(
+ "CREATE TABLE paimon.test_db.t (id INT NOT NULL, v INT, w INT,
PRIMARY KEY (id)) \
+ WITH ('bucket' = '2', 'write-only' = 'true',
'deletion-vectors.enabled' = 'true', 'deletion-vectors.merge-on-read' =
'{merge_on_read}')"
+ )).await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.t VALUES (1, 10, 100), (2, 30, 300)",
+ )
+ .await;
+ exec(&ctx, "CALL sys.compact(table => 'test_db.t')").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.t VALUES (1, 20, 200), (3, 40, 400)",
+ )
+ .await;
+ let before = snapshot(&catalog).await;
+ assert_eq!(
+ dml_count(&ctx, "UPDATE paimon.test_db.t SET w = 0 WHERE v =
10").await,
+ 0
+ );
+ assert_eq!(snapshot(&catalog).await, before);
+ assert_eq!(dml_count(&ctx, "UPDATE paimon.test_db.t SET w = (SELECT
MAX(w) FROM paimon.test_db.t) WHERE id IN (SELECT id FROM paimon.test_db.t
WHERE v = 20)").await, 1);
+ exec(&ctx, "SET 'paimon.deletion-vectors.merge-on-read' =
'true'").await;
+ assert_eq!(
+ rows(&ctx).await,
+ vec![
+ (1, Some(20), Some(400)),
+ (2, Some(30), Some(300)),
+ (3, Some(40), Some(400))
+ ]
+ );
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_respects_lexicographic_sequence_order() {
+ for (order, losing, winning) in [
+ ("ascending", (99, 1000), (101, 0)),
+ ("descending", (101, 0), (99, 1000)),
+ ] {
+ let (_tmp, _catalog, ctx) = setup(
+ 2,
+ &format!(", 'sequence.field' = 'v,w', 'sequence.field.sort-order'
= '{order}'"),
+ )
+ .await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 100, 100)").await;
+ let (losing_tie, winning_tie) = if order == "ascending" {
+ (99, 101)
+ } else {
+ (101, 99)
+ };
+ for (assigned, expected) in [
+ (losing, (100, 100)),
+ ((100, losing_tie), (100, 100)),
+ ((100, winning_tie), (100, winning_tie)),
+ (winning, winning),
+ ] {
+ assert_eq!(
+ dml_count(
+ &ctx,
+ &format!(
+ "UPDATE paimon.test_db.t SET v = {}, w = {}",
+ assigned.0, assigned.1
+ )
+ )
+ .await,
+ 1
+ );
+ assert_eq!(
+ rows(&ctx).await,
+ vec![(1, Some(expected.0), Some(expected.1))],
+ "{order}: {assigned:?}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn primary_key_update_assignment_failures_preserve_the_table() {
+ let (tmp, catalog, ctx) = setup(2, "").await;
+ exec(&ctx, "CREATE TABLE paimon.test_db.constrained (id INT NOT NULL, v
INT NOT NULL, PRIMARY KEY (id)) WITH ('bucket' = '1')").await;
+ exec(
+ &ctx,
+ "INSERT INTO paimon.test_db.constrained VALUES (1, 10)",
+ )
+ .await;
+ exec(&ctx, "INSERT INTO paimon.test_db.t VALUES (1, 10, 100)").await;
+ let before_snapshot = snapshot(&catalog).await;
+ let before_files = files_under(tmp.path());
+ for (sql, expected) in [
+ (
+ "UPDATE paimon.test_db.t SET v = CAST('invalid' AS INT)",
+ "cast",
+ ),
+ ("UPDATE paimon.test_db.t SET v = 2147483648", "cast"),
+ ("UPDATE paimon.test_db.constrained SET v = NULL", "non-null"),
+ ] {
+ assert_sql_error(&ctx, sql, expected).await;
+ assert_eq!(files_under(tmp.path()), before_files);
+ }
+ assert_eq!(snapshot(&catalog).await, before_snapshot);
+ assert_eq!(rows(&ctx).await, vec![(1, Some(10), Some(100))]);
+ assert_eq!(
+ common::collect_id_value(
+ &ctx,
+ "SELECT id, v AS value FROM paimon.test_db.constrained"
+ )
+ .await,
+ vec![(1, 10)]
+ );
+}
diff --git a/crates/integrations/datafusion/tests/update_tests.rs
b/crates/integrations/datafusion/tests/update_tests.rs
index b753d3d1..a06e2aed 100644
--- a/crates/integrations/datafusion/tests/update_tests.rs
+++ b/crates/integrations/datafusion/tests/update_tests.rs
@@ -672,32 +672,6 @@ async fn test_update_selects_rows_before_set() {
// ======================= Unsupported cases =======================
-#[tokio::test]
-async fn test_update_rejects_primary_key_table_without_data_evolution() {
- 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,
- "UPDATE paimon.test_db.pk_t SET name = 'x' WHERE id = 1",
- "primary-key tables without data-evolution",
- )
- .await;
- drop(tmp);
-}
-
#[tokio::test]
async fn test_rejects_primary_key_data_evolution_table_at_create() {
let (tmp, catalog) = create_test_env();
diff --git a/docs/src/sql.md b/docs/src/sql.md
index b9ab86fc..0bb18fe1 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1050,7 +1050,33 @@ For append-only tables (no primary key), updates are
executed using Copy-on-Writ
UPDATE paimon.my_db.t SET name = 'a_new' WHERE id = 1;
```
-For data-evolution row-tracking tables without primary keys, updates are
executed with row-id-based partial-column writes. Primary-key tables are not
supported for `UPDATE`.
+For data-evolution row-tracking tables without primary keys, updates are
executed with row-id-based partial-column writes.
+
+Ordinary primary-key tables using `merge-engine=deduplicate` support `UPDATE`
by
+writing complete updated rows with the `UPDATE_AFTER` row kind. All SET
+expressions use the original row; unassigned columns retain their values.
+Primary-key and partition columns cannot be assigned.
+
+The target and its live self-references in predicates and SET expressions use
+one captured snapshot, including uncompacted deletion-vector versions. Target
+validation and read-option restrictions follow the primary-key DELETE rules
+below. Explicit historical and incremental views keep their selected read view.
+
+Configured sequence values are preserved unless assigned by SET, and the normal
+sequence sort order applies to the updated rows. A lower-priority assigned
+sequence or a higher-priority concurrent upsert can leave the stored row
+unchanged. The affected-row count reports rows matching the predicate in the
+captured snapshot, including updates that lose under these merge rules. This
+does not provide serializable updates.
+
+No matches publish no snapshot. Publication retries reuse prepared files
without
+rescanning; repeating the SQL statement is a new operation. A commit error can
+occur after publication, so prepared files are retained and the error
identifies
+the table and commit user.
+
+Other merge engines, `rowkind.field`, query-authorized targets, aliases, joins,
+`FROM`, `RETURNING`, `OUTPUT`, `ORDER BY`, `LIMIT`, target modifiers and tuple
or
+qualified/nested SET targets are not supported by this primary-key UPDATE path.
### DELETE