Skip to main content

AnyDatabase

Struct AnyDatabase 

Source
#[non_exhaustive]
pub struct AnyDatabase { /* private fields */ }
Expand description

持有单个关系数据库连接池的运行时容器。

使用 #[non_exhaustive]:内部后端集合随 feature 变化,调用方不得按结构体字面量 构造,必须通过 AnyDatabase::mysql / AnyDatabase::postgres 构造(按 feature 启用)。

Implementations§

Source§

impl AnyDatabase

Source

pub fn mysql(database: Database) -> Self

用 MySQL 连接池构造容器(默认数据源)。

Source

pub fn postgres(database: Database) -> Self

用 PostgreSQL 连接池构造容器(默认数据源)。

Source

pub fn id(&self) -> &DatasourceId

返回逻辑数据源名。

Source

pub fn backend(&self) -> BackendKind

返回后端类型。

Source

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

返回后端静态能力契约。

Source

pub fn require_capabilities( &self, required: &[BackendCapability], ) -> Result<(), BaseError>

启动期能力门禁:校验后端是否支持全部 required 能力。

缺失任一能力时返回 BaseError::UnsupportedCapability,错误消息包含后端 类型与缺失能力名。调用方应在启动/初始化时一次性校验自己实际用到的能力集合, 而不是把检查散落到每个查询上——这样配置错误在启动期就 fail-fast,而不是执行 到方言专属语法时才暴露。

§示例
ⓘ
database.require_capabilities(&[
    BackendCapability::Select,
    BackendCapability::Savepoint,
])?;
Source

pub fn is_closed(&self) -> bool

连接池是否已关闭。

Source

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

健康检查:执行 SELECT 1 验证连接可用。

Source

pub async fn close(&self)

幂等关闭连接池。

Source

pub fn pool_status(&self) -> PoolStatus

返回连接池状态快照。

Source

pub fn as_mysql(&self) -> Option<&Database>

当容器持有 MySQL 后端时返回其连接池引用。

Source

pub fn as_postgres(&self) -> Option<&Database>

当容器持有 PostgreSQL 后端时返回其连接池引用。

Source

pub fn pool(&self) -> AnyPool

返回与当前后端共享同一连接池的可克隆句柄。

sqlx 连接池内部基于 Arc,克隆只是引用计数递增;本方法返回的 AnyPool 可在请求作用域内自由复制,不会复制物理连接。

Source

pub fn source_pool(&self) -> PoolHandle

返回带逻辑数据源身份的连接池句柄,供 TableQuery 做事务同源校验。

Source

pub async fn begin(&self) -> Result<AnyTransaction, DbError>

在当前后端上开启事务。

返回的 AnyTransaction 可传入 TableQuery 的 *_in_tx 系列方法,也可通过 AnyTransaction::commit / AnyTransaction::rollback 显式结束。未显式结束时 由 sqlx 在 drop 时尽力回滚。

Source

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

整事务重试:按次数与指数退避重跑 operation,只重试序列化失败与死锁。

仅 PostgreSQL 的 40001(序列化失败)与 40P01(死锁)会重试,判定复用 SqlErrorKind 的 SQLSTATE 归一,与 yang-db 的 PgDatabase::retry_transaction 口径一致。其他错误立即原样返回——包括约束冲突(如 23505)、 DbError::ConnectionError 与 SQLSTATE 08/53 类瞬时连接错误。提交阶段 断连时事务是否已生效未知,重试可能重复执行副作用,因此不属于可重试范围。

operation 每次被调用都应自行开启并结束一个事务(例如 self.begin() → 业务语句 → commit())。重试前 helper 按 backoff * 2^(n-1) 退避(最多放大 32 倍);失败事务的回滚由被丢弃的事务句柄兜底。

§示例
ⓘ
let value = database
    .retry_transaction(3, Duration::from_millis(50), || async {
        let mut tx = database.begin().await?;
        // ... 业务语句 ...
        tx.commit().await?;
        Ok(())
    })
    .await?;

Trait Implementations§

Source§

impl Clone for AnyDatabase

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 AnyDatabase

Source§

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

Formats the value using the given formatter. 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> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> 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> 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