1use std::fmt;
4use std::io;
5use std::sync::Arc;
6
7use giong::error::Code;
8
9#[derive(Clone)]
24pub struct Error(Arc<Inner>);
25
26struct Inner {
27 kind: ErrorKind,
28 message: String,
29 db: Option<DbError>,
30 sqlstate: Option<&'static str>,
33 source: Option<io::Error>,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum ErrorKind {
40 Config,
42 Connect,
45 Auth,
48 Db,
53 Type,
56 RowCount,
58 TooLarge,
61 Closed,
65 PoolTimeout,
68 Protocol,
71 Statement,
77}
78
79impl ErrorKind {
80 pub fn giong_code(self) -> Code {
83 match self {
84 ErrorKind::Config => Code::PostgresConfig,
85 ErrorKind::Connect => Code::PostgresConnect,
86 ErrorKind::Auth => Code::PostgresAuth,
87 ErrorKind::Db => Code::PostgresServer,
88 ErrorKind::Type => Code::PostgresType,
89 ErrorKind::RowCount => Code::PostgresRowCount,
90 ErrorKind::TooLarge => Code::PostgresTooLarge,
91 ErrorKind::Closed => Code::PostgresClosed,
92 ErrorKind::PoolTimeout => Code::PostgresPoolTimeout,
93 ErrorKind::Protocol => Code::PostgresProtocol,
94 ErrorKind::Statement => Code::PostgresStatement,
95 }
96 }
97}
98
99impl Error {
100 pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
101 Self(Arc::new(Inner {
102 kind,
103 message: message.into(),
104 db: None,
105 sqlstate: None,
106 source: None,
107 }))
108 }
109
110 pub(crate) fn with_sqlstate(sqlstate: &'static str, message: impl Into<String>) -> Self {
113 Self(Arc::new(Inner {
114 kind: ErrorKind::Db,
115 message: message.into(),
116 db: None,
117 sqlstate: Some(sqlstate),
118 source: None,
119 }))
120 }
121
122 pub(crate) fn io(kind: ErrorKind, message: impl Into<String>, source: io::Error) -> Self {
123 Self(Arc::new(Inner {
124 kind,
125 message: message.into(),
126 db: None,
127 sqlstate: None,
128 source: Some(source),
129 }))
130 }
131
132 pub(crate) fn from_db(db: DbError, note: Option<String>) -> Self {
133 Self(Arc::new(Inner {
134 kind: ErrorKind::Db,
135 message: note.unwrap_or_default(),
136 db: Some(db),
137 sqlstate: None,
138 source: None,
139 }))
140 }
141
142 pub(crate) fn with_db(kind: ErrorKind, message: impl Into<String>, db: DbError) -> Self {
143 Self(Arc::new(Inner {
144 kind,
145 message: message.into(),
146 db: Some(db),
147 sqlstate: None,
148 source: None,
149 }))
150 }
151
152 pub fn conversion(message: impl Into<String>) -> Self {
156 Self::new(ErrorKind::Type, message)
157 }
158
159 pub(crate) fn config(message: impl Into<String>) -> Self {
160 Self::new(ErrorKind::Config, message)
161 }
162
163 pub(crate) fn protocol(message: impl Into<String>) -> Self {
164 Self::new(
165 ErrorKind::Protocol,
166 format!(
167 "{}; the connection was closed (is this really a PostgreSQL server?)",
168 message.into()
169 ),
170 )
171 }
172
173 pub(crate) fn closed(message: impl Into<String>) -> Self {
174 Self::new(ErrorKind::Closed, message)
175 }
176
177 pub(crate) fn context(&self, context: &str) -> Self {
179 Self(Arc::new(Inner {
180 kind: self.0.kind,
181 message: if self.0.message.is_empty() {
182 context.to_owned()
183 } else {
184 format!("{context}: {}", self.0.message)
185 },
186 db: self.0.db.clone(),
187 sqlstate: self.0.sqlstate,
188 source: self
189 .0
190 .source
191 .as_ref()
192 .map(|e| io::Error::new(e.kind(), e.to_string())),
193 }))
194 }
195
196 pub fn kind(&self) -> ErrorKind {
198 self.0.kind
199 }
200
201 pub fn giong_code(&self) -> Code {
205 self.0.kind.giong_code()
206 }
207
208 pub fn db(&self) -> Option<&DbError> {
211 self.0.db.as_ref()
212 }
213
214 pub fn code(&self) -> Option<&str> {
219 match &self.0.db {
220 Some(db) => Some(db.code()),
221 None => self.0.sqlstate,
222 }
223 }
224}
225
226impl Error {
227 fn what(&self) -> String {
230 let inner = &self.0;
231 let mut parts = Vec::with_capacity(3);
232 if !inner.message.is_empty() {
233 parts.push(inner.message.clone());
234 }
235 if let Some(db) = &inner.db {
236 parts.push(db.to_string());
237 }
238 if let Some(source) = &inner.source {
239 parts.push(source.to_string());
240 }
241 parts.join(": ")
242 }
243}
244
245impl fmt::Display for Error {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 let code = self.giong_code();
248 let what = self.what();
249 let stop = if what.ends_with('.') { "" } else { "." };
250 write!(f, "{code}: {what}{stop} See {}", code.url())
251 }
252}
253
254impl fmt::Debug for Error {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 f.debug_struct("Error")
257 .field("kind", &self.0.kind)
258 .field("message", &self.to_string())
259 .finish()
260 }
261}
262
263impl std::error::Error for Error {
264 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
265 match &self.0.source {
266 Some(e) => Some(e),
267 None => self.0.db.as_ref().map(|db| db as _),
268 }
269 }
270}
271
272impl From<Error> for io::Error {
273 fn from(e: Error) -> Self {
274 let kind = match (&e.0.source, e.kind()) {
275 (Some(source), _) => source.kind(),
276 (None, ErrorKind::Config | ErrorKind::Statement) => io::ErrorKind::InvalidInput,
277 (None, ErrorKind::Auth) => io::ErrorKind::PermissionDenied,
278 (None, ErrorKind::Type | ErrorKind::Protocol) => io::ErrorKind::InvalidData,
279 (None, ErrorKind::PoolTimeout) => io::ErrorKind::TimedOut,
280 (None, ErrorKind::Closed) => io::ErrorKind::ConnectionAborted,
281 (None, _) => io::ErrorKind::Other,
282 };
283 io::Error::new(kind, giong::error::Error::wrap(e.giong_code(), e))
284 }
285}
286
287#[derive(Clone, Debug, PartialEq, Eq)]
289pub struct DbError {
290 severity: String,
291 code: String,
292 message: String,
293 detail: Option<String>,
294 hint: Option<String>,
295 position: Option<u32>,
296 where_: Option<String>,
297 schema: Option<String>,
298 table: Option<String>,
299 column: Option<String>,
300 constraint: Option<String>,
301 routine: Option<String>,
302}
303
304impl DbError {
305 pub(crate) fn parse(body: &[u8]) -> Result<Self, Error> {
307 let mut e = DbError {
308 severity: String::new(),
309 code: String::new(),
310 message: String::new(),
311 detail: None,
312 hint: None,
313 position: None,
314 where_: None,
315 schema: None,
316 table: None,
317 column: None,
318 constraint: None,
319 routine: None,
320 };
321 let mut rest = body;
322 loop {
323 let (&field, tail) = rest
324 .split_first()
325 .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
326 if field == 0 {
327 break;
328 }
329 let end = tail
330 .iter()
331 .position(|&b| b == 0)
332 .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
333 let value = String::from_utf8_lossy(&tail[..end]).into_owned();
334 rest = &tail[end + 1..];
335 match field {
336 b'V' => e.severity = value,
337 b'S' if e.severity.is_empty() => e.severity = value,
338 b'C' => e.code = value,
339 b'M' => e.message = value,
340 b'D' => e.detail = Some(value),
341 b'H' => e.hint = Some(value),
342 b'P' => e.position = value.parse().ok(),
343 b'W' => e.where_ = Some(value),
344 b's' => e.schema = Some(value),
345 b't' => e.table = Some(value),
346 b'c' => e.column = Some(value),
347 b'n' => e.constraint = Some(value),
348 b'R' => e.routine = Some(value),
349 _ => {}
350 }
351 }
352 Ok(e)
353 }
354
355 pub fn severity(&self) -> &str {
357 &self.severity
358 }
359
360 pub fn code(&self) -> &str {
363 &self.code
364 }
365
366 pub fn message(&self) -> &str {
368 &self.message
369 }
370
371 pub fn detail(&self) -> Option<&str> {
373 self.detail.as_deref()
374 }
375
376 pub fn hint(&self) -> Option<&str> {
378 self.hint.as_deref()
379 }
380
381 pub fn position(&self) -> Option<u32> {
383 self.position
384 }
385
386 pub fn where_(&self) -> Option<&str> {
388 self.where_.as_deref()
389 }
390
391 pub fn schema(&self) -> Option<&str> {
393 self.schema.as_deref()
394 }
395
396 pub fn table(&self) -> Option<&str> {
398 self.table.as_deref()
399 }
400
401 pub fn column(&self) -> Option<&str> {
403 self.column.as_deref()
404 }
405
406 pub fn constraint(&self) -> Option<&str> {
408 self.constraint.as_deref()
409 }
410
411 pub fn routine(&self) -> Option<&str> {
416 self.routine.as_deref()
417 }
418}
419
420impl fmt::Display for DbError {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 write!(f, "{} {}: {}", self.severity, self.code, self.message)?;
423 if let Some(detail) = &self.detail {
424 write!(f, " (detail: {detail})")?;
425 }
426 if let Some(hint) = &self.hint {
427 write!(f, " (hint: {hint})")?;
428 }
429 if let Some(position) = self.position {
430 write!(f, " (at character {position})")?;
431 }
432 Ok(())
433 }
434}
435
436impl std::error::Error for DbError {}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn shown_with_its_giong_code_and_link() {
444 let e = Error::new(
445 ErrorKind::Auth,
446 "password authentication failed for user \"app\"",
447 );
448 assert_eq!(
449 e.to_string(),
450 "GIONG-E3003: password authentication failed for user \"app\". See \
451 https://github.com/giong-run/Giong/blob/main/docs/errors/E3003.md"
452 .replace("blob/main", concat!("blob/v", env!("CARGO_PKG_VERSION")))
453 );
454 assert_eq!(e.giong_code(), Code::PostgresAuth);
455 }
456
457 #[test]
458 fn the_code_and_the_error_survive_the_conversion_to_io() {
459 let e = Error::new(ErrorKind::PoolTimeout, "no connection became free");
460 let shown = e.to_string();
461 let io: io::Error = e.into();
462 assert_eq!(io.kind(), io::ErrorKind::TimedOut);
463 assert_eq!(io.to_string(), shown);
464 assert_eq!(giong::error::code(&io), Some(Code::PostgresPoolTimeout));
465 let wrapped = io.get_ref().unwrap();
466 let wrapped = wrapped.downcast_ref::<giong::error::Error>().unwrap();
467 let back = wrapped.get_ref().unwrap().downcast_ref::<Error>().unwrap();
468 assert_eq!(back.kind(), ErrorKind::PoolTimeout);
469 }
470
471 #[test]
472 fn every_kind_has_its_own_code() {
473 let kinds = [
474 ErrorKind::Config,
475 ErrorKind::Connect,
476 ErrorKind::Auth,
477 ErrorKind::Db,
478 ErrorKind::Type,
479 ErrorKind::RowCount,
480 ErrorKind::TooLarge,
481 ErrorKind::Closed,
482 ErrorKind::PoolTimeout,
483 ErrorKind::Protocol,
484 ErrorKind::Statement,
485 ];
486 let codes: std::collections::HashSet<_> = kinds.iter().map(|k| k.giong_code()).collect();
487 assert_eq!(codes.len(), kinds.len());
488 assert!(codes.iter().all(|c| (3001..3100).contains(&c.number())));
489 }
490}