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 037e1cc3 fix(datafusion): honor ORDER BY and LIMIT in UPDATE and 
DELETE (#1397)
037e1cc3 is described below

commit 037e1cc333d69a61f6d251e7c106436c716140a3
Author: linfeng <[email protected]>
AuthorDate: Mon Nov 16 13:23:15 2026 +0800

    fix(datafusion): honor ORDER BY and LIMIT in UPDATE and DELETE (#1397)
---
 crates/integrations/datafusion/src/delete.rs       |  42 ++++---
 crates/integrations/datafusion/src/merge_into.rs   |  39 +++++-
 crates/integrations/datafusion/src/update.rs       |  43 ++++---
 .../integrations/datafusion/tests/delete_tests.rs  |  65 ++++++++++
 .../integrations/datafusion/tests/update_tests.rs  | 139 +++++++++++++++++++++
 5 files changed, 294 insertions(+), 34 deletions(-)

diff --git a/crates/integrations/datafusion/src/delete.rs 
b/crates/integrations/datafusion/src/delete.rs
index 11a14c02..bad2c812 100644
--- a/crates/integrations/datafusion/src/delete.rs
+++ b/crates/integrations/datafusion/src/delete.rs
@@ -29,8 +29,9 @@ use paimon::table::{CopyOnWriteMergeWriter, Table};
 use crate::error::to_datafusion_error;
 use crate::merge_into::TempTableTracker;
 use crate::merge_into::{
-    build_partition_set_from_where, extract_tracking_columns, 
is_delete_conflict,
-    is_row_id_conflict, ok_result, register_cow_target_table, 
retry_on_conflict,
+    build_dml_selection_clause, build_partition_set_from_where, 
dml_table_alias,
+    extract_tracking_columns, is_delete_conflict, is_row_id_conflict, 
ok_result,
+    register_cow_target_table, retry_on_conflict,
 };
 use crate::sql_context::SQLContext;
 
@@ -94,11 +95,12 @@ async fn execute_data_evolution_delete_once(
     let wb = table.new_write_builder();
     let mut writer = wb.new_delete().map_err(to_datafusion_error)?;
 
-    let where_clause = match &delete.selection {
-        Some(expr) => format!(" WHERE {expr}"),
-        None => String::new(),
-    };
-    let query_sql = format!("SELECT \"_ROW_ID\" FROM 
{table_ref}{where_clause}");
+    let selection_clause = build_dml_selection_clause(
+        delete.selection.as_ref(),
+        &delete.order_by,
+        delete.limit.as_ref(),
+    );
+    let query_sql = format!("SELECT \"_ROW_ID\" FROM 
{table_ref}{selection_clause}");
     let batches = ctx.ctx().sql(&query_sql).await?.collect().await?;
 
     let total_count: u64 = batches.iter().map(|batch| batch.num_rows() as 
u64).sum();
@@ -160,8 +162,14 @@ async fn execute_cow_delete_once(
     }
 
     let cow_target_qualified = cow_table_name;
-    let result =
-        execute_cow_delete_inner(ctx.ctx(), &cow_target_qualified, delete, 
&mut writer).await;
+    let result = execute_cow_delete_inner(
+        ctx.ctx(),
+        &cow_target_qualified,
+        table_ref,
+        delete,
+        &mut writer,
+    )
+    .await;
     let total_count = result?;
 
     let messages = writer.prepare_commit().await.map_err(to_datafusion_error)?;
@@ -179,17 +187,19 @@ async fn execute_cow_delete_once(
 async fn execute_cow_delete_inner(
     ctx: &SessionContext,
     cow_table_name: &str,
+    table_ref: &str,
     delete: &Delete,
     writer: &mut CopyOnWriteMergeWriter,
 ) -> DFResult<u64> {
-    let where_clause = match &delete.selection {
-        Some(expr) => format!(" WHERE {expr}"),
-        None => String::new(),
-    };
-
-    // Safety: where_clause comes from sqlparser AST to_string(), not raw user 
input.
+    let selection_clause = build_dml_selection_clause(
+        delete.selection.as_ref(),
+        &delete.order_by,
+        delete.limit.as_ref(),
+    );
+    let alias = dml_table_alias(ctx, table_ref);
     let query_sql = format!(
-        "SELECT \"__paimon_file_idx\", \"__paimon_row_offset\" FROM 
{cow_table_name}{where_clause}"
+        "SELECT \"__paimon_file_idx\", \"__paimon_row_offset\" \
+         FROM {cow_table_name} AS {alias}{selection_clause}"
     );
     let batches = ctx.sql(&query_sql).await?.collect().await?;
 
diff --git a/crates/integrations/datafusion/src/merge_into.rs 
b/crates/integrations/datafusion/src/merge_into.rs
index 6dc79a30..79c13952 100644
--- a/crates/integrations/datafusion/src/merge_into.rs
+++ b/crates/integrations/datafusion/src/merge_into.rs
@@ -36,7 +36,7 @@ use datafusion::arrow::datatypes::{DataType as ArrowDataType, 
Field, Schema, Sch
 use datafusion::arrow::record_batch::RecordBatchOptions;
 use datafusion::catalog::Session;
 use datafusion::common::tree_node::{Transformed, TreeNode};
-use datafusion::common::{Column, DFSchema, DFSchemaRef};
+use datafusion::common::{Column, DFSchema, DFSchemaRef, TableReference};
 use datafusion::datasource::sink::{DataSink, DataSinkExec};
 use datafusion::datasource::MemTable;
 use datafusion::error::{DataFusionError, Result as DFResult};
@@ -49,6 +49,7 @@ use datafusion::physical_expr::{expressions::Column as 
PhysicalColumn, PhysicalE
 use datafusion::physical_plan::projection::ProjectionExec;
 use datafusion::physical_plan::{DisplayAs, ExecutionPlan};
 use datafusion::prelude::{DataFrame, SessionContext};
+use datafusion::sql::sqlparser::ast::{Expr as SqlExpr, OrderByExpr};
 use futures::TryStreamExt;
 
 use paimon::spec::{datums_to_binary_row, extract_datum_from_arrow, 
CoreOptions, DataField};
@@ -1163,6 +1164,42 @@ pub(crate) fn build_partition_set_from_batches(
     Ok(Some(partition_set))
 }
 
+/// Use the original target name as the alias of an internal DML relation.
+pub(crate) fn dml_table_alias(ctx: &SessionContext, table_ref: &str) -> String 
{
+    let normalize = ctx
+        .state()
+        .config_options()
+        .sql_parser
+        .enable_ident_normalization;
+    let target = TableReference::parse_str_normalized(table_ref, !normalize);
+    quote_identifier(target.table())
+}
+
+/// Preserve DML row selection in the internal SELECT so filtering, global 
sorting,
+/// and limiting finish before any selected rows are passed to the writer.
+pub(crate) fn build_dml_selection_clause(
+    selection: Option<&SqlExpr>,
+    order_by: &[OrderByExpr],
+    limit: Option<&SqlExpr>,
+) -> String {
+    let mut clause = String::new();
+    if let Some(selection) = selection {
+        clause.push_str(&format!(" WHERE {selection}"));
+    }
+    if !order_by.is_empty() {
+        let order_by = order_by
+            .iter()
+            .map(ToString::to_string)
+            .collect::<Vec<_>>()
+            .join(", ");
+        clause.push_str(&format!(" ORDER BY {order_by}"));
+    }
+    if let Some(limit) = limit {
+        clause.push_str(&format!(" LIMIT {limit}"));
+    }
+    clause
+}
+
 /// Query a table for distinct partition values matching an optional WHERE 
clause.
 ///
 /// Returns `None` for non-partitioned tables.
diff --git a/crates/integrations/datafusion/src/update.rs 
b/crates/integrations/datafusion/src/update.rs
index 0fd7531d..f672081e 100644
--- a/crates/integrations/datafusion/src/update.rs
+++ b/crates/integrations/datafusion/src/update.rs
@@ -35,9 +35,10 @@ use paimon::table::{CopyOnWriteMergeWriter, Table};
 
 use crate::error::to_datafusion_error;
 use crate::merge_into::{
-    build_partition_set_from_where, extract_tracking_columns, 
is_delete_conflict,
-    is_row_id_conflict, ok_result, project_update_columns, quote_identifier,
-    register_cow_target_table, retry_on_conflict, validate_update_columns, 
TempTableTracker,
+    build_dml_selection_clause, build_partition_set_from_where, 
dml_table_alias,
+    extract_tracking_columns, is_delete_conflict, is_row_id_conflict, 
ok_result,
+    project_update_columns, quote_identifier, register_cow_target_table, 
retry_on_conflict,
+    validate_update_columns, TempTableTracker,
 };
 use crate::sql_context::{normalize_schema_identifier, SQLContext};
 
@@ -103,7 +104,7 @@ async fn execute_update_once(
         .new_data_evolution_writer(columns.clone())
         .map_err(to_datafusion_error)?;
 
-    // 3. Query the target table directly with WHERE filter.
+    // 3. Select the target rows with filtering, ordering, and limit.
     let table_ref = update.table.to_string();
 
     let select_parts: Vec<String> =
@@ -113,13 +114,17 @@ async fn execute_update_once(
             }))
             .collect();
 
-    let select_clause = select_parts.join(", ");
-    let where_clause = match &update.selection {
-        Some(expr) => format!(" WHERE {expr}"),
-        None => String::new(),
-    };
+    let selection_clause = build_dml_selection_clause(
+        update.selection.as_ref(),
+        &update.order_by,
+        update.limit.as_ref(),
+    );
 
-    let query_sql = format!("SELECT {select_clause} FROM 
{table_ref}{where_clause}");
+    let alias = dml_table_alias(ctx.ctx(), &table_ref);
+    let select_clause = select_parts.join(", ");
+    let query_sql = format!(
+        "SELECT {select_clause} FROM (SELECT * FROM 
{table_ref}{selection_clause}) AS {alias}"
+    );
     let batches = ctx.ctx().sql(&query_sql).await?.collect().await?;
 
     // 4. Project update columns (rename __upd_X → X)
@@ -234,14 +239,18 @@ async fn execute_cow_update_inner(
             }))
             .collect();
 
+    let table_ref = update.table.to_string();
+    let selection_clause = build_dml_selection_clause(
+        update.selection.as_ref(),
+        &update.order_by,
+        update.limit.as_ref(),
+    );
+    let alias = dml_table_alias(ctx, &table_ref);
     let select_clause = select_parts.join(", ");
-    let where_clause = match &update.selection {
-        Some(expr) => format!(" WHERE {expr}"),
-        None => String::new(),
-    };
-
-    // Safety: where_clause comes from sqlparser AST to_string(), not raw user 
input.
-    let query_sql = format!("SELECT {select_clause} FROM 
{cow_table_name}{where_clause}");
+    let query_sql = format!(
+        "SELECT {select_clause} FROM \
+         (SELECT * FROM {cow_table_name} AS {alias}{selection_clause}) AS 
{alias}"
+    );
     let join_result = ctx.sql(&query_sql).await?.collect().await?;
 
     let mut update_value_batches: Vec<RecordBatch> = Vec::new();
diff --git a/crates/integrations/datafusion/tests/delete_tests.rs 
b/crates/integrations/datafusion/tests/delete_tests.rs
index aa247afb..2c0d62ba 100644
--- a/crates/integrations/datafusion/tests/delete_tests.rs
+++ b/crates/integrations/datafusion/tests/delete_tests.rs
@@ -452,6 +452,71 @@ async fn test_delete_multiple_rows_from_single_commit() {
     assert_eq!(query(&sql_context).await, vec![(1, "a".into(), 10)]);
 }
 
+// ======================= ORDER BY and LIMIT =======================
+
+#[tokio::test]
+async fn test_delete_with_order_by_and_limit() {
+    for options in [
+        "",
+        "WITH (
+            'row-tracking.enabled' = 'true',
+            'data-evolution.enabled' = 'true',
+            'deletion-vectors.enabled' = 'true'
+        )",
+    ] {
+        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(&format!(
+                "CREATE TABLE paimon.test_db.t (id INT, name VARCHAR, pt INT) \
+                 PARTITIONED BY (pt) {options}"
+            ))
+            .await
+            .unwrap();
+
+        // Separate commits and partitions exercise global row selection.
+        exec(
+            &sql_context,
+            "INSERT INTO paimon.test_db.t (id, name, pt) VALUES (1, 'a', 1), 
(4, 'd', 2)",
+        )
+        .await;
+        exec(
+            &sql_context,
+            "INSERT INTO paimon.test_db.t (id, name, pt) VALUES (2, 'b', 1), 
(3, 'c', 2)",
+        )
+        .await;
+
+        let before = query_pt(&sql_context).await;
+        let cnt = dml_count(
+            &sql_context,
+            "DELETE FROM paimon.test_db.t WHERE id > 1 LIMIT 0",
+        )
+        .await;
+        assert_eq!(cnt, 0);
+        assert_eq!(query_pt(&sql_context).await, before);
+
+        let cnt = dml_count(
+            &sql_context,
+            "DELETE FROM paimon.test_db.t \
+             WHERE t.id <> 4 ORDER BY paimon.test_db.t.pt DESC, t.id ASC LIMIT 
2",
+        )
+        .await;
+        assert_eq!(cnt, 2);
+        assert_eq!(
+            query_pt(&sql_context).await,
+            vec![(2, "b".into(), 1), (4, "d".into(), 2)]
+        );
+
+        let cnt = dml_count(&sql_context, "DELETE FROM paimon.test_db.t LIMIT 
1").await;
+        assert_eq!(cnt, 1);
+        assert_eq!(query_pt(&sql_context).await.len(), 1);
+    }
+}
+
 // ======================= Unsupported cases =======================
 
 #[tokio::test]
diff --git a/crates/integrations/datafusion/tests/update_tests.rs 
b/crates/integrations/datafusion/tests/update_tests.rs
index 99c75c46..b753d3d1 100644
--- a/crates/integrations/datafusion/tests/update_tests.rs
+++ b/crates/integrations/datafusion/tests/update_tests.rs
@@ -531,6 +531,145 @@ async fn test_update_empty_table() {
     drop(tmp);
 }
 
+// ======================= ORDER BY and LIMIT =======================
+
+#[tokio::test]
+async fn test_update_with_order_by_and_limit() {
+    for options in [
+        "",
+        "WITH (
+            'row-tracking.enabled' = 'true',
+            'data-evolution.enabled' = 'true',
+            'deletion-vectors.enabled' = 'true'
+        )",
+    ] {
+        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(&format!(
+                "CREATE TABLE paimon.test_db.t (id INT, name VARCHAR, pt INT) \
+                 PARTITIONED BY (pt) {options}"
+            ))
+            .await
+            .unwrap();
+
+        // Separate commits and partitions exercise global row selection.
+        exec(
+            &sql_context,
+            "INSERT INTO paimon.test_db.t (id, name, pt) VALUES (1, 'a', 1), 
(4, 'd', 2)",
+        )
+        .await;
+        exec(
+            &sql_context,
+            "INSERT INTO paimon.test_db.t (id, name, pt) VALUES (2, 'b', 1), 
(3, 'c', 2)",
+        )
+        .await;
+
+        let before = query_pt(&sql_context).await;
+        let cnt = dml_count(
+            &sql_context,
+            "UPDATE paimon.test_db.t SET name = 'x' WHERE id > 1 LIMIT 0",
+        )
+        .await;
+        assert_eq!(cnt, 0);
+        assert_eq!(query_pt(&sql_context).await, before);
+
+        // ORDER BY uses the original values of the updated column.
+        let cnt = dml_count(
+            &sql_context,
+            "UPDATE paimon.test_db.t SET id = paimon.test_db.t.id + 10 \
+             WHERE t.id <> 4 ORDER BY t.pt DESC, t.id ASC LIMIT 2",
+        )
+        .await;
+        assert_eq!(cnt, 2);
+        assert_eq!(
+            query_pt(&sql_context).await,
+            vec![
+                (2, "b".into(), 1),
+                (4, "d".into(), 2),
+                (11, "a".into(), 1),
+                (13, "c".into(), 2),
+            ]
+        );
+
+        let cnt = dml_count(
+            &sql_context,
+            "UPDATE paimon.test_db.t SET name = 'limited' LIMIT 1",
+        )
+        .await;
+        assert_eq!(cnt, 1);
+        let rows = query_pt(&sql_context).await;
+        assert_eq!(
+            rows.iter().filter(|(_, name, _)| name == "limited").count(),
+            1
+        );
+    }
+}
+
+#[tokio::test]
+async fn test_update_selects_rows_before_set() {
+    for options in [
+        "",
+        "WITH (
+            'row-tracking.enabled' = 'true',
+            'data-evolution.enabled' = 'true',
+            'deletion-vectors.enabled' = 'true'
+        )",
+    ] {
+        for (assignment, ordering, expected) in [
+            (
+                "id + 100",
+                "__upd_id",
+                vec![(1, "a".into(), 20), (102, "b".into(), 10)],
+            ),
+            (
+                "12 / (2 - id)",
+                "id",
+                vec![(2, "b".into(), 10), (12, "a".into(), 20)],
+            ),
+        ] {
+            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(&format!(
+                    "CREATE TABLE paimon.test_db.t (id INT, name VARCHAR, 
__upd_id INT) {options}"
+                ))
+                .await
+                .unwrap();
+            exec(
+                &sql_context,
+                "INSERT INTO paimon.test_db.t (id, name, __upd_id) VALUES (1, 
'a', 20), (2, 'b', 10)",
+            )
+            .await;
+
+            let cnt = dml_count(
+                &sql_context,
+                &format!(
+                    "UPDATE paimon.test_db.t SET id = {assignment} ORDER BY 
{ordering} LIMIT 1"
+                ),
+            )
+            .await;
+            assert_eq!(cnt, 1);
+            assert_eq!(
+                query_int_str_int(
+                    &sql_context,
+                    "SELECT id, name, __upd_id FROM paimon.test_db.t ORDER BY 
id"
+                )
+                .await,
+                expected
+            );
+        }
+    }
+}
+
 // ======================= Unsupported cases =======================
 
 #[tokio::test]

Reply via email to