pub struct Database { /* private fields */ }Expand description
数据库连接管理器
管理 PostgreSQL 数据库连接池,提供查询构建和执行的入口点
§示例
use yang_db::postgres::Database;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 连接数据库
let db = Database::connect("postgres://user:password@localhost:5432/test").await?;
// 使用查询构建器
let builder = db.table(yang_db::table!("users"))
.field(yang_db::field!("id"))
.field(yang_db::field!("name"));
// 执行查询(需要实现 select 方法)
// let users = builder.select::<User>().await?;
Ok(())
}Implementations§
Source§impl Database
impl Database
Sourcepub async fn copy_from_csv<I, R>(
&self,
sql: &str,
rows: I,
) -> Result<u64, DbError>
pub async fn copy_from_csv<I, R>( &self, sql: &str, rows: I, ) -> Result<u64, DbError>
通过 COPY ... FROM STDIN 批量导入 CSV 行。
sql 必须是形如
COPY <表> [(列...)] FROM STDIN WITH (FORMAT csv, ...) 的语句,其余
格式选项由 SQL 文本决定。rows 的每一项是一条完整 CSV 记录:末尾缺少
\n 时自动补一个;字段内的 CSV 转义(引号、逗号、换行)由调用方负责,
本方法按字节原样发送,不做转义。
返回服务端确认的写入行数。失败时若连接协议状态已无法确认,该连接会被 关闭而不是放回连接池。
Sourcepub async fn copy_to_csv(&self, sql: &str) -> Result<Vec<u8>, DbError>
pub async fn copy_to_csv(&self, sql: &str) -> Result<Vec<u8>, DbError>
通过 COPY ... TO STDOUT 导出 CSV 数据。
sql 必须是形如
COPY (SELECT ...) TO STDOUT WITH (FORMAT csv, ...) 的语句。返回服务端
输出的完整原始字节(CSV 文本)。
输出会一次性收集到内存;导出超大结果集时请改用
stream_query 分页读取。
失败时若连接协议状态已无法确认,该连接会被关闭而不是放回连接池。
Source§impl Database
impl Database
Sourcepub const fn capabilities() -> &'static BackendCapabilities
pub const fn capabilities() -> &'static BackendCapabilities
返回 PostgreSQL 后端的静态能力契约。
Sourcepub async fn connect_with_config(
url: &str,
config: DatabaseConfig,
) -> Result<Self, DbError>
pub async fn connect_with_config( url: &str, config: DatabaseConfig, ) -> Result<Self, DbError>
使用自定义配置创建数据库连接
Sourcepub fn from_pool(pool: PgPool, config: DatabaseConfig) -> Result<Self, DbError>
pub fn from_pool(pool: PgPool, config: DatabaseConfig) -> Result<Self, DbError>
从调用方已创建的连接池构造数据库入口。
该构造器不建立连接,也不写入进程全局状态,供显式资源所有权与离线测试使用。
注意:after_connect/after_release 等会话钩子只在
Self::connect_with_config 建立的连接池上生效;from_pool 的既有连接
需要调用方自行设置,可用 Self::reset_connection 手工清理单条连接。
§错误
当 config 的连接数或超时参数非法时返回 DbError::InvalidArgument。
Sourcepub fn table(&self, table: &TableRef) -> QueryBuilder<'_>
pub fn table(&self, table: &TableRef) -> QueryBuilder<'_>
选择表,返回查询构建器
Sourcepub fn pool(&self) -> &PgPool
pub fn pool(&self) -> &PgPool
获取底层 sqlx 连接池的引用
sqlx 的 PgPool 内部基于 Arc,克隆代价低廉。上层(如 yang-base 的
ActionContext::table_query)需要把连接池注入 TableQuery 时,可用
db.pool().clone() 获得一个共享同一连接池的句柄。
Sourcepub fn pool_status(&self) -> PoolStatus
pub fn pool_status(&self) -> PoolStatus
返回连接池状态快照(与 MySQL / Redis 后端对称;NEW-12)。
max_size:配置的最大连接数(config.max_connections)size:当前池内连接总数(pool.size())available:当前空闲可借出连接数(pool.num_idle())waiting:调用Database自身入口(query/execute/transaction/acquire/ 流式游标/advisory lock/COPY 等)时,处于「池已无空闲连接且已达上限」的 在途 acquire 数。sqlx 不直接暴露等待者数,因此这是本库维护的近似值: 直接经Self::pool借出的调用(含QueryBuilder执行路径)不计入。
连接耗尽排查:available == 0 && size == max_size 即池被打满。
Sourcepub async fn health_check(&self) -> Result<bool, DbError>
pub async fn health_check(&self) -> Result<bool, DbError>
Sourcepub async fn close(&self)
pub async fn close(&self)
优雅关闭连接池(I3):停止发放新连接、等待在途连接归还后关闭。与 MySQL 对称。
幂等;close 后再用返回 PoolClosed 类错误而非 panic。
Sourcepub async fn query<T>(&self, sql: &str) -> Result<Vec<T>, DbError>
👎Deprecated since 0.1.0: 使用 query_with_params 替代,避免 SQL 注入风险
pub async fn query<T>(&self, sql: &str) -> Result<Vec<T>, DbError>
使用 query_with_params 替代,避免 SQL 注入风险
执行原生 SELECT 查询
⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL
字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [query_with_params]。
Sourcepub async fn execute(&self, sql: &str) -> Result<u64, DbError>
👎Deprecated since 0.1.0: 使用 execute_with_params 替代,避免 SQL 注入风险
pub async fn execute(&self, sql: &str) -> Result<u64, DbError>
使用 execute_with_params 替代,避免 SQL 注入风险
执行原生 INSERT/UPDATE/DELETE 查询
⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL
字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [execute_with_params]。
Sourcepub async fn transaction(&self) -> Result<Transaction, DbError>
pub async fn transaction(&self) -> Result<Transaction, DbError>
开始事务(使用数据库默认隔离级别 READ COMMITTED)
Sourcepub async fn transaction_with_isolation(
&self,
isolation: IsolationLevel,
) -> Result<Transaction, DbError>
pub async fn transaction_with_isolation( &self, isolation: IsolationLevel, ) -> Result<Transaction, DbError>
开始事务并设置隔离级别(NG-2)。
等价于 transaction_with_options 只指定
isolation。
Sourcepub async fn transaction_with_options(
&self,
options: TransactionOptions,
) -> Result<Transaction, DbError>
pub async fn transaction_with_options( &self, options: TransactionOptions, ) -> Result<Transaction, DbError>
按指定选项开始事务(Phase B)。
BEGIN 之后立即执行一条 SET TRANSACTION ...;选项全默认时不下发该语句。
隔离级别名只来自 crate::isolation::IsolationLevel 的 &'static str,
其余属性为布尔开关,无注入面。
Sourcepub async fn read_only_transaction(&self) -> Result<Transaction, DbError>
pub async fn read_only_transaction(&self) -> Result<Transaction, DbError>
开始只读事务。事务内写入由服务端拒绝(SQLSTATE 25006)。
Sourcepub async fn retry_transaction<T, F, Fut>(
&self,
operation: F,
max_attempts: u32,
) -> Result<T, DbError>
pub async fn retry_transaction<T, F, Fut>( &self, operation: F, max_attempts: u32, ) -> Result<T, DbError>
带重试地执行一个事务(默认事务选项)。
仅对 PostgreSQL 的序列化失败(SQLSTATE 40001)与死锁(40P01)重试, 其他错误立即返回。重试之间按指数退避(10ms 起,封顶 1s)。
operation 接收一个已开启的事务并对其负责:成功路径需自行 commit();
返回 Err 时事务被丢弃并自动回滚。
§错误
max_attempts 为 0 时返回 DbError::InvalidArgument。
Sourcepub async fn retry_transaction_with_options<T, F, Fut>(
&self,
options: TransactionOptions,
operation: F,
max_attempts: u32,
) -> Result<T, DbError>
pub async fn retry_transaction_with_options<T, F, Fut>( &self, options: TransactionOptions, operation: F, max_attempts: u32, ) -> Result<T, DbError>
同 retry_transaction,可指定事务选项。
Sourcepub async fn init(&self, sql_script: &str) -> Result<(), DbError>
👎Deprecated since 0.1.4: 请使用 execute_script(整脚本单事务,正确处理函数/DO 块与 dollar-quote)
pub async fn init(&self, sql_script: &str) -> Result<(), DbError>
请使用 execute_script(整脚本单事务,正确处理函数/DO 块与 dollar-quote)
初始化数据库(执行 SQL 脚本)
已弃用:直接委托给 Self::execute_script(整脚本单事务、dollar-quote/
注释感知的分句器)。新代码请直接用 execute_script。
Sourcepub async fn create_table(&self, create_sql: &str) -> Result<(), DbError>
👎Deprecated since 0.2.2: 裸 SQL 建表逃生舱;请使用 execute_script(单事务、可含多条 DDL)或外部迁移工具
pub async fn create_table(&self, create_sql: &str) -> Result<(), DbError>
裸 SQL 建表逃生舱;请使用 execute_script(单事务、可含多条 DDL)或外部迁移工具
创建表(执行一条可信 CREATE TABLE SQL)。
已弃用:本方法只透传裸 SQL,不做拆分、事务或标识符校验。请改用
Self::execute_script(单事务、正确切分多语句)或外部迁移工具。
Sourcepub async fn drop_table(&self, table_name: &TableRef) -> Result<(), DbError>
pub async fn drop_table(&self, table_name: &TableRef) -> Result<(), DbError>
删除表
表名经 quote_identifier 校验+转义(DB-6,双引号方言);非法表名返回
InvalidArgument。
Sourcepub async fn table_exists(&self, table_name: &TableRef) -> Result<bool, DbError>
pub async fn table_exists(&self, table_name: &TableRef) -> Result<bool, DbError>
检查表是否存在。
支持单段表名与 schema.table 限定名:标识符先按表名口径逐段校验并加引号,
再交给 to_regclass 解析(限定名直接定位 schema,单段名遵循连接的
search_path)。
Sourcepub async fn query_with_params<T>(
&self,
sql: &str,
params: Vec<Value>,
) -> Result<Vec<T>, DbError>
pub async fn query_with_params<T>( &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/test").await?;
let params = vec![json!("admin"), json!(1)];
// let users: Vec<User> = db.query_with_params("SELECT * FROM users WHERE role = $1 AND status = $2", params).await?;Sourcepub async fn execute_with_params(
&self,
sql: &str,
params: Vec<Value>,
) -> Result<u64, DbError>
pub async fn execute_with_params( &self, sql: &str, params: Vec<Value>, ) -> Result<u64, DbError>
执行带参数的原生 INSERT/UPDATE/DELETE 语句(参数化查询,防止 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/test").await?;
let params = vec![json!("张三"), json!("zhangsan@example.com")];
let rows = db.execute_with_params("INSERT INTO users (name, email) VALUES ($1, $2)", params).await?;Sourcepub async fn stream_query(
&self,
sql: &str,
params: Vec<Value>,
) -> Result<PgRowCursor, DbError>
pub async fn stream_query( &self, sql: &str, params: Vec<Value>, ) -> Result<PgRowCursor, DbError>
以服务端游标流式读取查询结果(默认每批 1000 行)。
游标在一条只读事务内声明(BEGIN READ ONLY + DECLARE ... CURSOR),
逐行消费时按批 FETCH,大结果集不会一次性进入内存。游标读尽或
PgRowCursor::close 后,内部事务 ROLLBACK 并把连接归还连接池。
未读尽即丢弃游标时无法在同步 Drop 中执行 ROLLBACK,实现会
detach 该连接(关闭而非归还),避免把带打开事务的连接放回池中。
§查询取消
sqlx 0.8 没有从连接池直接 cancel 某个查询的 API。需要取消时,可行替代是:
用 db.pool().acquire() 取一条独立连接并 SELECT pg_backend_pid() 记下后端
PID(即 cancel token),在另一条连接上执行
SELECT pg_cancel_backend($1)(或 pg_terminate_backend($1))。
§错误
SQL 为空或 batch_size 为 0 时返回 DbError::InvalidArgument。
Sourcepub async fn stream_query_with_batch_size(
&self,
sql: &str,
params: Vec<Value>,
batch_size: usize,
) -> Result<PgRowCursor, DbError>
pub async fn stream_query_with_batch_size( &self, sql: &str, params: Vec<Value>, batch_size: usize, ) -> Result<PgRowCursor, DbError>
同 stream_query,可指定每批拉取行数。
Sourcepub async fn advisory_lock(&self, key: i64) -> Result<PgAdvisoryLock, DbError>
pub async fn advisory_lock(&self, key: i64) -> Result<PgAdvisoryLock, DbError>
获取会话级排他 advisory lock(pg_advisory_lock),阻塞直到拿到锁。
会话级锁绑定在具体连接上,因此返回的 PgAdvisoryLock 持有该连接:
显式 PgAdvisoryLock::unlock 或丢弃 guard(导致连接关闭、服务端回收锁)
之前,这条连接不会再归还池中。guard 存活期间会占用一个池连接名额。
获取会话级共享 advisory lock(pg_advisory_lock_shared),阻塞直到拿到锁。
共享锁彼此不互斥,但与同 key 的排他锁互斥;其余语义与
advisory_lock 相同(RAII 解锁、绑定单条连接)。
Sourcepub async fn try_advisory_lock(
&self,
key: i64,
) -> Result<Option<PgAdvisoryLock>, DbError>
pub async fn try_advisory_lock( &self, key: i64, ) -> Result<Option<PgAdvisoryLock>, DbError>
尝试获取会话级排他 advisory lock(pg_try_advisory_lock),不阻塞。
返回 None 表示锁被其他会话占用;连接随即归还池。
尝试获取会话级共享 advisory lock(pg_try_advisory_lock_shared),不阻塞。
Sourcepub async fn server_version_num(&self) -> Result<i32, DbError>
pub async fn server_version_num(&self) -> Result<i32, DbError>
服务端的 server_version_num(如 PG 16.15 → 160015),首次调用后缓存到实例。
版本门控请优先使用 Self::supports。
Sourcepub async fn supports(&self, min_version: i32) -> Result<bool, DbError>
pub async fn supports(&self, min_version: i32) -> Result<bool, DbError>
判断服务端版本是否不低于 min_version(server_version_num 口径)。
例如 PG 14 及以上传 140000。
Sourcepub async fn prepare_transaction(
&self,
transaction: Transaction,
gid: &str,
) -> Result<(), DbError>
pub async fn prepare_transaction( &self, transaction: Transaction, gid: &str, ) -> Result<(), DbError>
将已开启的事务准备为两阶段提交(PREPARE TRANSACTION)。
成功返回后事务进入服务端 prepared 状态,transaction 句柄被消费;调用方需
通过 Self::commit_prepared 或 Self::rollback_prepared 收尾。
max_prepared_transactions = 0 时返回明确的 DbError::TransactionError。
Sourcepub async fn commit_prepared(&self, gid: &str) -> Result<(), DbError>
pub async fn commit_prepared(&self, gid: &str) -> Result<(), DbError>
提交一个已准备的两阶段事务(COMMIT PREPARED)。
必须在事务块之外执行;GID 只能是 [A-Za-z0-9_.:-] 白名单字符。
Sourcepub async fn rollback_prepared(&self, gid: &str) -> Result<(), DbError>
pub async fn rollback_prepared(&self, gid: &str) -> Result<(), DbError>
回滚一个已准备的两阶段事务(ROLLBACK PREPARED)。
必须在事务块之外执行;GID 约束同 Self::commit_prepared。
Sourcepub async fn explain(
&self,
sql: &str,
params: Vec<Value>,
) -> Result<Vec<String>, DbError>
pub async fn explain( &self, sql: &str, params: Vec<Value>, ) -> Result<Vec<String>, DbError>
执行 EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) 并返回解析后的计划文本。
sql 与 Self::query_with_params 一样是调用方提供的受信 SQL,$N
占位符由 params 绑定,绝不拼接参数值。返回值为每个 EXPLAIN 行中每个
计划对象的格式化 JSON 文本(通常是 1 个元素)。
注意:ANALYZE 会真实执行语句(包括写操作)。
Sourcepub async fn active_queries(&self) -> Result<Vec<ActiveQuery>, DbError>
pub async fn active_queries(&self) -> Result<Vec<ActiveQuery>, DbError>
查询当前会话活动(pg_stat_activity),返回结构化行。
包含当前连接自身;client_addr 以 host() 文本形式返回,避免 inet 解码
依赖。query 为最近一次执行的语句文本。
Sourcepub async fn lock_waits(&self) -> Result<Vec<LockWait>, DbError>
pub async fn lock_waits(&self) -> Result<Vec<LockWait>, DbError>
查询 pg_locks 阻塞链,返回结构化行。
每条记录表示一个未授予的锁请求及其一个阻塞者;同一等待者若有多个阻塞者
会出现多行(pg_blocking_pids 语义)。无阻塞时返回空列表。
Sourcepub async fn acquire_with_cancel_token(
&self,
) -> Result<(PoolConnection<Postgres>, CancelToken), DbError>
pub async fn acquire_with_cancel_token( &self, ) -> Result<(PoolConnection<Postgres>, CancelToken), DbError>
借出一条连接,并返回绑定该连接后端 PID 的 CancelToken。
调用方在返回的连接上执行长查询(可直接用 sqlx 在该连接上执行),另一个
任务/线程用 token 调 CancelToken::cancel 取消它。连接由调用方持有,
归还池时照常触发 after_release 清理。
取消操作需要另借一条连接,因此 max_connections < 2 时直接返回
DbError::InvalidArgument(池上限为 1 时取消会与目标查询互相等待)。
token 中的 backend_pid 只在目标连接仍被持有时有效;连接归还池并被复用
后,同一 PID 可能已指向另一个会话,此时不应再用该 token。
Sourcepub async fn reset_connection(&self) -> Result<(), DbError>
pub async fn reset_connection(&self) -> Result<(), DbError>
清洗连接池中一条连接的会话状态(DISCARD ALL)。
清空会话级 GUC、临时表、游标、prepared statement、LISTEN 与 advisory lock。
注意:DISCARD ALL 不能在事务块内执行。Database::from_pool 的调用方可用
它在借出/归还前后手工清理。
DISCARD ALL 内含 DEALLOCATE ALL,因此服务端清理后还会同步清空 sqlx 的
客户端语句缓存,避免后续复用该连接时命中已失效的缓存条目。
Source§impl Database
impl Database
Sourcepub async fn execute_script(&self, script: &str) -> Result<usize, DbError>
pub async fn execute_script(&self, script: &str) -> Result<usize, DbError>
在当前连接池上执行一个多语句脚本(整脚本单事务)。
脚本按 split_sql_script 切分后在同一事务内依次执行;任一条失败则整个
脚本回滚(DDL 在 PostgreSQL 中可事务化,因此建表失败不会留下半成品)。
注意:CREATE INDEX CONCURRENTLY、VACUUM 等不能在事务块内执行的语句会
被服务端拒绝;这类语句请单独执行。
返回执行的语句条数(空脚本返回 0,且不开事务)。
Trait Implementations§
Source§impl Backend for Database
impl Backend for Database
Source§fn backend_name(&self) -> &'static str
fn backend_name(&self) -> &'static str
mysql / postgres / redis)。Source§fn pool_status(&self) -> PoolStatus
fn pool_status(&self) -> PoolStatus
Auto Trait Implementations§
impl !Freeze for Database
impl !RefUnwindSafe for Database
impl !UnwindSafe for Database
impl Forget for Database
impl Move for Database
impl Send for Database
impl Sync for Database
impl Unpin for Database
impl UnsafeUnpin for Database
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> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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