Skip to main content

Transaction

Struct Transaction 

Source
pub struct Transaction { /* private fields */ }
Expand description

事务对象,封装一个数据库事务

内部连接以 Option<Box<dyn Connection>> 形式持有:

  • 事务执行期间,连接存在
  • 调用 take_connection() 可在 commit/rollback 后取回连接归还到连接池
  • Drop 时若事务仍 Active,会尝试 spawn 后台 rollback 任务

Implementations§

Source§

impl Transaction

Source

pub fn new(conn: Box<dyn Connection>, options: TransactOptions) -> Self

创建新事务(调用方应先通过 connection.begin_transaction() 启动事务)

L-5 修复:补充示例文档

通常通过 Connection::begin_transaction() 创建,而不是直接调用此方法。

§示例
use sz_orm_core::transaction::{Transaction, TransactOptions};

// 通常通过 Connection::begin_transaction 创建
let tx = Transaction::new(conn, TransactOptions::default());
assert!(tx.is_active());
Source

pub fn state(&self) -> TransactionState

获取当前事务状态

Source

pub fn is_active(&self) -> bool

检查事务是否仍然活跃

Source

pub async fn commit(&mut self) -> Result<(), TxError>

提交事务

L-5 修复:补充示例文档

提交后事务状态变为 Committed,不可再次 commit/rollback。 若未提交就 drop,会自动 rollback。

§示例
tx.execute("INSERT INTO users (name) VALUES ('Alice')").await?;
tx.execute("INSERT INTO users (name) VALUES ('Bob')").await?;
tx.commit().await?; // 提交两条 INSERT
Source

pub async fn rollback(&mut self) -> Result<(), TxError>

回滚事务

Source

pub async fn execute(&mut self, sql: &str) -> Result<u64, TxError>

在事务中执行 SQL(在事务未结束时执行)

Source

pub async fn query( &mut self, sql: &str, ) -> Result<Vec<HashMap<String, Value>>, TxError>

在事务中执行查询

Source

pub async fn savepoint(&mut self) -> Result<String, TxError>

创建保存点(用于嵌套事务)

返回自动生成的保存点名(格式 sp_<N>,N 单调递增)。

H-8 修复:检查嵌套深度,超过 options.max_nesting_depth 时返回 TxError::MaxNestingDepthExceeded

L-5 修复:补充示例文档

§示例
// 在外层事务中创建保存点
let sp = tx.savepoint().await?;
// 执行一些操作
tx.execute("INSERT INTO orders (id) VALUES (1)").await?;
// 出错时回滚到保存点(不影响外层事务的其他操作)
tx.rollback_to_savepoint(&sp).await?;
// 不再需要保存点时释放
tx.release_savepoint(&sp).await?;
Source

pub async fn rollback_to_savepoint(&mut self, name: &str) -> Result<(), TxError>

回滚到保存点

name 必须是合法的保存点名称(仅 ASCII 字母/数字/下划线,且不以数字开头)。 通常使用 savepoint() 返回的名称。

Source

pub async fn release_savepoint(&mut self, name: &str) -> Result<(), TxError>

释放保存点

name 必须是合法的保存点名称(仅 ASCII 字母/数字/下划线,且不以数字开头)。 通常使用 savepoint() 返回的名称。

Source

pub async fn take_connection(&mut self) -> Result<Box<dyn Connection>, TxError>

取出底层连接(用于归还到连接池)

仅在事务已 commit/rollback 后才能调用,否则返回 NotActive 错误。 重复调用返回 ConnectionTaken 错误。

典型用法:

tx.commit().await?;
let conn = tx.take_connection().await?;
pool.release(conn).await;
Source

pub fn options(&self) -> &TransactOptions

获取事务选项

Trait Implementations§

Source§

impl Drop for Transaction

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more