Skip to main content

DatabaseConfig

Struct DatabaseConfig 

Source
#[non_exhaustive]
pub struct DatabaseConfig {
Show 19 fields 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>,
}
Expand description

数据库配置

用于配置数据库连接池的参数

标注 #[non_exhaustive]:未来新增连接池参数不构成破坏性变更,外部请用 DatabaseConfig::default() 加 ..Default::default() 或链式 setter 构造。

§示例

use yang_db::postgres::DatabaseConfig;

// 使用默认配置
let config = DatabaseConfig::default();

// 自定义配置:#[non_exhaustive] 结构体跨 crate 不能用字面量,
// 用 default() + 链式 setter 构造
let config = DatabaseConfig::default()
    .with_min_connections(2)
    .with_max_lifetime(Some(1800))
    .with_test_before_acquire(true);

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§max_connections: u32

最大连接数

§connect_timeout: u64

连接超时时间(秒)

§idle_timeout: u64

空闲连接超时时间(秒)

§enable_logging: bool

是否启用日志

§min_connections: u32

最小(保活)连接数。默认 0(行为同改造前)。

§max_lifetime: Option<u64>

连接最大存活时间(秒)。None(默认)表示不限制,行为同改造前。

§test_before_acquire: bool

借出前是否 PING 探活。默认 false(行为同改造前)。

§search_path: Option<String>

连接建立时的 search_path(逗号分隔的 schema 列表,如 "app,public")。

设置为 Some 后,连接参数会追加 -c search_path=<值>;未设置时使用 服务端默认值。值在 Self::validate 中逐段校验,拒绝任意连接参数注入。

§statement_timeout_ms: Option<u64>

单条语句超时(毫秒)。None(默认)不设置,沿用服务端默认。

连接建立后执行 SET statement_timeout = <ms>。超时被服务端取消时返回 SQLSTATE 57014(crate::SqlErrorKind::QueryCanceled)。0 表示禁用超时。

注意:该设置通过连接池的 after_connect 钩子下发,只对 Database::connect_with_config 建立的连接生效;Database::from_pool 的既有连接需调用方自行设置。

§lock_timeout_ms: Option<u64>

锁等待超时(毫秒)。None(默认)不设置。超时返回 SQLSTATE 55P03 (crate::SqlErrorKind::LockNotAvailable)。0 表示禁用超时。

下发方式同 Self::statement_timeout_ms。

§idle_in_transaction_timeout_ms: Option<u64>

事务空闲超时(毫秒)。None(默认)不设置:事务开启后闲置超过该时长会被 服务端终止。0 表示禁用超时。

下发方式同 Self::statement_timeout_ms。

§application_name: Option<String>

连接建立时写入的 application_name(出现在 pg_stat_activity 中)。

通过 after_connect 钩子的 set_config('application_name', $1, false) 应用,值走绑定参数;最长 63 字节(服务端 NAMEDATALEN - 1)。

§statement_cache_size: Option<usize>

预编译语句缓存容量;None(默认)沿用 sqlx 默认值(100)。

经 PgBouncer 等事务级连接池时设为 Some(0) 关闭语句缓存,避免服务端 prepared statement 与连接绑定不一致。

§reset_on_release: bool

连接归还池前是否执行 DISCARD ALL。默认 false。

开启后由 after_release 钩子下发,清理 search_path/LISTEN/临时表/ prepared statement/advisory lock 等会话状态;同时在 before_acquire 钩子 重新应用本配置的会话 GUC(DISCARD ALL 中的 RESET ALL 会清掉它们)。

§require_utf8_client_encoding: bool

连接建立后是否校验收到的 client_encoding 为 UTF8。默认 true(fail-closed)。

非 UTF8(如 SQL_ASCII/LATIN1)会返回连接/配置错误,避免把非 UTF-8 字节当成 Rust String。

§ssl_mode: Option<SslMode>

TLS 模式;None(默认)沿用连接串中的 sslmode,若连接串也没写则 sqlx 默认 Prefer,可能回退到明文连接。

配置了 Self::ssl_root_cert 时,None 会被推导为 VerifyCa(见 Self::effective_ssl_mode),避免根证书被静默忽略;此时显式设置 Prefer/Require/Disable 会与根证书冲突并在 Self::validate 中报错。

