scyph_db/error.rs
1//! Database error type definitions.
2//!
3//! This module defines [`DbError`], the single unified error type returned by all public
4//! functions in `scyph-db`. It wraps `sqlx` errors and adds configuration-level failures
5//! with human-readable context messages.
6//!
7//! ## Error Hierarchy
8//!
9//! ```text
10//! DbError
11//! ├── Sqlx(sqlx::Error) — Query / connection failures
12//! ├── Configuration(String) — Missing env vars, invalid values
13//! └── Migration(MigrateError) — Migration load / execution failures
14//! ```
15//!
16//! ## Conversion to `AppError`
17//!
18//! [`DbError`] implements `From<DbError> for AppError` (from `scyph-core`), so it can be
19//! used directly in Axum handlers that return `Result<_, AppError>` via the `?` operator:
20//!
21//! ```rust,ignore
22//! use scyph_db::DbError;
23//! use scyph_core::AppError;
24//!
25//! async fn get_user(pool: &sqlx::PgPool, id: i64) -> Result<String, AppError> {
26//! let row = sqlx::query_scalar!("SELECT name FROM users WHERE id = $1", id)
27//! .fetch_one(pool)
28//! .await
29//! .map_err(DbError::Sqlx)?; // DbError -> AppError via From impl
30//! Ok(row)
31//! }
32//! ```
33
34use scyph_core::AppError;
35
36/// Unified error type for all database operations in `scyph-db`.
37///
38/// All public async functions in this crate return `Result<_, DbError>`. The three variants
39/// map directly to the three failure modes: infrastructure errors from `sqlx`, missing or
40/// invalid configuration supplied at startup, and migration runner failures.
41///
42/// ## Matching on Variants
43///
44/// ```rust,ignore
45/// use scyph_db::DbError;
46///
47/// async fn handle_error(err: DbError) {
48/// match err {
49/// DbError::Sqlx(e) => {
50/// // Check for specific sqlx error kinds
51/// if matches!(e, sqlx::Error::RowNotFound) {
52/// eprintln!("Record not found");
53/// } else {
54/// eprintln!("Database error: {e}");
55/// }
56/// }
57/// DbError::Configuration(msg) => {
58/// eprintln!("Startup configuration error: {msg}");
59/// // Typically unrecoverable — application should exit
60/// }
61/// DbError::Migration(e) => {
62/// eprintln!("Migration failed: {e}");
63/// // Check migration file syntax and version ordering
64/// }
65/// }
66/// }
67/// ```
68#[derive(Debug, thiserror::Error)]
69pub enum DbError {
70 /// Failure connecting to or querying PostgreSQL via `sqlx`.
71 ///
72 /// Wraps any [`sqlx::Error`] produced by connection acquisition, query execution,
73 /// transaction management, or pool operations. Common causes include:
74 /// - Network errors or TCP timeouts reaching the PostgreSQL host.
75 /// - Authentication failures (wrong password or role).
76 /// - Constraint violations (`UNIQUE`, `FOREIGN KEY`, `NOT NULL`).
77 /// - `sqlx::Error::RowNotFound` when `fetch_one()` returns no rows.
78 /// - `sqlx::Error::PoolTimedOut` when all connections are saturated.
79 #[error("Database error: {0}")]
80 Sqlx(#[from] sqlx::Error),
81
82 /// Missing or invalid configuration detected before any database connection is attempted.
83 ///
84 /// Contains a human-readable message describing what is wrong and which environment
85 /// variable or value is invalid. Returned by [`crate::build_pool`] when:
86 /// - `DATABASE_URL` is not set.
87 /// - `MAX_CONNECTIONS` or `MIN_CONNECTIONS` cannot be parsed as `u32`.
88 ///
89 /// Configuration errors are typically fatal — the application cannot start without
90 /// correct environment configuration.
91 #[error("Configuration error: {0}")]
92 Configuration(String),
93
94 /// Migration or seed runner failure from `sqlx::migrate`.
95 ///
96 /// Wraps [`sqlx::migrate::MigrateError`], which is returned when:
97 /// - A migration directory cannot be read or contains invalid `.sql` files.
98 /// - A migration SQL statement fails to execute (e.g. syntax error, type mismatch).
99 /// - The `_sqlx_migrations` tracking table cannot be created or queried.
100 #[error("Migration error: {0}")]
101 Migration(#[from] sqlx::migrate::MigrateError),
102}
103
104/// Returns `true` when the given `sqlx` error is a PostgreSQL unique-constraint
105/// violation (SQLSTATE `23505`).
106///
107/// Convenience helper for mapping duplicate-key errors to `409 Conflict` without
108/// string-matching the driver message.
109///
110/// # Example
111///
112/// ```rust,ignore
113/// use scyph_db::{DbError, is_unique_violation};
114/// use scyph_core::AppError;
115///
116/// async fn insert_user(pool: &sqlx::PgPool, email: &str) -> Result<(), AppError> {
117/// match sqlx::query!("INSERT INTO users (email) VALUES ($1)", email)
118/// .execute(pool)
119/// .await
120/// {
121/// Ok(_) => Ok(()),
122/// Err(e) if is_unique_violation(&e) => Err(AppError::Conflict("email taken".into())),
123/// Err(e) => Err(DbError::Sqlx(e).into()),
124/// }
125/// }
126/// ```
127pub fn is_unique_violation(err: &sqlx::Error) -> bool {
128 matches!(err, sqlx::Error::Database(db) if db.code().as_deref() == Some("23505"))
129}
130
131impl DbError {
132 /// Returns `true` when this error is a PostgreSQL unique-constraint
133 /// violation (SQLSTATE `23505`).
134 ///
135 /// Convenience for mapping duplicate-key errors to `409 Conflict` without
136 /// unwrapping the inner `sqlx::Error` by hand.
137 ///
138 /// # Example
139 ///
140 /// ```rust,ignore
141 /// use scyph_db::DbError;
142 /// use scyph_core::AppError;
143 ///
144 /// fn map(err: DbError) -> AppError {
145 /// if err.is_unique_violation() {
146 /// AppError::Conflict("duplicate key".into())
147 /// } else {
148 /// err.into()
149 /// }
150 /// }
151 /// ```
152 pub fn is_unique_violation(&self) -> bool {
153 matches!(self, DbError::Sqlx(e) if is_unique_violation(e))
154 }
155}
156
157impl From<DbError> for AppError {
158 /// Converts any [`DbError`] into an [`AppError::internal`] error.
159 ///
160 /// This blanket conversion allows `DbError` to be propagated through Axum handlers
161 /// and service functions that return `Result<_, AppError>` using the `?` operator.
162 /// The error message from the `DbError` variant is preserved in the internal error body.
163 fn from(err: DbError) -> Self {
164 AppError::internal(err.to_string())
165 }
166}