Skip to main content

DbPool

Struct DbPool 

Source
pub struct DbPool { /* private fields */ }
Expand description

连接池管理器

Implementations§

Source§

impl DbPool

Source

pub async fn new(url: &str) -> DbResult<Self>

创建新的连接池

§Arguments
  • url - 数据库连接 URL
§Errors

如果 URL 格式无效或不支持,返回错误

§Example
use dbnexus::DbPool;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = DbPool::new("sqlite://example.db").await?;
    Ok(())
}
Source

pub async fn with_config(config: DbConfig) -> DbResult<Self>

使用配置创建连接池

Source

pub async fn try_from_config(config: DbConfig) -> DbResult<Self>

使用配置结构体创建连接池

此方法接受一个 DbConfig 结构体,用于配置连接池的所有参数。 与 Self::new 方法功能相同,但更适合从配置结构体直接初始化。

§Example
/// ```rust
/// use dbnexus::DbPool;
/// use dbnexus::config::DbConfig;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let config = DbConfig {
///         url: "sqlite::memory:".to_string(),
///         max_connections: 10,
///         min_connections: 2,
///         ..Default::default()
///     };
///
///     let pool = DbPool::try_from_config(config).await?;
///     Ok(())
/// }
/// ```
§Errors

如果连接失败或配置无效,返回错误

Source

pub fn try_from(config: &DbConfig) -> Result<Self, ConfigError>

使用配置引用同步创建连接池(简化版本,带权限但不初始化缓存)

此方法是同步的,不会创建数据库连接。 实际的连接池创建和连接验证在首次获取连接时进行。

注意:此方法不会初始化权限缓存(需要异步初始化)。 如果需要完整的异步权限缓存功能,请使用 with_config() 异步方法。

§Example
use dbnexus::DbPool;
use dbnexus::config::DbConfig;

let runtime = tokio::runtime::Runtime::new()?;
let _guard = runtime.enter();

let config = DbConfig {
    url: "sqlite::memory:".to_string(),
    max_connections: 10,
    min_connections: 1,
    idle_timeout: 300,
    acquire_timeout: 5000,
    ..Default::default()
};

let pool = DbPool::try_from(&config)?;
§Errors

如果配置验证失败,返回错误

Source

pub fn metrics(&self) -> Option<&Arc<MetricsCollector>>

获取指标收集器(如果已设置)

Source

pub fn get_actual_config(&self) -> &DbConfig

获取实际应用的配置

返回当前连接池使用的配置。

§Returns

实际应用的配置

Source

pub async fn get_session(&self, role: &str) -> DbResult<Session>

从池中获取 Session(带 metrics 支持)

§Arguments
  • role - 角色名称,必须在权限配置中定义
§Errors

如果角色未在权限配置中定义,返回错误

§安全警告

此方法接受角色字符串参数,调用者应确保:

  • 已通过其他方式验证用户身份(如JWT Token、API Key等)
  • 角色字符串来自可信来源,而非直接的用户输入
  • 在生产环境中不要硬编码角色字符串
  • 建议结合 dbnexus::authentication::AuthenticationManager 使用
§示例
use dbnexus::{DbPool, authentication::AuthenticationManager};

// 安全用法:先验证Token,再从Token中提取角色
let auth_manager = AuthenticationManager::new(&jwt_secret);
let claims = auth_manager.verify_token(token)?;
let session = pool.get_session(&claims.role).await?;

// 不安全用法:直接使用用户输入
// let session = pool.get_session(user_input_role).await?; // 不要这样做!
Source

pub async fn check_connection_health(&self, conn: &DbConnection) -> bool

检查连接健康状态

通过执行轻量级查询来验证数据库连接的有效性。 使用数据库特定的健康检查查询:

  • SQLite: SELECT 1
  • PostgreSQL: SELECT 1
  • MySQL: SELECT 1
§Arguments
  • conn - 要检查的数据库连接
§Returns

如果连接有效返回 true,否则返回 false

Source

pub async fn clean_invalid_connections(&self) -> u32

清理无效连接

遍历空闲连接池,验证每个连接的有效性, 移除超时或断开连接的实例。

§Returns

被移除的无效连接数量

Source

pub async fn validate_and_recreate_connections(&self) -> Result<u32, DbErr>

验证并重新创建无效连接

检查所有空闲连接的健康状态,自动替换无效连接。 此方法会确保池中至少保持配置的最小连接数。

§Returns

被重新创建的连接数量,或错误

Source

pub fn parse_health_check_interval(value: &str) -> u64

解析健康检查间隔配置

解析传入的间隔值(秒),并限制在 5-300 秒范围内。 超出范围的值会触发警告日志。

§Arguments
  • value - 健康检查间隔配置值(由调用方从环境变量 DB_HEALTH_CHECK_INTERVAL 读取)
§Returns

返回解析后的间隔秒数,默认为 30 秒。

§Examples
use dbnexus::DbPool;
// 空字符串返回默认值 30
assert_eq!(DbPool::parse_health_check_interval(""), 30);

// 有效值返回该值
assert_eq!(DbPool::parse_health_check_interval("60"), 60);

// 超出范围的值返回限制后的值
assert_eq!(DbPool::parse_health_check_interval("1000"), 300);
Source

pub fn status(&self) -> PoolStatus

获取连接池状态

返回当前连接池的统计信息,包括总连接数、活跃连接数和空闲连接数。

§Returns

连接池状态信息

§Example
use dbnexus::DbPool;

let status = pool.status();
println!("Total: {}, Active: {}, Idle: {}",
    status.total, status.active, status.idle);
Source

pub fn pool_metrics(&self) -> PoolMetrics

获取连接池告警指标

从 metrics_collector(如果启用)获取告警相关指标,包括:

  • slow_acquires:获取时长超过 1s 的次数
  • timeout_errors:获取超时总次数(warn + error + critical 之和)
  • critical_timeouts:严重超时(≥10s)次数
  • wait_count:当前正在等待获取连接的协程数
  • max_waiters:历史最大并发等待者峰值
§Returns

连接池告警指标(始终返回有效值,metrics 未启用时所有计数为 0)

Source

pub fn config(&self) -> &DbConfig

获取配置

返回连接池的配置引用。

§Returns

连接池配置的引用

§Example
use dbnexus::DbPool;

let config = pool.config();
println!("Max connections: {}", config.max_connections);
Source

pub async fn run_auto_migrate(&self) -> Result<u32, DbError>

运行自动迁移

如果配置中启用了 auto_migrate,此方法会在连接池创建后自动执行迁移。 也可以手动调用此方法来执行迁移。

§Returns

成功应用的迁移数量

Source

pub async fn run_migrations( &self, migrations_dir: &Path, ) -> Result<u32, DbError>

手动运行迁移

§Arguments
  • migrations_dir - 迁移文件目录路径
§Returns

成功应用的迁移数量

Trait Implementations§

Source§

impl Clone for DbPool

Source§

fn clone(&self) -> DbPool

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 ConnectionPool for DbPool

Source§

fn get_session<'life0, 'life1, 'async_trait>( &'life0 self, role: &'life1 str, ) -> Pin<Box<dyn Future<Output = DbResult<Session>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

获取会话 Read more
Source§

fn status(&self) -> PoolStatus

获取连接池状态 Read more
Source§

fn config(&self) -> &DbConfig

获取配置 Read more
Source§

impl Drop for DbPool

DbPool 的优雅关闭

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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