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 75a2dfc5 feat(datafusion): support branch procedures on REST catalog
tables (#1346)
75a2dfc5 is described below
commit 75a2dfc58c930f13e46410a4cf7b2c7eaca8f415
Author: Nicholas Jiang <[email protected]>
AuthorDate: Mon Nov 9 14:02:44 2026 +0800
feat(datafusion): support branch procedures on REST catalog tables (#1346)
---
crates/integrations/datafusion/src/procedures.rs | 90 ++++--
crates/integrations/datafusion/tests/procedures.rs | 44 +++
.../datafusion/tests/rest_management_procedures.rs | 358 ++++++++++++++++++---
crates/paimon/tests/mock_server.rs | 211 +++++++++++-
docs/src/sql.md | 62 +++-
5 files changed, 676 insertions(+), 89 deletions(-)
diff --git a/crates/integrations/datafusion/src/procedures.rs
b/crates/integrations/datafusion/src/procedures.rs
index 50f3848f..6c614cb9 100644
--- a/crates/integrations/datafusion/src/procedures.rs
+++ b/crates/integrations/datafusion/src/procedures.rs
@@ -19,6 +19,8 @@
//!
//! Supported procedures:
//! - `CALL sys.create_branch(table => '...', branch => '...'[, tag => '...',
ignore_if_exists => true])`
+//! - `CALL sys.delete_branch(table => '...', branch => 'branch1,branch2')`
+//! - `CALL sys.fast_forward(table => '...', branch => '...')` (REST catalogs
only)
//! - `CALL sys.create_tag(table => '...', tag => '...', snapshot_id => ...,
time_retained => '...')`
//! - `CALL sys.replace_tag(table => '...', tag => '...', snapshot_id => ...,
time_retained => '...')`
//! - `CALL sys.delete_tag(table => '...', tag => '...')`
@@ -223,6 +225,7 @@ fn declared_parameters(proc_name: &str) -> Option<&'static
[&'static str]> {
"create_tag_from_watermark" => &["table", "tag", "watermark",
"time_retained"],
"rename_branch" => &["table", "from_branch", "to_branch"],
"delete_branch" => &["table", "branch"],
+ "fast_forward" => &["table", "branch"],
"create_global_index" => &["table", "index_column", "index_type",
"options"],
"drop_global_index" => &[
"table",
@@ -353,6 +356,7 @@ pub async fn execute_procedure(
}
"rename_branch" => proc_rename_branch(ctx, catalog, catalog_name,
&args).await,
"delete_branch" => proc_delete_branch(ctx, catalog, catalog_name,
&args).await,
+ "fast_forward" => proc_fast_forward(ctx, catalog, catalog_name,
&args).await,
"create_global_index" => proc_create_global_index(ctx, catalog,
catalog_name, &args).await,
"drop_global_index" => proc_drop_global_index(ctx, catalog,
catalog_name, &args).await,
"compact" => proc_compact(ctx, catalog, catalog_name, &args).await,
@@ -765,8 +769,7 @@ async fn proc_create_branch(
) -> DFResult<DataFrame> {
let branch = require_arg(args, "branch")?;
let ignore_if_exists = bool_arg(args, "ignore_if_exists")?;
- // Validate before the existence check: an invalid name must not become a
- // successful no-op just because it resolves to an existing directory.
+ // Validate before checking existence so invalid names cannot become
no-ops.
BranchManager::validate_branch_name(branch).map_err(to_datafusion_error)?;
if branch.contains('$') {
return Err(DataFusionError::Plan(format!(
@@ -774,11 +777,6 @@ async fn proc_create_branch(
)));
}
let table = get_table(catalog, catalog_name, args).await?;
- if table.rest_env().is_some() {
- return Err(DataFusionError::NotImplemented(
- "create_branch is not supported for tables managed by a REST
catalog".to_string(),
- ));
- }
if table.schema().core_options().is_format_table() {
return Err(DataFusionError::NotImplemented(
"create_branch requires a FileStoreTable; format-table is not
supported".to_string(),
@@ -790,6 +788,30 @@ async fn proc_create_branch(
));
}
+ // The REST catalog owns branch metadata and must handle the mutation.
+ if let Some(rest_env) = table.rest_env() {
+ let identifier = rest_env.identifier();
+ // Check existence first, as the filesystem path does, so an existing
+ // branch is a no-op without resolving the tag.
+ if ignore_if_exists
+ && catalog
+ .list_branches(identifier)
+ .await
+ .map_err(to_datafusion_error)?
+ .iter()
+ .any(|name| name == branch)
+ {
+ return ok_result(ctx);
+ }
+ let tag = args.get("tag").map(String::as_str);
+ return match catalog.create_branch(identifier, branch, tag).await {
+ Ok(()) => ok_result(ctx),
+ // The branch may have been created concurrently after the check.
+ Err(paimon::Error::BranchAlreadyExist { .. }) if ignore_if_exists
=> ok_result(ctx),
+ Err(error) => Err(to_datafusion_error(error)),
+ };
+ }
+
let manager = BranchManager::new(table.file_io().clone(),
table.location().to_string());
if ignore_if_exists
&& manager
@@ -845,14 +867,11 @@ async fn proc_delete_branch(
let table = get_table(catalog, catalog_name, args).await?;
let branch_str = require_arg(args, "branch")?;
- // A REST catalog owns branch metadata and the Rust REST catalog has no
- // branch-drop endpoint yet (Java `RESTCatalog.dropBranch` DELETEs through
the
- // catalog). Dropping the physical branch directory here would leave the
- // catalog still listing the branch while its data is gone. Refuse before
- // deleting anything, until a catalog-aware path exists.
- if table.rest_env().is_some() {
+ // REST branch endpoints address branches through the main table.
+ let rest_identifier = table.rest_env().map(|env| env.identifier());
+ if rest_identifier.is_some() && !table.is_main_branch() {
return Err(DataFusionError::NotImplemented(
- "delete_branch is not yet supported for tables managed by a REST
catalog".to_string(),
+ "delete_branch requires a main-branch source table".to_string(),
));
}
@@ -874,20 +893,53 @@ async fn proc_delete_branch(
BranchManager::validate_branch_name(branch_name).map_err(to_datafusion_error)?;
BranchManager::ensure_branch_deletable(options, branch_name)
.map_err(to_datafusion_error)?;
- if !bm
+ if let Some(identifier) = rest_identifier {
+ // Skip missing branches, as the filesystem path does.
+ match catalog.drop_branch(identifier, branch_name).await {
+ Ok(()) | Err(paimon::Error::BranchNotExist { .. }) => {}
+ Err(error) => return Err(to_datafusion_error(error)),
+ }
+ } else if bm
.branch_exists(branch_name)
.await
.map_err(to_datafusion_error)?
{
- continue;
+ bm.drop_branch(branch_name)
+ .await
+ .map_err(to_datafusion_error)?;
}
- bm.drop_branch(branch_name)
- .await
- .map_err(to_datafusion_error)?;
}
ok_result(ctx)
}
+async fn proc_fast_forward(
+ ctx: &SessionContext,
+ catalog: &Arc<dyn Catalog>,
+ catalog_name: &str,
+ args: &HashMap<String, String>,
+) -> DFResult<DataFrame> {
+ let branch = require_arg(args, "branch")?;
+ BranchManager::validate_branch_name(branch).map_err(to_datafusion_error)?;
+ let table = get_table(catalog, catalog_name, args).await?;
+ // Fast-forwarding requires coordinated snapshot, schema and tag changes;
+ // REST tables delegate those changes to the server.
+ let Some(rest_env) = table.rest_env() else {
+ return Err(DataFusionError::NotImplemented(
+ "fast_forward is only supported for tables managed by a REST
catalog".to_string(),
+ ));
+ };
+ if !table.is_main_branch() {
+ return Err(DataFusionError::NotImplemented(
+ "fast_forward requires a main-branch source table".to_string(),
+ ));
+ }
+ catalog
+ .fast_forward(rest_env.identifier(), branch)
+ .await
+ .map_err(to_datafusion_error)?;
+ ok_result(ctx)
+}
+
async fn proc_delete_tag(
ctx: &SessionContext,
catalog: &Arc<dyn Catalog>,
diff --git a/crates/integrations/datafusion/tests/procedures.rs
b/crates/integrations/datafusion/tests/procedures.rs
index e648aa7a..b1594f96 100644
--- a/crates/integrations/datafusion/tests/procedures.rs
+++ b/crates/integrations/datafusion/tests/procedures.rs
@@ -455,6 +455,50 @@ async fn
test_rename_branch_rejects_unopenable_source_and_target() {
table.copy_with_branch("b1").await.unwrap();
}
+#[tokio::test]
+async fn test_fast_forward_validates_arguments_and_rejects_filesystem_tables()
{
+ let (_tmp, catalog) = create_test_env();
+ let sql_context = create_sql_context(catalog.clone()).await;
+ exec(&sql_context, "CREATE SCHEMA paimon.test_db").await;
+ exec(&sql_context, "CREATE TABLE paimon.test_db.t1 (id INT)").await;
+ let table = catalog
+ .get_table(&Identifier::new("test_db", "t1"))
+ .await
+ .unwrap();
+ let bm = BranchManager::new(table.file_io().clone(),
table.location().to_string());
+ bm.create_branch("b1").await.unwrap();
+
+ for (arguments, error) in [
+ (
+ "table => 'test_db.t1'",
+ "Missing required argument: 'branch'",
+ ),
+ ("branch => 'b1'", "Missing required argument: 'table'"),
+ (
+ "table => 'test_db.t1', branch => 'b1', tag => 'release'",
+ "Argument tag is unknown.",
+ ),
+ (
+ "table => 'test_db.t1', branch => 'b1', branch => 'b2'",
+ "Procedure argument branch is duplicated.",
+ ),
+ ] {
+ assert_sql_error(
+ &sql_context,
+ &format!("CALL sys.fast_forward({arguments})"),
+ error,
+ )
+ .await;
+ }
+ assert_sql_error(
+ &sql_context,
+ "CALL sys.fast_forward(table => 'test_db.t1', branch => 'b1')",
+ "fast_forward is only supported for tables managed by a REST catalog",
+ )
+ .await;
+ assert!(bm.branch_exists("b1").await.unwrap());
+}
+
#[tokio::test]
async fn test_delete_branch() {
let (_tmp, catalog) = create_test_env();
diff --git a/crates/integrations/datafusion/tests/rest_management_procedures.rs
b/crates/integrations/datafusion/tests/rest_management_procedures.rs
index e1a50b31..d3ea23e3 100644
--- a/crates/integrations/datafusion/tests/rest_management_procedures.rs
+++ b/crates/integrations/datafusion/tests/rest_management_procedures.rs
@@ -20,7 +20,8 @@ mod common;
#[path = "../../../paimon/tests/mock_server.rs"]
mod mock_server;
-use std::collections::HashMap;
+use std::collections::{BTreeMap, HashMap};
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_array::{Array, RecordBatch};
@@ -714,43 +715,340 @@ async fn
test_replace_tag_rejected_on_rest_catalog_without_changing_metadata() {
}
}
-#[tokio::test]
-async fn test_create_branch_rejects_rest_tables_even_when_target_exists() {
- let (tmp, server, context) = setup().await;
+fn register_rest_table(
+ tmp: &tempfile::TempDir,
+ server: &RESTServer,
+ options: &[(&str, &str)],
+) -> PathBuf {
let schema = Schema::builder()
.column("id", DataType::Int(IntType::new()))
+ .options(
+ options
+ .iter()
+ .map(|(key, value)| (key.to_string(), value.to_string())),
+ )
.build()
.unwrap();
let root = tmp.path().join(format!("{DATABASE}.db/{TABLE}"));
let schema_path = root.join("schema/schema-0");
- let branch_path = root.join("branch/branch-existing/schema/schema-0");
- let schema_bytes = serde_json::to_vec(&paimon::spec::TableSchema::new(0,
&schema)).unwrap();
- for path in [&schema_path, &branch_path] {
- std::fs::create_dir_all(path.parent().unwrap()).unwrap();
- std::fs::write(path, &schema_bytes).unwrap();
- }
+ std::fs::create_dir_all(schema_path.parent().unwrap()).unwrap();
+ std::fs::write(
+ &schema_path,
+ serde_json::to_vec(&paimon::spec::TableSchema::new(0,
&schema)).unwrap(),
+ )
+ .unwrap();
server.add_table_with_schema(
DATABASE,
TABLE,
schema,
&format!("file://{}", root.display()),
);
+ root
+}
+
+fn error_response(code: i32, message: &str) -> paimon::api::ErrorResponse {
+ paimon::api::ErrorResponse::new(None, None, Some(message.to_string()),
Some(code))
+}
+
+fn table_files(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
+ let mut files = BTreeMap::new();
+ for entry in std::fs::read_dir(root).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ files.extend(table_files(&path));
+ } else {
+ let content = std::fs::read(&path).unwrap();
+ files.insert(path, content);
+ }
+ }
+ files
+}
+
+#[tokio::test]
+async fn test_create_branch_goes_through_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ let storage_only = root.join("branch/branch-stale/schema/schema-0");
+ std::fs::create_dir_all(storage_only.parent().unwrap()).unwrap();
+ std::fs::write(&storage_only, b"stale").unwrap();
+ let original_files = table_files(&root);
+ let tag = " release +一";
+ server.add_tag(DATABASE, TABLE, tag);
+ let create =
+ |args: &str| format!("CALL sys.create_branch(table =>
'{DATABASE}.{TABLE}', {args})");
+
+ assert_ok_row(&context, &create("branch => 'dev'")).await;
+ assert_ok_row(&context, &create("branch => 'stale'")).await;
+ assert_ok_row(
+ &context,
+ &create("branch => 'fresh', ignore_if_exists => true"),
+ )
+ .await;
+ for branch in [" dev", "dev ", "dev+", "一"] {
+ assert_ok_row(
+ &context,
+ &create(&format!("branch => '{branch}', tag => '{tag}'")),
+ )
+ .await;
+ }
+
+ server.set_list_branches_error(Some(error_response(403, "denied")));
+ for branch in ["dev", "new"] {
+ common::assert_sql_error(
+ &context,
+ &create(&format!("branch => '{branch}', ignore_if_exists =>
true")),
+ "Forbidden: denied",
+ )
+ .await;
+ }
+ assert_ok_row(&context, &create("branch => 'new'")).await;
+ server.set_list_branches_error(None);
+ let expected = ["dev", "stale", "fresh", " dev", "dev ", "dev+", "一",
"new"];
+ assert_eq!(server.branches(DATABASE, TABLE), expected);
+
+ common::assert_sql_error(&context, &create("branch => 'dev'"), "already
exists").await;
+ for ignore in ["false", "true"] {
+ common::assert_sql_error(
+ &context,
+ &create(&format!(
+ "branch => 'other', tag => 'missing', ignore_if_exists =>
{ignore}"
+ )),
+ "Tag missing does not exist",
+ )
+ .await;
+ }
+
+ server.set_branch_mutation_error(Some(error_response(409, "conflict")));
+ assert_ok_row(
+ &context,
+ &create("branch => 'raced', ignore_if_exists => true"),
+ )
+ .await;
+
+ server.set_branch_mutation_error(Some(error_response(403, "denied")));
+ for ignore in ["false", "true"] {
+ common::assert_sql_error(
+ &context,
+ &create(&format!("branch => 'denied', ignore_if_exists =>
{ignore}")),
+ "Forbidden: denied",
+ )
+ .await;
+ }
+ assert_ok_row(
+ &context,
+ &create("branch => 'dev', tag => 'missing', ignore_if_exists => true"),
+ )
+ .await;
+ assert_eq!(server.branches(DATABASE, TABLE), expected);
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test]
+async fn test_delete_branch_goes_through_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(
+ &tmp,
+ &server,
+ &[
+ ("scan.primary-branch", "primary"),
+ ("scan.fallback-branch", "fallback"),
+ ],
+ );
+ for branch in ["dev", "qa", "keep", "primary", "fallback", "keep ",
"keep+"] {
+ server.add_branch(DATABASE, TABLE, branch);
+ }
+ let dev_dir = root.join("branch/branch-dev");
+ std::fs::create_dir_all(&dev_dir).unwrap();
+ std::fs::write(dev_dir.join("marker"), b"catalog-owned").unwrap();
+ let original_files = table_files(&root);
+ let delete = |branches: &str| {
+ format!("CALL sys.delete_branch(table => '{DATABASE}.{TABLE}', branch
=> '{branches}')")
+ };
+
+ assert_ok_row(&context, &delete("dev,missing,,qa,dev,keep ,keep+")).await;
+ assert_eq!(
+ server.branches(DATABASE, TABLE),
+ ["keep", "primary", "fallback"]
+ );
+ let expected_calls = ["dev", "missing", "qa", "dev", "keep ", "keep+"]
+ .map(|branch| (DATABASE.to_string(), TABLE.to_string(),
branch.to_string()));
+ assert_eq!(server.drop_branch_calls(), expected_calls);
+
+ for (branch, option) in [
+ ("primary", "scan.primary-branch"),
+ ("fallback", "scan.fallback-branch"),
+ ] {
+ common::assert_sql_error(&context, &delete(branch), option).await;
+ }
+ assert_eq!(server.drop_branch_calls(), expected_calls);
+
+ server.set_branch_mutation_error(Some(error_response(403, "denied")));
+ common::assert_sql_error(&context, &delete("keep,missing"), "Forbidden:
denied").await;
+ let mut expected_calls = expected_calls.to_vec();
+ expected_calls.push((DATABASE.to_string(), TABLE.to_string(),
"keep".to_string()));
+ assert_eq!(server.drop_branch_calls(), expected_calls);
+ assert_eq!(
+ server.branches(DATABASE, TABLE),
+ ["keep", "primary", "fallback"]
+ );
+
+ server.set_branch_mutation_error(None);
+ common::assert_sql_error(
+ &context,
+ &delete("keep,primary,fallback"),
+ "scan.primary-branch",
+ )
+ .await;
+ assert_eq!(server.branches(DATABASE, TABLE), ["primary", "fallback"]);
+ expected_calls.push((DATABASE.to_string(), TABLE.to_string(),
"keep".to_string()));
+ assert_eq!(server.drop_branch_calls(), expected_calls);
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test]
+async fn test_fast_forward_goes_through_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ let original_files = table_files(&root);
+ let forward = |branch: &str| {
+ format!("CALL sys.fast_forward(table => '{DATABASE}.{TABLE}', branch
=> '{branch}')")
+ };
- for branch in ["new", "existing"] {
- for tag in ["", ", tag => 'missing'"] {
+ let mut expected = Vec::new();
+ for branch in ["dev", "dev +一", "forward"] {
+ server.add_branch(DATABASE, TABLE, branch);
+ assert_ok_row(&context, &forward(branch)).await;
+ expected.push((DATABASE.to_string(), TABLE.to_string(),
branch.to_string()));
+ }
+ assert_eq!(server.fast_forward_calls(), expected);
+
+ common::assert_sql_error(
+ &context,
+ &forward("missing"),
+ "Branch missing of table sales.orders does not exist",
+ )
+ .await;
+
+ server.set_branch_mutation_error(Some(error_response(403, "denied")));
+ common::assert_sql_error(&context, &forward("dev"), "Forbidden:
denied").await;
+ assert_eq!(server.fast_forward_calls(), expected);
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test]
+async fn test_branch_procedures_validate_names_on_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ let original_files = table_files(&root);
+ server.add_branch(DATABASE, TABLE, "main");
+ for procedure in ["create_branch", "delete_branch", "fast_forward"] {
+ for (branch, error) in [
+ ("main", "default branch"),
+ (" ", "cannot be empty or whitespace"),
+ ("123", "pure numeric"),
+ ("..", "cannot be '.' or '..'"),
+ ("dev/schema", "path separators"),
+ ("dev\\schema", "path separators"),
+ ("dev\n", "control characters"),
+ ] {
common::assert_sql_error(
&context,
&format!(
- "CALL sys.create_branch(table => '{DATABASE}.{TABLE}',
branch => '{branch}'{tag}, ignore_if_exists => true)"
+ "CALL sys.{procedure}(table => '{DATABASE}.{TABLE}',
branch => '{branch}')"
),
- "create_branch is not supported for tables managed by a REST
catalog",
+ error,
+ )
+ .await;
+ }
+ }
+ common::assert_sql_error(
+ &context,
+ &format!("CALL sys.create_branch(table => '{DATABASE}.{TABLE}', branch
=> 'main', ignore_if_exists => true)"),
+ "default branch",
+ )
+ .await;
+ common::assert_sql_error(
+ &context,
+ &format!("CALL sys.create_branch(table => '{DATABASE}.{TABLE}', branch
=> 'dev$tags', ignore_if_exists => true)"),
+ "cannot contain the SQL suffix delimiter",
+ )
+ .await;
+ assert_eq!(server.branches(DATABASE, TABLE), ["main"]);
+ assert!(server.drop_branch_calls().is_empty());
+ assert!(server.fast_forward_calls().is_empty());
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test]
+async fn test_branch_procedures_reject_unsupported_rest_tables() {
+ let (tmp, server, context) = setup().await;
+ server.add_branch(DATABASE, TABLE, "dev");
+ let procedure_sql = |procedure: &str, table: &str| {
+ let extra = if procedure == "create_branch" {
+ ", ignore_if_exists => true"
+ } else {
+ ""
+ };
+ format!("CALL sys.{procedure}(table => '{DATABASE}.{table}', branch =>
'dev'{extra})")
+ };
+
+ for procedure in ["create_branch", "delete_branch", "fast_forward"] {
+ common::assert_sql_error(
+ &context,
+ &procedure_sql(procedure, "missing"),
+ "Table sales.missing does not exist",
+ )
+ .await;
+ }
+
+ let root = register_rest_table(&tmp, &server, &[]);
+ let branch_table = format!("{TABLE}$branch_dev");
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .build()
+ .unwrap();
+ server.add_table_with_schema(
+ DATABASE,
+ &branch_table,
+ schema,
+ &format!("file://{}", root.display()),
+ );
+ for procedure in ["create_branch", "delete_branch", "fast_forward"] {
+ common::assert_sql_error(
+ &context,
+ &procedure_sql(procedure, &branch_table),
+ &format!("{procedure} requires a main-branch source table"),
+ )
+ .await;
+ }
+
+ for table_type in ["object-table", "lance-table", "iceberg-table"] {
+ let root = register_rest_table(&tmp, &server, &[("type", table_type)]);
+ let original_files = table_files(&root);
+ for procedure in ["create_branch", "delete_branch", "fast_forward"] {
+ common::assert_sql_error(
+ &context,
+ &procedure_sql(procedure, TABLE),
+ &format!("is declared '{table_type}' and cannot be read as a
Paimon table"),
)
.await;
- assert_eq!(std::fs::read(&schema_path).unwrap(), schema_bytes);
- assert_eq!(std::fs::read(&branch_path).unwrap(), schema_bytes);
-
assert_eq!(std::fs::read_dir(root.join("branch")).unwrap().count(), 1);
}
+ assert_eq!(table_files(&root), original_files);
}
+
+ let root = register_rest_table(&tmp, &server, &[("type", "format-table")]);
+ let original_files = table_files(&root);
+ common::assert_sql_error(
+ &context,
+ &procedure_sql("create_branch", TABLE),
+ "format-table is not supported",
+ )
+ .await;
+ assert_eq!(table_files(&root), original_files);
+ assert!(server.branches(DATABASE, "missing").is_empty());
+ assert_eq!(server.branches(DATABASE, TABLE), ["dev"]);
+ assert!(server.drop_branch_calls().is_empty());
+ assert!(server.fast_forward_calls().is_empty());
}
#[tokio::test]
@@ -927,32 +1225,6 @@ async fn
test_create_tag_from_watermark_rejects_readable_rest_catalog_table() {
server.abort();
}
-#[tokio::test]
-async fn test_delete_branch_rejected_on_rest_catalog() {
- // A REST catalog owns branch metadata and the Rust REST catalog has no
- // branch-drop endpoint yet, so `delete_branch` must refuse rather than
delete
- // a physical branch directory while the catalog still lists it. Without
the
- // guard the filesystem `BranchManager` runs and reports a different
error, so
- // this assertion is non-vacuous.
- let (tmp, server, context) = setup().await;
-
- // `get_table` needs a schema-bearing response; register one so resolution
- // reaches the REST guard rather than failing earlier on a missing schema.
- let schema = Schema::builder()
- .column("id", DataType::Int(IntType::new()))
- .build()
- .unwrap();
- let path = format!("file://{}/{DATABASE}.db/{TABLE}",
tmp.path().display());
- server.add_table_with_schema(DATABASE, TABLE, schema, &path);
-
- common::assert_sql_error(
- &context,
- &format!("CALL sys.delete_branch(table => '{DATABASE}.{TABLE}', branch
=> 'b1')"),
- "REST catalog",
- )
- .await;
-}
-
#[tokio::test]
async fn test_argument_validation_follows_java() {
let (_tmp, server, context) = setup().await;
diff --git a/crates/paimon/tests/mock_server.rs
b/crates/paimon/tests/mock_server.rs
index 0e92d60b..aae1f99b 100644
--- a/crates/paimon/tests/mock_server.rs
+++ b/crates/paimon/tests/mock_server.rs
@@ -21,10 +21,10 @@
//! for testing purposes.
use axum::{
- extract::{Extension, Json, Path, Query},
- http::{HeaderMap, StatusCode},
+ extract::{Extension, Json, OriginalUri, Path, Query},
+ http::{HeaderMap, StatusCode, Uri},
response::IntoResponse,
- routing::{get, post},
+ routing::{delete, get, post},
serve, Router,
};
use serde_json::json;
@@ -35,14 +35,14 @@ use tokio::task::JoinHandle;
use paimon::api::{
AlterDatabaseRequest, AlterTableRequest, AuditRESTResponse,
AuthTableQueryResponse,
- ConfigResponse, CreateFunctionRequest, CreatePartitionsRequest,
CreateTagRequest,
- CreateViewRequest, DataPolicy, DropPartitionsRequest, DropPolicyRequest,
ErrorResponse,
- GetDatabaseResponse, GetFunctionResponse, GetTableResponse,
GetTagResponse, GetViewResponse,
- ListDatabasesResponse, ListFunctionsResponse,
ListPartitionsByFilterRequest,
- ListPartitionsByNamesRequest, ListPartitionsResponse,
ListPermissionsResponse,
- ListPoliciesResponse, ListTablesResponse, ListViewsResponse,
PermissionAssignment,
- PermissionResource, PolicyRequest, PolicyType, RenameTableRequest,
ResourcePaths, ResourceType,
- RevokePermissionRequest,
+ ConfigResponse, CreateBranchRequest, CreateFunctionRequest,
CreatePartitionsRequest,
+ CreateTagRequest, CreateViewRequest, DataPolicy, DropPartitionsRequest,
DropPolicyRequest,
+ ErrorResponse, GetDatabaseResponse, GetFunctionResponse, GetTableResponse,
GetTagResponse,
+ GetViewResponse, ListBranchesResponse, ListDatabasesResponse,
ListFunctionsResponse,
+ ListPartitionsByFilterRequest, ListPartitionsByNamesRequest,
ListPartitionsResponse,
+ ListPermissionsResponse, ListPoliciesResponse, ListTablesResponse,
ListViewsResponse,
+ PermissionAssignment, PermissionResource, PolicyRequest, PolicyType,
RESTUtil,
+ RenameTableRequest, ResourcePaths, ResourceType, RevokePermissionRequest,
};
use paimon::catalog::{Function, Identifier};
use paimon::spec::{CommitKind, Partition, Snapshot};
@@ -50,6 +50,13 @@ use paimon::spec::{CommitKind, Partition, Snapshot};
type PartitionPageResponse = (Vec<Partition>, Option<String>);
type PartitionSpecPageResponse = (Vec<HashMap<String, String>>,
Option<String>);
+fn branch_name_from_uri(uri: &Uri) -> String {
+ // Branch paths use Java's form encoding. Decode the raw segment so spaces
+ // (`+`) remain distinct from literal plus signs (`%2B`), unlike Axum's
Path.
+ let (_, suffix) = uri.path().rsplit_once("/branches/").unwrap();
+ RESTUtil::decode_string(suffix.split('/').next().unwrap())
+}
+
#[derive(Clone, Debug, Default)]
struct MockState {
databases: HashMap<String, GetDatabaseResponse>,
@@ -58,6 +65,11 @@ struct MockState {
views: HashMap<String, GetViewResponse>,
functions: HashMap<String, GetFunctionResponse>,
tags: HashMap<String, GetTagResponse>,
+ branches: HashMap<String, Vec<String>>,
+ drop_branch_calls: Vec<(String, String, String)>,
+ fast_forward_calls: Vec<(String, String, String)>,
+ branch_mutation_error: Option<ErrorResponse>,
+ list_branches_error: Option<ErrorResponse>,
partitions: HashMap<String, Vec<Partition>>,
partition_page_responses: HashMap<String, Vec<PartitionPageResponse>>,
partition_list_call_counts: HashMap<String, usize>,
@@ -1163,6 +1175,104 @@ impl RESTServer {
}
}
+ pub async fn list_branches(
+ Path((db, table)): Path<(String, String)>,
+ Extension(state): Extension<Arc<RESTServer>>,
+ ) -> impl IntoResponse {
+ let state = state.inner.lock().unwrap();
+ if let Some(error) = state.list_branches_error.clone() {
+ return Self::error_response(error);
+ }
+ let key = format!("{db}.{table}");
+ if !state.tables.contains_key(&key) {
+ return resource_error(StatusCode::NOT_FOUND, "TABLE", &table);
+ }
+ let branches = state.branches.get(&key).cloned().unwrap_or_default();
+ let response = ListBranchesResponse {
+ branches: Some(branches),
+ };
+ (StatusCode::OK, Json(response)).into_response()
+ }
+
+ pub async fn create_branch(
+ Path((db, table)): Path<(String, String)>,
+ Extension(state): Extension<Arc<RESTServer>>,
+ Json(request): Json<CreateBranchRequest>,
+ ) -> impl IntoResponse {
+ let mut state = state.inner.lock().unwrap();
+ if let Some(error) = state.branch_mutation_error.clone() {
+ return Self::error_response(error);
+ }
+ let key = format!("{db}.{table}");
+ if !state.tables.contains_key(&key) {
+ return resource_error(StatusCode::NOT_FOUND, "TABLE", &table);
+ }
+ if let Some(tag) = &request.from_tag {
+ if !state.tags.contains_key(&format!("{key}.{tag}")) {
+ return resource_error(StatusCode::NOT_FOUND, "TAG", tag);
+ }
+ }
+ let branches = state.branches.entry(key).or_default();
+ if branches.contains(&request.branch) {
+ return resource_error(StatusCode::CONFLICT, "BRANCH",
&request.branch);
+ }
+ branches.push(request.branch);
+ (StatusCode::OK, Json(json!(""))).into_response()
+ }
+
+ pub async fn drop_branch(
+ Path((db, table, _)): Path<(String, String, String)>,
+ OriginalUri(uri): OriginalUri,
+ Extension(state): Extension<Arc<RESTServer>>,
+ ) -> impl IntoResponse {
+ let mut state = state.inner.lock().unwrap();
+ let branch = branch_name_from_uri(&uri);
+ state
+ .drop_branch_calls
+ .push((db.clone(), table.clone(), branch.clone()));
+ if let Some(error) = state.branch_mutation_error.clone() {
+ return Self::error_response(error);
+ }
+ let key = format!("{db}.{table}");
+ if !state.tables.contains_key(&key) {
+ return resource_error(StatusCode::NOT_FOUND, "TABLE", &table);
+ }
+ let removed = state.branches.get_mut(&key).is_some_and(|branches| {
+ let before = branches.len();
+ branches.retain(|name| name != &branch);
+ branches.len() < before
+ });
+ if !removed {
+ return resource_error(StatusCode::NOT_FOUND, "BRANCH", &branch);
+ }
+ (StatusCode::OK, Json(json!(""))).into_response()
+ }
+
+ pub async fn fast_forward(
+ Path((db, table, _)): Path<(String, String, String)>,
+ OriginalUri(uri): OriginalUri,
+ Extension(state): Extension<Arc<RESTServer>>,
+ ) -> impl IntoResponse {
+ let mut state = state.inner.lock().unwrap();
+ if let Some(error) = state.branch_mutation_error.clone() {
+ return Self::error_response(error);
+ }
+ let branch = branch_name_from_uri(&uri);
+ let key = format!("{db}.{table}");
+ if !state.tables.contains_key(&key) {
+ return resource_error(StatusCode::NOT_FOUND, "TABLE", &table);
+ }
+ if !state
+ .branches
+ .get(&key)
+ .is_some_and(|branches| branches.contains(&branch))
+ {
+ return resource_error(StatusCode::NOT_FOUND, "BRANCH", &branch);
+ }
+ state.fast_forward_calls.push((db, table, branch));
+ (StatusCode::OK, Json(json!(""))).into_response()
+ }
+
/// Handle POST /databases/:db/tables/:table/partitions - create
partitions.
pub async fn create_partitions(
Path((db, table)): Path<(String, String)>,
@@ -1627,14 +1737,14 @@ impl RESTServer {
)
}
- fn policy_error(error: ErrorResponse) -> axum::response::Response {
+ fn error_response(error: ErrorResponse) -> axum::response::Response {
let status = StatusCode::from_u16(error.code.unwrap_or(500) as u16)
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
(status, Json(error)).into_response()
}
fn table_not_found(table: &str) -> axum::response::Response {
- Self::policy_error(ErrorResponse::new(
+ Self::error_response(ErrorResponse::new(
Some("TABLE".to_string()),
Some(table.to_string()),
Some("Table not found".to_string()),
@@ -1699,7 +1809,7 @@ impl RESTServer {
let mut inner = state.inner.lock().unwrap();
inner.create_policy_bodies.push(body.clone());
if let Some(error) = inner.create_policy_error.clone() {
- return Self::policy_error(error);
+ return Self::error_response(error);
}
let request: PolicyRequest = match serde_json::from_value(body) {
Ok(request) => request,
@@ -1733,7 +1843,7 @@ impl RESTServer {
Some(column) => format!("{policy_type}:{principal}:{column}"),
None => format!("{policy_type}:{principal}"),
};
- return Self::policy_error(ErrorResponse::new(
+ return Self::error_response(ErrorResponse::new(
Some(ErrorResponse::RESOURCE_TYPE_POLICY.to_string()),
Some(name),
Some("Policy already exists.".to_string()),
@@ -1753,7 +1863,7 @@ impl RESTServer {
let mut inner = state.inner.lock().unwrap();
inner.drop_policy_bodies.push(body.clone());
if let Some(error) = inner.drop_policy_error.clone() {
- return Self::policy_error(error);
+ return Self::error_response(error);
}
let request: DropPolicyRequest = match serde_json::from_value(body) {
Ok(request) => request,
@@ -1772,7 +1882,7 @@ impl RESTServer {
let before = policies.len();
policies.retain(|policy| Self::policy_identity(policy) != identity);
if policies.len() == before {
- return Self::policy_error(ErrorResponse::new(
+ return Self::error_response(ErrorResponse::new(
Some(ErrorResponse::RESOURCE_TYPE_POLICY.to_string()),
Some(format!("{}:{}", request.policy_type, request.principal)),
Some("Policy does not exist.".to_string()),
@@ -2314,6 +2424,61 @@ impl RESTServer {
self.inner.lock().unwrap().drop_policy_error = error;
}
+ /// Register a tag of `database.table` pointing at snapshot 1.
+ pub fn add_tag(&self, database: &str, table: &str, tag: &str) {
+ self.inner.lock().unwrap().tags.insert(
+ format!("{database}.{table}.{tag}"),
+ GetTagResponse {
+ tag_name: tag.to_string(),
+ snapshot: tag_snapshot(1),
+ tag_create_time: None,
+ tag_time_retained: None,
+ },
+ );
+ }
+
+ /// Register a branch of `database.table` in the catalog.
+ pub fn add_branch(&self, database: &str, table: &str, branch: &str) {
+ self.inner
+ .lock()
+ .unwrap()
+ .branches
+ .entry(format!("{database}.{table}"))
+ .or_default()
+ .push(branch.to_string());
+ }
+
+ /// Branches of `database.table` known to the catalog, in creation order.
+ pub fn branches(&self, database: &str, table: &str) -> Vec<String> {
+ self.inner
+ .lock()
+ .unwrap()
+ .branches
+ .get(&format!("{database}.{table}"))
+ .cloned()
+ .unwrap_or_default()
+ }
+
+ /// Branch-drop attempts received by the server, including failed requests.
+ pub fn drop_branch_calls(&self) -> Vec<(String, String, String)> {
+ self.inner.lock().unwrap().drop_branch_calls.clone()
+ }
+
+ /// Successful fast-forward calls, as `(db, table, branch)`.
+ pub fn fast_forward_calls(&self) -> Vec<(String, String, String)> {
+ self.inner.lock().unwrap().fast_forward_calls.clone()
+ }
+
+ /// Make every branch mutation answer with `error` (status from its
`code`).
+ pub fn set_branch_mutation_error(&self, error: Option<ErrorResponse>) {
+ self.inner.lock().unwrap().branch_mutation_error = error;
+ }
+
+ /// Make every list-branches call answer with `error` (status from its
`code`).
+ pub fn set_list_branches_error(&self, error: Option<ErrorResponse>) {
+ self.inner.lock().unwrap().list_branches_error = error;
+ }
+
/// Return all create-partitions calls received by the server.
pub fn create_partitions_calls(&self) -> Vec<(String, String,
CreatePartitionsRequest)> {
self.inner.lock().unwrap().create_partitions_calls.clone()
@@ -2457,6 +2622,18 @@ pub async fn start_mock_server(
&format!("{prefix}/databases/:db/tables/:table/tags/:tag"),
get(RESTServer::get_tag).delete(RESTServer::delete_tag),
)
+ .route(
+ &format!("{prefix}/databases/:db/tables/:table/branches"),
+ get(RESTServer::list_branches).post(RESTServer::create_branch),
+ )
+ .route(
+ &format!("{prefix}/databases/:db/tables/:table/branches/:branch"),
+ delete(RESTServer::drop_branch),
+ )
+ .route(
+
&format!("{prefix}/databases/:db/tables/:table/branches/:branch/forward"),
+ post(RESTServer::fast_forward),
+ )
.route(
&format!("{prefix}/databases/:db/tables/:table/partitions"),
get(RESTServer::list_partitions).post(RESTServer::create_partitions),
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 3cec9a76..ebcd509a 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1381,20 +1381,62 @@ names, pure ASCII numeric names, `.`, `..`, path
separators, and control
characters are rejected. SQL also rejects `$` in target branch names because it
separates branch and system-table suffixes in object names. Branch names
preserve
leading and trailing spaces.
-When creating a branch, tag names are passed unchanged to Core; trailing
-whitespace is invalid.
+Tag names are passed unchanged. The REST server validates them for REST tables;
+Core validates them for filesystem-managed tables and rejects trailing
whitespace.
Branch-name and source-table validation also apply when `ignore_if_exists` is
`true`.
-Only non-REST FileStore tables resolved on `main` are supported. REST tables,
-format tables, external engine tables, and already resolved non-main source
-tables are rejected. The procedure does not resolve `$branch_<name>` or system
-table suffixes in its `table` argument and does not create from another branch.
+Only FileStore tables resolved on `main` are supported. Format tables, external
+engine tables, and non-main source tables are rejected. The `table` argument is
+passed to the selected catalog without additional branch or system-table suffix
+resolution. The procedure does not create from another branch.
-Creation reuses the Core metadata-copy path. Existence checks and file copies
-are not transactional; storage errors are returned and can leave partial branch
-metadata. `ignore_if_exists` checks name existence and does not repair a
partial
-creation.
+For tables managed by a REST catalog, the branch is created through the
catalog,
+which owns branch metadata, and the procedure does not write table storage
+itself. `ignore_if_exists` checks the catalog's branch list. An existing branch
+reported by a concurrent creation is also ignored when this option is `true`.
+Other catalog errors are returned to the caller.
+
+For filesystem-managed tables, creation reuses the Core metadata-copy path.
+Existence checks and file copies are not transactional; storage errors are
+returned and can leave partial branch metadata. `ignore_if_exists` checks name
+existence and does not repair a partial creation.
+
+### delete_branch
+
+Delete one or more branches:
+
+```sql
+CALL sys.delete_branch(table => 'paimon.my_db.my_table', branch =>
'dev,release_branch');
+```
+
+`table` and `branch` are required. `table` accepts `database.table` or
+`catalog.database.table`. The comma-separated branch names are processed in
+order, empty entries are skipped, and leading and trailing spaces are
+preserved. Missing branches are ignored. Names must pass the Core name
validator;
+`main` and branches configured by `scan.primary-branch` or
`scan.fallback-branch`
+cannot be deleted. Unset the corresponding option before deleting such a
branch.
+
+REST tables require a main-branch source table and delete branches through the
+catalog without writing table storage. Filesystem-managed tables use Core's
+branch manager. The operation returns one row with `result = 'OK'`. A
validation
+or catalog/storage error stops the batch; earlier deletions are not rolled
back.
+
+### fast_forward
+
+Fast-forward the main branch to a branch:
+
+```sql
+CALL sys.fast_forward(table => 'paimon.my_db.my_table', branch =>
'release_branch');
+```
+
+`table` and `branch` are required. `table` accepts `database.table` or
+`catalog.database.table`. Only tables managed by a REST catalog are supported:
+the REST server performs the fast-forward, and the procedure does not write
+table storage itself. Filesystem-managed tables are rejected. The `table`
+argument must resolve to the main branch, and the branch name must pass the
Core
+name validator, so `main` is rejected. A missing branch returns an error.
Success
+returns one row with `result = 'OK'`.
### create_tag