§ssl_root_cert: Option<PathBuf>

根证书(CA)PEM 文件路径;VerifyCa/VerifyFull 必填。

只在 ssl_mode 为 None(自动推导为 VerifyCa)、VerifyCa 或 VerifyFull 时允许配置。

§ssl_client_cert: Option<PathBuf>

客户端证书 PEM 文件路径;与 Self::ssl_client_key 成对出现。

§ssl_client_key: Option<PathBuf>

客户端私钥 PEM 文件路径;与 Self::ssl_client_cert 成对出现。

Implementations§

Source§

impl DatabaseConfig

Source

pub fn with_min_connections(self, n: u32) -> Self

设置最小(保活)连接数(链式)。

Source

pub fn with_max_lifetime(self, secs: Option<u64>) -> Self

设置连接最大存活时间(秒,None 为不限制)(链式)。

Source

pub fn with_test_before_acquire(self, enabled: bool) -> Self

设置借出前是否 PING 探活(链式)。

Source

pub fn with_search_path(self, search_path: impl Into<String>) -> Self

设置连接建立时的 search_path(链式)。

值为逗号分隔的 schema 列表,例如 "app,public";每段都会在 Self::validate 中按严格标识符校验。

Source

pub fn with_statement_timeout_ms( self, timeout_ms: impl Into<Option<u64>>, ) -> Self

设置单条语句超时(毫秒,链式)。None 或 0 表示不限制。

Source

pub fn with_lock_timeout_ms(self, timeout_ms: impl Into<Option<u64>>) -> Self

设置锁等待超时(毫秒,链式)。None 或 0 表示不限制。

Source

pub fn with_idle_in_transaction_timeout_ms( self, timeout_ms: impl Into<Option<u64>>, ) -> Self

设置事务空闲超时(毫秒,链式)。None 或 0 表示不限制。

Source

pub fn with_application_name(self, application_name: impl Into<String>) -> Self

设置 application_name(链式)。None 表示不设置。

Source

pub fn with_statement_cache_size(self, capacity: usize) -> Self

设置预编译语句缓存容量(链式);Some(0) 关闭缓存(PgBouncer 事务池)。

Source

pub fn with_reset_on_release(self, enabled: bool) -> Self

设置连接归还前是否执行 DISCARD ALL(链式,默认关闭)。

Source

pub fn with_require_utf8_client_encoding(self, enabled: bool) -> Self

设置是否强制 client_encoding 为 UTF8(链式,默认开启)。

Source

pub fn with_ssl_mode(self, mode: Option<SslMode>) -> Self

设置 TLS 模式(链式);None 沿用连接串中的 sslmode。

Source

pub fn with_ssl_root_cert(self, path: impl Into<PathBuf>) -> Self

设置根证书 PEM 路径(链式)。

Source

pub fn effective_ssl_mode(&self) -> Option<SslMode>

实际生效的 TLS 模式。

  • ssl_mode = Some(m):原样返回 Some(m);
  • ssl_mode = None 且配置了 Self::ssl_root_cert:返回 Some(SslMode::VerifyCa),避免根证书被静默忽略;
  • 其余情况返回 None,沿用连接串中的 sslmode(连接串也没写时 sqlx 默认 Prefer,可能回退到明文)。
Source

pub fn with_ssl_client_cert(self, path: impl Into<PathBuf>) -> Self

设置客户端证书 PEM 路径(链式);需同时设置 Self::with_ssl_client_key。

Source

pub fn with_ssl_client_key(self, path: impl Into<PathBuf>) -> Self

设置客户端私钥 PEM 路径(链式);需同时设置 Self::with_ssl_client_cert。

Source

pub fn validate(&self) -> Result<(), DbError>

校验数据库连接池配置是否适合生产运行。

Builder 方法保持纯赋值以兼容历史调用;真正建池前由连接入口显式校验,避免将明显 非法的配置下推给 sqlx 后才在运行时失败。

Trait Implementations§

Source§

impl Clone for DatabaseConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DatabaseConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DatabaseConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more