Skip to content

feat(transaction): Add TransactionAction and related classes #1420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 190 additions & 0 deletions crates/iceberg/src/transaction/action.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// 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 std::mem::take;
use std::sync::Arc;

use async_trait::async_trait;

use crate::table::Table;
use crate::transaction::Transaction;
use crate::{Result, TableRequirement, TableUpdate};

/// A boxed, thread-safe reference to a `TransactionAction`.
pub type BoxedTransactionAction = Arc<dyn TransactionAction>;

/// A trait representing an atomic action that can be part of a transaction.
///
/// Implementors of this trait define how a specific action is committed to a table.
/// Each action is responsible for generating the updates and requirements needed
/// to modify the table metadata.
#[async_trait]
pub trait TransactionAction: Sync + Send {
/// Commits this action against the provided table and returns the resulting updates.
/// NOTE: This function is intended for internal use only and should not be called directly by users.
///
/// # Arguments
///
/// * `table` - The current state of the table this action should apply to.
///
/// # Returns
///
/// An `ActionCommit` containing table updates and table requirements,
/// or an error if the commit fails.
#[allow(dead_code)]
async fn commit(self: Arc<Self>, table: &Table) -> Result<ActionCommit>;
}

/// A helper trait for applying a `TransactionAction` to a `Transaction`.
///
/// This is implemented for all `TransactionAction` types
/// to allow easy chaining of actions into a transaction context.
pub trait ApplyTransactionAction {
/// Adds this action to the given transaction.
///
/// # Arguments
///
/// * `tx` - The transaction to apply the action to.
///
/// # Returns
///
/// The modified transaction containing this action, or an error if the operation fails.
#[allow(dead_code)]
fn apply(self, tx: Transaction) -> Result<Transaction>;
}

impl<T: TransactionAction + 'static> ApplyTransactionAction for T {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this apply will have different implementation? If not, maybe we can provide a "apply" function in Transaction directly, like:

let action1 ...
let action2 ...
 let tx = Transaction::new(&table);
tx.apply(action1).apply(action2)..

Looks like these two method implement the same effect and just a function in Transaction maybe more clear.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's an auto implementation and will be apply to all transaction actions.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This enables fluent api call like this:

let mut tx = action.add_file("x1")
.add_file("x2")
.apply(tx);

fn apply(self, mut tx: Transaction) -> Result<Transaction>
where Self: Sized {
tx.actions.push(Arc::new(self));
Ok(tx)
}
}

/// The result of committing a `TransactionAction`.
///
/// This struct contains the updates to apply to the table's metadata
/// and any preconditions that must be satisfied before the update can be committed.
pub struct ActionCommit {
updates: Vec<TableUpdate>,
requirements: Vec<TableRequirement>,
}

impl ActionCommit {
/// Creates a new `ActionCommit` from the given updates and requirements.
#[allow(dead_code)]
pub fn new(updates: Vec<TableUpdate>, requirements: Vec<TableRequirement>) -> Self {
Self {
updates,
requirements,
}
}

/// Consumes and returns the list of table updates.
#[allow(dead_code)]
pub fn take_updates(&mut self) -> Vec<TableUpdate> {
take(&mut self.updates)
}

/// Consumes and returns the list of table requirements.
#[allow(dead_code)]
pub fn take_requirements(&mut self) -> Vec<TableRequirement> {
take(&mut self.requirements)
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;
use std::sync::Arc;

use async_trait::async_trait;
use uuid::Uuid;

use crate::table::Table;
use crate::transaction::Transaction;
use crate::transaction::action::{ActionCommit, ApplyTransactionAction, TransactionAction};
use crate::transaction::tests::make_v2_table;
use crate::{Result, TableRequirement, TableUpdate};

struct TestAction;

#[async_trait]
impl TransactionAction for TestAction {
async fn commit(self: Arc<Self>, _table: &Table) -> Result<ActionCommit> {
Ok(ActionCommit::new(
vec![TableUpdate::SetLocation {
location: String::from("s3://bucket/prefix/table/"),
}],
vec![TableRequirement::UuidMatch {
uuid: Uuid::from_str("9c12d441-03fe-4693-9a96-a0705ddf69c1")?,
}],
))
}
}

#[tokio::test]
async fn test_commit_transaction_action() {
let table = make_v2_table();
let action = TestAction;

let mut action_commit = Arc::new(action).commit(&table).await.unwrap();

let updates = action_commit.take_updates();
let requirements = action_commit.take_requirements();

assert_eq!(updates[0], TableUpdate::SetLocation {
location: String::from("s3://bucket/prefix/table/")
});
assert_eq!(requirements[0], TableRequirement::UuidMatch {
uuid: Uuid::from_str("9c12d441-03fe-4693-9a96-a0705ddf69c1").unwrap()
});
}

#[test]
fn test_apply_transaction_action() {
let table = make_v2_table();
let action = TestAction;
let tx = Transaction::new(&table);

let updated_tx = action.apply(tx).unwrap();

// There should be one action in the transaction now
assert_eq!(updated_tx.actions.len(), 1);
}

#[test]
fn test_action_commit() {
// Create dummy updates and requirements
let location = String::from("s3://bucket/prefix/table/");
let uuid = Uuid::new_v4();
let updates = vec![TableUpdate::SetLocation { location }];
let requirements = vec![TableRequirement::UuidMatch { uuid }];

let mut action_commit = ActionCommit::new(updates.clone(), requirements.clone());

let taken_updates = action_commit.take_updates();
let taken_requirements = action_commit.take_requirements();

// Check values are returned correctly
assert_eq!(taken_updates, updates);
assert_eq!(taken_requirements, requirements);

assert!(action_commit.take_updates().is_empty());
assert!(action_commit.take_requirements().is_empty());
}
}
4 changes: 4 additions & 0 deletions crates/iceberg/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

//! This module contains transaction api.

mod action;
mod append;
mod snapshot;
mod sort_order;
Expand All @@ -32,6 +33,7 @@ use crate::TableUpdate::UpgradeFormatVersion;
use crate::error::Result;
use crate::spec::FormatVersion;
use crate::table::Table;
use crate::transaction::action::BoxedTransactionAction;
use crate::transaction::append::FastAppendAction;
use crate::transaction::sort_order::ReplaceSortOrderAction;
use crate::{Catalog, Error, ErrorKind, TableCommit, TableRequirement, TableUpdate};
Expand All @@ -40,6 +42,7 @@ use crate::{Catalog, Error, ErrorKind, TableCommit, TableRequirement, TableUpdat
pub struct Transaction<'a> {
base_table: &'a Table,
current_table: Table,
actions: Vec<BoxedTransactionAction>,
updates: Vec<TableUpdate>,
requirements: Vec<TableRequirement>,
}
Expand All @@ -50,6 +53,7 @@ impl<'a> Transaction<'a> {
Self {
base_table: table,
current_table: table.clone(),
actions: vec![],
updates: vec![],
requirements: vec![],
}
Expand Down
Loading