Skip to main content

yang_db/postgres/
database.rs

1use crate::error::DbError;
2use crate::postgres::transaction::{
3    next_cursor_name, normalize_stream_sql, validate_prepared_gid, TransactionOptions,
4    DEFAULT_STREAM_BATCH_SIZE,
5};
6use crate::postgres::{QueryBuilder, Transaction};
7use crate::{BackendCapabilities, PoolStatus, POSTGRES_CAPABILITIES};
8use sqlx::postgres::{PgPool, PgSslMode};
9use std::collections::VecDeque;
10use std::path::PathBuf;
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::sync::Arc;
13use tokio::sync::OnceCell;
14
15/// PostgreSQL `application_name` 的字节上限(`NAMEDATALEN - 1`)。
16const MAX_APPLICATION_NAME_BYTES: usize = 63;
17
18/// `DISCARD ALL`(归还连接前的会话状态清理)。
19const DISCARD_ALL_SQL: &str = "DISCARD ALL";
20
21/// 取消目标后端正在执行的语句(不影响连接,语句以 SQLSTATE 57014 结束)。
22const CANCEL_BACKEND_SQL: &str = "SELECT pg_cancel_backend($1)";
23
24/// 强制终止目标后端连接(以 SQLSTATE 57P01 结束)。
25const TERMINATE_BACKEND_SQL: &str = "SELECT pg_terminate_backend($1)";
26
27/// PostgreSQL 连接 TLS 模式(与 libpq `sslmode` 对齐)。
28///
29/// 只暴露常用的 5 种:`Disable` / `Prefer` / `Require` / `VerifyCa` / `VerifyFull`。
30/// 通过 [`DatabaseConfig::with_ssl_mode`] 设置;未设置时沿用连接串中的 `sslmode`
31/// (连接串也没写时 sqlx 默认 `Prefer`,可能回退到明文)。
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum SslMode {
35    /// 只尝试非 TLS 连接。
36    Disable,
37    /// 优先 TLS,失败时回退到非 TLS。
38    Prefer,
39    /// 只建立 TLS 连接,但**不校验**服务端证书(与 libpq 一致)。需要校验证书请用
40    /// [`SslMode::VerifyCa`] / [`SslMode::VerifyFull`]。
41    Require,
42    /// 只建立 TLS 连接,并校验服务端证书由受信任 CA 签发。
43    VerifyCa,
44    /// 只建立 TLS 连接,并校验 CA 签发与主机名。
45    VerifyFull,
46}
47
48impl SslMode {
49    fn as_pg_ssl_mode(self) -> PgSslMode {
50        match self {
51            Self::Disable => PgSslMode::Disable,
52            Self::Prefer => PgSslMode::Prefer,
53            Self::Require => PgSslMode::Require,
54            Self::VerifyCa => PgSslMode::VerifyCa,
55            Self::VerifyFull => PgSslMode::VerifyFull,
56        }
57    }
58
59    /// 该模式是否校验 CA 证书(需要根证书)。
60    fn requires_root_cert(self) -> bool {
61        matches!(self, Self::VerifyCa | Self::VerifyFull)
62    }
63}
64
65/// 数据库配置
66///
67/// 用于配置数据库连接池的参数
68///
69/// 标注 `#[non_exhaustive]`:未来新增连接池参数不构成破坏性变更,外部请用
70/// `DatabaseConfig::default()` 加 `..Default::default()` 或链式 setter 构造。
71///
72/// # 示例
73///
74/// ```rust
75/// use yang_db::postgres::DatabaseConfig;
76///
77/// // 使用默认配置
78/// let config = DatabaseConfig::default();
79///
80/// // 自定义配置:#[non_exhaustive] 结构体跨 crate 不能用字面量,
81/// // 用 default() + 链式 setter 构造
82/// let config = DatabaseConfig::default()
83///     .with_min_connections(2)
84///     .with_max_lifetime(Some(1800))
85///     .with_test_before_acquire(true);
86/// ```
87#[derive(Debug, Clone)]
88#[non_exhaustive]
89pub struct DatabaseConfig {
90    /// 最大连接数
91    pub max_connections: u32,
92    /// 连接超时时间(秒)
93    pub connect_timeout: u64,
94    /// 空闲连接超时时间(秒)
95    pub idle_timeout: u64,
96    /// 是否启用日志
97    pub enable_logging: bool,
98    /// 最小(保活)连接数。默认 0(行为同改造前)。
99    pub min_connections: u32,
100    /// 连接最大存活时间(秒)。`None`(默认)表示不限制,行为同改造前。
101    pub max_lifetime: Option<u64>,
102    /// 借出前是否 PING 探活。默认 false(行为同改造前)。
103    pub test_before_acquire: bool,
104    /// 连接建立时的 `search_path`(逗号分隔的 schema 列表,如 `"app,public"`)。
105    ///
106    /// 设置为 `Some` 后,连接参数会追加 `-c search_path=<值>`;未设置时使用
107    /// 服务端默认值。值在 [`Self::validate`] 中逐段校验,拒绝任意连接参数注入。
108    pub search_path: Option<String>,
109    /// 单条语句超时(毫秒)。`None`(默认)不设置,沿用服务端默认。
110    ///
111    /// 连接建立后执行 `SET statement_timeout = <ms>`。超时被服务端取消时返回
112    /// SQLSTATE 57014([`crate::SqlErrorKind::QueryCanceled`])。`0` 表示禁用超时。
113    ///
114    /// 注意:该设置通过连接池的 `after_connect` 钩子下发,只对
115    /// [`Database::connect_with_config`] 建立的连接生效;[`Database::from_pool`]
116    /// 的既有连接需调用方自行设置。
117    pub statement_timeout_ms: Option<u64>,
118    /// 锁等待超时(毫秒)。`None`(默认)不设置。超时返回 SQLSTATE 55P03
119    /// ([`crate::SqlErrorKind::LockNotAvailable`])。`0` 表示禁用超时。
120    ///
121    /// 下发方式同 [`Self::statement_timeout_ms`]。
122    pub lock_timeout_ms: Option<u64>,
123    /// 事务空闲超时(毫秒)。`None`(默认)不设置:事务开启后闲置超过该时长会被
124    /// 服务端终止。`0` 表示禁用超时。
125    ///
126    /// 下发方式同 [`Self::statement_timeout_ms`]。
127    pub idle_in_transaction_timeout_ms: Option<u64>,
128    /// 连接建立时写入的 `application_name`(出现在 `pg_stat_activity` 中)。
129    ///
130    /// 通过 `after_connect` 钩子的 `set_config('application_name', $1, false)`
131    /// 应用,值走绑定参数;最长 63 字节(服务端 `NAMEDATALEN - 1`)。
132    pub application_name: Option<String>,
133    /// 预编译语句缓存容量;`None`(默认)沿用 sqlx 默认值(100)。
134    ///
135    /// 经 PgBouncer 等事务级连接池时设为 `Some(0)` 关闭语句缓存,避免服务端
136    /// prepared statement 与连接绑定不一致。
137    pub statement_cache_size: Option<usize>,
138    /// 连接归还池前是否执行 `DISCARD ALL`。默认 `false`。
139    ///
140    /// 开启后由 `after_release` 钩子下发,清理 `search_path`/`LISTEN`/临时表/
141    /// prepared statement/advisory lock 等会话状态;同时在 `before_acquire` 钩子
142    /// 重新应用本配置的会话 GUC(`DISCARD ALL` 中的 `RESET ALL` 会清掉它们)。
143    pub reset_on_release: bool,
144    /// 连接建立后是否校验收到的 `client_encoding` 为 UTF8。默认 `true`(fail-closed)。
145    ///
146    /// 非 UTF8(如 `SQL_ASCII`/`LATIN1`)会返回连接/配置错误,避免把非 UTF-8
147    /// 字节当成 Rust `String`。
148    pub require_utf8_client_encoding: bool,
149    /// TLS 模式;`None`(默认)沿用连接串中的 `sslmode`,若连接串也没写则 sqlx
150    /// 默认 `Prefer`,可能回退到明文连接。
151    ///
152    /// 配置了 [`Self::ssl_root_cert`] 时,`None` 会被推导为 `VerifyCa`(见
153    /// [`Self::effective_ssl_mode`]),避免根证书被静默忽略;此时显式设置
154    /// `Prefer`/`Require`/`Disable` 会与根证书冲突并在 [`Self::validate`] 中报错。
155    pub ssl_mode: Option<SslMode>,
156    /// 根证书(CA)PEM 文件路径;`VerifyCa`/`VerifyFull` 必填。
157    ///
158    /// 只在 `ssl_mode` 为 `None`(自动推导为 `VerifyCa`)、`VerifyCa` 或
159    /// `VerifyFull` 时允许配置。
160    pub ssl_root_cert: Option<PathBuf>,
161    /// 客户端证书 PEM 文件路径;与 [`Self::ssl_client_key`] 成对出现。
162    pub ssl_client_cert: Option<PathBuf>,
163    /// 客户端私钥 PEM 文件路径;与 [`Self::ssl_client_cert`] 成对出现。
164    pub ssl_client_key: Option<PathBuf>,
165}
166
167impl Default for DatabaseConfig {
168    fn default() -> Self {
169        Self {
170            max_connections: 10,
171            connect_timeout: 30,
172            idle_timeout: 600,
173            enable_logging: false,
174            min_connections: 0,
175            max_lifetime: None,
176            test_before_acquire: false,
177            search_path: None,
178            statement_timeout_ms: None,
179            lock_timeout_ms: None,
180            idle_in_transaction_timeout_ms: None,
181            application_name: None,
182            statement_cache_size: None,
183            reset_on_release: false,
184            require_utf8_client_encoding: true,
185            ssl_mode: None,
186            ssl_root_cert: None,
187            ssl_client_cert: None,
188            ssl_client_key: None,
189        }
190    }
191}
192
193impl DatabaseConfig {
194    /// 设置最小(保活)连接数(链式)。
195    pub fn with_min_connections(mut self, n: u32) -> Self {
196        self.min_connections = n;
197        self
198    }
199
200    /// 设置连接最大存活时间(秒,`None` 为不限制)(链式)。
201    pub fn with_max_lifetime(mut self, secs: Option<u64>) -> Self {
202        self.max_lifetime = secs;
203        self
204    }
205
206    /// 设置借出前是否 PING 探活(链式)。
207    pub fn with_test_before_acquire(mut self, enabled: bool) -> Self {
208        self.test_before_acquire = enabled;
209        self
210    }
211
212    /// 设置连接建立时的 `search_path`(链式)。
213    ///
214    /// 值为逗号分隔的 schema 列表,例如 `"app,public"`;每段都会在
215    /// [`Self::validate`] 中按严格标识符校验。
216    pub fn with_search_path(mut self, search_path: impl Into<String>) -> Self {
217        self.search_path = Some(search_path.into());
218        self
219    }
220
221    /// 设置单条语句超时(毫秒,链式)。`None` 或 `0` 表示不限制。
222    pub fn with_statement_timeout_ms(mut self, timeout_ms: impl Into<Option<u64>>) -> Self {
223        self.statement_timeout_ms = timeout_ms.into();
224        self
225    }
226
227    /// 设置锁等待超时(毫秒,链式)。`None` 或 `0` 表示不限制。
228    pub fn with_lock_timeout_ms(mut self, timeout_ms: impl Into<Option<u64>>) -> Self {
229        self.lock_timeout_ms = timeout_ms.into();
230        self
231    }
232
233    /// 设置事务空闲超时(毫秒,链式)。`None` 或 `0` 表示不限制。
234    pub fn with_idle_in_transaction_timeout_ms(
235        mut self,
236        timeout_ms: impl Into<Option<u64>>,
237    ) -> Self {
238        self.idle_in_transaction_timeout_ms = timeout_ms.into();
239        self
240    }
241
242    /// 设置 `application_name`(链式)。`None` 表示不设置。
243    pub fn with_application_name(mut self, application_name: impl Into<String>) -> Self {
244        self.application_name = Some(application_name.into());
245        self
246    }
247
248    /// 设置预编译语句缓存容量(链式);`Some(0)` 关闭缓存(PgBouncer 事务池)。
249    pub fn with_statement_cache_size(mut self, capacity: usize) -> Self {
250        self.statement_cache_size = Some(capacity);
251        self
252    }
253
254    /// 设置连接归还前是否执行 `DISCARD ALL`(链式,默认关闭)。
255    pub fn with_reset_on_release(mut self, enabled: bool) -> Self {
256        self.reset_on_release = enabled;
257        self
258    }
259
260    /// 设置是否强制 `client_encoding` 为 UTF8(链式,默认开启)。
261    pub fn with_require_utf8_client_encoding(mut self, enabled: bool) -> Self {
262        self.require_utf8_client_encoding = enabled;
263        self
264    }
265
266    /// 设置 TLS 模式(链式);`None` 沿用连接串中的 `sslmode`。
267    pub fn with_ssl_mode(mut self, mode: Option<SslMode>) -> Self {
268        self.ssl_mode = mode;
269        self
270    }
271
272    /// 设置根证书 PEM 路径(链式)。
273    pub fn with_ssl_root_cert(mut self, path: impl Into<PathBuf>) -> Self {
274        self.ssl_root_cert = Some(path.into());
275        self
276    }
277
278    /// 实际生效的 TLS 模式。
279    ///
280    /// - `ssl_mode = Some(m)`:原样返回 `Some(m)`;
281    /// - `ssl_mode = None` 且配置了 [`Self::ssl_root_cert`]:返回
282    ///   `Some(SslMode::VerifyCa)`,避免根证书被静默忽略;
283    /// - 其余情况返回 `None`,沿用连接串中的 `sslmode`(连接串也没写时 sqlx 默认
284    ///   `Prefer`,可能回退到明文)。
285    pub fn effective_ssl_mode(&self) -> Option<SslMode> {
286        match self.ssl_mode {
287            Some(mode) => Some(mode),
288            None if self.ssl_root_cert.is_some() => Some(SslMode::VerifyCa),
289            None => None,
290        }
291    }
292
293    /// 设置客户端证书 PEM 路径(链式);需同时设置 [`Self::with_ssl_client_key`]。
294    pub fn with_ssl_client_cert(mut self, path: impl Into<PathBuf>) -> Self {
295        self.ssl_client_cert = Some(path.into());
296        self
297    }
298
299    /// 设置客户端私钥 PEM 路径(链式);需同时设置 [`Self::with_ssl_client_cert`]。
300    pub fn with_ssl_client_key(mut self, path: impl Into<PathBuf>) -> Self {
301        self.ssl_client_key = Some(path.into());
302        self
303    }
304
305    /// 校验数据库连接池配置是否适合生产运行。
306    ///
307    /// Builder 方法保持纯赋值以兼容历史调用;真正建池前由连接入口显式校验,避免将明显
308    /// 非法的配置下推给 sqlx 后才在运行时失败。
309    pub fn validate(&self) -> std::result::Result<(), DbError> {
310        if self.max_connections == 0 {
311            return Err(DbError::InvalidArgument(
312                "PostgreSQL max_connections 必须大于 0".to_string(),
313            ));
314        }
315        if self.min_connections > self.max_connections {
316            return Err(DbError::InvalidArgument(format!(
317                "PostgreSQL min_connections({}) 不能大于 max_connections({})",
318                self.min_connections, self.max_connections
319            )));
320        }
321        if self.connect_timeout == 0 {
322            return Err(DbError::InvalidArgument(
323                "PostgreSQL connect_timeout 必须大于 0 秒".to_string(),
324            ));
325        }
326        if self.idle_timeout == 0 {
327            return Err(DbError::InvalidArgument(
328                "PostgreSQL idle_timeout 必须大于 0 秒".to_string(),
329            ));
330        }
331        if self.idle_timeout <= self.connect_timeout {
332            return Err(DbError::InvalidArgument(format!(
333                "PostgreSQL idle_timeout({}) 必须大于 connect_timeout({})",
334                self.idle_timeout, self.connect_timeout
335            )));
336        }
337        if matches!(self.max_lifetime, Some(0)) {
338            return Err(DbError::InvalidArgument(
339                "PostgreSQL max_lifetime 为 Some 时必须大于 0 秒".to_string(),
340            ));
341        }
342        if let Some(search_path) = &self.search_path {
343            if search_path.trim().is_empty() {
344                return Err(DbError::InvalidArgument(
345                    "PostgreSQL search_path 不能为空".to_string(),
346                ));
347            }
348            for segment in search_path.split(',') {
349                let segment = segment.trim();
350                if segment.is_empty() || crate::sql_types::Identifier::parse(segment).is_err() {
351                    return Err(DbError::InvalidArgument(format!(
352                        "PostgreSQL search_path 片段非法: {segment:?}"
353                    )));
354                }
355            }
356        }
357        if let Some(application_name) = &self.application_name {
358            if application_name.is_empty() {
359                return Err(DbError::InvalidArgument(
360                    "PostgreSQL application_name 不能为空字符串".to_string(),
361                ));
362            }
363            if application_name.contains('\0') {
364                return Err(DbError::InvalidArgument(
365                    "PostgreSQL application_name 不能包含 NUL 字符".to_string(),
366                ));
367            }
368            if application_name.len() > MAX_APPLICATION_NAME_BYTES {
369                return Err(DbError::InvalidArgument(format!(
370                    "PostgreSQL application_name 不能超过 {MAX_APPLICATION_NAME_BYTES} 字节,当前 {} 字节",
371                    application_name.len()
372                )));
373            }
374        }
375        if let Some(mode) = self.ssl_mode {
376            if mode.requires_root_cert() && self.ssl_root_cert.is_none() {
377                return Err(DbError::InvalidArgument(format!(
378                    "PostgreSQL ssl_mode = {mode:?} 必须提供 ssl_root_cert(CA 证书)"
379                )));
380            }
381            if self.ssl_root_cert.is_some()
382                && matches!(mode, SslMode::Prefer | SslMode::Require | SslMode::Disable)
383            {
384                return Err(DbError::InvalidArgument(format!(
385                    "PostgreSQL ssl_mode = {mode:?} 不能与 ssl_root_cert 同时配置;根证书只适用于 \
386                     VerifyCa/VerifyFull(ssl_mode 为 None 时会自动按 VerifyCa 使用根证书)"
387                )));
388            }
389            if mode == SslMode::Disable
390                && (self.ssl_root_cert.is_some()
391                    || self.ssl_client_cert.is_some()
392                    || self.ssl_client_key.is_some())
393            {
394                return Err(DbError::InvalidArgument(
395                    "PostgreSQL ssl_mode = Disable 时不能配置 TLS 证书".to_string(),
396                ));
397            }
398        }
399        if self.ssl_client_cert.is_some() != self.ssl_client_key.is_some() {
400            return Err(DbError::InvalidArgument(
401                "PostgreSQL ssl_client_cert 与 ssl_client_key 必须成对提供".to_string(),
402            ));
403        }
404        Ok(())
405    }
406}
407
408/// 数据库连接管理器
409///
410/// 管理 PostgreSQL 数据库连接池,提供查询构建和执行的入口点
411///
412/// # 示例
413///
414/// ```rust,no_run
415/// use yang_db::postgres::Database;
416///
417/// #[tokio::main]
418/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
419///     // 连接数据库
420///     let db = Database::connect("postgres://user:password@localhost:5432/test").await?;
421///
422///     // 使用查询构建器
423///     let builder = db.table(yang_db::table!("users"))
424///         .field(yang_db::field!("id"))
425///         .field(yang_db::field!("name"));
426///
427///     // 执行查询(需要实现 select 方法)
428///     // let users = builder.select::<User>().await?;
429///
430///     Ok(())
431/// }
432/// ```
433pub struct Database {
434    pool: PgPool,
435    config: DatabaseConfig,
436    /// 服务端 `server_version_num` 的进程内缓存(首次探测后固定)。
437    server_version: OnceCell<i32>,
438    /// 正在等待连接的 acquire 计数(池已无空闲连接且达到上限时计入)。
439    waiting: Arc<AtomicUsize>,
440}
441
442impl Database {
443    /// 返回 PostgreSQL 后端的静态能力契约。
444    pub const fn capabilities() -> &'static BackendCapabilities {
445        &POSTGRES_CAPABILITIES
446    }
447
448    /// 创建数据库连接
449    ///
450    /// # 参数
451    /// - url: 数据库连接字符串,格式:postgres://user:password@host:port/database
452    ///
453    /// # 返回
454    /// - Ok(Database): 成功创建的数据库实例
455    /// - Err(DbError): 连接失败错误
456    pub async fn connect(url: &str) -> Result<Self, DbError> {
457        Self::connect_with_config(url, DatabaseConfig::default()).await
458    }
459
460    /// 使用自定义配置创建数据库连接
461    pub async fn connect_with_config(url: &str, config: DatabaseConfig) -> Result<Self, DbError> {
462        use sqlx::postgres::PgPoolOptions;
463        use std::str::FromStr;
464        use std::time::Duration;
465
466        config.validate()?;
467
468        // 使用配置参数创建连接池
469        let mut options = PgPoolOptions::new()
470            .max_connections(config.max_connections)
471            .min_connections(config.min_connections)
472            .acquire_timeout(Duration::from_secs(config.connect_timeout))
473            .idle_timeout(Duration::from_secs(config.idle_timeout))
474            .test_before_acquire(config.test_before_acquire);
475        if let Some(secs) = config.max_lifetime {
476            options = options.max_lifetime(Duration::from_secs(secs));
477        }
478
479        // 连接串解析为 PgConnectOptions 后再追加 search_path;值已在 validate()
480        // 中逐段校验,不会把任意启动参数注入连接。
481        let mut connect_options =
482            sqlx::postgres::PgConnectOptions::from_str(url).map_err(|error| {
483                DbError::ConnectionError(format!("无效的 PostgreSQL 连接串: {error}"))
484            })?;
485        if let Some(search_path) = &config.search_path {
486            // sqlx 的 options 以空格切分 `-c k=v` 参数,值内空格会被当成下一段参数。
487            // 这里统一去掉逗号两侧空白,再写入启动参数。
488            let normalized = search_path
489                .split(',')
490                .map(str::trim)
491                .collect::<Vec<_>>()
492                .join(",");
493            connect_options = connect_options.options([("search_path", normalized)]);
494        }
495        // TLS 配置:模式与证书都已在上面的 validate() 中校验(verify-ca/full 必须
496        // 提供根证书,客户端证书与私钥必须成对)。effective_ssl_mode 会把
497        // “有根证书但未指定模式”推导为 VerifyCa,避免根证书被静默忽略。
498        if let Some(mode) = config.effective_ssl_mode() {
499            connect_options = connect_options.ssl_mode(mode.as_pg_ssl_mode());
500        }
501        if let Some(path) = &config.ssl_root_cert {
502            connect_options = connect_options.ssl_root_cert(path);
503        }
504        if let Some(path) = &config.ssl_client_cert {
505            connect_options = connect_options.ssl_client_cert(path);
506        }
507        if let Some(path) = &config.ssl_client_key {
508            connect_options = connect_options.ssl_client_key(path);
509        }
510        if let Some(capacity) = config.statement_cache_size {
511            connect_options = connect_options.statement_cache_capacity(capacity);
512        }
513
514        // 语句/锁/事务空闲超时通过每条新连接的 after_connect 钩子下发。三个值均为
515        // 受控 u64,直接拼进 SET 语句无注入面。
516        let statement_timeout_ms = config.statement_timeout_ms;
517        let lock_timeout_ms = config.lock_timeout_ms;
518        let idle_in_transaction_timeout_ms = config.idle_in_transaction_timeout_ms;
519        let timeout_statements = timeout_statements(
520            statement_timeout_ms,
521            lock_timeout_ms,
522            idle_in_transaction_timeout_ms,
523        );
524        // 会话 GUC 基线:统一时区/日期/浮点输出格式,避免同一查询随服务器
525        // locale 或时区漂移。网络传输格式本身不受影响(BYTEA/JSONB 等)。
526        let mut session_statements = vec![
527            "SET TimeZone = 'UTC'".to_string(),
528            "SET DateStyle = 'ISO, YMD'".to_string(),
529            "SET IntervalStyle = 'postgres'".to_string(),
530            "SET extra_float_digits = 3".to_string(),
531            "SET standard_conforming_strings = on".to_string(),
532        ];
533        session_statements.extend(timeout_statements);
534        let session_setup = SessionSetup {
535            application_name: config.application_name.clone(),
536            statements: session_statements,
537            require_utf8_client_encoding: config.require_utf8_client_encoding,
538        };
539        let after_connect_setup = session_setup.clone();
540        options = options.after_connect(move |conn, _meta| {
541            let setup = after_connect_setup.clone();
542            Box::pin(async move { setup.apply(conn).await })
543        });
544        if config.reset_on_release {
545            // 归还前 DISCARD ALL 清空会话状态;它内含 RESET ALL,会清掉 after_connect
546            // 设置的 GUC,所以借出复用连接时(before_acquire)重新应用一遍。
547            options = options.after_release(|conn, _meta| {
548                Box::pin(async move {
549                    sqlx::query(DISCARD_ALL_SQL).execute(&mut *conn).await?;
550                    // DISCARD ALL 内含 DEALLOCATE ALL,服务端已清空 prepared statement;
551                    // 必须同步清理 sqlx 的客户端语句缓存,否则 before_acquire 重放相同
552                    // SET 语句时会命中已失效的缓存(SQLSTATE 26000),连接被
553                    // hard-close 后重建,池退化为每次借出都新建连接。
554                    // 对服务端已不存在的语句发 Close 按 PG 协议是 no-op,只回 CloseComplete。
555                    sqlx::Connection::clear_cached_statements(&mut *conn).await?;
556                    Ok(true)
557                })
558            });
559            let before_acquire_setup = session_setup;
560            options = options.before_acquire(move |conn, _meta| {
561                let setup = before_acquire_setup.clone();
562                Box::pin(async move { setup.apply(conn).await.map(|_| true) })
563            });
564        }
565
566        let pool = options.connect_with(connect_options).await?;
567
568        Ok(Self {
569            pool,
570            config,
571            server_version: OnceCell::new(),
572            waiting: Arc::new(AtomicUsize::new(0)),
573        })
574    }
575
576    /// 从调用方已创建的连接池构造数据库入口。
577    ///
578    /// 该构造器不建立连接,也不写入进程全局状态,供显式资源所有权与离线测试使用。
579    ///
580    /// 注意:`after_connect`/`after_release` 等会话钩子只在
581    /// [`Self::connect_with_config`] 建立的连接池上生效;`from_pool` 的既有连接
582    /// 需要调用方自行设置,可用 [`Self::reset_connection`] 手工清理单条连接。
583    ///
584    /// # 错误
585    ///
586    /// 当 `config` 的连接数或超时参数非法时返回 [`DbError::InvalidArgument`]。
587    pub fn from_pool(pool: PgPool, config: DatabaseConfig) -> Result<Self, DbError> {
588        config.validate()?;
589        Ok(Self {
590            pool,
591            config,
592            server_version: OnceCell::new(),
593            waiting: Arc::new(AtomicUsize::new(0)),
594        })
595    }
596
597    /// 选择表,返回查询构建器
598    pub fn table(&self, table: &crate::TableRef) -> QueryBuilder<'_> {
599        QueryBuilder::new(&self.pool, table.as_str(), self.config.enable_logging)
600    }
601
602    /// 获取底层 sqlx 连接池的引用
603    ///
604    /// sqlx 的 `PgPool` 内部基于 `Arc`,克隆代价低廉。上层(如 yang-base 的
605    /// `ActionContext::table_query`)需要把连接池注入 `TableQuery` 时,可用
606    /// `db.pool().clone()` 获得一个共享同一连接池的句柄。
607    pub fn pool(&self) -> &PgPool {
608        &self.pool
609    }
610
611    /// 返回连接池状态快照(与 MySQL / Redis 后端对称;NEW-12)。
612    ///
613    /// - `max_size`:配置的最大连接数(`config.max_connections`)
614    /// - `size`:当前池内连接总数(`pool.size()`)
615    /// - `available`:当前空闲可借出连接数(`pool.num_idle()`)
616    /// - `waiting`:调用 [`Database`] 自身入口(query/execute/transaction/acquire/
617    ///   流式游标/advisory lock/COPY 等)时,处于「池已无空闲连接且已达上限」的
618    ///   在途 acquire 数。sqlx 不直接暴露等待者数,因此这是本库维护的近似值:
619    ///   直接经 [`Self::pool`] 借出的调用(含 `QueryBuilder` 执行路径)不计入。
620    ///
621    /// 连接耗尽排查:`available == 0 && size == max_size` 即池被打满。
622    pub fn pool_status(&self) -> PoolStatus {
623        PoolStatus {
624            max_size: self.config.max_connections as usize,
625            size: self.pool.size() as usize,
626            available: self.pool.num_idle(),
627            waiting: self.waiting.load(Ordering::Relaxed),
628        }
629    }
630
631    /// 记录一次连接获取:调用时池已无空闲连接且达到上限,则计为潜在等待者。
632    ///
633    /// 返回的 guard 在 acquire 完成(成功或失败)后立即 drop,避免把执行时间
634    /// 误算成等待时间。
635    fn track_acquire(&self) -> AcquireWaiter<'_> {
636        let would_wait = self.pool.num_idle() == 0
637            && self.pool.size() >= self.pool.options().get_max_connections();
638        if would_wait {
639            self.waiting.fetch_add(1, Ordering::Relaxed);
640        }
641        AcquireWaiter {
642            counter: &self.waiting,
643            armed: would_wait,
644        }
645    }
646
647    /// 从连接池借出一条连接,并计入 [`Self::pool_status`] 的 `waiting` 统计。
648    pub(crate) async fn acquire(
649        &self,
650    ) -> Result<sqlx::pool::PoolConnection<sqlx::Postgres>, DbError> {
651        let waiter = self.track_acquire();
652        let conn = self.pool.acquire().await?;
653        drop(waiter);
654        Ok(conn)
655    }
656
657    /// 健康检查:执行 `SELECT 1` 验证连接可用(与 MySQL 后端对称;NEW-12)。
658    ///
659    /// # 返回
660    /// - `Ok(true)`:连接正常
661    /// - `Err(DbError)`:查询失败(连接不可用)
662    pub async fn health_check(&self) -> Result<bool, DbError> {
663        let mut conn = self.acquire().await?;
664        sqlx::query("SELECT 1").execute(&mut *conn).await?;
665        Ok(true)
666    }
667
668    /// 优雅关闭连接池(I3):停止发放新连接、等待在途连接归还后关闭。与 MySQL 对称。
669    ///
670    /// 幂等;close 后再用返回 `PoolClosed` 类错误而非 panic。
671    pub async fn close(&self) {
672        self.pool.close().await;
673    }
674
675    /// 连接池是否已关闭(I3)。
676    pub fn is_closed(&self) -> bool {
677        self.pool.is_closed()
678    }
679
680    /// 执行原生 SELECT 查询
681    ///
682    /// ⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL
683    /// 字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [`query_with_params`]。
684    #[deprecated(
685        since = "0.1.0",
686        note = "使用 query_with_params 替代,避免 SQL 注入风险"
687    )]
688    pub async fn query<T>(&self, sql: &str) -> Result<Vec<T>, DbError>
689    where
690        T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
691    {
692        if self.config.enable_logging {
693            log::debug!("执行原生查询: {}", sql);
694        }
695
696        let rows = sqlx::query_as::<_, T>(sql).fetch_all(&self.pool).await?;
697
698        Ok(rows)
699    }
700
701    /// 执行原生 INSERT/UPDATE/DELETE 查询
702    ///
703    /// ⚠️ 安全警告:此方法接受裸 SQL 字符串,不进行参数化处理。调用方必须确保 SQL
704    /// 字符串不包含用户输入,否则存在 SQL 注入风险。请优先使用 [`execute_with_params`]。
705    #[deprecated(
706        since = "0.1.0",
707        note = "使用 execute_with_params 替代,避免 SQL 注入风险"
708    )]
709    pub async fn execute(&self, sql: &str) -> Result<u64, DbError> {
710        if self.config.enable_logging {
711            log::debug!("执行原生语句: {}", sql);
712        }
713
714        let result = sqlx::query(sql).execute(&self.pool).await?;
715
716        Ok(result.rows_affected())
717    }
718
719    /// 开始事务(使用数据库默认隔离级别 READ COMMITTED)
720    pub async fn transaction(&self) -> Result<Transaction, DbError> {
721        let waiter = self.track_acquire();
722        let tx = self.pool.begin().await?;
723        drop(waiter);
724        Ok(Transaction::new(tx, self.config.enable_logging))
725    }
726
727    /// 开始事务并设置隔离级别(NG-2)。
728    ///
729    /// 等价于 [`transaction_with_options`](Self::transaction_with_options) 只指定
730    /// `isolation`。
731    pub async fn transaction_with_isolation(
732        &self,
733        isolation: crate::isolation::IsolationLevel,
734    ) -> Result<Transaction, DbError> {
735        self.transaction_with_options(TransactionOptions::default().with_isolation(isolation))
736            .await
737    }
738
739    /// 按指定选项开始事务(Phase B)。
740    ///
741    /// `BEGIN` 之后立即执行一条 `SET TRANSACTION ...`;选项全默认时不下发该语句。
742    /// 隔离级别名只来自 [`crate::isolation::IsolationLevel`] 的 `&'static str`,
743    /// 其余属性为布尔开关,无注入面。
744    pub async fn transaction_with_options(
745        &self,
746        options: TransactionOptions,
747    ) -> Result<Transaction, DbError> {
748        let waiter = self.track_acquire();
749        let mut tx = self.pool.begin().await?;
750        drop(waiter);
751        if let Some(sql) = options.set_transaction_sql() {
752            if self.config.enable_logging {
753                log::debug!("设置 PostgreSQL 事务属性: {}", sql);
754            }
755            sqlx::query(&sql).execute(&mut *tx).await?;
756        }
757        Ok(Transaction::new(tx, self.config.enable_logging))
758    }
759
760    /// 开始只读事务。事务内写入由服务端拒绝(SQLSTATE 25006)。
761    pub async fn read_only_transaction(&self) -> Result<Transaction, DbError> {
762        self.transaction_with_options(TransactionOptions::read_only())
763            .await
764    }
765
766    /// 带重试地执行一个事务(默认事务选项)。
767    ///
768    /// 仅对 PostgreSQL 的序列化失败(SQLSTATE 40001)与死锁(40P01)重试,
769    /// 其他错误立即返回。重试之间按指数退避(10ms 起,封顶 1s)。
770    ///
771    /// `operation` 接收一个已开启的事务并对其负责:成功路径需自行 `commit()`;
772    /// 返回 `Err` 时事务被丢弃并自动回滚。
773    ///
774    /// # 错误
775    ///
776    /// `max_attempts` 为 0 时返回 [`DbError::InvalidArgument`]。
777    pub async fn retry_transaction<T, F, Fut>(
778        &self,
779        operation: F,
780        max_attempts: u32,
781    ) -> Result<T, DbError>
782    where
783        F: FnMut(Transaction) -> Fut,
784        Fut: std::future::Future<Output = Result<T, DbError>>,
785    {
786        self.retry_transaction_with_options(TransactionOptions::default(), operation, max_attempts)
787            .await
788    }
789
790    /// 同 [`retry_transaction`](Self::retry_transaction),可指定事务选项。
791    pub async fn retry_transaction_with_options<T, F, Fut>(
792        &self,
793        options: TransactionOptions,
794        mut operation: F,
795        max_attempts: u32,
796    ) -> Result<T, DbError>
797    where
798        F: FnMut(Transaction) -> Fut,
799        Fut: std::future::Future<Output = Result<T, DbError>>,
800    {
801        if max_attempts == 0 {
802            return Err(DbError::InvalidArgument(
803                "重试次数 max_attempts 必须大于 0".to_string(),
804            ));
805        }
806
807        let mut attempt = 0u32;
808        loop {
809            attempt += 1;
810            let transaction = self.transaction_with_options(options).await?;
811            match operation(transaction).await {
812                Ok(value) => return Ok(value),
813                Err(error) => {
814                    if !is_serialization_conflict(&error) || attempt >= max_attempts {
815                        return Err(error);
816                    }
817                    let backoff = retry_backoff(attempt);
818                    if self.config.enable_logging {
819                        log::warn!(
820                            "事务序列化冲突(第 {attempt} 次尝试),{:?} 后重试: {error}",
821                            backoff
822                        );
823                    }
824                    tokio::time::sleep(backoff).await;
825                }
826            }
827        }
828    }
829
830    /// 初始化数据库(执行 SQL 脚本)
831    ///
832    /// 已弃用:直接委托给 [`Self::execute_script`](整脚本单事务、dollar-quote/
833    /// 注释感知的分句器)。新代码请直接用 `execute_script`。
834    #[deprecated(
835        since = "0.1.4",
836        note = "请使用 execute_script(整脚本单事务,正确处理函数/DO 块与 dollar-quote)"
837    )]
838    pub async fn init(&self, sql_script: &str) -> Result<(), DbError> {
839        self.execute_script(sql_script).await.map(|_| ())
840    }
841
842    /// 创建表(执行一条可信 `CREATE TABLE` SQL)。
843    ///
844    /// 已弃用:本方法只透传裸 SQL,不做拆分、事务或标识符校验。请改用
845    /// [`Self::execute_script`](单事务、正确切分多语句)或外部迁移工具。
846    #[deprecated(
847        since = "0.2.2",
848        note = "裸 SQL 建表逃生舱;请使用 execute_script(单事务、可含多条 DDL)或外部迁移工具"
849    )]
850    pub async fn create_table(&self, create_sql: &str) -> Result<(), DbError> {
851        let mut conn = self.acquire().await?;
852        sqlx::query(create_sql).execute(&mut *conn).await?;
853        Ok(())
854    }
855
856    /// 删除表
857    ///
858    /// 表名经 `quote_identifier` 校验+转义(DB-6,双引号方言);非法表名返回
859    /// `InvalidArgument`。
860    pub async fn drop_table(&self, table_name: &crate::TableRef) -> Result<(), DbError> {
861        let quoted = crate::postgres::identifier::quote_table(table_name.as_str())?;
862        let sql = format!("DROP TABLE IF EXISTS {}", quoted);
863        let mut conn = self.acquire().await?;
864        sqlx::query(&sql).execute(&mut *conn).await?;
865        Ok(())
866    }
867
868    /// 检查表是否存在。
869    ///
870    /// 支持单段表名与 `schema.table` 限定名:标识符先按表名口径逐段校验并加引号,
871    /// 再交给 `to_regclass` 解析(限定名直接定位 schema,单段名遵循连接的
872    /// `search_path`)。
873    pub async fn table_exists(&self, table_name: &crate::TableRef) -> Result<bool, DbError> {
874        // to_regclass 接收 SQL 标识符文本;传入已加引号的受控标识符,
875        // 既避免大小写折叠,也不拼接进 SQL 文本(仍走 $1 绑定)。
876        let quoted = crate::postgres::identifier::quote_table(table_name.as_str())?;
877        let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL")
878            .bind(quoted)
879            .fetch_one(&self.pool)
880            .await?;
881
882        Ok(exists)
883    }
884
885    /// 执行带参数的原生 SELECT 查询(参数化查询,防止 SQL 注入)
886    ///
887    /// # 参数
888    /// - sql: SQL 查询语句,使用 `$N` 作为参数占位符
889    /// - params: 参数列表,使用 `serde_json::Value` 类型
890    ///
891    /// # 返回
892    /// - Ok(Vec<T>): 查询结果列表
893    /// - Err(DbError): 查询失败错误
894    ///
895    /// # 示例
896    ///
897    /// ```rust,no_run
898    /// use yang_db::postgres::Database;
899    /// use serde_json::json;
900    ///
901    /// # async fn example() -> Result<(), yang_db::DbError> {
902    /// let db = Database::connect("postgres://postgres:postgres@localhost/test").await?;
903    /// let params = vec![json!("admin"), json!(1)];
904    /// // let users: Vec<User> = db.query_with_params("SELECT * FROM users WHERE role = $1 AND status = $2", params).await?;
905    /// # Ok(())
906    /// # }
907    /// ```
908    pub async fn query_with_params<T>(
909        &self,
910        sql: &str,
911        params: Vec<serde_json::Value>,
912    ) -> Result<Vec<T>, DbError>
913    where
914        T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
915    {
916        if self.config.enable_logging {
917            log::debug!("执行参数化查询: {}, 参数数量: {}", sql, params.len());
918        }
919
920        // 构建查询并逐一绑定参数
921        let mut conn = self.acquire().await?;
922        let mut query = sqlx::query_as::<_, T>(sql);
923        for param in &params {
924            query = bind_json_param_as(query, param);
925        }
926
927        let rows = query.fetch_all(&mut *conn).await?;
928        Ok(rows)
929    }
930
931    /// 执行带参数的原生 INSERT/UPDATE/DELETE 语句(参数化查询,防止 SQL 注入)
932    ///
933    /// # 参数
934    /// - sql: SQL 语句,使用 `$N` 作为参数占位符
935    /// - params: 参数列表,使用 `serde_json::Value` 类型
936    ///
937    /// # 返回
938    /// - Ok(u64): 受影响的行数
939    /// - Err(DbError): 执行失败错误
940    ///
941    /// # 示例
942    ///
943    /// ```rust,no_run
944    /// use yang_db::postgres::Database;
945    /// use serde_json::json;
946    ///
947    /// # async fn example() -> Result<(), yang_db::DbError> {
948    /// let db = Database::connect("postgres://postgres:postgres@localhost/test").await?;
949    /// let params = vec![json!("张三"), json!("zhangsan@example.com")];
950    /// let rows = db.execute_with_params("INSERT INTO users (name, email) VALUES ($1, $2)", params).await?;
951    /// # Ok(())
952    /// # }
953    /// ```
954    pub async fn execute_with_params(
955        &self,
956        sql: &str,
957        params: Vec<serde_json::Value>,
958    ) -> Result<u64, DbError> {
959        if self.config.enable_logging {
960            log::debug!("执行参数化语句: {}, 参数数量: {}", sql, params.len());
961        }
962
963        // 构建查询并逐一绑定参数
964        let mut conn = self.acquire().await?;
965        let mut query = sqlx::query(sql);
966        for param in &params {
967            query = bind_json_param(query, param);
968        }
969
970        let result = query.execute(&mut *conn).await?;
971        Ok(result.rows_affected())
972    }
973
974    /// 以服务端游标流式读取查询结果(默认每批 1000 行)。
975    ///
976    /// 游标在一条只读事务内声明(`BEGIN READ ONLY` + `DECLARE ... CURSOR`),
977    /// 逐行消费时按批 `FETCH`,大结果集不会一次性进入内存。游标读尽或
978    /// [`PgRowCursor::close`] 后,内部事务 `ROLLBACK` 并把连接归还连接池。
979    ///
980    /// 未读尽即丢弃游标时无法在同步 `Drop` 中执行 `ROLLBACK`,实现会
981    /// `detach` 该连接(关闭而非归还),避免把带打开事务的连接放回池中。
982    ///
983    /// # 查询取消
984    ///
985    /// sqlx 0.8 没有从连接池直接 cancel 某个查询的 API。需要取消时,可行替代是:
986    /// 用 `db.pool().acquire()` 取一条独立连接并 `SELECT pg_backend_pid()` 记下后端
987    /// PID(即 cancel token),在另一条连接上执行
988    /// `SELECT pg_cancel_backend($1)`(或 `pg_terminate_backend($1)`)。
989    ///
990    /// # 错误
991    ///
992    /// SQL 为空或 `batch_size` 为 0 时返回 [`DbError::InvalidArgument`]。
993    pub async fn stream_query(
994        &self,
995        sql: &str,
996        params: Vec<serde_json::Value>,
997    ) -> Result<PgRowCursor, DbError> {
998        self.stream_query_with_batch_size(sql, params, DEFAULT_STREAM_BATCH_SIZE)
999            .await
1000    }
1001
1002    /// 同 [`stream_query`](Self::stream_query),可指定每批拉取行数。
1003    pub async fn stream_query_with_batch_size(
1004        &self,
1005        sql: &str,
1006        params: Vec<serde_json::Value>,
1007        batch_size: usize,
1008    ) -> Result<PgRowCursor, DbError> {
1009        if batch_size == 0 {
1010            return Err(DbError::InvalidArgument(
1011                "流式查询 batch_size 必须大于 0".to_string(),
1012            ));
1013        }
1014        let body = normalize_stream_sql(sql)?;
1015        let mut conn = self.acquire().await?;
1016        // 服务端游标必须存在于事务块内;统一用只读事务,明确流式入口只面向查询。
1017        sqlx::query("BEGIN READ ONLY").execute(&mut *conn).await?;
1018
1019        let cursor_name = next_cursor_name();
1020        let declare = format!("DECLARE {} CURSOR FOR {}", cursor_name, body);
1021        if self.config.enable_logging {
1022            log::debug!("声明流式游标: {}", declare);
1023        }
1024        let mut query = sqlx::query(&declare);
1025        for param in &params {
1026            query = bind_json_param(query, param);
1027        }
1028        if let Err(error) = query.execute(&mut *conn).await {
1029            // 声明失败时回滚,连接保持干净可归还池。
1030            let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
1031            return Err(error.into());
1032        }
1033
1034        Ok(PgRowCursor::new(
1035            conn,
1036            cursor_name,
1037            batch_size,
1038            self.config.enable_logging,
1039        ))
1040    }
1041
1042    /// 获取会话级排他 advisory lock(`pg_advisory_lock`),阻塞直到拿到锁。
1043    ///
1044    /// 会话级锁绑定在具体连接上,因此返回的 [`PgAdvisoryLock`] 持有该连接:
1045    /// 显式 [`PgAdvisoryLock::unlock`] 或丢弃 guard(导致连接关闭、服务端回收锁)
1046    /// 之前,这条连接不会再归还池中。guard 存活期间会占用一个池连接名额。
1047    pub async fn advisory_lock(&self, key: i64) -> Result<PgAdvisoryLock, DbError> {
1048        self.acquire_advisory_lock(key, AdvisoryLockMode::Exclusive)
1049            .await
1050    }
1051
1052    /// 获取会话级共享 advisory lock(`pg_advisory_lock_shared`),阻塞直到拿到锁。
1053    ///
1054    /// 共享锁彼此不互斥,但与同 key 的排他锁互斥;其余语义与
1055    /// [`advisory_lock`](Self::advisory_lock) 相同(RAII 解锁、绑定单条连接)。
1056    pub async fn advisory_lock_shared(&self, key: i64) -> Result<PgAdvisoryLock, DbError> {
1057        self.acquire_advisory_lock(key, AdvisoryLockMode::Shared)
1058            .await
1059    }
1060
1061    /// 尝试获取会话级排他 advisory lock(`pg_try_advisory_lock`),不阻塞。
1062    ///
1063    /// 返回 `None` 表示锁被其他会话占用;连接随即归还池。
1064    pub async fn try_advisory_lock(&self, key: i64) -> Result<Option<PgAdvisoryLock>, DbError> {
1065        self.try_acquire_advisory_lock(key, AdvisoryLockMode::Exclusive)
1066            .await
1067    }
1068
1069    /// 尝试获取会话级共享 advisory lock(`pg_try_advisory_lock_shared`),不阻塞。
1070    pub async fn try_advisory_lock_shared(
1071        &self,
1072        key: i64,
1073    ) -> Result<Option<PgAdvisoryLock>, DbError> {
1074        self.try_acquire_advisory_lock(key, AdvisoryLockMode::Shared)
1075            .await
1076    }
1077
1078    async fn acquire_advisory_lock(
1079        &self,
1080        key: i64,
1081        mode: AdvisoryLockMode,
1082    ) -> Result<PgAdvisoryLock, DbError> {
1083        let mut conn = self.acquire().await?;
1084        if self.config.enable_logging {
1085            log::debug!("获取 PG 会话级 advisory lock: key={key}, mode={mode:?}");
1086        }
1087        sqlx::query(mode.lock_sql())
1088            .bind(key)
1089            .execute(&mut *conn)
1090            .await?;
1091        Ok(PgAdvisoryLock {
1092            conn: Some(conn),
1093            key,
1094            mode,
1095        })
1096    }
1097
1098    async fn try_acquire_advisory_lock(
1099        &self,
1100        key: i64,
1101        mode: AdvisoryLockMode,
1102    ) -> Result<Option<PgAdvisoryLock>, DbError> {
1103        let mut conn = self.acquire().await?;
1104        let acquired: bool = sqlx::query_scalar(mode.try_lock_sql())
1105            .bind(key)
1106            .fetch_one(&mut *conn)
1107            .await?;
1108        if acquired {
1109            Ok(Some(PgAdvisoryLock {
1110                conn: Some(conn),
1111                key,
1112                mode,
1113            }))
1114        } else {
1115            Ok(None)
1116        }
1117    }
1118
1119    /// 服务端的 `server_version_num`(如 PG 16.15 → `160015`),首次调用后缓存到实例。
1120    ///
1121    /// 版本门控请优先使用 [`Self::supports`]。
1122    pub async fn server_version_num(&self) -> Result<i32, DbError> {
1123        let version = self
1124            .server_version
1125            .get_or_try_init(|| async {
1126                let mut conn = self.acquire().await?;
1127                let value: i32 =
1128                    sqlx::query_scalar("SELECT current_setting('server_version_num')::int")
1129                        .fetch_one(&mut *conn)
1130                        .await?;
1131                Ok::<i32, DbError>(value)
1132            })
1133            .await?;
1134        Ok(*version)
1135    }
1136
1137    /// 判断服务端版本是否不低于 `min_version`(`server_version_num` 口径)。
1138    ///
1139    /// 例如 PG 14 及以上传 `140000`。
1140    pub async fn supports(&self, min_version: i32) -> Result<bool, DbError> {
1141        Ok(self.server_version_num().await? >= min_version)
1142    }
1143
1144    /// 将已开启的事务准备为两阶段提交(`PREPARE TRANSACTION`)。
1145    ///
1146    /// 成功返回后事务进入服务端 prepared 状态,`transaction` 句柄被消费;调用方需
1147    /// 通过 [`Self::commit_prepared`] 或 [`Self::rollback_prepared`] 收尾。
1148    /// `max_prepared_transactions = 0` 时返回明确的 [`DbError::TransactionError`]。
1149    pub async fn prepare_transaction(
1150        &self,
1151        transaction: Transaction,
1152        gid: &str,
1153    ) -> Result<(), DbError> {
1154        transaction.prepare(gid).await
1155    }
1156
1157    /// 提交一个已准备的两阶段事务(`COMMIT PREPARED`)。
1158    ///
1159    /// 必须在事务块之外执行;GID 只能是 `[A-Za-z0-9_.:-]` 白名单字符。
1160    pub async fn commit_prepared(&self, gid: &str) -> Result<(), DbError> {
1161        validate_prepared_gid(gid)?;
1162        let sql = format!("COMMIT PREPARED '{gid}'");
1163        if self.config.enable_logging {
1164            log::debug!("提交已准备事务: gid={gid}");
1165        }
1166        let mut conn = self.acquire().await?;
1167        sqlx::query(&sql).execute(&mut *conn).await?;
1168        Ok(())
1169    }
1170
1171    /// 回滚一个已准备的两阶段事务(`ROLLBACK PREPARED`)。
1172    ///
1173    /// 必须在事务块之外执行;GID 约束同 [`Self::commit_prepared`]。
1174    pub async fn rollback_prepared(&self, gid: &str) -> Result<(), DbError> {
1175        validate_prepared_gid(gid)?;
1176        let sql = format!("ROLLBACK PREPARED '{gid}'");
1177        if self.config.enable_logging {
1178            log::debug!("回滚已准备事务: gid={gid}");
1179        }
1180        let mut conn = self.acquire().await?;
1181        sqlx::query(&sql).execute(&mut *conn).await?;
1182        Ok(())
1183    }
1184
1185    /// 执行 `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` 并返回解析后的计划文本。
1186    ///
1187    /// `sql` 与 [`Self::query_with_params`] 一样是调用方提供的受信 SQL,`$N`
1188    /// 占位符由 `params` 绑定,绝不拼接参数值。返回值为每个 EXPLAIN 行中每个
1189    /// 计划对象的格式化 JSON 文本(通常是 1 个元素)。
1190    ///
1191    /// 注意:`ANALYZE` 会真实执行语句(包括写操作)。
1192    pub async fn explain(
1193        &self,
1194        sql: &str,
1195        params: Vec<serde_json::Value>,
1196    ) -> Result<Vec<String>, DbError> {
1197        let statement = explain_statement(sql)?;
1198        if self.config.enable_logging {
1199            log::debug!("执行 EXPLAIN: {}, 参数数量: {}", statement, params.len());
1200        }
1201        let mut query = sqlx::query_as::<_, (serde_json::Value,)>(&statement);
1202        for param in &params {
1203            query = bind_json_param_as(query, param);
1204        }
1205        let mut conn = self.acquire().await?;
1206        let rows = query.fetch_all(&mut *conn).await?;
1207        explain_rows_to_strings(rows)
1208    }
1209
1210    /// 查询当前会话活动(`pg_stat_activity`),返回结构化行。
1211    ///
1212    /// 包含当前连接自身;`client_addr` 以 `host()` 文本形式返回,避免 inet 解码
1213    /// 依赖。`query` 为最近一次执行的语句文本。
1214    pub async fn active_queries(&self) -> Result<Vec<ActiveQuery>, DbError> {
1215        let mut conn = self.acquire().await?;
1216        let rows = sqlx::query_as::<_, ActiveQuery>(
1217            "SELECT pid,
1218                    usename::text AS usename,
1219                    application_name,
1220                    host(client_addr) AS client_addr,
1221                    state,
1222                    wait_event_type,
1223                    wait_event,
1224                    query_start,
1225                    query
1226             FROM pg_stat_activity
1227             ORDER BY query_start DESC NULLS LAST, pid",
1228        )
1229        .fetch_all(&mut *conn)
1230        .await?;
1231        Ok(rows)
1232    }
1233
1234    /// 查询 `pg_locks` 阻塞链,返回结构化行。
1235    ///
1236    /// 每条记录表示一个未授予的锁请求及其一个阻塞者;同一等待者若有多个阻塞者
1237    /// 会出现多行(`pg_blocking_pids` 语义)。无阻塞时返回空列表。
1238    pub async fn lock_waits(&self) -> Result<Vec<LockWait>, DbError> {
1239        let mut conn = self.acquire().await?;
1240        let rows = sqlx::query_as::<_, LockWait>(
1241            "SELECT blocked.pid AS blocked_pid,
1242                    blocking.pid AS blocking_pid,
1243                    blocked.query AS blocked_query,
1244                    blocking.query AS blocking_query,
1245                    CASE
1246                        WHEN l.relation IS NULL OR l.relation = 0 THEN NULL
1247                        ELSE l.relation::regclass::text
1248                    END AS relation,
1249                    l.locktype AS lock_type,
1250                    l.mode AS mode,
1251                    blocked.wait_event AS wait_event
1252             FROM pg_locks l
1253             JOIN pg_stat_activity blocked ON blocked.pid = l.pid
1254             CROSS JOIN LATERAL unnest(pg_blocking_pids(l.pid)) AS bp(blocking_pid)
1255             JOIN pg_stat_activity blocking ON blocking.pid = bp.blocking_pid
1256             WHERE NOT l.granted
1257             ORDER BY blocked.pid, blocking.pid",
1258        )
1259        .fetch_all(&mut *conn)
1260        .await?;
1261        Ok(rows)
1262    }
1263
1264    /// 借出一条连接,并返回绑定该连接后端 PID 的 [`CancelToken`]。
1265    ///
1266    /// 调用方在返回的连接上执行长查询(可直接用 sqlx 在该连接上执行),另一个
1267    /// 任务/线程用 token 调 [`CancelToken::cancel`] 取消它。连接由调用方持有,
1268    /// 归还池时照常触发 `after_release` 清理。
1269    ///
1270    /// 取消操作需要另借一条连接,因此 `max_connections < 2` 时直接返回
1271    /// [`DbError::InvalidArgument`](池上限为 1 时取消会与目标查询互相等待)。
1272    ///
1273    /// token 中的 `backend_pid` 只在目标连接仍被持有时有效;连接归还池并被复用
1274    /// 后,同一 PID 可能已指向另一个会话,此时不应再用该 token。
1275    pub async fn acquire_with_cancel_token(
1276        &self,
1277    ) -> Result<(sqlx::pool::PoolConnection<sqlx::Postgres>, CancelToken), DbError> {
1278        if self.config.max_connections < 2 {
1279            return Err(DbError::InvalidArgument(format!(
1280                "PostgreSQL 取消令牌需要至少 2 条连接(取消要另借一条连接),当前 \
1281                 max_connections = {}",
1282                self.config.max_connections
1283            )));
1284        }
1285        let mut conn = self.acquire().await?;
1286        let backend_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
1287            .fetch_one(&mut *conn)
1288            .await?;
1289        let token = CancelToken {
1290            pool: self.pool.clone(),
1291            backend_pid,
1292        };
1293        Ok((conn, token))
1294    }
1295
1296    /// 清洗连接池中一条连接的会话状态(`DISCARD ALL`)。
1297    ///
1298    /// 清空会话级 GUC、临时表、游标、prepared statement、LISTEN 与 advisory lock。
1299    /// 注意:`DISCARD ALL` 不能在事务块内执行。`Database::from_pool` 的调用方可用
1300    /// 它在借出/归还前后手工清理。
1301    ///
1302    /// `DISCARD ALL` 内含 `DEALLOCATE ALL`,因此服务端清理后还会同步清空 sqlx 的
1303    /// 客户端语句缓存,避免后续复用该连接时命中已失效的缓存条目。
1304    pub async fn reset_connection(&self) -> Result<(), DbError> {
1305        let mut conn = self.acquire().await?;
1306        sqlx::query(DISCARD_ALL_SQL).execute(&mut *conn).await?;
1307        sqlx::Connection::clear_cached_statements(&mut *conn).await?;
1308        Ok(())
1309    }
1310}
1311
1312/// 查询取消令牌:记录目标后端 PID,可在另一条连接上取消/终止其当前语句。
1313///
1314/// 关闭连接不会取消它正在执行的查询;只有 `pg_cancel_backend`(语句级,连接可
1315/// 继续使用)或 `pg_terminate_backend`(连接级)会。取消成功后目标语句以
1316/// SQLSTATE 57014 结束,映射为 [`crate::SqlErrorKind::QueryCanceled`] /
1317/// [`crate::DbErrorCategory::Timeout`]。
1318///
1319/// **生命周期约束**:token 只在目标连接仍被持有时有效。连接一旦归还连接池并被
1320/// 复用,`backend_pid` 可能已指向另一个会话,此时用该 token 取消会误伤其他查询。
1321#[derive(Debug, Clone)]
1322pub struct CancelToken {
1323    pool: PgPool,
1324    backend_pid: i32,
1325}
1326
1327impl CancelToken {
1328    /// 目标连接的服务端后端 PID。
1329    pub fn backend_pid(&self) -> i32 {
1330        self.backend_pid
1331    }
1332
1333    /// 取消目标后端正在执行的语句(`pg_cancel_backend`)。
1334    ///
1335    /// 返回 `true` 表示信号已送达;语句是否立即结束取决于服务端。后端已结束或
1336    /// 不存在时返回 `false`。
1337    pub async fn cancel(&self) -> Result<bool, DbError> {
1338        Ok(sqlx::query_scalar(CANCEL_BACKEND_SQL)
1339            .bind(self.backend_pid)
1340            .fetch_one(&self.pool)
1341            .await?)
1342    }
1343
1344    /// 强制终止目标后端连接(`pg_terminate_backend`)。
1345    pub async fn terminate(&self) -> Result<bool, DbError> {
1346        Ok(sqlx::query_scalar(TERMINATE_BACKEND_SQL)
1347            .bind(self.backend_pid)
1348            .fetch_one(&self.pool)
1349            .await?)
1350    }
1351}
1352
1353/// `pg_stat_activity` 中的一条会话快照。
1354#[derive(Debug, Clone, sqlx::FromRow)]
1355pub struct ActiveQuery {
1356    /// 后端进程 ID。
1357    pub pid: i32,
1358    /// 登录角色名。
1359    pub usename: Option<String>,
1360    /// 应用名(连接串中的 `application_name`)。
1361    pub application_name: Option<String>,
1362    /// 客户端地址(`host(client_addr)` 文本)。
1363    pub client_addr: Option<String>,
1364    /// 会话状态(`active` / `idle` / `idle in transaction` 等)。
1365    pub state: Option<String>,
1366    /// 等待事件类别。
1367    pub wait_event_type: Option<String>,
1368    /// 等待事件名。
1369    pub wait_event: Option<String>,
1370    /// 当前语句开始时间。
1371    pub query_start: Option<chrono::DateTime<chrono::Utc>>,
1372    /// 最近一次执行的语句文本。
1373    pub query: String,
1374}
1375
1376/// `pg_locks` 中的一条阻塞关系。
1377#[derive(Debug, Clone, sqlx::FromRow)]
1378pub struct LockWait {
1379    /// 被阻塞的后端进程 ID。
1380    pub blocked_pid: i32,
1381    /// 阻塞该请求的后端进程 ID。
1382    pub blocking_pid: i32,
1383    /// 被阻塞会话最近执行的语句。
1384    pub blocked_query: Option<String>,
1385    /// 阻塞会话最近执行的语句。
1386    pub blocking_query: Option<String>,
1387    /// 锁对象(表/索引等);事务级锁为 `None`。
1388    pub relation: Option<String>,
1389    /// 锁类型(`relation` / `tuple` / `transactionid` 等)。
1390    pub lock_type: Option<String>,
1391    /// 锁模式(`AccessShareLock` / `AccessExclusiveLock` 等)。
1392    pub mode: Option<String>,
1393    /// 被阻塞会话的等待事件。
1394    pub wait_event: Option<String>,
1395}
1396
1397/// 构造 EXPLAIN 前置语句;`sql` 为空时拒绝。
1398fn explain_statement(sql: &str) -> Result<String, DbError> {
1399    let trimmed = sql.trim().trim_end_matches(';').trim_end();
1400    if trimmed.is_empty() {
1401        return Err(DbError::InvalidArgument(
1402            "EXPLAIN 的 SQL 不能为空".to_string(),
1403        ));
1404    }
1405    Ok(format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {trimmed}"))
1406}
1407
1408/// 把 `EXPLAIN ... FORMAT JSON` 的行解析为格式化计划文本。
1409///
1410/// 每个行的第一列是 JSON 数组(通常只含一个计划对象);对数组逐个元素输出
1411/// 格式化 JSON,非数组值原样输出。
1412fn explain_rows_to_strings(rows: Vec<(serde_json::Value,)>) -> Result<Vec<String>, DbError> {
1413    let mut plans = Vec::new();
1414    for (row,) in rows {
1415        let items = match row {
1416            serde_json::Value::Array(items) => items,
1417            other => vec![other],
1418        };
1419        for item in items {
1420            plans.push(serde_json::to_string_pretty(&item).map_err(|error| {
1421                DbError::SerializationError(format!("EXPLAIN 计划序列化失败: {error}"))
1422            })?);
1423        }
1424    }
1425    Ok(plans)
1426}
1427
1428/// 生成连接建立后需要执行的超时 `SET` 语句。
1429///
1430/// 三个值都是受控 `u64`(毫秒),直接拼进语句无注入面;`None` 表示不下发。
1431fn timeout_statements(
1432    statement_timeout_ms: Option<u64>,
1433    lock_timeout_ms: Option<u64>,
1434    idle_in_transaction_timeout_ms: Option<u64>,
1435) -> Vec<String> {
1436    let mut statements = Vec::new();
1437    if let Some(ms) = statement_timeout_ms {
1438        statements.push(format!("SET statement_timeout = {ms}"));
1439    }
1440    if let Some(ms) = lock_timeout_ms {
1441        statements.push(format!("SET lock_timeout = {ms}"));
1442    }
1443    if let Some(ms) = idle_in_transaction_timeout_ms {
1444        statements.push(format!("SET idle_in_transaction_session_timeout = {ms}"));
1445    }
1446    statements
1447}
1448
1449/// 是否为可整事务重试的序列化冲突(40001)或死锁(40P01)。
1450fn is_serialization_conflict(error: &DbError) -> bool {
1451    matches!(error.sqlstate(), Some("40001") | Some("40P01"))
1452}
1453
1454/// 第 `attempt` 次失败后的指数退避:10ms、20ms、40ms……封顶 1s。
1455fn retry_backoff(attempt: u32) -> std::time::Duration {
1456    let exponent = attempt.saturating_sub(1).min(7);
1457    std::time::Duration::from_millis((10u64 << exponent).min(1_000))
1458}
1459
1460/// `waiting` 计数的 RAII guard:离开作用域时把计入的等待者数减回去。
1461struct AcquireWaiter<'a> {
1462    counter: &'a AtomicUsize,
1463    armed: bool,
1464}
1465
1466impl Drop for AcquireWaiter<'_> {
1467    fn drop(&mut self) {
1468        if self.armed {
1469            self.counter.fetch_sub(1, Ordering::Relaxed);
1470        }
1471    }
1472}
1473
1474/// 每条新连接需要下发的会话初始化动作(`after_connect` / `before_acquire` 共用)。
1475#[derive(Debug, Clone)]
1476struct SessionSetup {
1477    /// `application_name`,经 `set_config(..., false)` 绑定写入。
1478    application_name: Option<String>,
1479    /// 会话 GUC 基线(时区/日期格式/超时等)。
1480    statements: Vec<String>,
1481    /// 是否要求 `client_encoding = UTF8`(fail-closed)。
1482    require_utf8_client_encoding: bool,
1483}
1484
1485impl SessionSetup {
1486    /// 在指定连接上应用全部会话初始化动作。
1487    ///
1488    /// 返回 `sqlx::Error` 以便直接作为连接池钩子的错误;非 UTF8 编码返回
1489    /// `Error::Configuration`,经 `DbError::from` 映射为连接错误。
1490    async fn apply(&self, conn: &mut sqlx::PgConnection) -> Result<(), sqlx::Error> {
1491        if let Some(application_name) = &self.application_name {
1492            sqlx::query("SELECT set_config('application_name', $1, false)")
1493                .bind(application_name)
1494                .execute(&mut *conn)
1495                .await?;
1496        }
1497        for sql in &self.statements {
1498            sqlx::query(sql).execute(&mut *conn).await?;
1499        }
1500        if self.require_utf8_client_encoding {
1501            let encoding: String = sqlx::query_scalar("SELECT current_setting('client_encoding')")
1502                .fetch_one(&mut *conn)
1503                .await?;
1504            if !client_encoding_is_utf8(&encoding) {
1505                return Err(sqlx::Error::Configuration(
1506                    format!(
1507                        "PostgreSQL client_encoding 必须为 UTF8,当前为 {encoding:?};\
1508                         如确需其他编码请设置 DatabaseConfig::with_require_utf8_client_encoding(false)"
1509                    )
1510                    .into(),
1511                ));
1512            }
1513        }
1514        Ok(())
1515    }
1516}
1517
1518/// `client_encoding` 是否为 UTF8(服务端返回 `UTF8`;大小写不敏感)。
1519fn client_encoding_is_utf8(encoding: &str) -> bool {
1520    matches!(
1521        encoding.trim().to_ascii_uppercase().as_str(),
1522        "UTF8" | "UTF-8" | "UNICODE"
1523    )
1524}
1525
1526/// 会话级 advisory lock 的共享/排他模式。
1527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1528enum AdvisoryLockMode {
1529    Exclusive,
1530    Shared,
1531}
1532
1533impl AdvisoryLockMode {
1534    /// 阻塞获取锁的 SQL。
1535    fn lock_sql(self) -> &'static str {
1536        match self {
1537            Self::Exclusive => "SELECT pg_advisory_lock($1)",
1538            Self::Shared => "SELECT pg_advisory_lock_shared($1)",
1539        }
1540    }
1541
1542    /// 非阻塞尝试获取锁的 SQL。
1543    fn try_lock_sql(self) -> &'static str {
1544        match self {
1545            Self::Exclusive => "SELECT pg_try_advisory_lock($1)",
1546            Self::Shared => "SELECT pg_try_advisory_lock_shared($1)",
1547        }
1548    }
1549
1550    /// 释放会话级锁的 SQL(共享锁必须用 `_shared` 版本解锁)。
1551    fn unlock_sql(self) -> &'static str {
1552        match self {
1553            Self::Exclusive => "SELECT pg_advisory_unlock($1)",
1554            Self::Shared => "SELECT pg_advisory_unlock_shared($1)",
1555        }
1556    }
1557}
1558
1559/// 会话级 advisory lock 的 RAII guard。
1560///
1561/// 锁绑定在 guard 持有的那条连接上:显式 [`unlock`](Self::unlock) 会执行
1562/// `pg_advisory_unlock`(共享锁为 `pg_advisory_unlock_shared`)并把连接归还池;
1563/// 未解锁即丢弃时无法在同步 `Drop` 中执行异步解锁,因此 `detach` 连接使其关闭,
1564/// 由服务端回收该会话持有的全部会话级锁。
1565pub struct PgAdvisoryLock {
1566    conn: Option<sqlx::pool::PoolConnection<sqlx::Postgres>>,
1567    key: i64,
1568    mode: AdvisoryLockMode,
1569}
1570
1571impl PgAdvisoryLock {
1572    /// 锁键。
1573    pub fn key(&self) -> i64 {
1574        self.key
1575    }
1576
1577    /// 是否为共享锁(`pg_advisory_lock_shared`)。
1578    pub fn is_shared(&self) -> bool {
1579        self.mode == AdvisoryLockMode::Shared
1580    }
1581
1582    /// 释放锁;返回服务端解锁函数的结果。
1583    ///
1584    /// 返回 `true` 表示锁已真正释放,连接可安全归还池。返回 `false` 表示服务端
1585    /// 未释放该锁(例如锁不属于此会话或已被释放)——此时连接里可能仍带着会话级
1586    /// 锁,直接还池会让锁泄漏到池中,因此改为 `detach` 连接使其关闭,由服务端
1587    /// 回收该会话的全部会话级锁。
1588    pub async fn unlock(mut self) -> Result<bool, DbError> {
1589        let mode = self.mode;
1590        let conn = self
1591            .conn
1592            .as_mut()
1593            .ok_or_else(|| DbError::TransactionError("advisory lock 已释放".to_string()))?;
1594        let unlocked: bool = sqlx::query_scalar(mode.unlock_sql())
1595            .bind(self.key)
1596            .fetch_one(&mut **conn)
1597            .await?;
1598        if unlocked {
1599            // 锁已释放,连接可以安全归还连接池。
1600            self.conn.take();
1601        } else {
1602            // 服务端未确认释放:关闭会话,让服务端回收锁,避免泄漏到池中。
1603            if let Some(conn) = self.conn.take() {
1604                let _ = conn.detach();
1605            }
1606        }
1607        Ok(unlocked)
1608    }
1609
1610    /// 释放会话级 advisory lock,与 [`unlock`](Self::unlock) 等价。
1611    ///
1612    /// 会话级锁绑定在具体连接上,因此释放入口在 guard 而不是 `Database`:
1613    /// `Database` 上执行 `pg_advisory_unlock` 只会作用于池中随机一条连接,
1614    /// 无法保证解除的是持锁会话。
1615    pub async fn advisory_unlock(self) -> Result<bool, DbError> {
1616        self.unlock().await
1617    }
1618}
1619
1620impl Drop for PgAdvisoryLock {
1621    fn drop(&mut self) {
1622        if let Some(conn) = self.conn.take() {
1623            log::warn!(
1624                "PG 会话级 advisory lock({}) 未显式 unlock 即被丢弃;关闭连接以让服务端回收锁",
1625                self.key
1626            );
1627            let _ = conn.detach();
1628        }
1629    }
1630}
1631
1632/// 连接池上的服务端游标(`DECLARE ... CURSOR` + 分批 `FETCH`)。
1633///
1634/// 逐行消费:缓冲区为空时才向后端拉取下一批,内存占用以 `batch_size` 为上限。
1635pub struct PgRowCursor {
1636    conn: Option<sqlx::pool::PoolConnection<sqlx::Postgres>>,
1637    cursor_name: String,
1638    batch_size: usize,
1639    buffer: VecDeque<sqlx::postgres::PgRow>,
1640    exhausted: bool,
1641    closed: bool,
1642    enable_logging: bool,
1643}
1644
1645impl PgRowCursor {
1646    fn new(
1647        conn: sqlx::pool::PoolConnection<sqlx::Postgres>,
1648        cursor_name: String,
1649        batch_size: usize,
1650        enable_logging: bool,
1651    ) -> Self {
1652        Self {
1653            conn: Some(conn),
1654            cursor_name,
1655            batch_size,
1656            buffer: VecDeque::with_capacity(batch_size.min(1024)),
1657            exhausted: false,
1658            closed: false,
1659            enable_logging,
1660        }
1661    }
1662
1663    /// 每批拉取的最大行数。
1664    pub fn batch_size(&self) -> usize {
1665        self.batch_size
1666    }
1667
1668    /// 取下一条结果;流结束返回 `Ok(None)`。
1669    pub async fn next(&mut self) -> Result<Option<sqlx::postgres::PgRow>, DbError> {
1670        loop {
1671            if let Some(row) = self.buffer.pop_front() {
1672                return Ok(Some(row));
1673            }
1674            if self.exhausted {
1675                self.release().await?;
1676                return Ok(None);
1677            }
1678            self.fetch_batch().await?;
1679        }
1680    }
1681
1682    /// 提前关闭游标,丢弃尚未消费的缓冲行,并把连接归还池。
1683    pub async fn close(mut self) -> Result<(), DbError> {
1684        self.buffer.clear();
1685        self.release().await
1686    }
1687
1688    async fn fetch_batch(&mut self) -> Result<(), DbError> {
1689        let conn = self
1690            .conn
1691            .as_mut()
1692            .ok_or_else(|| DbError::TransactionError("流式游标已关闭".to_string()))?;
1693        let sql = format!(
1694            "FETCH FORWARD {} FROM {}",
1695            self.batch_size, self.cursor_name
1696        );
1697        if self.enable_logging {
1698            log::debug!("游标拉取: {}", sql);
1699        }
1700        let rows = sqlx::query(&sql).fetch_all(&mut **conn).await?;
1701        if rows.len() < self.batch_size {
1702            self.exhausted = true;
1703        }
1704        self.buffer.extend(rows);
1705        Ok(())
1706    }
1707
1708    /// 关闭游标并结束内部只读事务;连接清理失败时丢弃连接而非归还池。
1709    async fn release(&mut self) -> Result<(), DbError> {
1710        if self.closed {
1711            return Ok(());
1712        }
1713        self.closed = true;
1714        self.exhausted = true;
1715
1716        if let Some(mut conn) = self.conn.take() {
1717            let close_sql = format!("CLOSE {}", self.cursor_name);
1718            let close_ok = sqlx::query(&close_sql).execute(&mut *conn).await.is_ok();
1719            let rollback_ok = sqlx::query("ROLLBACK").execute(&mut *conn).await.is_ok();
1720            if !(close_ok && rollback_ok) {
1721                // 清理失败:不能把可能仍带打开事务的连接归还池。
1722                let _ = conn.detach();
1723                return Err(DbError::TransactionError(
1724                    "流式游标关闭失败,连接已丢弃".to_string(),
1725                ));
1726            }
1727        }
1728        Ok(())
1729    }
1730}
1731
1732impl Drop for PgRowCursor {
1733    fn drop(&mut self) {
1734        if let Some(conn) = self.conn.take() {
1735            // 同步 Drop 无法执行 ROLLBACK,detach 让连接关闭而不是带着打开事务回池。
1736            let _ = conn.detach();
1737        }
1738    }
1739}
1740
1741/// 未类型化 NULL 参数。
1742///
1743/// PARSE 阶段发送参数类型 OID 0(未指定),让 PostgreSQL 依据 SQL 上下文推断
1744/// 参数类型(与字符串字面量一致)。这使 `$1::text`、`$1::uuid`、
1745/// `$1::timestamptz`、`$1::numeric`、`$1::int + 1` 等显式 cast 场景都能接受
1746/// NULL;若固定绑定成 `int4`,这些 cast 会报 42883。绑定值本身编码为 NULL
1747/// (长度 -1),不写入任何数据。
1748#[derive(Debug, Clone, Copy)]
1749struct PgUntypedNull;
1750
1751impl sqlx::Type<sqlx::Postgres> for PgUntypedNull {
1752    fn type_info() -> sqlx::postgres::PgTypeInfo {
1753        // OID 0 = 未指定类型,由服务端推断。
1754        sqlx::postgres::PgTypeInfo::with_oid(sqlx::postgres::types::Oid(0))
1755    }
1756}
1757
1758impl sqlx::Encode<'_, sqlx::Postgres> for PgUntypedNull {
1759    fn encode_by_ref(
1760        &self,
1761        _buffer: &mut sqlx::postgres::PgArgumentBuffer,
1762    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
1763        Ok(sqlx::encode::IsNull::Yes)
1764    }
1765
1766    fn size_hint(&self) -> usize {
1767        0
1768    }
1769}
1770
1771/// 共享 `serde_json::Value` 参数绑定逻辑的内部宏
1772///
1773/// `Query` 与 `QueryAs` 的 `bind` 是各自的固有方法、没有公共 trait,
1774/// 无法用泛型函数复用,这里用宏共享同一套 `match` 体,
1775/// 保证两类查询的绑定行为完全一致。
1776///
1777/// PostgreSQL 适配要点:
1778/// - 数字优先按 `i64` 绑定,浮点按 `f64` 原生绑定(PostgreSQL 不会把文本
1779///   隐式转换为数值列,故不能像 MySQL 那样以字符串绑定浮点)。
1780/// - NULL 绑定为未类型化 NULL([`PgUntypedNull`]),由服务端按 SQL 上下文推断
1781///   参数类型;固定绑定成 `int4` 会让 `$1::uuid` / `$1::timestamptz` 等显式
1782///   cast 报 42883。
1783/// - 数组 / 对象作为原生 `serde_json::Value` 绑定(sqlx 的 json feature 已开启,
1784///   对应 PostgreSQL 的 JSON / JSONB),而非序列化成字符串。
1785macro_rules! bind_json_value {
1786    ($query:expr, $param:expr) => {
1787        match $param {
1788            // 字符串类型直接绑定
1789            serde_json::Value::String(s) => $query.bind(s.clone()),
1790            // 数字类型按 i64 → u64 顶半区 → f64 分类绑定
1791            serde_json::Value::Number(n) => match crate::json_param::classify_json_number(n) {
1792                Some(crate::json_param::JsonNumber::Int(i)) => $query.bind(i),
1793                Some(crate::json_param::JsonNumber::Uint(u)) => $query.bind(u.to_string()),
1794                Some(crate::json_param::JsonNumber::Float(f)) => $query.bind(f),
1795                None => $query.bind(PgUntypedNull),
1796            },
1797            // 布尔类型绑定
1798            serde_json::Value::Bool(b) => $query.bind(*b),
1799            // 未类型化 NULL:PARSE 时发送 OID 0,由服务端按上下文推断类型
1800            serde_json::Value::Null => $query.bind(PgUntypedNull),
1801            // 数组和对象作为原生 JSON / JSONB 绑定
1802            other => $query.bind(other.clone()),
1803        }
1804    };
1805}
1806
1807/// 将 `serde_json::Value` 参数绑定到 `query_as` 查询
1808///
1809/// # 参数
1810/// - query: sqlx query_as 查询对象
1811/// - param: JSON 参数值
1812///
1813/// # 返回
1814/// - 绑定参数后的查询对象
1815fn bind_json_param_as<'q, T>(
1816    query: sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>,
1817    param: &serde_json::Value,
1818) -> sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>
1819where
1820    T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
1821{
1822    bind_json_value!(query, param)
1823}
1824
1825/// 将 `serde_json::Value` 参数绑定到执行查询
1826///
1827/// # 参数
1828/// - query: sqlx 执行查询对象
1829/// - param: JSON 参数值
1830///
1831/// # 返回
1832/// - 绑定参数后的查询对象
1833fn bind_json_param<'q>(
1834    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
1835    param: &serde_json::Value,
1836) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
1837    bind_json_value!(query, param)
1838}
1839
1840#[cfg(test)]
1841#[allow(clippy::unwrap_used, clippy::expect_used)]
1842mod tests {
1843    use super::*;
1844
1845    #[test]
1846    fn test_database_config_validate_accepts_default_config() {
1847        let config = DatabaseConfig::default();
1848
1849        assert!(config.validate().is_ok());
1850    }
1851
1852    #[test]
1853    fn test_database_config_validate_rejects_invalid_pool_size() {
1854        assert!(matches!(
1855            DatabaseConfig {
1856                max_connections: 0,
1857                ..DatabaseConfig::default()
1858            }
1859            .validate(),
1860            Err(DbError::InvalidArgument(_))
1861        ));
1862
1863        assert!(matches!(
1864            DatabaseConfig {
1865                max_connections: 2,
1866                min_connections: 3,
1867                ..DatabaseConfig::default()
1868            }
1869            .validate(),
1870            Err(DbError::InvalidArgument(_))
1871        ));
1872    }
1873
1874    #[test]
1875    fn test_database_config_validate_rejects_invalid_timeouts() {
1876        for config in [
1877            DatabaseConfig {
1878                connect_timeout: 0,
1879                ..DatabaseConfig::default()
1880            },
1881            DatabaseConfig {
1882                idle_timeout: 0,
1883                ..DatabaseConfig::default()
1884            },
1885            DatabaseConfig {
1886                max_lifetime: Some(0),
1887                ..DatabaseConfig::default()
1888            },
1889        ] {
1890            assert!(matches!(
1891                config.validate(),
1892                Err(DbError::InvalidArgument(_))
1893            ));
1894        }
1895
1896        assert!(matches!(
1897            DatabaseConfig {
1898                connect_timeout: 30,
1899                idle_timeout: 30,
1900                ..DatabaseConfig::default()
1901            }
1902            .validate(),
1903            Err(DbError::InvalidArgument(_))
1904        ));
1905    }
1906
1907    #[tokio::test]
1908    async fn test_connect_with_config_rejects_invalid_config_before_connecting() {
1909        let config = DatabaseConfig {
1910            max_connections: 0,
1911            ..DatabaseConfig::default()
1912        };
1913        let result =
1914            Database::connect_with_config("postgres://postgres:bad@127.0.0.1:1/test", config).await;
1915
1916        assert!(matches!(result, Err(DbError::InvalidArgument(_))));
1917    }
1918
1919    #[test]
1920    fn test_search_path_validation_accepts_identifier_lists_only() {
1921        assert!(DatabaseConfig::default().search_path.is_none());
1922
1923        let config = DatabaseConfig::default().with_search_path("app, public");
1924        assert_eq!(config.search_path.as_deref(), Some("app, public"));
1925        assert!(config.validate().is_ok());
1926
1927        for invalid in [
1928            "",
1929            "   ",
1930            "app,,public",
1931            "app; DROP SCHEMA public",
1932            "app public",
1933        ] {
1934            let config = DatabaseConfig::default().with_search_path(invalid);
1935            assert!(
1936                matches!(config.validate(), Err(DbError::InvalidArgument(_))),
1937                "search_path 应拒绝 {invalid:?}"
1938            );
1939        }
1940    }
1941
1942    #[tokio::test]
1943    async fn health_check_propagates_closed_pool_error() -> Result<(), sqlx::Error> {
1944        let pool = sqlx::postgres::PgPoolOptions::new()
1945            .connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")?;
1946        let db = Database {
1947            pool,
1948            config: DatabaseConfig::default(),
1949            server_version: OnceCell::new(),
1950            waiting: Arc::new(AtomicUsize::new(0)),
1951        };
1952
1953        db.close().await;
1954
1955        assert!(db.is_closed());
1956        assert!(matches!(db.health_check().await, Err(DbError::PoolClosed)));
1957        Ok(())
1958    }
1959
1960    #[test]
1961    fn timeout_config_is_opt_in_and_renders_set_statements() {
1962        let default_config = DatabaseConfig::default();
1963        assert!(default_config.statement_timeout_ms.is_none());
1964        assert!(default_config.lock_timeout_ms.is_none());
1965        assert!(default_config.idle_in_transaction_timeout_ms.is_none());
1966        assert!(timeout_statements(None, None, None).is_empty());
1967
1968        let config = DatabaseConfig::default()
1969            .with_statement_timeout_ms(5_000u64)
1970            .with_lock_timeout_ms(Some(250))
1971            .with_idle_in_transaction_timeout_ms(30_000u64);
1972        assert_eq!(config.statement_timeout_ms, Some(5_000));
1973        assert_eq!(config.lock_timeout_ms, Some(250));
1974        assert_eq!(config.idle_in_transaction_timeout_ms, Some(30_000));
1975        assert!(config.validate().is_ok());
1976
1977        assert_eq!(
1978            timeout_statements(
1979                config.statement_timeout_ms,
1980                config.lock_timeout_ms,
1981                config.idle_in_transaction_timeout_ms
1982            ),
1983            vec![
1984                "SET statement_timeout = 5000".to_string(),
1985                "SET lock_timeout = 250".to_string(),
1986                "SET idle_in_transaction_session_timeout = 30000".to_string(),
1987            ]
1988        );
1989    }
1990
1991    #[test]
1992    fn only_serialization_failures_and_deadlocks_are_retried() {
1993        use crate::error::SqlErrorInfo;
1994
1995        assert!(is_serialization_conflict(&DbError::DatabaseError(
1996            Box::new(SqlErrorInfo::new("40001", "could not serialize access"))
1997        )));
1998        assert!(is_serialization_conflict(&DbError::DatabaseError(
1999            Box::new(SqlErrorInfo::new("40P01", "deadlock detected"))
2000        )));
2001        for other in ["23505", "57014", "55P03", "42P01"] {
2002            assert!(
2003                !is_serialization_conflict(&DbError::DatabaseError(Box::new(SqlErrorInfo::new(
2004                    other, "other"
2005                )))),
2006                "SQLSTATE {other} 不应触发事务重试"
2007            );
2008        }
2009        assert!(!is_serialization_conflict(&DbError::TransactionError(
2010            "local".to_string()
2011        )));
2012    }
2013
2014    #[test]
2015    fn retry_backoff_grows_exponentially_and_caps() {
2016        use std::time::Duration;
2017
2018        assert_eq!(retry_backoff(1), Duration::from_millis(10));
2019        assert_eq!(retry_backoff(2), Duration::from_millis(20));
2020        assert_eq!(retry_backoff(3), Duration::from_millis(40));
2021        assert_eq!(retry_backoff(7), Duration::from_millis(640));
2022        assert_eq!(retry_backoff(8), Duration::from_millis(1_000));
2023        assert_eq!(retry_backoff(100), Duration::from_millis(1_000));
2024    }
2025
2026    #[test]
2027    fn explain_statement_prefixes_trusted_sql_and_rejects_empty() {
2028        assert_eq!(
2029            explain_statement("SELECT $1::int + 1").unwrap(),
2030            "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT $1::int + 1"
2031        );
2032        assert_eq!(
2033            explain_statement("  SELECT 1;  ").unwrap(),
2034            "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT 1"
2035        );
2036        for invalid in ["", "   ", " ; "] {
2037            assert!(matches!(
2038                explain_statement(invalid),
2039                Err(DbError::InvalidArgument(_))
2040            ));
2041        }
2042    }
2043
2044    #[test]
2045    fn explain_rows_are_flattened_to_pretty_json_per_plan() {
2046        let rows = vec![
2047            (serde_json::json!([
2048                {"Plan": {"Node Type": "Result"}, "Execution Time": 0.1}
2049            ]),),
2050            (serde_json::json!([{"Plan": {"Node Type": "Seq Scan"}}]),),
2051        ];
2052        let plans = explain_rows_to_strings(rows).unwrap();
2053        assert_eq!(plans.len(), 2);
2054        for plan in &plans {
2055            let parsed: serde_json::Value = serde_json::from_str(plan).unwrap();
2056            assert!(parsed.get("Plan").is_some(), "计划文本应可解析为 JSON");
2057        }
2058        assert!(plans[0].contains("\"Node Type\": \"Result\""));
2059
2060        // 非数组行原样保留为单个计划文本。
2061        let plans = explain_rows_to_strings(vec![(serde_json::json!({"Plan": {}}),)]).unwrap();
2062        assert_eq!(plans.len(), 1);
2063        assert!(plans[0].contains("Plan"));
2064    }
2065
2066    /// 取消令牌需要另一条连接:池上限 < 2 时必须立即报错,而不是等到超时。
2067    #[tokio::test]
2068    async fn acquire_with_cancel_token_requires_at_least_two_connections() {
2069        let pool = sqlx::postgres::PgPoolOptions::new()
2070            .max_connections(1)
2071            .connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")
2072            .unwrap();
2073        let db = Database {
2074            pool,
2075            config: DatabaseConfig {
2076                max_connections: 1,
2077                ..DatabaseConfig::default()
2078            },
2079            server_version: OnceCell::new(),
2080            waiting: Arc::new(AtomicUsize::new(0)),
2081        };
2082        assert!(matches!(
2083            db.acquire_with_cancel_token().await,
2084            Err(DbError::InvalidArgument(_))
2085        ));
2086    }
2087
2088    /// P1-19:取消 SQL 必须绑定参数,57014 映射为 Timeout 且不可重试。
2089    #[test]
2090    fn cancel_token_sql_and_57014_mapping() {
2091        use crate::error::{DbErrorCategory, SqlErrorInfo};
2092
2093        assert_eq!(CANCEL_BACKEND_SQL, "SELECT pg_cancel_backend($1)");
2094        assert_eq!(TERMINATE_BACKEND_SQL, "SELECT pg_terminate_backend($1)");
2095        assert!(CANCEL_BACKEND_SQL.contains("$1"));
2096        assert!(TERMINATE_BACKEND_SQL.contains("$1"));
2097
2098        let canceled = DbError::DatabaseError(Box::new(SqlErrorInfo::new(
2099            "57014",
2100            "canceling statement due to user request",
2101        )));
2102        assert_eq!(canceled.sqlstate(), Some("57014"));
2103        assert_eq!(canceled.category(), DbErrorCategory::Timeout);
2104        assert!(!canceled.is_retryable());
2105    }
2106
2107    /// P1-18:会话级共享锁使用 `_shared` 函数,排他锁保持原函数。
2108    #[test]
2109    fn advisory_lock_sql_covers_shared_and_exclusive() {
2110        assert_eq!(
2111            AdvisoryLockMode::Exclusive.lock_sql(),
2112            "SELECT pg_advisory_lock($1)"
2113        );
2114        assert_eq!(
2115            AdvisoryLockMode::Shared.lock_sql(),
2116            "SELECT pg_advisory_lock_shared($1)"
2117        );
2118        assert_eq!(
2119            AdvisoryLockMode::Exclusive.try_lock_sql(),
2120            "SELECT pg_try_advisory_lock($1)"
2121        );
2122        assert_eq!(
2123            AdvisoryLockMode::Shared.try_lock_sql(),
2124            "SELECT pg_try_advisory_lock_shared($1)"
2125        );
2126        assert_eq!(
2127            AdvisoryLockMode::Exclusive.unlock_sql(),
2128            "SELECT pg_advisory_unlock($1)"
2129        );
2130        assert_eq!(
2131            AdvisoryLockMode::Shared.unlock_sql(),
2132            "SELECT pg_advisory_unlock_shared($1)"
2133        );
2134    }
2135
2136    /// unlock 返回 false 时不得把仍可能持锁的连接还池,必须 detach 关闭会话。
2137    #[tokio::test]
2138    #[ignore = "需要真实 PostgreSQL 实例"]
2139    async fn advisory_unlock_false_detaches_instead_of_returning_connection() {
2140        let url = std::env::var("PG_TEST_URL")
2141            .unwrap_or_else(|_| "postgres://postgres:postgres@127.0.0.1:55432/test".to_string());
2142        let db = Database::connect(&url).await.expect("PG 必须可连接");
2143        let conn = db.acquire().await.expect("借出连接应成功");
2144        assert_eq!(db.pool.size(), 1);
2145
2146        // 该会话从未持有这把锁,服务端 pg_advisory_unlock 返回 false。
2147        let lock = PgAdvisoryLock {
2148            conn: Some(conn),
2149            key: 987_654_321,
2150            mode: AdvisoryLockMode::Exclusive,
2151        };
2152        assert!(!lock.unlock().await.expect("解锁调用应成功"));
2153        assert_eq!(
2154            db.pool.size(),
2155            0,
2156            "unlock 返回 false 时必须 detach 关闭会话,而不是把连接还池"
2157        );
2158    }
2159
2160    /// P1-20:application_name / statement cache / DISCARD ALL / UTF-8 校验配置。
2161    #[test]
2162    fn runtime_config_defaults_and_setters() {
2163        let default = DatabaseConfig::default();
2164        assert!(default.application_name.is_none());
2165        assert!(default.statement_cache_size.is_none());
2166        assert!(!default.reset_on_release);
2167        assert!(default.require_utf8_client_encoding);
2168        assert!(default.ssl_mode.is_none());
2169
2170        let config = DatabaseConfig::default()
2171            .with_application_name("yang-test")
2172            .with_statement_cache_size(0)
2173            .with_reset_on_release(true)
2174            .with_require_utf8_client_encoding(false);
2175        assert_eq!(config.application_name.as_deref(), Some("yang-test"));
2176        assert_eq!(config.statement_cache_size, Some(0));
2177        assert!(config.reset_on_release);
2178        assert!(!config.require_utf8_client_encoding);
2179        assert!(config.validate().is_ok());
2180
2181        assert_eq!(DISCARD_ALL_SQL, "DISCARD ALL");
2182    }
2183
2184    #[test]
2185    fn application_name_is_validated() {
2186        for invalid in [String::new(), "a\0b".to_string(), "a".repeat(64)] {
2187            let config = DatabaseConfig::default().with_application_name(invalid.clone());
2188            assert!(
2189                matches!(config.validate(), Err(DbError::InvalidArgument(_))),
2190                "application_name 应拒绝 {invalid:?}"
2191            );
2192        }
2193        // 63 字节上限内合法。
2194        let config = DatabaseConfig::default().with_application_name("a".repeat(63));
2195        assert!(config.validate().is_ok());
2196    }
2197
2198    /// P1-21:TLS 配置组合校验与 sqlx 模式映射。
2199    #[test]
2200    fn ssl_config_validation_and_mode_mapping() {
2201        assert!(matches!(
2202            SslMode::Disable.as_pg_ssl_mode(),
2203            PgSslMode::Disable
2204        ));
2205        assert!(matches!(
2206            SslMode::Prefer.as_pg_ssl_mode(),
2207            PgSslMode::Prefer
2208        ));
2209        assert!(matches!(
2210            SslMode::Require.as_pg_ssl_mode(),
2211            PgSslMode::Require
2212        ));
2213        assert!(matches!(
2214            SslMode::VerifyCa.as_pg_ssl_mode(),
2215            PgSslMode::VerifyCa
2216        ));
2217        assert!(matches!(
2218            SslMode::VerifyFull.as_pg_ssl_mode(),
2219            PgSslMode::VerifyFull
2220        ));
2221
2222        // verify-ca / verify-full 缺根证书必须报错。
2223        for mode in [SslMode::VerifyCa, SslMode::VerifyFull] {
2224            let missing = DatabaseConfig::default().with_ssl_mode(Some(mode));
2225            assert!(
2226                matches!(missing.validate(), Err(DbError::InvalidArgument(_))),
2227                "{mode:?} 缺 ssl_root_cert 应报错"
2228            );
2229            let with_root = DatabaseConfig::default()
2230                .with_ssl_mode(Some(mode))
2231                .with_ssl_root_cert("/etc/ssl/root.pem");
2232            assert!(with_root.validate().is_ok());
2233        }
2234
2235        // disable 模式不允许证书。
2236        assert!(matches!(
2237            DatabaseConfig::default()
2238                .with_ssl_mode(Some(SslMode::Disable))
2239                .with_ssl_root_cert("/etc/ssl/root.pem")
2240                .validate(),
2241            Err(DbError::InvalidArgument(_))
2242        ));
2243
2244        // 客户端证书与私钥必须成对。
2245        assert!(matches!(
2246            DatabaseConfig::default()
2247                .with_ssl_mode(Some(SslMode::Require))
2248                .with_ssl_client_cert("/etc/ssl/client.pem")
2249                .validate(),
2250            Err(DbError::InvalidArgument(_))
2251        ));
2252        assert!(DatabaseConfig::default()
2253            .with_ssl_mode(Some(SslMode::Require))
2254            .with_ssl_client_cert("/etc/ssl/client.pem")
2255            .with_ssl_client_key("/etc/ssl/client.key")
2256            .validate()
2257            .is_ok());
2258
2259        // 未指定模式且无根证书:沿用连接串 sslmode。
2260        assert!(DatabaseConfig::default().effective_ssl_mode().is_none());
2261        // 未指定模式但有根证书:自动按 verify-ca 使用根证书(不能静默忽略)。
2262        assert_eq!(
2263            DatabaseConfig::default()
2264                .with_ssl_root_cert("/etc/ssl/root.pem")
2265                .effective_ssl_mode(),
2266            Some(SslMode::VerifyCa)
2267        );
2268        // 显式模式原样返回。
2269        for mode in [
2270            SslMode::Disable,
2271            SslMode::Prefer,
2272            SslMode::Require,
2273            SslMode::VerifyCa,
2274            SslMode::VerifyFull,
2275        ] {
2276            assert_eq!(
2277                DatabaseConfig::default()
2278                    .with_ssl_mode(Some(mode))
2279                    .effective_ssl_mode(),
2280                Some(mode)
2281            );
2282        }
2283        // 有根证书但未指定模式:validate 通过。
2284        assert!(DatabaseConfig::default()
2285            .with_ssl_root_cert("/etc/ssl/root.pem")
2286            .validate()
2287            .is_ok());
2288
2289        // prefer/require 不允许携带根证书(sqlx 在这两种模式下不校验证书,
2290        // 根证书会被静默忽略);需要校验请显式用 verify-ca/verify-full。
2291        for mode in [SslMode::Prefer, SslMode::Require] {
2292            assert!(
2293                matches!(
2294                    DatabaseConfig::default()
2295                        .with_ssl_mode(Some(mode))
2296                        .with_ssl_root_cert("/etc/ssl/root.pem")
2297                        .validate(),
2298                    Err(DbError::InvalidArgument(_))
2299                ),
2300                "{mode:?} + ssl_root_cert 应报错(根证书不会被该校验模式使用)"
2301            );
2302        }
2303    }
2304
2305    /// P1-22:client_encoding 判定口径(UTF8 大小写/别名容忍,其余 fail-closed)。
2306    #[test]
2307    fn client_encoding_must_be_utf8() {
2308        for ok in ["UTF8", "utf8", "Utf-8", "UNICODE", " UTF8 "] {
2309            assert!(client_encoding_is_utf8(ok), "{ok:?} 应视为 UTF8");
2310        }
2311        for bad in ["SQL_ASCII", "LATIN1", "WIN1252", "EUC_JP", ""] {
2312            assert!(!client_encoding_is_utf8(bad), "{bad:?} 不应视为 UTF8");
2313        }
2314    }
2315
2316    /// P1-20:waiting 计数在 acquire 结束时归还,pool_status 读取同一原子值。
2317    #[tokio::test]
2318    async fn waiting_counter_is_raii_and_reflected_in_pool_status() -> Result<(), sqlx::Error> {
2319        let counter = AtomicUsize::new(0);
2320        {
2321            counter.fetch_add(1, Ordering::Relaxed);
2322            let _waiter = AcquireWaiter {
2323                counter: &counter,
2324                armed: true,
2325            };
2326            assert_eq!(counter.load(Ordering::Relaxed), 1);
2327        }
2328        assert_eq!(counter.load(Ordering::Relaxed), 0);
2329
2330        // 未计入等待的 guard 不应改动计数。
2331        {
2332            let _waiter = AcquireWaiter {
2333                counter: &counter,
2334                armed: false,
2335            };
2336        }
2337        assert_eq!(counter.load(Ordering::Relaxed), 0);
2338
2339        let pool = sqlx::postgres::PgPoolOptions::new()
2340            .connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")?;
2341        let db = Database {
2342            pool,
2343            config: DatabaseConfig::default(),
2344            server_version: OnceCell::new(),
2345            waiting: Arc::new(AtomicUsize::new(3)),
2346        };
2347        assert_eq!(db.pool_status().waiting, 3);
2348        Ok(())
2349    }
2350}