Skip to main content

GlobalDatabase

Struct GlobalDatabase 

Source
pub struct GlobalDatabase;
Expand description

全局数据库访问器

封装 yang-db::Database,提供全局静态访问接口。 所有数据库操作都通过 yang-db 库实现。

Implementations§

Source§

impl GlobalDatabase

Source

pub async fn init(url: &str, config: DatabaseConfig) -> Result<(), BaseError>

初始化全局数据库

§参数
  • url: 数据库连接字符串,格式:mysql://user:password@host:port/database
  • config: 数据库配置,包含连接池参数
§返回
  • Ok(()): 初始化成功
  • Err(BaseError): 初始化失败
§错误
  • DatabaseConnectionFailed: 数据库连接失败(包装 DbError 保留错误链)
  • DatabaseAlreadyInitialized: 数据库已经初始化
§说明

使用 yang-db::Database::connect_with_config 创建数据库连接。 此方法只能调用一次,重复调用将返回错误。

§示例
ⓘ
use yang_base::database::GlobalDatabase;
use yang_db::DatabaseConfig;

let config = DatabaseConfig::default()
    .with_min_connections(2)
    .with_max_lifetime(Some(1800));

GlobalDatabase::init("mysql://root:password@localhost/test", config).await?;
Source

pub fn get() -> Result<&'static Database, BaseError>

获取全局数据库实例

§返回
  • Ok(&'static Database): yang-db::Database 实例的静态引用
  • Err(BaseError): 数据库未初始化
§错误
  • DatabaseNotInitialized: 数据库未初始化,需要先调用 init 方法
§API 一致性说明 (A-M4)

本方法名为 get(),而 Redis 对等方法名为 GlobalRedis::client()。 这是历史命名不对称,未来应统一为同一种命名风格(例如都叫 get() 或都叫 client())。

§示例
ⓘ
let db = GlobalDatabase::get()?;
let builder = db.table("users");
Source

pub fn table(table_name: &str) -> Result<QueryBuilder<'static>, BaseError>

选择表,返回查询构建器

§参数
  • table_name: 表名
§返回
  • Ok(QueryBuilder): yang-db 查询构建器
  • Err(BaseError): 数据库未初始化
§说明

调用 yang-db::Database::table 方法创建查询构建器。 返回的 QueryBuilder 可以链式调用各种查询方法。

§示例
ⓘ
// 查询用户
let users = GlobalDatabase::table("users")?
    .field("id")
    .field("name")
    .where_eq("status", 1)
    .select::<User>()
    .await?;

// 插入数据
GlobalDatabase::table("users")?
    .insert(vec![
        ("name", "Alice"),
        ("email", "alice@example.com"),
    ])
    .await?;
Source

pub async fn query<T>(sql: &str) -> Result<Vec<T>, BaseError>
where T: for<'r> FromRow<'r, MySqlRow> + Send + Unpin,

执行原生 SELECT 查询

§参数
  • sql: SQL 查询语句
§返回
  • Ok(Vec<T>): 查询结果列表
  • Err(BaseError): 查询失败
§类型参数
  • T: 结果类型,必须实现 sqlx::FromRow trait
§错误
  • DatabaseNotInitialized: 数据库未初始化
  • DatabaseQueryFailed: 查询执行失败
§说明

调用 yang-db::Database::query 方法执行原生 SQL 查询。 适用于复杂查询或查询构建器无法满足的场景。

§示例
ⓘ
#[derive(sqlx::FromRow)]
struct User {
    id: i32,
    name: String,
}

let users: Vec<User> = GlobalDatabase::query(
    "SELECT id, name FROM users WHERE status = 1"
).await?;
Source

pub async fn query_with_params<T>( sql: &str, params: Vec<Value>, ) -> Result<Vec<T>, BaseError>
where T: for<'r> FromRow<'r, MySqlRow> + Send + Unpin,

执行参数化 SELECT 查询

§参数
  • sql: 包含 ? 占位符的 SQL 查询语句
  • params: 按占位符顺序绑定的参数
Source

pub async fn execute(sql: &str) -> Result<u64, BaseError>

执行原生 INSERT/UPDATE/DELETE 查询

§参数
  • sql: SQL 语句
§返回
  • Ok(u64): 受影响的行数
  • Err(BaseError): 执行失败
§错误
  • DatabaseNotInitialized: 数据库未初始化
  • DatabaseExecuteFailed: 语句执行失败
§说明

调用 yang-db::Database::execute 方法执行原生 SQL 语句。 适用于 INSERT、UPDATE、DELETE 等修改数据的操作。

§示例
ⓘ
// 插入数据
let affected = GlobalDatabase::execute(
    "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')"
).await?;

// 更新数据
let affected = GlobalDatabase::execute(
    "UPDATE users SET status = 1 WHERE id = 1"
).await?;

// 删除数据
let affected = GlobalDatabase::execute(
    "DELETE FROM users WHERE id = 1"
).await?;
Source

pub async fn execute_with_params( sql: &str, params: Vec<Value>, ) -> Result<u64, BaseError>

执行参数化 INSERT/UPDATE/DELETE 查询

§参数
  • sql: 包含 ? 占位符的 SQL 语句
  • params: 按占位符顺序绑定的参数
Source

pub async fn transaction() -> Result<Transaction, BaseError>

开始事务

§返回
  • Ok(Transaction): yang-db 事务对象
  • Err(BaseError): 开始事务失败
§错误
  • DatabaseNotInitialized: 数据库未初始化
  • DatabaseTransactionFailed: 开始事务失败
§说明

调用 yang-db::Database::transaction 方法创建事务。 事务中的所有操作要么全部成功,要么全部回滚。

§示例
ⓘ
// 开始事务
let mut tx = GlobalDatabase::transaction().await?;

// 在事务中执行操作
tx.execute("INSERT INTO users (name) VALUES ('Alice')").await?;
tx.execute("INSERT INTO logs (action) VALUES ('user_created')").await?;

// 提交事务
tx.commit().await?;

// 或者回滚事务
// tx.rollback().await?;
Source

pub async fn health_check() -> Result<bool, BaseError>

数据库健康检查

通过执行 SELECT 1 验证数据库连接是否可用。查询返回非空结果即视为健康。

§返回
  • Ok(true): 数据库连接正常
  • Ok(false): 查询成功但未返回结果(异常状态)
  • Err(BaseError): 数据库未初始化或查询失败
§错误
  • DatabaseNotInitialized: 数据库未初始化,需要先调用 init 方法
  • DatabaseQueryFailed: 健康检查查询执行失败
Source

pub fn pool_status() -> Result<PoolStatus, BaseError>

获取数据库连接池状态快照

转发 yang-db Database::pool_status,与 GlobalRedis::pool_status 对称。用于监控连接池水位、排查连接耗尽。

§返回
  • Ok(PoolStatus): 连接池状态(max_size/size/available/waiting)
  • Err(BaseError::DatabaseNotInitialized): 数据库未初始化
Source

pub async fn close()

优雅关闭全局数据库连接池(I3):停止发放新连接、等待在途连接归还后关闭。

供编排式停机(crate::lifecycle)调用。OnceLock 单例不重置,仅原地 drain 连接池——停机后不应再 dispatch,再用会得到连接池关闭错误。未初始化时为 no-op。

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> 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, 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