Skip to main content

Transaction

Struct Transaction 

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

数据库事务(PostgreSQL)

Implementations§

Source§

impl Transaction

Source

pub async fn commit(self) -> Result<(), DbError>

提交事务

Source

pub async fn rollback(self) -> Result<(), DbError>

回滚事务

Source

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

👎Deprecated since 0.1.0:

使用 execute_with_params / query_with_params 等参数化方法替代

执行原生 SQL

§弃用说明

已弃用(与 MySQL Transaction::execute 对齐)。请使用参数化查询方法 execute_with_params 或 query_with_params 以防 SQL 注入。

Source

pub async fn execute_with_params( &mut self, sql: &str, params: Vec<Value>, ) -> Result<u64, DbError>

执行带参数的原生 SQL(参数化查询,防止 SQL 注入)

§参数
  • sql: SQL 语句,使用 $N 作为参数占位符
  • params: 参数列表,使用 serde_json::Value 类型
§返回
  • Ok(u64): 受影响的行数
  • Err(DbError): 执行失败错误
§示例
use yang_db::postgres::Database;
use serde_json::json;

let db = Database::connect("postgres://postgres:postgres@localhost:5432/test").await?;
let mut tx = db.transaction().await?;
let params = vec![json!("张三"), json!("张三@example.com")];
tx.execute_with_params("INSERT INTO users (name, email) VALUES ($1, $2)", params).await?;
tx.commit().await?;
Source

