Skip to main content

Database

Struct Database 

Source
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

Source

pub async fn copy_from_csv<I, R>( &self, sql: &str, rows: I, ) -> Result<u64, DbError>
where I: IntoIterator<Item = R>, R: AsRef<[u8]>,

通过 COPY ... FROM STDIN 批量导入 CSV 行。

sql 必须是形如 COPY <表> [(列...)] FROM STDIN WITH (FORMAT csv, ...) 的语句,其余 格式选项由 SQL 文本决定。rows 的每一项是一条完整 CSV 记录:末尾缺少 \n 时自动补一个;字段内的 CSV 转义(引号、逗号、换行)由调用方负责, 本方法按字节原样发送,不做转义。

返回服务端确认的写入行数。失败时若连接协议状态已无法确认,该连接会被 关闭而不是放回连接池。

Source

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

Source

pub const fn capabilities() -> &'static BackendCapabilities

返回 PostgreSQL 后端的静态能力契约。

Source

pub async fn connect(url: &str) -> Result<Self, DbError>

创建数据库连接

§参数
  • url: 数据库连接字符串,格式:postgres://user:password@host:port/database
§返回
  • Ok(Database): 成功创建的数据库实例
  • Err(DbError): 连接失败错误
Source

pub async fn connect_with_config( url: &str, config: DatabaseConfig, ) -> Result<Self, DbError>

使用自定义配置创建数据库连接

Source

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。

Source

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

选择表,返回查询构建器

Source

pub fn pool(&self) -> &PgPool

获取底层 sqlx 连接池的引用

sqlx 的 PgPool 内部基于 Arc,克隆代价低廉。上层(如 yang-base 的 ActionContext::table_query)需要把连接池注入 TableQuery 时,可用 db.pool().clone() 获得一个共享同一连接池的句柄。

Source

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 即池被打满。

Source

pub async fn health_check(&self) -> Result<bool, DbError>

健康检查:执行 SELECT 1 验证连接可用(与 MySQL 后端对称;NEW-12)。

§返回
  • Ok(true):连接正常
  • Err(DbError):查询失败(连接不可用)
Source

pub async fn close(&self)

优雅关闭连接池(I3):停止发放新连接、等待在途连接归还后关闭。与 MySQL 对称。

幂等;close 后再用返回 PoolClosed 类错误而非 panic。

Source

pub fn is_closed(&self) -> bool

连接池是否已关闭(I3)。

Source

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

👎Deprecated since 0.1.0:

使用 query_with_params 替代,避免 SQL 注入风险

执行原生 SELECT 查询

⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL 字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [query_with_params]。

Source

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

👎Deprecated since 0.1.0:

使用 execute_with_params 替代,避免 SQL 注入风险

执行原生 INSERT/UPDATE/DELETE 查询

⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL 字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [execute_with_params]。

Source

pub async fn transaction(&self) -> Result<Transaction, DbError>

开始事务(使用数据库默认隔离级别 READ COMMITTED)

Source

pub async fn transaction_with_isolation( &self, isolation: IsolationLevel, ) -> Result<Transaction, DbError>

开始事务并设置隔离级别(NG-2)。

等价于 transaction_with_options 只指定 isolation。

Source

pub async fn transaction_with_options( &self, options: TransactionOptions, ) -> Result<Transaction, DbError>

按指定选项开始事务(Phase B)。

BEGIN 之后立即执行一条 SET TRANSACTION ...;选项全默认时不下发该语句。 隔离级别名只来自 crate::isolation::IsolationLevel 的 &'static str, 其余属性为布尔开关,无注入面。

Source

pub async fn read_only_transaction(&self) -> Result<Transaction, DbError>

开始只读事务。事务内写入由服务端拒绝(SQLSTATE 25006)。

Source

pub async fn retry_transaction<T, F, Fut>( &self, operation: F, max_attempts: u32, ) -> Result<T, DbError>
where F: FnMut(Transaction) -> Fut, Fut: Future<Output = Result<T, DbError>>,

带重试地执行一个事务(默认事务选项)。

仅对 PostgreSQL 的序列化失败(SQLSTATE 40001)与死锁(40P01)重试, 其他错误立即返回。重试之间按指数退避(10ms 起,封顶 1s)。

operation 接收一个已开启的事务并对其负责:成功路径需自行 commit(); 返回 Err 时事务被丢弃并自动回滚。

§错误

max_attempts 为 0 时返回 DbError::InvalidArgument。

Source

pub async fn retry_transaction_with_options<T, F, Fut>( &self, options: TransactionOptions, operation: F, max_attempts: u32, ) -> Result<T, DbError>
where F: FnMut(Transaction) -> Fut, Fut: Future<Output = Result<T, DbError>>,

同 retry_transaction,可指定事务选项。

Source

pub async fn init(&self, sql_script: &str) -> Result<(), DbError>

👎Deprecated since 0.1.4:

请使用 execute_script(整脚本单事务,正确处理函数/DO 块与 dollar-quote)

初始化数据库(执行 SQL 脚本)

