use crate::error::DbError;
use crate::postgres::params::{json_signature, keyed_sql, PgUntypedNull};
use crate::postgres::transaction::{
next_cursor_name, normalize_stream_sql, validate_prepared_gid, TransactionOptions,
DEFAULT_STREAM_BATCH_SIZE,
};
use crate::postgres::{QueryBuilder, Transaction};
use crate::{BackendCapabilities, PoolStatus, POSTGRES_CAPABILITIES};
use sqlx::postgres::{PgPool, PgSslMode};
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::OnceCell;
const MAX_APPLICATION_NAME_BYTES: usize = 63;
const DISCARD_ALL_SQL: &str = "DISCARD ALL";
const CANCEL_BACKEND_SQL: &str = "SELECT pg_cancel_backend($1)";
const TERMINATE_BACKEND_SQL: &str = "SELECT pg_terminate_backend($1)";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SslMode {
Disable,
Prefer,
Require,
VerifyCa,
VerifyFull,
}
impl SslMode {
fn as_pg_ssl_mode(self) -> PgSslMode {
match self {
Self::Disable => PgSslMode::Disable,
Self::Prefer => PgSslMode::Prefer,
Self::Require => PgSslMode::Require,
Self::VerifyCa => PgSslMode::VerifyCa,
Self::VerifyFull => PgSslMode::VerifyFull,
}
}
fn requires_root_cert(self) -> bool {
matches!(self, Self::VerifyCa | Self::VerifyFull)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DatabaseConfig {
pub max_connections: u32,
pub connect_timeout: u64,
pub idle_timeout: u64,
pub enable_logging: bool,
pub min_connections: u32,
pub max_lifetime: Option<u64>,
pub test_before_acquire: bool,
pub search_path: Option<String>,
pub statement_timeout_ms: Option<u64>,
pub lock_timeout_ms: Option<u64>,
pub idle_in_transaction_timeout_ms: Option<u64>,
pub application_name: Option<String>,
pub statement_cache_size: Option<usize>,
pub reset_on_release: bool,
pub require_utf8_client_encoding: bool,
pub ssl_mode: Option<SslMode>,
pub ssl_root_cert: Option<PathBuf>,
pub ssl_client_cert: Option<PathBuf>,
pub ssl_client_key: Option<PathBuf>,
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
max_connections: 10,
connect_timeout: 30,
idle_timeout: 600,
enable_logging: false,
min_connections: 0,
max_lifetime: None,
test_before_acquire: false,
search_path: None,
statement_timeout_ms: None,
lock_timeout_ms: None,
idle_in_transaction_timeout_ms: None,
application_name: None,
statement_cache_size: None,
reset_on_release: false,
require_utf8_client_encoding: true,
ssl_mode: None,
ssl_root_cert: None,
ssl_client_cert: None,
ssl_client_key: None,
}
}
}
impl DatabaseConfig {
pub fn with_min_connections(mut self, n: u32) -> Self {
self.min_connections = n;
self
}
pub fn with_max_lifetime(mut self, secs: Option<u64>) -> Self {
self.max_lifetime = secs;
self
}
pub fn with_test_before_acquire(mut self, enabled: bool) -> Self {
self.test_before_acquire = enabled;
self
}
pub fn with_search_path(mut self, search_path: impl Into<String>) -> Self {
self.search_path = Some(search_path.into());
self
}
pub fn with_statement_timeout_ms(mut self, timeout_ms: impl Into<Option<u64>>) -> Self {
self.statement_timeout_ms = timeout_ms.into();
self
}
pub fn with_lock_timeout_ms(mut self, timeout_ms: impl Into<Option<u64>>) -> Self {
self.lock_timeout_ms = timeout_ms.into();
self
}
pub fn with_idle_in_transaction_timeout_ms(
mut self,
timeout_ms: impl Into<Option<u64>>,
) -> Self {
self.idle_in_transaction_timeout_ms = timeout_ms.into();
self
}
pub fn with_application_name(mut self, application_name: impl Into<String>) -> Self {
self.application_name = Some(application_name.into());
self
}
pub fn with_statement_cache_size(mut self, capacity: usize) -> Self {
self.statement_cache_size = Some(capacity);
self
}
pub fn with_reset_on_release(mut self, enabled: bool) -> Self {
self.reset_on_release = enabled;
self
}
pub fn with_require_utf8_client_encoding(mut self, enabled: bool) -> Self {
self.require_utf8_client_encoding = enabled;
self
}
pub fn with_ssl_mode(mut self, mode: Option<SslMode>) -> Self {
self.ssl_mode = mode;
self
}
pub fn with_ssl_root_cert(mut self, path: impl Into<PathBuf>) -> Self {
self.ssl_root_cert = Some(path.into());
self
}
pub fn effective_ssl_mode(&self) -> Option<SslMode> {
match self.ssl_mode {
Some(mode) => Some(mode),
None if self.ssl_root_cert.is_some() => Some(SslMode::VerifyCa),
None => None,
}
}
pub fn with_ssl_client_cert(mut self, path: impl Into<PathBuf>) -> Self {
self.ssl_client_cert = Some(path.into());
self
}
pub fn with_ssl_client_key(mut self, path: impl Into<PathBuf>) -> Self {
self.ssl_client_key = Some(path.into());
self
}
pub fn validate(&self) -> std::result::Result<(), DbError> {
if self.max_connections == 0 {
return Err(DbError::InvalidArgument(
"PostgreSQL max_connections 必须大于 0".to_string(),
));
}
if self.min_connections > self.max_connections {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL min_connections({}) 不能大于 max_connections({})",
self.min_connections, self.max_connections
)));
}
if self.connect_timeout == 0 {
return Err(DbError::InvalidArgument(
"PostgreSQL connect_timeout 必须大于 0 秒".to_string(),
));
}
if self.idle_timeout == 0 {
return Err(DbError::InvalidArgument(
"PostgreSQL idle_timeout 必须大于 0 秒".to_string(),
));
}
if self.idle_timeout <= self.connect_timeout {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL idle_timeout({}) 必须大于 connect_timeout({})",
self.idle_timeout, self.connect_timeout
)));
}
if matches!(self.max_lifetime, Some(0)) {
return Err(DbError::InvalidArgument(
"PostgreSQL max_lifetime 为 Some 时必须大于 0 秒".to_string(),
));
}
if let Some(search_path) = &self.search_path {
if search_path.trim().is_empty() {
return Err(DbError::InvalidArgument(
"PostgreSQL search_path 不能为空".to_string(),
));
}
for segment in search_path.split(',') {
let segment = segment.trim();
if segment.is_empty() || crate::sql_types::Identifier::parse(segment).is_err() {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL search_path 片段非法: {segment:?}"
)));
}
}
}
if let Some(application_name) = &self.application_name {
if application_name.is_empty() {
return Err(DbError::InvalidArgument(
"PostgreSQL application_name 不能为空字符串".to_string(),
));
}
if application_name.contains('\0') {
return Err(DbError::InvalidArgument(
"PostgreSQL application_name 不能包含 NUL 字符".to_string(),
));
}
if application_name.len() > MAX_APPLICATION_NAME_BYTES {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL application_name 不能超过 {MAX_APPLICATION_NAME_BYTES} 字节,当前 {} 字节",
application_name.len()
)));
}
}
if let Some(mode) = self.ssl_mode {
if mode.requires_root_cert() && self.ssl_root_cert.is_none() {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL ssl_mode = {mode:?} 必须提供 ssl_root_cert(CA 证书)"
)));
}
if self.ssl_root_cert.is_some()
&& matches!(mode, SslMode::Prefer | SslMode::Require | SslMode::Disable)
{
return Err(DbError::InvalidArgument(format!(
"PostgreSQL ssl_mode = {mode:?} 不能与 ssl_root_cert 同时配置;根证书只适用于 \
VerifyCa/VerifyFull(ssl_mode 为 None 时会自动按 VerifyCa 使用根证书)"
)));
}
if mode == SslMode::Disable
&& (self.ssl_root_cert.is_some()
|| self.ssl_client_cert.is_some()
|| self.ssl_client_key.is_some())
{
return Err(DbError::InvalidArgument(
"PostgreSQL ssl_mode = Disable 时不能配置 TLS 证书".to_string(),
));
}
}
if self.ssl_client_cert.is_some() != self.ssl_client_key.is_some() {
return Err(DbError::InvalidArgument(
"PostgreSQL ssl_client_cert 与 ssl_client_key 必须成对提供".to_string(),
));
}
Ok(())
}
}
pub struct Database {
pool: PgPool,
config: DatabaseConfig,
server_version: OnceCell<i32>,
waiting: Arc<AtomicUsize>,
}
impl Clone for Database {
fn clone(&self) -> Self {
Self {
pool: self.pool.clone(),
config: self.config.clone(),
server_version: OnceCell::new(),
waiting: Arc::clone(&self.waiting),
}
}
}
impl Database {
pub const fn capabilities() -> &'static BackendCapabilities {
&POSTGRES_CAPABILITIES
}
pub async fn connect(url: &str) -> Result<Self, DbError> {
Self::connect_with_config(url, DatabaseConfig::default()).await
}
pub async fn connect_with_config(url: &str, config: DatabaseConfig) -> Result<Self, DbError> {
use sqlx::postgres::PgPoolOptions;
use std::str::FromStr;
use std::time::Duration;
config.validate()?;
let mut options = PgPoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(Duration::from_secs(config.connect_timeout))
.idle_timeout(Duration::from_secs(config.idle_timeout))
.test_before_acquire(config.test_before_acquire);
if let Some(secs) = config.max_lifetime {
options = options.max_lifetime(Duration::from_secs(secs));
}
let mut connect_options =
sqlx::postgres::PgConnectOptions::from_str(url).map_err(|error| {
DbError::ConnectionError(format!("无效的 PostgreSQL 连接串: {error}"))
})?;
if let Some(search_path) = &config.search_path {
let normalized = search_path
.split(',')
.map(str::trim)
.collect::<Vec<_>>()
.join(",");
connect_options = connect_options.options([("search_path", normalized)]);
}
if let Some(mode) = config.effective_ssl_mode() {
connect_options = connect_options.ssl_mode(mode.as_pg_ssl_mode());
}
if let Some(path) = &config.ssl_root_cert {
connect_options = connect_options.ssl_root_cert(path);
}
if let Some(path) = &config.ssl_client_cert {
connect_options = connect_options.ssl_client_cert(path);
}
if let Some(path) = &config.ssl_client_key {
connect_options = connect_options.ssl_client_key(path);
}
if let Some(capacity) = config.statement_cache_size {
connect_options = connect_options.statement_cache_capacity(capacity);
}
let statement_timeout_ms = config.statement_timeout_ms;
let lock_timeout_ms = config.lock_timeout_ms;
let idle_in_transaction_timeout_ms = config.idle_in_transaction_timeout_ms;
let timeout_statements = timeout_statements(
statement_timeout_ms,
lock_timeout_ms,
idle_in_transaction_timeout_ms,
);
let mut session_statements = vec![
"SET TimeZone = 'UTC'".to_string(),
"SET DateStyle = 'ISO, YMD'".to_string(),
"SET IntervalStyle = 'postgres'".to_string(),
"SET extra_float_digits = 3".to_string(),
"SET standard_conforming_strings = on".to_string(),
];
session_statements.extend(timeout_statements);
let session_setup = SessionSetup {
application_name: config.application_name.clone(),
statements: session_statements,
require_utf8_client_encoding: config.require_utf8_client_encoding,
};
let after_connect_setup = session_setup.clone();
options = options.after_connect(move |conn, _meta| {
let setup = after_connect_setup.clone();
Box::pin(async move { setup.apply(conn).await })
});
if config.reset_on_release {
options = options.after_release(|conn, _meta| {
Box::pin(async move {
sqlx::query(DISCARD_ALL_SQL).execute(&mut *conn).await?;
sqlx::Connection::clear_cached_statements(&mut *conn).await?;
Ok(true)
})
});
let before_acquire_setup = session_setup;
options = options.before_acquire(move |conn, _meta| {
let setup = before_acquire_setup.clone();
Box::pin(async move { setup.apply(conn).await.map(|_| true) })
});
}
let pool = options.connect_with(connect_options).await?;
Ok(Self {
pool,
config,
server_version: OnceCell::new(),
waiting: Arc::new(AtomicUsize::new(0)),
})
}
pub fn from_pool(pool: PgPool, config: DatabaseConfig) -> Result<Self, DbError> {
config.validate()?;
Ok(Self {
pool,
config,
server_version: OnceCell::new(),
waiting: Arc::new(AtomicUsize::new(0)),
})
}
pub fn table(&self, table: &crate::TableRef) -> QueryBuilder<'_> {
QueryBuilder::new(&self.pool, table.as_str(), self.config.enable_logging)
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
pub fn pool_status(&self) -> PoolStatus {
PoolStatus {
max_size: self.config.max_connections as usize,
size: self.pool.size() as usize,
available: self.pool.num_idle(),
waiting: self.waiting.load(Ordering::Relaxed),
}
}
fn track_acquire(&self) -> AcquireWaiter<'_> {
let would_wait = self.pool.num_idle() == 0
&& self.pool.size() >= self.pool.options().get_max_connections();
if would_wait {
self.waiting.fetch_add(1, Ordering::Relaxed);
}
AcquireWaiter {
counter: &self.waiting,
armed: would_wait,
}
}
pub(crate) async fn acquire(
&self,
) -> Result<sqlx::pool::PoolConnection<sqlx::Postgres>, DbError> {
let waiter = self.track_acquire();
let conn = self.pool.acquire().await?;
drop(waiter);
Ok(conn)
}
pub async fn health_check(&self) -> Result<bool, DbError> {
let mut conn = self.acquire().await?;
sqlx::query("SELECT 1").execute(&mut *conn).await?;
Ok(true)
}
pub async fn close(&self) {
self.pool.close().await;
}
pub fn is_closed(&self) -> bool {
self.pool.is_closed()
}
#[deprecated(
since = "0.1.0",
note = "使用 query_with_params 替代,避免 SQL 注入风险"
)]
pub async fn query<T>(&self, sql: &str) -> Result<Vec<T>, DbError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
{
if self.config.enable_logging {
log::debug!("执行原生查询: {}", sql);
}
let rows = sqlx::query_as::<_, T>(sql).fetch_all(&self.pool).await?;
Ok(rows)
}
#[deprecated(
since = "0.1.0",
note = "使用 execute_with_params 替代,避免 SQL 注入风险"
)]
pub async fn execute(&self, sql: &str) -> Result<u64, DbError> {
if self.config.enable_logging {
log::debug!("执行原生语句: {}", sql);
}
let result = sqlx::query(sql).execute(&self.pool).await?;
Ok(result.rows_affected())
}
pub async fn transaction(&self) -> Result<Transaction, DbError> {
let waiter = self.track_acquire();
let tx = self.pool.begin().await?;
drop(waiter);
Ok(Transaction::new(tx, self.config.enable_logging))
}
pub async fn transaction_with_isolation(
&self,
isolation: crate::isolation::IsolationLevel,
) -> Result<Transaction, DbError> {
self.transaction_with_options(TransactionOptions::default().with_isolation(isolation))
.await
}
pub async fn transaction_with_options(
&self,
options: TransactionOptions,
) -> Result<Transaction, DbError> {
let waiter = self.track_acquire();
let mut tx = self.pool.begin().await?;
drop(waiter);
if let Some(sql) = options.set_transaction_sql() {
if self.config.enable_logging {
log::debug!("设置 PostgreSQL 事务属性: {}", sql);
}
sqlx::query(&sql).execute(&mut *tx).await?;
}
Ok(Transaction::new(tx, self.config.enable_logging))
}
pub async fn read_only_transaction(&self) -> Result<Transaction, DbError> {
self.transaction_with_options(TransactionOptions::read_only())
.await
}
pub async fn retry_transaction<T, F, Fut>(
&self,
operation: F,
max_attempts: u32,
) -> Result<T, DbError>
where
F: FnMut(Transaction) -> Fut,
Fut: std::future::Future<Output = Result<T, DbError>>,
{
self.retry_transaction_with_options(TransactionOptions::default(), operation, max_attempts)
.await
}
pub async fn retry_transaction_with_options<T, F, Fut>(
&self,
options: TransactionOptions,
mut operation: F,
max_attempts: u32,
) -> Result<T, DbError>
where
F: FnMut(Transaction) -> Fut,
Fut: std::future::Future<Output = Result<T, DbError>>,
{
if max_attempts == 0 {
return Err(DbError::InvalidArgument(
"重试次数 max_attempts 必须大于 0".to_string(),
));
}
let mut attempt = 0u32;
loop {
attempt += 1;
let transaction = self.transaction_with_options(options).await?;
match operation(transaction).await {
Ok(value) => return Ok(value),
Err(error) => {
if !is_serialization_conflict(&error) || attempt >= max_attempts {
return Err(error);
}
let backoff = retry_backoff(attempt);
if self.config.enable_logging {
log::warn!(
"事务序列化冲突(第 {attempt} 次尝试),{:?} 后重试: {error}",
backoff
);
}
tokio::time::sleep(backoff).await;
}
}
}
}
#[deprecated(
since = "0.1.4",
note = "请使用 execute_script(整脚本单事务,正确处理函数/DO 块与 dollar-quote)"
)]
pub async fn init(&self, sql_script: &str) -> Result<(), DbError> {
self.execute_script(sql_script).await.map(|_| ())
}
#[deprecated(
since = "0.2.2",
note = "裸 SQL 建表逃生舱;请使用 execute_script(单事务、可含多条 DDL)或外部迁移工具"
)]
pub async fn create_table(&self, create_sql: &str) -> Result<(), DbError> {
let mut conn = self.acquire().await?;
sqlx::query(create_sql).execute(&mut *conn).await?;
Ok(())
}
pub async fn drop_table(&self, table_name: &crate::TableRef) -> Result<(), DbError> {
let quoted = crate::postgres::identifier::quote_table(table_name.as_str())?;
let sql = format!("DROP TABLE IF EXISTS {}", quoted);
let mut conn = self.acquire().await?;
sqlx::query(&sql).execute(&mut *conn).await?;
Ok(())
}
pub async fn table_exists(&self, table_name: &crate::TableRef) -> Result<bool, DbError> {
let quoted = crate::postgres::identifier::quote_table(table_name.as_str())?;
let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL")
.bind(quoted)
.fetch_one(&self.pool)
.await?;
Ok(exists)
}
pub async fn query_with_params<T>(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<Vec<T>, DbError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
{
if self.config.enable_logging {
log::debug!("执行参数化查询: {}, 参数数量: {}", sql, params.len());
}
let mut conn = self.acquire().await?;
let statement = keyed_sql(sql, json_signature(¶ms));
let mut query = sqlx::query_as::<_, T>(&statement);
for param in ¶ms {
query = bind_json_param_as(query, param);
}
let rows = query.fetch_all(&mut *conn).await?;
Ok(rows)
}
pub async fn execute_with_params(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<u64, DbError> {
if self.config.enable_logging {
log::debug!("执行参数化语句: {}, 参数数量: {}", sql, params.len());
}
let mut conn = self.acquire().await?;
let statement = keyed_sql(sql, json_signature(¶ms));
let mut query = sqlx::query(&statement);
for param in ¶ms {
query = bind_json_param(query, param);
}
let result = query.execute(&mut *conn).await?;
Ok(result.rows_affected())
}
pub async fn stream_query(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<PgRowCursor, DbError> {
self.stream_query_with_batch_size(sql, params, DEFAULT_STREAM_BATCH_SIZE)
.await
}
pub async fn stream_query_with_batch_size(
&self,
sql: &str,
params: Vec<serde_json::Value>,
batch_size: usize,
) -> Result<PgRowCursor, DbError> {
if batch_size == 0 {
return Err(DbError::InvalidArgument(
"流式查询 batch_size 必须大于 0".to_string(),
));
}
let body = normalize_stream_sql(sql)?;
let mut conn = self.acquire().await?;
sqlx::query("BEGIN READ ONLY").execute(&mut *conn).await?;
let cursor_name = next_cursor_name();
let declare = format!("DECLARE {} CURSOR FOR {}", cursor_name, body);
if self.config.enable_logging {
log::debug!("声明流式游标: {}", declare);
}
let keyed_declare = keyed_sql(&declare, json_signature(¶ms));
let mut query = sqlx::query(&keyed_declare);
for param in ¶ms {
query = bind_json_param(query, param);
}
if let Err(error) = query.execute(&mut *conn).await {
let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
return Err(error.into());
}
Ok(PgRowCursor::new(
conn,
cursor_name,
batch_size,
self.config.enable_logging,
))
}
pub async fn advisory_lock(&self, key: i64) -> Result<PgAdvisoryLock, DbError> {
self.acquire_advisory_lock(key, AdvisoryLockMode::Exclusive)
.await
}
pub async fn advisory_lock_shared(&self, key: i64) -> Result<PgAdvisoryLock, DbError> {
self.acquire_advisory_lock(key, AdvisoryLockMode::Shared)
.await
}
pub async fn try_advisory_lock(&self, key: i64) -> Result<Option<PgAdvisoryLock>, DbError> {
self.try_acquire_advisory_lock(key, AdvisoryLockMode::Exclusive)
.await
}
pub async fn try_advisory_lock_shared(
&self,
key: i64,
) -> Result<Option<PgAdvisoryLock>, DbError> {
self.try_acquire_advisory_lock(key, AdvisoryLockMode::Shared)
.await
}
async fn acquire_advisory_lock(
&self,
key: i64,
mode: AdvisoryLockMode,
) -> Result<PgAdvisoryLock, DbError> {
let mut conn = self.acquire().await?;
if self.config.enable_logging {
log::debug!("获取 PG 会话级 advisory lock: key={key}, mode={mode:?}");
}
sqlx::query(mode.lock_sql())
.bind(key)
.execute(&mut *conn)
.await?;
Ok(PgAdvisoryLock {
conn: Some(conn),
key,
mode,
})
}
async fn try_acquire_advisory_lock(
&self,
key: i64,
mode: AdvisoryLockMode,
) -> Result<Option<PgAdvisoryLock>, DbError> {
let mut conn = self.acquire().await?;
let acquired: bool = sqlx::query_scalar(mode.try_lock_sql())
.bind(key)
.fetch_one(&mut *conn)
.await?;
if acquired {
Ok(Some(PgAdvisoryLock {
conn: Some(conn),
key,
mode,
}))
} else {
Ok(None)
}
}
pub async fn server_version_num(&self) -> Result<i32, DbError> {
let version = self
.server_version
.get_or_try_init(|| async {
let mut conn = self.acquire().await?;
let value: i32 =
sqlx::query_scalar("SELECT current_setting('server_version_num')::int")
.fetch_one(&mut *conn)
.await?;
Ok::<i32, DbError>(value)
})
.await?;
Ok(*version)
}
pub async fn supports(&self, min_version: i32) -> Result<bool, DbError> {
Ok(self.server_version_num().await? >= min_version)
}
pub async fn prepare_transaction(
&self,
transaction: Transaction,
gid: &str,
) -> Result<(), DbError> {
transaction.prepare(gid).await
}
pub async fn commit_prepared(&self, gid: &str) -> Result<(), DbError> {
validate_prepared_gid(gid)?;
let sql = format!("COMMIT PREPARED '{gid}'");
if self.config.enable_logging {
log::debug!("提交已准备事务: gid={gid}");
}
let mut conn = self.acquire().await?;
sqlx::query(&sql).execute(&mut *conn).await?;
Ok(())
}
pub async fn rollback_prepared(&self, gid: &str) -> Result<(), DbError> {
validate_prepared_gid(gid)?;
let sql = format!("ROLLBACK PREPARED '{gid}'");
if self.config.enable_logging {
log::debug!("回滚已准备事务: gid={gid}");
}
let mut conn = self.acquire().await?;
sqlx::query(&sql).execute(&mut *conn).await?;
Ok(())
}
pub async fn explain(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<Vec<String>, DbError> {
let statement = explain_statement(sql)?;
let keyed_statement = keyed_sql(&statement, json_signature(¶ms));
if self.config.enable_logging {
log::debug!("执行 EXPLAIN: {}, 参数数量: {}", statement, params.len());
}
let mut query = sqlx::query_as::<_, (serde_json::Value,)>(&keyed_statement);
for param in ¶ms {
query = bind_json_param_as(query, param);
}
let mut conn = self.acquire().await?;
let rows = query.fetch_all(&mut *conn).await?;
explain_rows_to_strings(rows)
}
pub async fn active_queries(&self) -> Result<Vec<ActiveQuery>, DbError> {
let mut conn = self.acquire().await?;
let rows = sqlx::query_as::<_, ActiveQuery>(
"SELECT pid,
usename::text AS usename,
application_name,
host(client_addr) AS client_addr,
state,
wait_event_type,
wait_event,
query_start,
query
FROM pg_stat_activity
ORDER BY query_start DESC NULLS LAST, pid",
)
.fetch_all(&mut *conn)
.await?;
Ok(rows)
}
pub async fn lock_waits(&self) -> Result<Vec<LockWait>, DbError> {
let mut conn = self.acquire().await?;
let rows = sqlx::query_as::<_, LockWait>(
"SELECT blocked.pid AS blocked_pid,
blocking.pid AS blocking_pid,
blocked.query AS blocked_query,
blocking.query AS blocking_query,
CASE
WHEN l.relation IS NULL OR l.relation = 0 THEN NULL
ELSE l.relation::regclass::text
END AS relation,
l.locktype AS lock_type,
l.mode AS mode,
blocked.wait_event AS wait_event
FROM pg_locks l
JOIN pg_stat_activity blocked ON blocked.pid = l.pid
CROSS JOIN LATERAL unnest(pg_blocking_pids(l.pid)) AS bp(blocking_pid)
JOIN pg_stat_activity blocking ON blocking.pid = bp.blocking_pid
WHERE NOT l.granted
ORDER BY blocked.pid, blocking.pid",
)
.fetch_all(&mut *conn)
.await?;
Ok(rows)
}
pub async fn acquire_with_cancel_token(
&self,
) -> Result<(sqlx::pool::PoolConnection<sqlx::Postgres>, CancelToken), DbError> {
if self.config.max_connections < 2 {
return Err(DbError::InvalidArgument(format!(
"PostgreSQL 取消令牌需要至少 2 条连接(取消要另借一条连接),当前 \
max_connections = {}",
self.config.max_connections
)));
}
let mut conn = self.acquire().await?;
let backend_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&mut *conn)
.await?;
let token = CancelToken {
pool: self.pool.clone(),
backend_pid,
};
Ok((conn, token))
}
pub async fn reset_connection(&self) -> Result<(), DbError> {
let mut conn = self.acquire().await?;
sqlx::query(DISCARD_ALL_SQL).execute(&mut *conn).await?;
sqlx::Connection::clear_cached_statements(&mut *conn).await?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct CancelToken {
pool: PgPool,
backend_pid: i32,
}
impl CancelToken {
pub fn backend_pid(&self) -> i32 {
self.backend_pid
}
pub async fn cancel(&self) -> Result<bool, DbError> {
Ok(sqlx::query_scalar(CANCEL_BACKEND_SQL)
.bind(self.backend_pid)
.fetch_one(&self.pool)
.await?)
}
pub async fn terminate(&self) -> Result<bool, DbError> {
Ok(sqlx::query_scalar(TERMINATE_BACKEND_SQL)
.bind(self.backend_pid)
.fetch_one(&self.pool)
.await?)
}
}
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct ActiveQuery {
pub pid: i32,
pub usename: Option<String>,
pub application_name: Option<String>,
pub client_addr: Option<String>,
pub state: Option<String>,
pub wait_event_type: Option<String>,
pub wait_event: Option<String>,
pub query_start: Option<chrono::DateTime<chrono::Utc>>,
pub query: String,
}
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct LockWait {
pub blocked_pid: i32,
pub blocking_pid: i32,
pub blocked_query: Option<String>,
pub blocking_query: Option<String>,
pub relation: Option<String>,
pub lock_type: Option<String>,
pub mode: Option<String>,
pub wait_event: Option<String>,
}
fn explain_statement(sql: &str) -> Result<String, DbError> {
let trimmed = sql.trim().trim_end_matches(';').trim_end();
if trimmed.is_empty() {
return Err(DbError::InvalidArgument(
"EXPLAIN 的 SQL 不能为空".to_string(),
));
}
Ok(format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {trimmed}"))
}
fn explain_rows_to_strings(rows: Vec<(serde_json::Value,)>) -> Result<Vec<String>, DbError> {
let mut plans = Vec::new();
for (row,) in rows {
let items = match row {
serde_json::Value::Array(items) => items,
other => vec![other],
};
for item in items {
plans.push(serde_json::to_string_pretty(&item).map_err(|error| {
DbError::SerializationError(format!("EXPLAIN 计划序列化失败: {error}"))
})?);
}
}
Ok(plans)
}
fn timeout_statements(
statement_timeout_ms: Option<u64>,
lock_timeout_ms: Option<u64>,
idle_in_transaction_timeout_ms: Option<u64>,
) -> Vec<String> {
let mut statements = Vec::new();
if let Some(ms) = statement_timeout_ms {
statements.push(format!("SET statement_timeout = {ms}"));
}
if let Some(ms) = lock_timeout_ms {
statements.push(format!("SET lock_timeout = {ms}"));
}
if let Some(ms) = idle_in_transaction_timeout_ms {
statements.push(format!("SET idle_in_transaction_session_timeout = {ms}"));
}
statements
}
fn is_serialization_conflict(error: &DbError) -> bool {
matches!(error.sqlstate(), Some("40001") | Some("40P01"))
}
fn retry_backoff(attempt: u32) -> std::time::Duration {
let exponent = attempt.saturating_sub(1).min(7);
std::time::Duration::from_millis((10u64 << exponent).min(1_000))
}
struct AcquireWaiter<'a> {
counter: &'a AtomicUsize,
armed: bool,
}
impl Drop for AcquireWaiter<'_> {
fn drop(&mut self) {
if self.armed {
self.counter.fetch_sub(1, Ordering::Relaxed);
}
}
}
#[derive(Debug, Clone)]
struct SessionSetup {
application_name: Option<String>,
statements: Vec<String>,
require_utf8_client_encoding: bool,
}
impl SessionSetup {
async fn apply(&self, conn: &mut sqlx::PgConnection) -> Result<(), sqlx::Error> {
if let Some(application_name) = &self.application_name {
sqlx::query("SELECT set_config('application_name', $1, false)")
.bind(application_name)
.execute(&mut *conn)
.await?;
}
for sql in &self.statements {
sqlx::query(sql).execute(&mut *conn).await?;
}
if self.require_utf8_client_encoding {
let encoding: String = sqlx::query_scalar("SELECT current_setting('client_encoding')")
.fetch_one(&mut *conn)
.await?;
if !client_encoding_is_utf8(&encoding) {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL client_encoding 必须为 UTF8,当前为 {encoding:?};\
如确需其他编码请设置 DatabaseConfig::with_require_utf8_client_encoding(false)"
)
.into(),
));
}
}
Ok(())
}
}
fn client_encoding_is_utf8(encoding: &str) -> bool {
matches!(
encoding.trim().to_ascii_uppercase().as_str(),
"UTF8" | "UTF-8" | "UNICODE"
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AdvisoryLockMode {
Exclusive,
Shared,
}
impl AdvisoryLockMode {
fn lock_sql(self) -> &'static str {
match self {
Self::Exclusive => "SELECT pg_advisory_lock($1)",
Self::Shared => "SELECT pg_advisory_lock_shared($1)",
}
}
fn try_lock_sql(self) -> &'static str {
match self {
Self::Exclusive => "SELECT pg_try_advisory_lock($1)",
Self::Shared => "SELECT pg_try_advisory_lock_shared($1)",
}
}
fn unlock_sql(self) -> &'static str {
match self {
Self::Exclusive => "SELECT pg_advisory_unlock($1)",
Self::Shared => "SELECT pg_advisory_unlock_shared($1)",
}
}
}
pub struct PgAdvisoryLock {
conn: Option<sqlx::pool::PoolConnection<sqlx::Postgres>>,
key: i64,
mode: AdvisoryLockMode,
}
impl PgAdvisoryLock {
pub fn key(&self) -> i64 {
self.key
}
pub fn is_shared(&self) -> bool {
self.mode == AdvisoryLockMode::Shared
}
pub async fn unlock(mut self) -> Result<bool, DbError> {
let mode = self.mode;
let conn = self
.conn
.as_mut()
.ok_or_else(|| DbError::TransactionError("advisory lock 已释放".to_string()))?;
let unlocked: bool = sqlx::query_scalar(mode.unlock_sql())
.bind(self.key)
.fetch_one(&mut **conn)
.await?;
if unlocked {
self.conn.take();
} else {
if let Some(conn) = self.conn.take() {
let _ = conn.detach();
}
}
Ok(unlocked)
}
pub async fn advisory_unlock(self) -> Result<bool, DbError> {
self.unlock().await
}
}
impl Drop for PgAdvisoryLock {
fn drop(&mut self) {
if let Some(conn) = self.conn.take() {
log::warn!(
"PG 会话级 advisory lock({}) 未显式 unlock 即被丢弃;关闭连接以让服务端回收锁",
self.key
);
let _ = conn.detach();
}
}
}
pub struct PgRowCursor {
conn: Option<sqlx::pool::PoolConnection<sqlx::Postgres>>,
cursor_name: String,
batch_size: usize,
buffer: VecDeque<sqlx::postgres::PgRow>,
exhausted: bool,
closed: bool,
enable_logging: bool,
}
impl PgRowCursor {
fn new(
conn: sqlx::pool::PoolConnection<sqlx::Postgres>,
cursor_name: String,
batch_size: usize,
enable_logging: bool,
) -> Self {
Self {
conn: Some(conn),
cursor_name,
batch_size,
buffer: VecDeque::with_capacity(batch_size.min(1024)),
exhausted: false,
closed: false,
enable_logging,
}
}
pub fn batch_size(&self) -> usize {
self.batch_size
}
pub async fn next(&mut self) -> Result<Option<sqlx::postgres::PgRow>, DbError> {
loop {
if let Some(row) = self.buffer.pop_front() {
return Ok(Some(row));
}
if self.exhausted {
self.release().await?;
return Ok(None);
}
self.fetch_batch().await?;
}
}
pub async fn close(mut self) -> Result<(), DbError> {
self.buffer.clear();
self.release().await
}
async fn fetch_batch(&mut self) -> Result<(), DbError> {
let conn = self
.conn
.as_mut()
.ok_or_else(|| DbError::TransactionError("流式游标已关闭".to_string()))?;
let sql = format!(
"FETCH FORWARD {} FROM {}",
self.batch_size, self.cursor_name
);
if self.enable_logging {
log::debug!("游标拉取: {}", sql);
}
let rows = sqlx::query(&sql).fetch_all(&mut **conn).await?;
if rows.len() < self.batch_size {
self.exhausted = true;
}
self.buffer.extend(rows);
Ok(())
}
async fn release(&mut self) -> Result<(), DbError> {
if self.closed {
return Ok(());
}
self.closed = true;
self.exhausted = true;
if let Some(mut conn) = self.conn.take() {
let close_sql = format!("CLOSE {}", self.cursor_name);
let close_ok = sqlx::query(&close_sql).execute(&mut *conn).await.is_ok();
let rollback_ok = sqlx::query("ROLLBACK").execute(&mut *conn).await.is_ok();
if !(close_ok && rollback_ok) {
let _ = conn.detach();
return Err(DbError::TransactionError(
"流式游标关闭失败,连接已丢弃".to_string(),
));
}
}
Ok(())
}
}
impl Drop for PgRowCursor {
fn drop(&mut self) {
if let Some(conn) = self.conn.take() {
let _ = conn.detach();
}
}
}
macro_rules! bind_json_value {
($query:expr, $param:expr) => {
match $param {
serde_json::Value::String(s) => $query.bind(s.clone()),
serde_json::Value::Number(n) => match crate::json_param::classify_json_number(n) {
Some(crate::json_param::JsonNumber::Int(i)) => $query.bind(i),
Some(crate::json_param::JsonNumber::Uint(u)) => $query.bind(u.to_string()),
Some(crate::json_param::JsonNumber::Float(f)) => $query.bind(f),
None => $query.bind(PgUntypedNull),
},
serde_json::Value::Bool(b) => $query.bind(*b),
serde_json::Value::Null => $query.bind(PgUntypedNull),
other => $query.bind(other.clone()),
}
};
}
fn bind_json_param_as<'q, T>(
query: sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>,
param: &serde_json::Value,
) -> sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>
where
T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
bind_json_value!(query, param)
}
fn bind_json_param<'q>(
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
param: &serde_json::Value,
) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
bind_json_value!(query, param)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn test_database_config_validate_accepts_default_config() {
let config = DatabaseConfig::default();
assert!(config.validate().is_ok());
}
#[test]
fn test_database_config_validate_rejects_invalid_pool_size() {
assert!(matches!(
DatabaseConfig {
max_connections: 0,
..DatabaseConfig::default()
}
.validate(),
Err(DbError::InvalidArgument(_))
));
assert!(matches!(
DatabaseConfig {
max_connections: 2,
min_connections: 3,
..DatabaseConfig::default()
}
.validate(),
Err(DbError::InvalidArgument(_))
));
}
#[test]
fn test_database_config_validate_rejects_invalid_timeouts() {
for config in [
DatabaseConfig {
connect_timeout: 0,
..DatabaseConfig::default()
},
DatabaseConfig {
idle_timeout: 0,
..DatabaseConfig::default()
},
DatabaseConfig {
max_lifetime: Some(0),
..DatabaseConfig::default()
},
] {
assert!(matches!(
config.validate(),
Err(DbError::InvalidArgument(_))
));
}
assert!(matches!(
DatabaseConfig {
connect_timeout: 30,
idle_timeout: 30,
..DatabaseConfig::default()
}
.validate(),
Err(DbError::InvalidArgument(_))
));
}
#[tokio::test]
async fn test_connect_with_config_rejects_invalid_config_before_connecting() {
let config = DatabaseConfig {
max_connections: 0,
..DatabaseConfig::default()
};
let result =
Database::connect_with_config("postgres://postgres:bad@127.0.0.1:1/test", config).await;
assert!(matches!(result, Err(DbError::InvalidArgument(_))));
}
#[test]
fn test_search_path_validation_accepts_identifier_lists_only() {
assert!(DatabaseConfig::default().search_path.is_none());
let config = DatabaseConfig::default().with_search_path("app, public");
assert_eq!(config.search_path.as_deref(), Some("app, public"));
assert!(config.validate().is_ok());
for invalid in [
"",
" ",
"app,,public",
"app; DROP SCHEMA public",
"app public",
] {
let config = DatabaseConfig::default().with_search_path(invalid);
assert!(
matches!(config.validate(), Err(DbError::InvalidArgument(_))),
"search_path 应拒绝 {invalid:?}"
);
}
}
#[tokio::test]
async fn health_check_propagates_closed_pool_error() -> Result<(), sqlx::Error> {
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")?;
let db = Database {
pool,
config: DatabaseConfig::default(),
server_version: OnceCell::new(),
waiting: Arc::new(AtomicUsize::new(0)),
};
db.close().await;
assert!(db.is_closed());
assert!(matches!(db.health_check().await, Err(DbError::PoolClosed)));
Ok(())
}
#[test]
fn timeout_config_is_opt_in_and_renders_set_statements() {
let default_config = DatabaseConfig::default();
assert!(default_config.statement_timeout_ms.is_none());
assert!(default_config.lock_timeout_ms.is_none());
assert!(default_config.idle_in_transaction_timeout_ms.is_none());
assert!(timeout_statements(None, None, None).is_empty());
let config = DatabaseConfig::default()
.with_statement_timeout_ms(5_000u64)
.with_lock_timeout_ms(Some(250))
.with_idle_in_transaction_timeout_ms(30_000u64);
assert_eq!(config.statement_timeout_ms, Some(5_000));
assert_eq!(config.lock_timeout_ms, Some(250));
assert_eq!(config.idle_in_transaction_timeout_ms, Some(30_000));
assert!(config.validate().is_ok());
assert_eq!(
timeout_statements(
config.statement_timeout_ms,
config.lock_timeout_ms,
config.idle_in_transaction_timeout_ms
),
vec![
"SET statement_timeout = 5000".to_string(),
"SET lock_timeout = 250".to_string(),
"SET idle_in_transaction_session_timeout = 30000".to_string(),
]
);
}
#[test]
fn only_serialization_failures_and_deadlocks_are_retried() {
use crate::error::SqlErrorInfo;
assert!(is_serialization_conflict(&DbError::DatabaseError(
Box::new(SqlErrorInfo::new("40001", "could not serialize access"))
)));
assert!(is_serialization_conflict(&DbError::DatabaseError(
Box::new(SqlErrorInfo::new("40P01", "deadlock detected"))
)));
for other in ["23505", "57014", "55P03", "42P01"] {
assert!(
!is_serialization_conflict(&DbError::DatabaseError(Box::new(SqlErrorInfo::new(
other, "other"
)))),
"SQLSTATE {other} 不应触发事务重试"
);
}
assert!(!is_serialization_conflict(&DbError::TransactionError(
"local".to_string()
)));
}
#[test]
fn retry_backoff_grows_exponentially_and_caps() {
use std::time::Duration;
assert_eq!(retry_backoff(1), Duration::from_millis(10));
assert_eq!(retry_backoff(2), Duration::from_millis(20));
assert_eq!(retry_backoff(3), Duration::from_millis(40));
assert_eq!(retry_backoff(7), Duration::from_millis(640));
assert_eq!(retry_backoff(8), Duration::from_millis(1_000));
assert_eq!(retry_backoff(100), Duration::from_millis(1_000));
}
#[test]
fn explain_statement_prefixes_trusted_sql_and_rejects_empty() {
assert_eq!(
explain_statement("SELECT $1::int + 1").unwrap(),
"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT $1::int + 1"
);
assert_eq!(
explain_statement(" SELECT 1; ").unwrap(),
"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT 1"
);
for invalid in ["", " ", " ; "] {
assert!(matches!(
explain_statement(invalid),
Err(DbError::InvalidArgument(_))
));
}
}
#[test]
fn explain_rows_are_flattened_to_pretty_json_per_plan() {
let rows = vec![
(serde_json::json!([
{"Plan": {"Node Type": "Result"}, "Execution Time": 0.1}
]),),
(serde_json::json!([{"Plan": {"Node Type": "Seq Scan"}}]),),
];
let plans = explain_rows_to_strings(rows).unwrap();
assert_eq!(plans.len(), 2);
for plan in &plans {
let parsed: serde_json::Value = serde_json::from_str(plan).unwrap();
assert!(parsed.get("Plan").is_some(), "计划文本应可解析为 JSON");
}
assert!(plans[0].contains("\"Node Type\": \"Result\""));
let plans = explain_rows_to_strings(vec![(serde_json::json!({"Plan": {}}),)]).unwrap();
assert_eq!(plans.len(), 1);
assert!(plans[0].contains("Plan"));
}
#[tokio::test]
async fn acquire_with_cancel_token_requires_at_least_two_connections() {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")
.unwrap();
let db = Database {
pool,
config: DatabaseConfig {
max_connections: 1,
..DatabaseConfig::default()
},
server_version: OnceCell::new(),
waiting: Arc::new(AtomicUsize::new(0)),
};
assert!(matches!(
db.acquire_with_cancel_token().await,
Err(DbError::InvalidArgument(_))
));
}
#[test]
fn cancel_token_sql_and_57014_mapping() {
use crate::error::{DbErrorCategory, SqlErrorInfo};
assert_eq!(CANCEL_BACKEND_SQL, "SELECT pg_cancel_backend($1)");
assert_eq!(TERMINATE_BACKEND_SQL, "SELECT pg_terminate_backend($1)");
assert!(CANCEL_BACKEND_SQL.contains("$1"));
assert!(TERMINATE_BACKEND_SQL.contains("$1"));
let canceled = DbError::DatabaseError(Box::new(SqlErrorInfo::new(
"57014",
"canceling statement due to user request",
)));
assert_eq!(canceled.sqlstate(), Some("57014"));
assert_eq!(canceled.category(), DbErrorCategory::Timeout);
assert!(!canceled.is_retryable());
}
#[test]
fn advisory_lock_sql_covers_shared_and_exclusive() {
assert_eq!(
AdvisoryLockMode::Exclusive.lock_sql(),
"SELECT pg_advisory_lock($1)"
);
assert_eq!(
AdvisoryLockMode::Shared.lock_sql(),
"SELECT pg_advisory_lock_shared($1)"
);
assert_eq!(
AdvisoryLockMode::Exclusive.try_lock_sql(),
"SELECT pg_try_advisory_lock($1)"
);
assert_eq!(
AdvisoryLockMode::Shared.try_lock_sql(),
"SELECT pg_try_advisory_lock_shared($1)"
);
assert_eq!(
AdvisoryLockMode::Exclusive.unlock_sql(),
"SELECT pg_advisory_unlock($1)"
);
assert_eq!(
AdvisoryLockMode::Shared.unlock_sql(),
"SELECT pg_advisory_unlock_shared($1)"
);
}
#[tokio::test]
#[ignore = "需要真实 PostgreSQL 实例"]
async fn advisory_unlock_false_detaches_instead_of_returning_connection() {
let url = std::env::var("PG_TEST_URL")
.unwrap_or_else(|_| "postgres://postgres:postgres@127.0.0.1:55432/test".to_string());
let db = Database::connect(&url).await.expect("PG 必须可连接");
let conn = db.acquire().await.expect("借出连接应成功");
assert_eq!(db.pool.size(), 1);
let lock = PgAdvisoryLock {
conn: Some(conn),
key: 987_654_321,
mode: AdvisoryLockMode::Exclusive,
};
assert!(!lock.unlock().await.expect("解锁调用应成功"));
assert_eq!(
db.pool.size(),
0,
"unlock 返回 false 时必须 detach 关闭会话,而不是把连接还池"
);
}
#[test]
fn runtime_config_defaults_and_setters() {
let default = DatabaseConfig::default();
assert!(default.application_name.is_none());
assert!(default.statement_cache_size.is_none());
assert!(!default.reset_on_release);
assert!(default.require_utf8_client_encoding);
assert!(default.ssl_mode.is_none());
let config = DatabaseConfig::default()
.with_application_name("yang-test")
.with_statement_cache_size(0)
.with_reset_on_release(true)
.with_require_utf8_client_encoding(false);
assert_eq!(config.application_name.as_deref(), Some("yang-test"));
assert_eq!(config.statement_cache_size, Some(0));
assert!(config.reset_on_release);
assert!(!config.require_utf8_client_encoding);
assert!(config.validate().is_ok());
assert_eq!(DISCARD_ALL_SQL, "DISCARD ALL");
}
#[test]
fn application_name_is_validated() {
for invalid in [String::new(), "a\0b".to_string(), "a".repeat(64)] {
let config = DatabaseConfig::default().with_application_name(invalid.clone());
assert!(
matches!(config.validate(), Err(DbError::InvalidArgument(_))),
"application_name 应拒绝 {invalid:?}"
);
}
let config = DatabaseConfig::default().with_application_name("a".repeat(63));
assert!(config.validate().is_ok());
}
#[test]
fn ssl_config_validation_and_mode_mapping() {
assert!(matches!(
SslMode::Disable.as_pg_ssl_mode(),
PgSslMode::Disable
));
assert!(matches!(
SslMode::Prefer.as_pg_ssl_mode(),
PgSslMode::Prefer
));
assert!(matches!(
SslMode::Require.as_pg_ssl_mode(),
PgSslMode::Require
));
assert!(matches!(
SslMode::VerifyCa.as_pg_ssl_mode(),
PgSslMode::VerifyCa
));
assert!(matches!(
SslMode::VerifyFull.as_pg_ssl_mode(),
PgSslMode::VerifyFull
));
for mode in [SslMode::VerifyCa, SslMode::VerifyFull] {
let missing = DatabaseConfig::default().with_ssl_mode(Some(mode));
assert!(
matches!(missing.validate(), Err(DbError::InvalidArgument(_))),
"{mode:?} 缺 ssl_root_cert 应报错"
);
let with_root = DatabaseConfig::default()
.with_ssl_mode(Some(mode))
.with_ssl_root_cert("/etc/ssl/root.pem");
assert!(with_root.validate().is_ok());
}
assert!(matches!(
DatabaseConfig::default()
.with_ssl_mode(Some(SslMode::Disable))
.with_ssl_root_cert("/etc/ssl/root.pem")
.validate(),
Err(DbError::InvalidArgument(_))
));
assert!(matches!(
DatabaseConfig::default()
.with_ssl_mode(Some(SslMode::Require))
.with_ssl_client_cert("/etc/ssl/client.pem")
.validate(),
Err(DbError::InvalidArgument(_))
));
assert!(DatabaseConfig::default()
.with_ssl_mode(Some(SslMode::Require))
.with_ssl_client_cert("/etc/ssl/client.pem")
.with_ssl_client_key("/etc/ssl/client.key")
.validate()
.is_ok());
assert!(DatabaseConfig::default().effective_ssl_mode().is_none());
assert_eq!(
DatabaseConfig::default()
.with_ssl_root_cert("/etc/ssl/root.pem")
.effective_ssl_mode(),
Some(SslMode::VerifyCa)
);
for mode in [
SslMode::Disable,
SslMode::Prefer,
SslMode::Require,
SslMode::VerifyCa,
SslMode::VerifyFull,
] {
assert_eq!(
DatabaseConfig::default()
.with_ssl_mode(Some(mode))
.effective_ssl_mode(),
Some(mode)
);
}
assert!(DatabaseConfig::default()
.with_ssl_root_cert("/etc/ssl/root.pem")
.validate()
.is_ok());
for mode in [SslMode::Prefer, SslMode::Require] {
assert!(
matches!(
DatabaseConfig::default()
.with_ssl_mode(Some(mode))
.with_ssl_root_cert("/etc/ssl/root.pem")
.validate(),
Err(DbError::InvalidArgument(_))
),
"{mode:?} + ssl_root_cert 应报错(根证书不会被该校验模式使用)"
);
}
}
#[test]
fn client_encoding_must_be_utf8() {
for ok in ["UTF8", "utf8", "Utf-8", "UNICODE", " UTF8 "] {
assert!(client_encoding_is_utf8(ok), "{ok:?} 应视为 UTF8");
}
for bad in ["SQL_ASCII", "LATIN1", "WIN1252", "EUC_JP", ""] {
assert!(!client_encoding_is_utf8(bad), "{bad:?} 不应视为 UTF8");
}
}
#[tokio::test]
async fn waiting_counter_is_raii_and_reflected_in_pool_status() -> Result<(), sqlx::Error> {
let counter = AtomicUsize::new(0);
{
counter.fetch_add(1, Ordering::Relaxed);
let _waiter = AcquireWaiter {
counter: &counter,
armed: true,
};
assert_eq!(counter.load(Ordering::Relaxed), 1);
}
assert_eq!(counter.load(Ordering::Relaxed), 0);
{
let _waiter = AcquireWaiter {
counter: &counter,
armed: false,
};
}
assert_eq!(counter.load(Ordering::Relaxed), 0);
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://postgres:test@127.0.0.1:5432/test")?;
let db = Database {
pool,
config: DatabaseConfig::default(),
server_version: OnceCell::new(),
waiting: Arc::new(AtomicUsize::new(3)),
};
assert_eq!(db.pool_status().waiting, 3);
Ok(())
}
}