uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Read-only validation, snapshot marking, and statement failure cleanup.

use uqa_sql::{
    plan::UnifiedPlan,
    semantics::effects::{
        read_only::{forbidden_command, plan_sets_transaction_snapshot, read_only_error},
        QueryEffectContext,
    },
    SQLError,
};

/// Session transaction observations and the existing rollback/abort boundary.
pub trait StatementTransactions {
    fn transaction_depth(&self) -> usize;
    /// A commit has sealed its effects but its durable outcome is unresolved. Statement cleanup must preserve that attempt instead of treating it as an ordinary aborted transaction.
    fn commit_resolution_pending(&self) -> bool {
        false
    }
    fn current_transaction_is_read_only(&self) -> bool;
    fn mark_transaction_snapshot_set(&self);
    /// Successful execution leaves session-owned caches current. Adapters may retain that exact private read view; an error, undo or later external change must still require ordinary refresh.
    fn retain_completed_statement_snapshot(&self) {}
    fn abort_after_error(&self, error: SQLError) -> SQLError;
    fn rollback(&self) -> Result<(), SQLError>;
}

/// Complete an already-bound SQL transaction exit that has no active block. Callers with a prepared definition must bind its inputs before using this completion.
pub(super) fn complete_idle_transaction(
    transactions: &dyn StatementTransactions,
    notices: &crate::query::NoticeQueue,
    statement: &uqa_sql::ast::TransactionStmt,
) -> Option<uqa_sql::SQLResult> {
    if transactions.transaction_depth() != 0
        || !matches!(
            statement,
            uqa_sql::ast::TransactionStmt::Commit | uqa_sql::ast::TransactionStmt::Rollback
        )
    {
        return None;
    }
    notices.push(
        uqa_sql::semantics::effects::transaction_blocks::no_transaction_in_progress_warning(),
    );
    Some(uqa_sql::SQLResult::empty().with_command_tag(
        uqa_sql::result::completion::transaction_completion(statement, false),
    ))
}

pub fn validate_transaction_plan(
    transactions: &dyn StatementTransactions,
    effects: &QueryEffectContext<'_>,
    plan: &UnifiedPlan,
) -> Result<(), SQLError> {
    if transactions.current_transaction_is_read_only() {
        if let Some(command) = forbidden_command(effects, plan)? {
            return Err(read_only_error(command));
        }
    }
    if plan_sets_transaction_snapshot(plan) {
        transactions.mark_transaction_snapshot_set();
    }
    Ok(())
}

pub fn abort_explicit_statement_error(
    transactions: &dyn StatementTransactions,
    error: SQLError,
) -> SQLError {
    if transactions.transaction_depth() == 0 || transactions.commit_resolution_pending() {
        error
    } else {
        transactions.abort_after_error(error)
    }
}

pub fn rollback_implicit_statement(
    transactions: &dyn StatementTransactions,
    action: &str,
) -> Result<(), SQLError> {
    transactions.rollback().map_err(|rollback_error| {
        rollback_error.with_context(format!("{action}: autocommit rollback failed"))
    })
}

pub fn rollback_after_statement_error<T>(
    transactions: &dyn StatementTransactions,
    statement_error: SQLError,
) -> Result<T, SQLError> {
    if transactions.transaction_depth() == 0 || transactions.commit_resolution_pending() {
        return Err(statement_error);
    }
    match transactions.rollback() {
        Ok(()) => Err(statement_error),
        Err(rollback_error) if rollback_error.sqlstate() == Some("08007") => {
            Err(rollback_error.with_context(format!("original statement error: {statement_error}")))
        }
        Err(rollback_error) => {
            Err(statement_error.with_cleanup(rollback_error, "autocommit rollback also failed"))
        }
    }
}

#[cfg(test)]
mod tests;