use uqa_sql::{
plan::UnifiedPlan,
semantics::effects::{
read_only::{forbidden_command, plan_sets_transaction_snapshot, read_only_error},
QueryEffectContext,
},
SQLError,
};
pub trait StatementTransactions {
fn transaction_depth(&self) -> usize;
fn commit_resolution_pending(&self) -> bool {
false
}
fn current_transaction_is_read_only(&self) -> bool;
fn mark_transaction_snapshot_set(&self);
fn retain_completed_statement_snapshot(&self) {}
fn abort_after_error(&self, error: SQLError) -> SQLError;
fn rollback(&self) -> Result<(), SQLError>;
}
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;