Skip to main content

pglite_oxide/pglite/
errors.rs

1use std::error::Error;
2use std::fmt;
3
4use serde_json::Value;
5
6use crate::pglite::interface::QueryOptions;
7use crate::protocol::messages::DatabaseError;
8
9/// Rich error type that mirrors the TypeScript `PGliteError` by carrying the
10/// original database error along with query context.
11pub struct PgliteError {
12    source: DatabaseError,
13    query: String,
14    params: Vec<Value>,
15    query_options: Option<QueryOptions>,
16}
17
18impl PgliteError {
19    pub fn new(
20        source: DatabaseError,
21        query: impl Into<String>,
22        params: Vec<Value>,
23        query_options: Option<QueryOptions>,
24    ) -> Self {
25        Self {
26            source,
27            query: query.into(),
28            params,
29            query_options,
30        }
31    }
32
33    pub fn database_error(&self) -> &DatabaseError {
34        &self.source
35    }
36
37    pub fn query(&self) -> &str {
38        &self.query
39    }
40
41    pub fn params(&self) -> &[Value] {
42        &self.params
43    }
44
45    pub fn query_options(&self) -> Option<&QueryOptions> {
46        self.query_options.as_ref()
47    }
48}
49
50impl fmt::Display for PgliteError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        write!(f, "{}", self.source)
53    }
54}
55
56impl fmt::Debug for PgliteError {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.debug_struct("PgliteError")
59            .field("source", &self.source)
60            .field("query", &self.query)
61            .field("params", &self.params)
62            .field("has_query_options", &self.query_options.is_some())
63            .finish()
64    }
65}
66
67impl Error for PgliteError {
68    fn source(&self) -> Option<&(dyn Error + 'static)> {
69        Some(&self.source)
70    }
71}