Skip to main content

wordval_db/
lib.rs

1//! # wordval-db
2//!
3//! Wordval 数据库层:Row 模式 CRUD、事务、Hook、SQL 模板、多数据库支持。
4//!
5//! ## 1.0.5 → 1.0.6 升级注意(breaking)
6//!
7//! 1. **`DbError::Rollback` 由单字段元组变体改为结构体变体**
8//!    `Rollback { msg: String, source: Option<Box<dyn Error + Send + Sync>> }`。
9//!    原来构造/匹配 `Rollback(m)` 的代码需改为 `Rollback { msg, source }`;
10//!    `Db::transaction_err` / `transaction_err_with` 可保留完整 source 链。
11//! 2. **feature 拆分**:后端(`sqlite` / `postgres` / `mysql`)与类型扩展
12//!    (`uuid` / `rust_decimal` / `chrono`)及工厂(`factory`)均按 feature 门控。
13//!    默认 features = `["sqlite", "factory", "chrono", "uuid", "rust_decimal"]`,
14//!    与 1.0.x 行为兼容;仅依赖 `sqlite` 时按需补启类型 feature。
15//!
16//! ## 设计理念
17//!
18//! 1. **Db + Row 模式** — 无需定义 Model 即可操作,字段追踪 + 类型安全
19//! 2. **事务 RAII** — Rust 的 `?` 天然保证异常时自动回滚
20//! 3. **Hook 生命周期** — before/after 拦截 CRUD,支持审计、时间戳自动填充
21//! 4. **配置驱动** — 从 `AppConfig` 创建连接池,支持加密密码存储
22//! 5. **多数据库** — PostgreSQL / MySQL / SQLite,工厂按 type 自动选择
23//!
24//! ## 主要模块
25//!
26//! - [`db`] — 核心 `Db` 类型与 CRUD 操作
27//! - [`row`] — `Row` 动态行类型
28//! - [`tx`] — 事务支持
29//! - [`hook`] — CRUD 生命周期钩子
30//! - [`query`] — SQL 查询构建器 `Q`
31//! - [`factory`] — 数据库连接工厂(feature `factory`)
32//! - [`sqlite`] — SQLite 独立连接构建器(feature `sqlite`)
33//! - [`row_executor`] — `Db` / `ActiveTx` 共享的 Row 写入 trait(事务内 Row 写)
34//! - [`script`] — `split_sql_statements` 与 `execute_script`(单连接多语句)
35//!
36//! ## 快速开始
37//!
38//! ```ignore
39//! use wordval_db::{Db, Row};
40//!
41//! let db = wordval_db::create_db(&config.database).await?;
42//!
43//! // 插入(表名在 Row 上声明,字段改动会被追踪)
44//! // 注意:Row 携带非 Null 主键值时按该值原样插入、不走自增;
45//! // 需要数据库自增请勿 set 主键字段(或用 Row::without_pk 清除)
46//! let mut row = Row::table("user");
47//! row.set("name", "Alice");
48//! let id = db.insert(&row).await?;
49//!
50//! // 查询
51//! let users = db.query("SELECT * FROM user WHERE age > ?", &[18i64.into()]).await?;
52//! ```
53
54pub mod ar;
55pub mod db;
56pub mod dialect;
57#[cfg(feature = "factory")]
58pub mod factory;
59pub mod hook;
60// Migrator 依赖 wordval_config::MigrationConfig,与 factory 共享 wordval-config 可选依赖
61#[cfg(feature = "factory")]
62pub mod migrate;
63pub mod param;
64pub mod query;
65pub mod row;
66pub mod row_executor;
67pub mod script;
68#[cfg(feature = "sqlite")]
69/// SQLite 独立连接入口(`wordval_db::sqlite::builder`),见 [`sqlite`] 模块文档。
70#[path = "sqlite_builder.rs"]
71pub mod sqlite;
72pub mod tx;
73
74pub use ar::{ActiveRecord, FromRow, ToRow, TryFromRow};
75pub use db::{Db, NamingStrategy, SoftDelete};
76pub use dialect::Dialect;
77#[cfg(feature = "factory")]
78pub use factory::{create_db, create_db_if_enabled};
79pub use hook::{Hook, HookChain};
80pub use param::{push_param, DbTypeHint, IntoParams, Param};
81pub use query::Q;
82pub use row::{FieldValue, Row, RowExt};
83pub use row_executor::RowExecutor;
84pub use script::split_sql_statements;
85pub use tx::{ActiveTx, DbExecutor, Isolation};
86pub use wordval_core::PageQuery;
87
88// 类型 crate 重导出:`#[derive(Model)]` 生成的代码经 `wordval_db::chrono` /
89// `wordval_db::uuid` 引用(消费者无需为展开代码再直接依赖这两个 crate),
90// 业务代码也可直接 `use wordval_db::chrono::...`。
91#[cfg(feature = "chrono")]
92pub use chrono;
93#[cfg(feature = "uuid")]
94pub use uuid;
95
96#[cfg(not(any(feature = "postgres", feature = "mysql", feature = "sqlite")))]
97compile_error!(
98    "wordval-db: 请至少启用一个后端 feature(postgres / mysql / sqlite);\
99     default features 已包含 sqlite"
100);
101
102/// wordval-db 错误
103#[derive(Debug, thiserror::Error)]
104pub enum DbError {
105    #[error("数据库错误: {0}")]
106    Sqlx(#[from] sqlx::Error),
107
108    #[error("序列化错误: {0}")]
109    Serde(#[from] serde_json::Error),
110
111    #[error("参数错误: {0}")]
112    Argument(String),
113
114    /// 查询目标记录不存在(`Q::one` / `Q::one_as` 空结果)。
115    ///
116    /// 语义上属于"资源未找到"而非服务端故障:映射 HTTP **404**,业务码
117    /// **40401**([`wordval_core::codes::RECORD_NOT_FOUND`],区别于路由未找到
118    /// 的 404,见 `From<DbError> for ApiError`),避免把正常的空结果当成
119    /// 500 内部错误。「空属于正常业务流程」的查询请用 `Q::first`/`Q::list`,
120    /// 空结果返回 `None`/空集合,不报错。
121    #[error("{0}")]
122    NotFound(String),
123
124    /// 当前后端不支持请求的能力(如事务隔离级别),不静默降级。
125    #[error("后端不支持该能力: {0}")]
126    UnsupportedCapability(String),
127
128    /// 事务闭包返回 `Err` 导致回滚时的包装错误。
129    ///
130    /// **1.0.6 破坏性变更**:由 `Rollback(String)` 改为结构体变体,
131    /// 新增 `source` 字段保留原始错误(`Db::transaction_err` 路径下非空)。
132    /// Display 输出保持 `事务回滚: {msg}` 不变。
133    #[error("事务回滚: {msg}")]
134    Rollback {
135        msg: String,
136        #[source]
137        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
138    },
139
140    #[error("{0}")]
141    Other(String),
142}
143
144impl DbError {
145    /// 返回错误类别的标签(用于构造对外消息)
146    ///
147    /// 分类标签与 `#[error]` 显示前缀一致;`Other` 无显示前缀,
148    /// 但在分类标签中归入"数据库错误"。
149    /// 作为独立方法便于 `From<DbError> for ApiError` 等场景复用。
150    pub fn category_label(&self) -> &'static str {
151        match self {
152            DbError::Sqlx(_) => "数据库错误",
153            DbError::Serde(_) => "序列化错误",
154            DbError::Argument(_) => "参数错误",
155            DbError::NotFound(_) => "记录不存在",
156            DbError::UnsupportedCapability(_) => "后端不支持该能力",
157            DbError::Rollback { .. } => "事务回滚",
158            DbError::Other(_) => "数据库错误",
159        }
160    }
161
162    /// 是否唯一约束 / 主键冲突(可用于幂等 INSERT 的冲突分支判定)
163    ///
164    /// 各后端错误码:
165    /// - SQLite:`2067`(UNIQUE/PRIMARY KEY constraint failed)、`1555`(PRIMARY KEY must be unique);
166    /// - PostgreSQL:`23505`(unique_violation);
167    /// - MySQL:`1062`(Duplicate entry)、`1586`。
168    ///
169    /// `Rollback` 包装(事务闭包内 INSERT 冲突经 `Db::transaction*` 回卷)时
170    /// 递归检查 `source` 链中的原始 `DbError`,保证事务内外判定语义一致。
171    pub fn is_unique_violation(&self) -> bool {
172        match self {
173            DbError::Sqlx(e) => e
174                .as_database_error()
175                .is_some_and(|d| matches!(d.code().unwrap_or_default().as_ref(), "2067" | "1555" | "23505" | "1062" | "1586")),
176            DbError::Rollback { source: Some(src), .. } => src
177                .downcast_ref::<DbError>()
178                .is_some_and(DbError::is_unique_violation),
179            _ => false,
180        }
181    }
182}
183
184pub type DbResult<T> = Result<T, DbError>;
185
186impl From<DbError> for wordval_core::Error {
187    fn from(e: DbError) -> Self {
188        wordval_core::Error::Msg(e.to_string())
189    }
190}
191
192impl From<DbError> for wordval_core::ApiError {
193    fn from(e: DbError) -> Self {
194        let detail = e.to_string();
195        match &e {
196            // 参数错误 → 400,前端可见分类标签 + 具体描述
197            DbError::Argument(msg) => {
198                wordval_core::ApiError::bad_request(format!("{}: {}", e.category_label(), msg))
199            }
200            // 记录不存在 → HTTP 404 + 业务码 40401(区别于路由 404 的 404);
201            // 空结果是正常业务语义,非内部故障
202            DbError::NotFound(msg) => wordval_core::ApiError::record_not_found(msg.clone()),
203            // 其余 → 500,前端仅看到注册表中的模糊提示,详情写入日志
204            _ => {
205                tracing::error!(target: "wordval_db_error", detail = %detail, "数据库内部错误");
206                wordval_core::ApiError::internal_masked(
207                    wordval_core::error_registry::error_message_of(
208                        wordval_core::ErrorCode::Internal,
209                    ),
210                    detail,
211                )
212            }
213        }
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn not_found_maps_to_404() {
223        let api: wordval_core::ApiError = DbError::NotFound("记录不存在".into()).into();
224        assert_eq!(api.status, 404, "空结果必须是 404 而非 500");
225        assert_eq!(
226            api.code,
227            wordval_core::codes::RECORD_NOT_FOUND,
228            "业务码须为 40401,前端可与路由 404 区分"
229        );
230        assert_eq!(api.msg, "记录不存在");
231        // 对照:寻址级(路由)404 的业务码是 404
232        assert_ne!(
233            api.code,
234            wordval_core::codes::NOT_FOUND,
235            "记录级与路由级 404 必须可区分"
236        );
237    }
238
239    #[test]
240    fn argument_maps_to_400_and_other_to_500() {
241        let bad: wordval_core::ApiError = DbError::Argument("limit 不能为负数".into()).into();
242        assert_eq!(bad.status, 400);
243        let internal: wordval_core::ApiError = DbError::Other("boom".into()).into();
244        assert_eq!(internal.status, 500);
245    }
246}