Skip to main content

utopia_query/
error.rs

1//! [`Error`]: why a query could not be parsed, validated or compiled.
2
3use std::fmt;
4use std::sync::Arc;
5
6/// Why a query could not be parsed, validated or compiled.
7///
8/// PHP: one variant per exception class the library throws, with the same
9/// message ([`Error::php_class`] names the class).
10#[derive(Debug, Clone, thiserror::Error)]
11pub enum Error {
12    /// A malformed query, or an error raised by [`Error::new`].
13    ///
14    /// PHP: `Utopia\Query\Exception`.
15    #[error("{message}")]
16    Query {
17        /// The message (lossy when [`Error::message_bytes`] is not UTF-8).
18        message: String,
19        /// The code (`0` unless given to [`Error::new`]).
20        code: i64,
21        /// The error this one wraps.
22        previous: Option<Arc<dyn std::error::Error + Send + Sync>>,
23        /// The exact message, when it is not UTF-8 (a message quoting part
24        /// of a multi-byte character of the input).
25        raw: Option<Arc<[u8]>>,
26    },
27    /// An input the library refuses: an unsafe identifier, a missing table, an
28    /// invalid option.
29    ///
30    /// PHP: `Utopia\Query\Exception\ValidationException`.
31    #[error("{0}")]
32    Validation(String),
33    /// A feature the dialect cannot express.
34    ///
35    /// PHP: `Utopia\Query\Exception\UnsupportedException`.
36    #[error("{0}")]
37    Unsupported(String),
38    /// An invalid constructor argument of a hook.
39    ///
40    /// PHP: `\InvalidArgumentException`.
41    #[error("{0}")]
42    InvalidArgument(String),
43    /// A name that is not one of an enumeration's values.
44    ///
45    /// PHP: `\ValueError`, from `Method::from()` and the other enums' `from()`.
46    #[error("{0}")]
47    InvalidValue(String),
48    /// An argument of the wrong type, where PHP's type checks reject it
49    /// (only where a Rust type cannot rule it out, such as a nested query
50    /// that is not an array).
51    ///
52    /// PHP: `\TypeError`.
53    #[error("{0}")]
54    Type(String),
55    /// A statement executed without an executor.
56    ///
57    /// PHP: `\BadMethodCallException`.
58    #[error("{0}")]
59    NoExecutor(String),
60    /// A value PHP's engine cannot convert, such as an object in a string
61    /// (`Object of class stdClass could not be converted to string`).
62    ///
63    /// PHP: `\Error`.
64    #[error("{0}")]
65    Engine(String),
66    /// A value `json_encode` cannot encode (invalid UTF-8, a non-finite
67    /// float), with the code PHP's `json_last_error()` reports.
68    ///
69    /// PHP: `\JsonException`.
70    #[error("{message}")]
71    Json {
72        /// The message.
73        message: String,
74        /// The `JSON_ERROR_*` code.
75        code: i64,
76    },
77}
78
79impl PartialEq for Error {
80    /// Same class, message and code.
81    fn eq(&self, other: &Self) -> bool {
82        self.php_class() == other.php_class() && self.to_string() == other.to_string() && self.code() == other.code()
83    }
84}
85
86impl Error {
87    /// A [`Error::Query`] with `message` and `code`, as `new Exception($message, $code)`.
88    ///
89    /// ```
90    /// use utopia_query::{Code, Error};
91    ///
92    /// assert_eq!(Error::new("test", Code::from("42")).code(), 42);
93    /// assert_eq!(Error::new("test", Code::from("abc")).code(), 0);
94    /// ```
95    ///
96    /// ```php
97    /// use Utopia\Query\Exception;
98    ///
99    /// echo (new Exception('test', '42'))->getCode(), "\n";  // 42
100    /// echo (new Exception('test', 'abc'))->getCode(), "\n"; // 0
101    /// ```
102    pub fn new(message: impl Into<String>, code: impl Into<Code>) -> Self {
103        Error::Query { message: message.into(), code: code.into().0, previous: None, raw: None }
104    }
105
106    /// A [`Error::Query`] wrapping `previous`, as `new Exception($message, $code, $previous)`.
107    pub fn with_previous(
108        message: impl Into<String>,
109        code: impl Into<Code>,
110        previous: Arc<dyn std::error::Error + Send + Sync>,
111    ) -> Self {
112        Error::Query { message: message.into(), code: code.into().0, previous: Some(previous), raw: None }
113    }
114
115    /// A [`Error::Query`] with code 0.
116    pub(crate) fn query(message: impl Into<String>) -> Self {
117        Error::new(message, 0)
118    }
119
120    /// A [`Error::Query`] with code 0 whose message is bytes (PHP strings
121    /// are: a message can quote a partial UTF-8 character).
122    pub(crate) fn query_bytes(message: Vec<u8>) -> Self {
123        match String::from_utf8(message) {
124            Ok(message) => Error::query(message),
125            Err(e) => {
126                let bytes = e.into_bytes();
127                Error::Query {
128                    message: String::from_utf8_lossy(&bytes).into_owned(),
129                    code: 0,
130                    previous: None,
131                    raw: Some(bytes.into()),
132                }
133            }
134        }
135    }
136
137    /// The message as PHP has it, byte for byte (`to_string()` is the same
138    /// text, lossy where it is not UTF-8).
139    ///
140    /// PHP: `getMessage()`.
141    pub fn message_bytes(&self) -> std::borrow::Cow<'_, [u8]> {
142        match self {
143            Error::Query { raw: Some(raw), .. } => std::borrow::Cow::Borrowed(raw),
144            other => std::borrow::Cow::Owned(other.to_string().into_bytes()),
145        }
146    }
147
148    /// The code: what [`Error::new`] was given, `0` for every error the library raises.
149    ///
150    /// PHP: `getCode()`.
151    pub fn code(&self) -> i64 {
152        match self {
153            Error::Query { code, .. } | Error::Json { code, .. } => *code,
154            _ => 0,
155        }
156    }
157
158    /// The error this one wraps.
159    ///
160    /// PHP: `getPrevious()`.
161    pub fn previous(&self) -> Option<&Arc<dyn std::error::Error + Send + Sync>> {
162        match self {
163            Error::Query { previous, .. } => previous.as_ref(),
164            _ => None,
165        }
166    }
167
168    /// The name of the PHP exception class this error matches.
169    ///
170    /// ```
171    /// use utopia_query::Error;
172    ///
173    /// assert_eq!(Error::Validation("x".into()).php_class(), "Utopia\\Query\\Exception\\ValidationException");
174    /// ```
175    ///
176    /// ```php
177    /// use Utopia\Query\Exception\ValidationException;
178    ///
179    /// echo ValidationException::class, "\n"; // Utopia\Query\Exception\ValidationException
180    /// ```
181    pub fn php_class(&self) -> &'static str {
182        match self {
183            Error::Query { .. } => "Utopia\\Query\\Exception",
184            Error::Validation(_) => "Utopia\\Query\\Exception\\ValidationException",
185            Error::Unsupported(_) => "Utopia\\Query\\Exception\\UnsupportedException",
186            Error::InvalidArgument(_) => "InvalidArgumentException",
187            Error::InvalidValue(_) => "ValueError",
188            Error::Type(_) => "TypeError",
189            Error::NoExecutor(_) => "BadMethodCallException",
190            Error::Engine(_) => "Error",
191            Error::Json { .. } => "JsonException",
192        }
193    }
194
195    /// Whether PHP's class for this error extends `Utopia\Query\Exception`
196    /// (catching that class catches it).
197    pub fn is_query_exception(&self) -> bool {
198        matches!(self, Error::Query { .. } | Error::Validation(_) | Error::Unsupported(_))
199    }
200}
201
202/// An exception code: an integer, or a string PHP turns into one (a numeric
203/// string is cast, anything else is `0`).
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub struct Code(pub i64);
206
207impl From<i64> for Code {
208    /// The integer.
209    fn from(code: i64) -> Self {
210        Code(code)
211    }
212}
213
214impl From<&str> for Code {
215    /// `(int)` of a numeric string, else `0`.
216    fn from(code: &str) -> Self {
217        Code(match php_std::value::numeric_str(code) {
218            Some(_) => php_std::format::Arg::Str(code.as_bytes()).to_int(),
219            None => 0,
220        })
221    }
222}
223
224impl fmt::Display for Code {
225    /// The integer.
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        write!(f, "{}", self.0)
228    }
229}
230
231/// The result of the library's fallible operations.
232pub type Result<T, E = Error> = std::result::Result<T, E>;