pub struct Transaction { /* private fields */ }Expand description
数据库事务(PostgreSQL)
Implementations§
Source§impl Transaction
impl Transaction
Sourcepub async fn execute(&mut self, sql: &str) -> Result<u64, DbError>
👎Deprecated since 0.1.0: 使用 execute_with_params / query_with_params 等参数化方法替代
pub async fn execute(&mut self, sql: &str) -> Result<u64, DbError>
使用 execute_with_params / query_with_params 等参数化方法替代
执行原生 SQL
§弃用说明
已弃用(与 MySQL Transaction::execute 对齐)。请使用参数化查询方法
execute_with_params 或
query_with_params 以防 SQL 注入。
Sourcepub async fn execute_with_params(
&mut self,
sql: &str,
params: Vec<Value>,
) -> Result<u64, DbError>
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?;Sourcepub async fn query_with_params<T>(
&mut self,
sql: &str,
params: Vec<Value>,
) -> Result<Vec<T>, DbError>
pub async fn query_with_params<T>( &mut self, sql: &str, params: Vec<Value>, ) -> Result<Vec<T>, DbError>
执行带参数的原生 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?;Sourcepub async fn select<T>(
&mut self,
query: QueryBuilder<'_>,
) -> Result<Vec<T>, DbError>
pub async fn select<T>( &mut self, query: QueryBuilder<'_>, ) -> Result<Vec<T>, DbError>
在当前事务中执行普通 QueryBuilder SELECT。
Sourcepub async fn select_for_update<T>(
&mut self,
query: QueryBuilder<'_>,
) -> Result<Vec<T>, DbError>
pub async fn select_for_update<T>( &mut self, query: QueryBuilder<'_>, ) -> Result<Vec<T>, DbError>
在当前事务中执行 FOR UPDATE SELECT。
在当前事务中执行 FOR SHARE SELECT。
Sourcepub async fn select_locked<T>(
&mut self,
query: QueryBuilder<'_>,
lock: RowLock,
) -> Result<Vec<T>, DbError>
pub async fn select_locked<T>( &mut self, query: QueryBuilder<'_>, lock: RowLock, ) -> Result<Vec<T>, DbError>
在当前事务中按指定模式执行行锁 SELECT。
Sourcepub async fn select_locked_with<T>(
&mut self,
query: QueryBuilder<'_>,
lock: RowLock,
of: &[&FieldRef],
nowait: bool,
skip_locked: bool,
) -> Result<Vec<T>, DbError>
pub async fn select_locked_with<T>( &mut self, query: QueryBuilder<'_>, lock: RowLock, of: &[&FieldRef], nowait: bool, skip_locked: bool, ) -> Result<Vec<T>, DbError>
在当前事务中执行完整的行锁 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 识别。
Sourcepub fn table(&mut self, table: &TableRef) -> QueryBuilder<'_>
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?;Sourcepub async fn savepoint(&mut self, name: &str) -> Result<(), DbError>
pub async fn savepoint(&mut self, name: &str) -> Result<(), DbError>
在当前事务内创建保存点(SAVEPOINT)。
name 必须是合法 SQL 标识符(首字符字母/下划线,其余字母/数字/下划线);
非法名称返回 DbError::InvalidArgument,不会被拼接进 SQL。
Sourcepub async fn rollback_to(&mut self, name: &str) -> Result<(), DbError>
pub async fn rollback_to(&mut self, name: &str) -> Result<(), DbError>
回滚到指定保存点(ROLLBACK TO SAVEPOINT)。
只撤销保存点之后的工作;保存点之前的外层事务与更早的保存点不受影响。
Sourcepub async fn release_savepoint(&mut self, name: &str) -> Result<(), DbError>
pub async fn release_savepoint(&mut self, name: &str) -> Result<(), DbError>
释放保存点(RELEASE SAVEPOINT)。
Sourcepub async fn set_local(&mut self, key: &str, value: &str) -> Result<(), DbError>
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):键名经严格校验后以字符串常量进入,
值仍走绑定参数,安全性不变。
Sourcepub async fn lock_table(
&mut self,
table: &TableRef,
mode: TableLockMode,
) -> Result<(), DbError>
pub async fn lock_table( &mut self, table: &TableRef, mode: TableLockMode, ) -> Result<(), DbError>
在当前事务内获取表级锁(LOCK TABLE ... IN <mode> MODE)。
表名按 table / schema.table 口径校验并加引号;锁在事务结束时自动释放。
模式见 TableLockMode。
Sourcepub async fn prepare(self, gid: &str) -> Result<(), DbError>
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 字节)。
Sourcepub async fn advisory_xact_lock(&mut self, key: i64) -> Result<(), DbError>
pub async fn advisory_xact_lock(&mut self, key: i64) -> Result<(), DbError>
获取事务级排他 advisory lock(pg_advisory_xact_lock),事务结束自动释放。
该调用会阻塞直到拿到锁;需要非阻塞语义请用
try_advisory_xact_lock。
获取事务级共享 advisory lock(pg_advisory_xact_lock_shared),事务结束自动释放。
共享锁彼此不互斥,但与同 key 的排他锁互斥。
Sourcepub async fn try_advisory_xact_lock(
&mut self,
key: i64,
) -> Result<bool, DbError>
pub async fn try_advisory_xact_lock( &mut self, key: i64, ) -> Result<bool, DbError>
尝试获取事务级排他 advisory lock(pg_try_advisory_xact_lock),不阻塞。
返回 true 表示已持有锁,false 表示锁被其他会话占用。
尝试获取事务级共享 advisory lock(pg_try_advisory_xact_lock_shared),不阻塞。
Sourcepub async fn execute_script_in_transaction(
&mut self,
script: &str,
) -> Result<usize, DbError>
pub async fn execute_script_in_transaction( &mut self, script: &str, ) -> Result<usize, DbError>
在当前事务内执行多语句脚本(不新开事务)。
脚本经 split_sql_script 按
PostgreSQL 词法切分(识别单/双引号、行/块注释与 dollar-quote),函数体、
DO 块内的分号不会被误切。任一条语句失败时本方法返回错误,事务进入中止
态,需由调用方 rollback()(或回滚到保存点)。
返回执行的语句条数(空脚本返回 0)。
Sourcepub async fn stream_query(
&mut self,
sql: &str,
params: Vec<Value>,
) -> Result<TxRowCursor<'_>, DbError>
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。
Sourcepub async fn stream_query_with_batch_size(
&mut self,
sql: &str,
params: Vec<Value>,
batch_size: usize,
) -> Result<TxRowCursor<'_>, DbError>
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
impl Drop for Transaction
Auto Trait Implementations§
impl !RefUnwindSafe for Transaction
impl !UnwindSafe for Transaction
impl Forget for Transaction
impl Freeze for Transaction
impl Move for Transaction
impl Send for Transaction
impl Sync for Transaction
impl Unpin for Transaction
impl UnsafeUnpin for Transaction
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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