已弃用:直接委托给 Self::execute_script(整脚本单事务、dollar-quote/ 注释感知的分句器)。新代码请直接用 execute_script。

Source

pub async fn create_table(&self, create_sql: &str) -> Result<(), DbError>

👎Deprecated since 0.2.2:

裸 SQL 建表逃生舱;请使用 execute_script(单事务、可含多条 DDL)或外部迁移工具

创建表(执行一条可信 CREATE TABLE SQL)。

已弃用:本方法只透传裸 SQL,不做拆分、事务或标识符校验。请改用 Self::execute_script(单事务、正确切分多语句)或外部迁移工具。

Source

pub async fn drop_table(&self, table_name: &TableRef) -> Result<(), DbError>

删除表

表名经 quote_identifier 校验+转义(DB-6,双引号方言);非法表名返回 InvalidArgument。

Source

pub async fn table_exists(&self, table_name: &TableRef) -> Result<bool, DbError>

检查表是否存在。

支持单段表名与 schema.table 限定名:标识符先按表名口径逐段校验并加引号, 再交给 to_regclass 解析(限定名直接定位 schema,单段名遵循连接的 search_path)。

Source

pub async fn query_with_params<T>( &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/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?;
Source

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?;
Source

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。

Source

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

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

Source

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

获取会话级排他 advisory lock(pg_advisory_lock),阻塞直到拿到锁。

会话级锁绑定在具体连接上,因此返回的 PgAdvisoryLock 持有该连接: 显式 PgAdvisoryLock::unlock 或丢弃 guard(导致连接关闭、服务端回收锁) 之前,这条连接不会再归还池中。guard 存活期间会占用一个池连接名额。

Source

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

获取会话级共享 advisory lock(pg_advisory_lock_shared),阻塞直到拿到锁。

共享锁彼此不互斥,但与同 key 的排他锁互斥;其余语义与 advisory_lock 相同(RAII 解锁、绑定单条连接)。

Source

pub async fn try_advisory_lock( &self, key: i64, ) -> Result<Option<PgAdvisoryLock>, DbError>

尝试获取会话级排他 advisory lock(pg_try_advisory_lock),不阻塞。

返回 None 表示锁被其他会话占用;连接随即归还池。

Source

pub async fn try_advisory_lock_shared( &self, key: i64, ) -> Result<Option<PgAdvisoryLock>, DbError>

尝试获取会话级共享 advisory lock(pg_try_advisory_lock_shared),不阻塞。

Source

pub async fn server_version_num(&self) -> Result<i32, DbError>

服务端的 server_version_num(如 PG 16.15 → 160015),首次调用后缓存到实例。

版本门控请优先使用 Self::supports。

Source

pub async fn supports(&self, min_version: i32) -> Result<bool, DbError>

判断服务端版本是否不低于 min_version(server_version_num 口径)。

例如 PG 14 及以上传 140000。

Source

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。

Source

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

提交一个已准备的两阶段事务(COMMIT PREPARED)。

必须在事务块之外执行;GID 只能是 [A-Za-z0-9_.:-] 白名单字符。

Source

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

回滚一个已准备的两阶段事务(ROLLBACK PREPARED)。

必须在事务块之外执行;GID 约束同 Self::commit_prepared。

Source

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 会真实执行语句(包括写操作)。

Source

pub async fn active_queries(&self) -> Result<Vec<ActiveQuery>, DbError>

查询当前会话活动(pg_stat_activity),返回结构化行。

包含当前连接自身;client_addr 以 host() 文本形式返回,避免 inet 解码 依赖。query 为最近一次执行的语句文本。

Source

pub async fn lock_waits(&self) -> Result<Vec<LockWait>, DbError>

查询 pg_locks 阻塞链,返回结构化行。

每条记录表示一个未授予的锁请求及其一个阻塞者;同一等待者若有多个阻塞者 会出现多行(pg_blocking_pids 语义)。无阻塞时返回空列表。

Source

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。

Source

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

Source

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

在当前连接池上执行一个多语句脚本(整脚本单事务)。

脚本按 split_sql_script 切分后在同一事务内依次执行;任一条失败则整个 脚本回滚(DDL 在 PostgreSQL 中可事务化,因此建表失败不会留下半成品)。

注意:CREATE INDEX CONCURRENTLY、VACUUM 等不能在事务块内执行的语句会 被服务端拒绝;这类语句请单独执行。

返回执行的语句条数(空脚本返回 0,且不开事务)。

Source§

impl Database

Source

pub async fn notify(&self, channel: &str, payload: &str) -> Result<(), DbError>

向指定通道发送通知(pg_notify)。

参数通过 $1 / $2 绑定,不拼接 SQL。事务内调用时通知在事务提交后 才投递;通道名与载荷长度在本地先做校验,非法输入返回 DbError::InvalidArgument。

Trait Implementations§

Source§

impl Backend for Database

Source§

fn backend_name(&self) -> &'static str

后端名称(mysql / postgres / redis)。
Source§

fn pool_status(&self) -> PoolStatus

连接池状态。
Source§

fn health_check<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<bool, DbError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

健康检查。
Source§

fn close<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

关闭连接池(幂等)。

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