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