yggdrasil/db/mod.rs
1//! 数据库连接模块。
2//!
3//! 本模块根据 `server` feature 的启用情况提供两套实现:
4//! - 启用 `server` 时,从 `pool` 子模块暴露真实的 PostgreSQL 连接池;
5//! - 未启用 `server` 时(例如仅编译 WASM 前端),提供一个 `DummyPool` stub,
6//! 使代码在缺少数据库依赖的情况下仍能编译通过。
7//!
8//! 这种 stub 模式是 Dioxus fullstack 项目的常见做法:服务端函数体在 WASM 构建时会被剥离,
9//! 但模块结构必须保持一致,因此需要一个占位实现来满足编译器的符号解析。
10
11/// 错误格式化工具:把 `std::error::Error` 的 source 链完整展开为字符串。
12///
13/// 存在的原因:`tokio_postgres::Error` 的 `Display` 对 DB 侧错误只会打印
14/// 无信息量的占位串 `db error`,真正的消息文本(如
15/// `column "x" of relation "y" already exists`、SQLSTATE、约束名)藏在
16/// `source()` 链里的 `postgres::error::DbError`。不主动遍历链,日志和错误
17/// 字符串就会全部折叠成 `db error`,无法定位失败原因。
18///
19/// 用法:`format!("...: {}", format_with_sources(&e))` 或直接
20/// `format_with_sources(&e)` 得到完整的 `e: cause: deeper cause`。
21#[cfg(feature = "server")]
22pub fn format_with_sources(e: &dyn std::error::Error) -> String {
23 use std::fmt::Write;
24 let mut s = e.to_string();
25 let mut cur: &dyn std::error::Error = e;
26 while let Some(next) = cur.source() {
27 // 跳过与外层 Display 完全相同的占位层(如 tokio_postgres 的 `db error`),
28 // 避免输出 `db error: db error` 这种重复。只在能带来新信息时追加。
29 let next_disp = next.to_string();
30 if !next_disp.is_empty() && next_disp != s {
31 let _ = write!(s, ": {next_disp}");
32 }
33 cur = next;
34 }
35 s
36}
37
38/// 真实的 PostgreSQL 连接池实现,仅在启用 server feature 时编译。
39#[cfg(feature = "server")]
40pub mod pool;
41
42/// 连接获取的指数退避重试策略,仅在启用 server feature 时编译。
43#[cfg(feature = "server")]
44pub mod retry;
45
46/// 数据库迁移运行器,仅在启用 server feature 时编译。
47#[cfg(feature = "server")]
48pub mod migrate;
49
50/// 占位连接池实现,仅在不启用 server feature 时编译。
51///
52/// `DummyPool` 是一个最小 stub:它提供与真实连接池相同的公开接口形状
53///(如 `get` 与 `get_conn`),但所有方法都直接返回错误。
54/// 这样可以在不引入 deadpool-postgres、tokio-postgres 等依赖的情况下,
55/// 让依赖 `db::pool::DB_POOL` 的代码通过前端编译。
56/// **请勿删除此 stub**,否则非 server 构建将无法通过编译。
57#[cfg(not(feature = "server"))]
58#[allow(dead_code)]
59pub mod pool {
60 /// 占位连接池,无实际数据库连接能力。
61 pub struct DummyPool;
62
63 impl DummyPool {
64 /// 占位方法,永远返回错误。
65 pub async fn get(&self) -> Result<(), ()> {
66 Err(())
67 }
68 }
69
70 /// 占位全局连接池实例。
71 pub static DB_POOL: DummyPool = DummyPool;
72
73 /// 占位函数,永远返回错误。
74 pub async fn get_conn() -> Result<(), ()> {
75 Err(())
76 }
77}