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 source: Option<io::Error>,
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35#[non_exhaustive]
36pub enum ErrorKind {
37 Config,
39 Connect,
42 Auth,
45 Db,
48 Type,
51 RowCount,
53 TooLarge,
56 Closed,
60 PoolTimeout,
63 Protocol,
66}
67
68impl ErrorKind {
69 pub fn giong_code(self) -> Code {
72 match self {
73 ErrorKind::Config => Code::PostgresConfig,
74 ErrorKind::Connect => Code::PostgresConnect,
75 ErrorKind::Auth => Code::PostgresAuth,
76 ErrorKind::Db => Code::PostgresServer,
77 ErrorKind::Type => Code::PostgresType,
78 ErrorKind::RowCount => Code::PostgresRowCount,
79 ErrorKind::TooLarge => Code::PostgresTooLarge,
80 ErrorKind::Closed => Code::PostgresClosed,
81 ErrorKind::PoolTimeout => Code::PostgresPoolTimeout,
82 ErrorKind::Protocol => Code::PostgresProtocol,
83 }
84 }
85}
86
87impl Error {
88 pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
89 Self(Arc::new(Inner {
90 kind,
91 message: message.into(),
92 db: None,
93 source: None,
94 }))
95 }
96
97 pub(crate) fn io(kind: ErrorKind, message: impl Into<String>, source: io::Error) -> Self {
98 Self(Arc::new(Inner {
99 kind,
100 message: message.into(),
101 db: None,
102 source: Some(source),
103 }))
104 }
105
106 pub(crate) fn from_db(db: DbError, note: Option<String>) -> Self {
107 Self(Arc::new(Inner {
108 kind: ErrorKind::Db,
109 message: note.unwrap_or_default(),
110 db: Some(db),
111 source: None,
112 }))
113 }
114
115 pub(crate) fn with_db(kind: ErrorKind, message: impl Into<String>, db: DbError) -> Self {
116 Self(Arc::new(Inner {
117 kind,
118 message: message.into(),
119 db: Some(db),
120 source: None,
121 }))
122 }
123
124 pub fn conversion(message: impl Into<String>) -> Self {
128 Self::new(ErrorKind::Type, message)
129 }
130
131 pub(crate) fn config(message: impl Into<String>) -> Self {
132 Self::new(ErrorKind::Config, message)
133 }
134
135 pub(crate) fn protocol(message: impl Into<String>) -> Self {
136 Self::new(
137 ErrorKind::Protocol,
138 format!(
139 "{}; the connection was closed (is this really a PostgreSQL server?)",
140 message.into()
141 ),
142 )
143 }
144
145 pub(crate) fn closed(message: impl Into<String>) -> Self {
146 Self::new(ErrorKind::Closed, message)
147 }
148
149 pub(crate) fn context(&self, context: &str) -> Self {
151 Self(Arc::new(Inner {
152 kind: self.0.kind,
153 message: if self.0.message.is_empty() {
154 context.to_owned()
155 } else {
156 format!("{context}: {}", self.0.message)
157 },
158 db: self.0.db.clone(),
159 source: self
160 .0
161 .source
162 .as_ref()
163 .map(|e| io::Error::new(e.kind(), e.to_string())),
164 }))
165 }
166
167 pub fn kind(&self) -> ErrorKind {
169 self.0.kind
170 }
171
172 pub fn giong_code(&self) -> Code {
176 self.0.kind.giong_code()
177 }
178
179 pub fn db(&self) -> Option<&DbError> {
182 self.0.db.as_ref()
183 }
184
185 pub fn code(&self) -> Option<&str> {
189 self.0.db.as_ref().map(|db| db.code())
190 }
191}
192
193impl Error {
194 fn what(&self) -> String {
197 let inner = &self.0;
198 let mut parts = Vec::with_capacity(3);
199 if !inner.message.is_empty() {
200 parts.push(inner.message.clone());
201 }
202 if let Some(db) = &inner.db {
203 parts.push(db.to_string());
204 }
205 if let Some(source) = &inner.source {
206 parts.push(source.to_string());
207 }
208 parts.join(": ")
209 }
210}
211
212impl fmt::Display for Error {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 let code = self.giong_code();
215 let what = self.what();
216 let stop = if what.ends_with('.') { "" } else { "." };
217 write!(f, "{code}: {what}{stop} See {}", code.url())
218 }
219}
220
221impl fmt::Debug for Error {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 f.debug_struct("Error")
224 .field("kind", &self.0.kind)
225 .field("message", &self.to_string())
226 .finish()
227 }
228}
229
230impl std::error::Error for Error {
231 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
232 match &self.0.source {
233 Some(e) => Some(e),
234 None => self.0.db.as_ref().map(|db| db as _),
235 }
236 }
237}
238
239impl From<Error> for io::Error {
240 fn from(e: Error) -> Self {
241 let kind = match (&e.0.source, e.kind()) {
242 (Some(source), _) => source.kind(),
243 (None, ErrorKind::Config) => io::ErrorKind::InvalidInput,
244 (None, ErrorKind::Auth) => io::ErrorKind::PermissionDenied,
245 (None, ErrorKind::Type | ErrorKind::Protocol) => io::ErrorKind::InvalidData,
246 (None, ErrorKind::PoolTimeout) => io::ErrorKind::TimedOut,
247 (None, ErrorKind::Closed) => io::ErrorKind::ConnectionAborted,
248 (None, _) => io::ErrorKind::Other,
249 };
250 io::Error::new(kind, giong::error::Error::wrap(e.giong_code(), e))
251 }
252}
253
254#[derive(Clone, Debug, PartialEq, Eq)]
256pub struct DbError {
257 severity: String,
258 code: String,
259 message: String,
260 detail: Option<String>,
261 hint: Option<String>,
262 position: Option<u32>,
263 where_: Option<String>,
264 schema: Option<String>,
265 table: Option<String>,
266 column: Option<String>,
267 constraint: Option<String>,
268}
269
270impl DbError {
271 pub(crate) fn parse(body: &[u8]) -> Result<Self, Error> {
273 let mut e = DbError {
274 severity: String::new(),
275 code: String::new(),
276 message: String::new(),
277 detail: None,
278 hint: None,
279 position: None,
280 where_: None,
281 schema: None,
282 table: None,
283 column: None,
284 constraint: None,
285 };
286 let mut rest = body;
287 loop {
288 let (&field, tail) = rest
289 .split_first()
290 .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
291 if field == 0 {
292 break;
293 }
294 let end = tail
295 .iter()
296 .position(|&b| b == 0)
297 .ok_or_else(|| Error::protocol("an error message from the server is truncated"))?;
298 let value = String::from_utf8_lossy(&tail[..end]).into_owned();
299 rest = &tail[end + 1..];
300 match field {
301 b'V' => e.severity = value,
302 b'S' if e.severity.is_empty() => e.severity = value,
303 b'C' => e.code = value,
304 b'M' => e.message = value,
305 b'D' => e.detail = Some(value),
306 b'H' => e.hint = Some(value),
307 b'P' => e.position = value.parse().ok(),
308 b'W' => e.where_ = Some(value),
309 b's' => e.schema = Some(value),
310 b't' => e.table = Some(value),
311 b'c' => e.column = Some(value),
312 b'n' => e.constraint = Some(value),
313 _ => {}
314 }
315 }
316 Ok(e)
317 }
318
319 pub fn severity(&self) -> &str {
321 &self.severity
322 }
323
324 pub fn code(&self) -> &str {
327 &self.code
328 }
329
330 pub fn message(&self) -> &str {
332 &self.message
333 }
334
335 pub fn detail(&self) -> Option<&str> {
337 self.detail.as_deref()
338 }
339
340 pub fn hint(&self) -> Option<&str> {
342 self.hint.as_deref()
343 }
344
345 pub fn position(&self) -> Option<u32> {
347 self.position
348 }
349
350 pub fn where_(&self) -> Option<&str> {
352 self.where_.as_deref()
353 }
354
355 pub fn schema(&self) -> Option<&str> {
357 self.schema.as_deref()
358 }
359
360 pub fn table(&self) -> Option<&str> {
362 self.table.as_deref()
363 }
364
365 pub fn column(&self) -> Option<&str> {
367 self.column.as_deref()
368 }
369
370 pub fn constraint(&self) -> Option<&str> {
372 self.constraint.as_deref()
373 }
374}
375
376impl fmt::Display for DbError {
377 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378 write!(f, "{} {}: {}", self.severity, self.code, self.message)?;
379 if let Some(detail) = &self.detail {
380 write!(f, " (detail: {detail})")?;
381 }
382 if let Some(hint) = &self.hint {
383 write!(f, " (hint: {hint})")?;
384 }
385 if let Some(position) = self.position {
386 write!(f, " (at character {position})")?;
387 }
388 Ok(())
389 }
390}
391
392impl std::error::Error for DbError {}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn shown_with_its_giong_code_and_link() {
400 let e = Error::new(
401 ErrorKind::Auth,
402 "password authentication failed for user \"app\"",
403 );
404 assert_eq!(
405 e.to_string(),
406 "GIONG-E3003: password authentication failed for user \"app\". See \
407 https://github.com/giong-run/Giong/blob/main/docs/errors/E3003.md"
408 );
409 assert_eq!(e.giong_code(), Code::PostgresAuth);
410 }
411
412 #[test]
413 fn the_code_and_the_error_survive_the_conversion_to_io() {
414 let e = Error::new(ErrorKind::PoolTimeout, "no connection became free");
415 let shown = e.to_string();
416 let io: io::Error = e.into();
417 assert_eq!(io.kind(), io::ErrorKind::TimedOut);
418 assert_eq!(io.to_string(), shown);
419 assert_eq!(giong::error::code(&io), Some(Code::PostgresPoolTimeout));
420 let wrapped = io.get_ref().unwrap();
421 let wrapped = wrapped.downcast_ref::<giong::error::Error>().unwrap();
422 let back = wrapped.get_ref().unwrap().downcast_ref::<Error>().unwrap();
423 assert_eq!(back.kind(), ErrorKind::PoolTimeout);
424 }
425
426 #[test]
427 fn every_kind_has_its_own_code() {
428 let kinds = [
429 ErrorKind::Config,
430 ErrorKind::Connect,
431 ErrorKind::Auth,
432 ErrorKind::Db,
433 ErrorKind::Type,
434 ErrorKind::RowCount,
435 ErrorKind::TooLarge,
436 ErrorKind::Closed,
437 ErrorKind::PoolTimeout,
438 ErrorKind::Protocol,
439 ];
440 let codes: std::collections::HashSet<_> = kinds.iter().map(|k| k.giong_code()).collect();
441 assert_eq!(codes.len(), kinds.len());
442 assert!(codes.iter().all(|c| (3001..3100).contains(&c.number())));
443 }
444}