pub async fn query_with_params<T>( &mut self, sql: &str, params: Vec<Value>, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

执行带参数的原生 SELECT 查询(参数化查询,防止 SQL 注入)

§参数
  • sql: SQL 查询语句,使用 $N 作为参数占位符
  • params: 参数列表,使用 serde_json::Value 类型
§返回
  • Ok(Vec): 查询结果列表
  • Err(DbError): 查询失败错误
§示例
use yang_db::postgres::Database;
use serde_json::json;

let db = Database::connect("postgres://postgres:postgres@localhost:5432/test").await?;
let mut tx = db.transaction().await?;
let params = vec![json!(1i64)];
// let users: Vec<User> = tx.query_with_params("SELECT * FROM users WHERE id = $1", params).await?;
tx.commit().await?;
Source

pub async fn select<T>( &mut self, query: QueryBuilder<'_>, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

在当前事务中执行普通 QueryBuilder SELECT。

Source

pub async fn select_for_update<T>( &mut self, query: QueryBuilder<'_>, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

在当前事务中执行 FOR UPDATE SELECT。

Source

pub async fn select_for_share<T>( &mut self, query: QueryBuilder<'_>, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

在当前事务中执行 FOR SHARE SELECT。

Source

pub async fn select_locked<T>( &mut self, query: QueryBuilder<'_>, lock: RowLock, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

在当前事务中按指定模式执行行锁 SELECT。

Source

pub async fn select_locked_with<T>( &mut self, query: QueryBuilder<'_>, lock: RowLock, of: &[&FieldRef], nowait: bool, skip_locked: bool, ) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, PgRow> + Send + Unpin,

在当前事务中执行完整的行锁 SELECT:可指定 FOR ... OF 表列表、NOWAIT 或 SKIP LOCKED(与 QueryBuilder::try_to_sql_with_lock 的 SQL 语义一致)。

nowait 与 skip_locked 互斥,同时为 true 时返回 DbError::InvalidArgument;ForUpdateSkipLocked / ForShareSkipLocked 隐含 SKIP LOCKED。锁冲突在 NOWAIT 下返回 SQLSTATE 55P03, 可通过 DbError::sqlstate 或 DbError::sql_error 识别。

Source

pub fn table(&mut self, table: &TableRef) -> QueryBuilder<'_>

选择表,返回事务中的查询构建器

§参数
  • table_name: 表名
§返回
  • QueryBuilder: 与连接池路径共享的事务查询构建器
§示例
use yang_db::postgres::Database;
use serde_json::json;

let db = Database::connect("postgres://postgres:postgres@localhost:5432/test").await?;
let mut tx = db.transaction().await?;

// 在事务中插入数据
let user_data = json!({"name": "张三", "email": "zhangsan@example.com"});
let user_id = tx.table(yang_db::table!("users")).insert(&user_data).await?;

// 在事务中更新数据
let update_data = json!({"status": 1});
tx.table(yang_db::table!("users"))
    .where_and(yang_db::field!("id"), yang_db::CompareOp::Eq, user_id)?
    .update(&update_data)
    .await?;

// 提交事务
tx.commit().await?;
Source

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

在当前事务内创建保存点(SAVEPOINT)。

name 必须是合法 SQL 标识符(首字符字母/下划线,其余字母/数字/下划线); 非法名称返回 DbError::InvalidArgument,不会被拼接进 SQL。

Source

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

回滚到指定保存点(ROLLBACK TO SAVEPOINT)。

只撤销保存点之后的工作;保存点之前的外层事务与更早的保存点不受影响。

Source

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

释放保存点(RELEASE SAVEPOINT)。

Source

pub async fn set_local(&mut self, key: &str, value: &str) -> Result<(), DbError>

设置事务级会话参数(SET LOCAL 语义,随事务提交/回滚自动失效)。

key 必须是白名单标识符(允许点号,如 app.tenant_id),非法名返回 DbError::InvalidArgument;value 通过绑定参数传入。

实现说明:PostgreSQL 的 SET 语法在扩展查询协议下不接受参数占位符 (SET LOCAL "k" = $1 会报语法错误),因此这里用等价的 set_config('k', $1, true):键名经严格校验后以字符串常量进入, 值仍走绑定参数,安全性不变。

Source

pub async fn lock_table( &mut self, table: &TableRef, mode: TableLockMode, ) -> Result<(), DbError>

在当前事务内获取表级锁(LOCK TABLE ... IN <mode> MODE)。

表名按 table / schema.table 口径校验并加引号;锁在事务结束时自动释放。 模式见 TableLockMode。

Source

pub async fn prepare(self, gid: &str) -> Result<(), DbError>

将当前事务准备为两阶段提交(PREPARE TRANSACTION '<gid>'),消费事务句柄。

成功后事务进入服务端 prepared 状态,需在任意连接上调用 Database::commit_prepared 或 Database::rollback_prepared 收尾。服务端 max_prepared_transactions = 0 时返回明确的 DbError::TransactionError,而非仅透传驱动报文。

GID 不能参数化,只接受 [A-Za-z0-9_.:-] 白名单字符(最长 200 字节)。

Source

pub async fn advisory_xact_lock(&mut self, key: i64) -> Result<(), DbError>

获取事务级排他 advisory lock(pg_advisory_xact_lock),事务结束自动释放。

该调用会阻塞直到拿到锁;需要非阻塞语义请用 try_advisory_xact_lock。

Source

pub async fn advisory_xact_lock_shared( &mut self, key: i64, ) -> Result<(), DbError>

获取事务级共享 advisory lock(pg_advisory_xact_lock_shared),事务结束自动释放。

共享锁彼此不互斥,但与同 key 的排他锁互斥。

Source

pub async fn try_advisory_xact_lock( &mut self, key: i64, ) -> Result<bool, DbError>

尝试获取事务级排他 advisory lock(pg_try_advisory_xact_lock),不阻塞。

返回 true 表示已持有锁,false 表示锁被其他会话占用。

Source

pub async fn try_advisory_xact_lock_shared( &mut self, key: i64, ) -> Result<bool, DbError>

尝试获取事务级共享 advisory lock(pg_try_advisory_xact_lock_shared),不阻塞。

Source

pub async fn execute_script_in_transaction( &mut self, script: &str, ) -> Result<usize, DbError>

在当前事务内执行多语句脚本(不新开事务)。

脚本经 split_sql_script 按 PostgreSQL 词法切分(识别单/双引号、行/块注释与 dollar-quote),函数体、 DO 块内的分号不会被误切。任一条语句失败时本方法返回错误,事务进入中止 态,需由调用方 rollback()(或回滚到保存点)。

返回执行的语句条数(空脚本返回 0)。

Source

pub async fn stream_query( &mut self, sql: &str, params: Vec<Value>, ) -> Result<TxRowCursor<'_>, DbError>

在当前事务内以服务端游标流式读取结果集(默认每批 1000 行)。

游标通过 DECLARE ... CURSOR FOR + 分批 FETCH 实现,大结果集不会一次性 进入内存。游标借出事务的可变引用,使用期间不能再操作同一事务;未读尽即丢弃 时,服务端游标随事务结束(提交/回滚)一并释放。

§错误

SQL 为空或 batch_size 为 0 时返回 DbError::InvalidArgument。

Source

pub async fn stream_query_with_batch_size( &mut self, sql: &str, params: Vec<Value>, batch_size: usize, ) -> Result<TxRowCursor<'_>, DbError>

同 stream_query,可指定每批拉取行数。

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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