utopia_database/error.rs
1//! The errors database operations fail with.
2
3use std::fmt;
4
5/// What a database operation failed with: a kind (one per PHP exception
6/// class), a message, and the integer code PHP's exception carries.
7///
8/// PHP: `Utopia\Database\Exception` and its subclasses in
9/// `Utopia\Database\Exception\*`, plus the driver and engine exceptions that
10/// escape the library unmapped (`PDOException`, `TypeError`, ...). The kind is
11/// the class ([`Error::php_class`]); `instanceof` is [`Error::is_a`] (a
12/// [`Kind::Unique`] error is also a [`Kind::Duplicate`] one, as `Unique`
13/// extends `Duplicate`).
14#[derive(Debug, Clone, PartialEq)]
15pub struct Error {
16 kind: Kind,
17 message: String,
18 code: i64,
19 /// The attribute an [`Kind::Order`] error is about (`getAttribute()`).
20 attribute: Option<String>,
21 /// The exception this one wraps (`getPrevious()`).
22 previous: Option<Box<Error>>,
23 /// The message as PHP has it, when it is not UTF-8 (`message` is then
24 /// its lossy form).
25 raw: Option<Vec<u8>>,
26 /// What a driver reported, when it did (boxed: most errors carry none).
27 driver: Option<Box<Driver>>,
28 /// What the database recorded about this failure (PHP keeps it in
29 /// `WeakMap`s keyed by the exception object); never compared.
30 marks: Marks,
31}
32
33/// The facts a database records about a failure it let through: PHP's
34/// `$committedFailures`, `$transactionFailures` and `$unconfirmedCommits`
35/// `WeakMap`s of `Trait\Transactions`, carried by the error itself.
36#[derive(Debug, Clone, Copy, Default)]
37pub(crate) struct Marks(u8);
38
39impl PartialEq for Marks {
40 fn eq(&self, _: &Self) -> bool {
41 true
42 }
43}
44
45/// A fact [`Marks`] records.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[repr(u8)]
48pub(crate) enum Mark {
49 /// Raised after its outermost transaction committed (`$committedFailures`).
50 Committed = 1,
51 /// Let through by an adapter transaction (`$transactionFailures`).
52 Transaction = 2,
53 /// The `Unconfirmed` failure of a commit, not one its callback threw
54 /// (`$unconfirmedCommits`).
55 UnconfirmedCommit = 4,
56}
57
58/// The codes a driver error carries besides the integer code.
59#[derive(Debug, Clone, PartialEq, Default)]
60struct Driver {
61 /// The string code (a SQLSTATE such as `HY000`) the error was built
62 /// with (`$state`).
63 state: Option<String>,
64 /// The driver's own error code of a [`Kind::Pdo`] error
65 /// (`PDOException::$errorInfo[1]`, such as MySQL's `2006`).
66 code: Option<i64>,
67 /// The server's error labels of a [`Kind::Mongo`] error
68 /// (`Utopia\Mongo\Exception::getErrorLabels()`).
69 labels: Vec<String>,
70}
71
72/// The kinds of [`Error`], one per PHP exception class.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum Kind {
75 /// `Utopia\Database\Exception`: any other failure.
76 Database,
77 /// `Exception\Authorization`: the roles lack a permission.
78 Authorization,
79 /// `Exception\Schema`: a schema definition or a document breaks the rules
80 /// of its collection's schema (the parent of [`Kind::Structure`],
81 /// [`Kind::Type`], [`Kind::Character`], [`Kind::Truncate`],
82 /// [`Kind::Index`], [`Kind::Dependency`], [`Kind::Limit`] and
83 /// [`Kind::Relationship`]).
84 Schema,
85 /// `Exception\Contention`: the engine aborted a statement over a lock
86 /// conflict (a [`Kind::Transaction`]).
87 Contention,
88 /// `Exception\Mismatch`: a resource exists with another definition (a
89 /// [`Kind::Duplicate`]).
90 Mismatch,
91 /// `Exception\Refused`: an adapter reported, without an error, that it
92 /// did not apply a schema change.
93 Refused,
94 /// `Exception\Unconfirmed`: a commit could not be confirmed, so its
95 /// writes may or may not be stored.
96 Unconfirmed,
97 /// `Exception\Character`: a value has characters the adapter cannot store.
98 Character,
99 /// `Exception\Conflict`: the document changed after the request started.
100 Conflict,
101 /// `Exception\Dependency`: an attribute is used by an index.
102 Dependency,
103 /// `Exception\Duplicate`: a collection, attribute, index or document exists.
104 Duplicate,
105 /// `Exception\Index`: an invalid index.
106 Index,
107 /// `Exception\Limit`: a limit (attributes, indexes, size, bounds) is reached.
108 Limit,
109 /// `Exception\NotFound`: a collection, attribute, index or document is missing.
110 NotFound,
111 /// `Exception\Operator`: an operator cannot apply.
112 Operator,
113 /// `Exception\Order`: an order or cursor attribute is unusable.
114 Order,
115 /// `Exception\Query`: an invalid query.
116 Query,
117 /// `Exception\Relationship`: an invalid relationship operation.
118 Relationship,
119 /// `Exception\Restricted`: an `onDelete: restrict` relationship blocks a delete.
120 Restricted,
121 /// `Exception\Structure`: a document does not match its collection.
122 Structure,
123 /// `Exception\Timeout`: the statement exceeded the configured timeout.
124 Timeout,
125 /// `Exception\Transaction`: a transaction could not start, commit or roll back.
126 Transaction,
127 /// `Exception\Truncate`: a value is longer than its column.
128 Truncate,
129 /// `Exception\Type`: a value of the wrong type for its column.
130 Type,
131 /// `Exception\Unique`: a unique index is violated (a [`Kind::Duplicate`]).
132 Unique,
133 /// `PDOException`: a driver error the adapter does not map.
134 Pdo,
135 /// `TypeError`, raised by the engine on a wrong argument type.
136 TypeError,
137 /// `ValueError`, raised by the engine on a wrong argument value.
138 ValueError,
139 /// `JsonException`.
140 Json,
141 /// `DivisionByZeroError`, raised by the engine on a division or modulo by zero.
142 DivisionByZero,
143 /// `Exception`: PHP's base exception, thrown by library code with `new \Exception`.
144 Exception,
145 /// `DateMalformedIntervalStringException`: `DateInterval` rejected an
146 /// interval string (`DateTime::addSeconds` with `PHP_INT_MIN` seconds).
147 DateMalformedIntervalString,
148 /// `Error`: an engine error (using an object as an array, a string
149 /// offset that cannot be assigned or unset, ...).
150 Error,
151 /// `RuntimeException`: raised by a caller's callback (a transaction's
152 /// body, an `onNext`) and passed through.
153 Runtime,
154 /// `RedisException`: a Redis command of the Redis adapter failed outside
155 /// a transaction wrapper (phpredis's exception, passed through).
156 Redis,
157 /// `Utopia\Mongo\Exception`: a MongoDB failure the Mongo adapter does
158 /// not map (passed through from utopia-php/mongo).
159 Mongo,
160 /// `Utopia\Mongo\UnsentException`: a MongoDB command that never reached
161 /// the server (passed through from utopia-php/mongo).
162 MongoUnsent,
163 /// `MongoDB\Driver\Exception\UnexpectedValueException`: PHP's MongoDB
164 /// extension refused to encode a command (a key holding a null byte, a
165 /// string that is not UTF-8).
166 MongoUnexpectedValue,
167 /// `DateMalformedStringException`: `new DateTime($value)` rejected a
168 /// date string.
169 DateMalformedString,
170 /// `InvalidArgumentException`: an invalid argument (the integer
171 /// arithmetic of [`crate::validator::big_int::BigInt`], a profiler
172 /// capacity below 1, an invalid hook argument).
173 InvalidArgument,
174 /// `BadMethodCallException`: a call the object cannot serve (a query
175 /// builder without an executor).
176 BadMethodCall,
177 /// `Utopia\Query\Exception\ValidationException`: a statement the query
178 /// library's builder refused, passed through where PHP's adapter does
179 /// not wrap it in a [`Kind::Query`] error (an upsert's statement).
180 QueryValidation,
181 /// `Utopia\Cache\Exception\Unavailable`: the cache could not confirm
182 /// an operation (a versioned record that kept changing or is invalid,
183 /// a flush that failed), passed through from utopia-php/cache.
184 CacheUnavailable,
185}
186
187impl Kind {
188 /// The PHP class of errors of this kind.
189 pub fn php_class(self) -> &'static str {
190 match self {
191 Kind::Database => "Utopia\\Database\\Exception",
192 Kind::Authorization => "Utopia\\Database\\Exception\\Authorization",
193 Kind::Schema => "Utopia\\Database\\Exception\\Schema",
194 Kind::Contention => "Utopia\\Database\\Exception\\Contention",
195 Kind::Mismatch => "Utopia\\Database\\Exception\\Mismatch",
196 Kind::Refused => "Utopia\\Database\\Exception\\Refused",
197 Kind::Unconfirmed => "Utopia\\Database\\Exception\\Unconfirmed",
198 Kind::Character => "Utopia\\Database\\Exception\\Character",
199 Kind::Conflict => "Utopia\\Database\\Exception\\Conflict",
200 Kind::Dependency => "Utopia\\Database\\Exception\\Dependency",
201 Kind::Duplicate => "Utopia\\Database\\Exception\\Duplicate",
202 Kind::Index => "Utopia\\Database\\Exception\\Index",
203 Kind::Limit => "Utopia\\Database\\Exception\\Limit",
204 Kind::NotFound => "Utopia\\Database\\Exception\\NotFound",
205 Kind::Operator => "Utopia\\Database\\Exception\\Operator",
206 Kind::Order => "Utopia\\Database\\Exception\\Order",
207 Kind::Query => "Utopia\\Database\\Exception\\Query",
208 Kind::Relationship => "Utopia\\Database\\Exception\\Relationship",
209 Kind::Restricted => "Utopia\\Database\\Exception\\Restricted",
210 Kind::Structure => "Utopia\\Database\\Exception\\Structure",
211 Kind::Timeout => "Utopia\\Database\\Exception\\Timeout",
212 Kind::Transaction => "Utopia\\Database\\Exception\\Transaction",
213 Kind::Truncate => "Utopia\\Database\\Exception\\Truncate",
214 Kind::Type => "Utopia\\Database\\Exception\\Type",
215 Kind::Unique => "Utopia\\Database\\Exception\\Unique",
216 Kind::Pdo => "PDOException",
217 Kind::TypeError => "TypeError",
218 Kind::ValueError => "ValueError",
219 Kind::Json => "JsonException",
220 Kind::DivisionByZero => "DivisionByZeroError",
221 Kind::Exception => "Exception",
222 Kind::DateMalformedIntervalString => "DateMalformedIntervalStringException",
223 Kind::Error => "Error",
224 Kind::Runtime => "RuntimeException",
225 Kind::Redis => "RedisException",
226 Kind::Mongo => "Utopia\\Mongo\\Exception",
227 Kind::MongoUnsent => "Utopia\\Mongo\\UnsentException",
228 Kind::MongoUnexpectedValue => "MongoDB\\Driver\\Exception\\UnexpectedValueException",
229 Kind::DateMalformedString => "DateMalformedStringException",
230 Kind::InvalidArgument => "InvalidArgumentException",
231 Kind::BadMethodCall => "BadMethodCallException",
232 Kind::QueryValidation => "Utopia\\Query\\Exception\\ValidationException",
233 Kind::CacheUnavailable => "Utopia\\Cache\\Exception\\Unavailable",
234 }
235 }
236
237 /// The kind of errors of the PHP class `class` (the inverse of
238 /// [`Kind::php_class`]); `None` for a class no kind stands for.
239 pub fn from_php_class(class: &str) -> Option<Kind> {
240 const ALL: [Kind; 43] = [
241 Kind::Database,
242 Kind::Authorization,
243 Kind::Schema,
244 Kind::Contention,
245 Kind::Mismatch,
246 Kind::Refused,
247 Kind::Unconfirmed,
248 Kind::Character,
249 Kind::Conflict,
250 Kind::Dependency,
251 Kind::Duplicate,
252 Kind::Index,
253 Kind::Limit,
254 Kind::NotFound,
255 Kind::Operator,
256 Kind::Order,
257 Kind::Query,
258 Kind::Relationship,
259 Kind::Restricted,
260 Kind::Structure,
261 Kind::Timeout,
262 Kind::Transaction,
263 Kind::Truncate,
264 Kind::Type,
265 Kind::Unique,
266 Kind::Pdo,
267 Kind::TypeError,
268 Kind::ValueError,
269 Kind::Json,
270 Kind::DivisionByZero,
271 Kind::Exception,
272 Kind::DateMalformedIntervalString,
273 Kind::Error,
274 Kind::Runtime,
275 Kind::Redis,
276 Kind::Mongo,
277 Kind::MongoUnsent,
278 Kind::MongoUnexpectedValue,
279 Kind::DateMalformedString,
280 Kind::InvalidArgument,
281 Kind::BadMethodCall,
282 Kind::QueryValidation,
283 Kind::CacheUnavailable,
284 ];
285 let class = class.strip_prefix('\\').unwrap_or(class);
286 ALL.into_iter().find(|k| k.php_class().eq_ignore_ascii_case(class))
287 }
288
289 /// The kind this kind's PHP class extends, if it extends another
290 /// database exception: `Unique` and `Mismatch` extend
291 /// [`Kind::Duplicate`], `Contention` extends [`Kind::Transaction`],
292 /// `Order` and `Operator` extend [`Kind::Query`], the schema violations
293 /// extend [`Kind::Schema`], and every other `Exception\*` extends
294 /// [`Kind::Database`].
295 pub fn parent(self) -> Option<Kind> {
296 match self {
297 Kind::Unique | Kind::Mismatch => Some(Kind::Duplicate),
298 Kind::Contention => Some(Kind::Transaction),
299 Kind::Order | Kind::Operator => Some(Kind::Query),
300 Kind::Structure
301 | Kind::Type
302 | Kind::Character
303 | Kind::Truncate
304 | Kind::Index
305 | Kind::Dependency
306 | Kind::Limit
307 | Kind::Relationship => Some(Kind::Schema),
308 Kind::Database
309 | Kind::Pdo
310 | Kind::TypeError
311 | Kind::ValueError
312 | Kind::Json
313 | Kind::DivisionByZero
314 | Kind::Exception
315 | Kind::DateMalformedIntervalString
316 | Kind::Error
317 | Kind::Runtime
318 | Kind::Redis
319 | Kind::Mongo
320 | Kind::MongoUnexpectedValue
321 | Kind::DateMalformedString
322 | Kind::InvalidArgument
323 | Kind::BadMethodCall
324 | Kind::QueryValidation
325 | Kind::CacheUnavailable => None,
326 Kind::MongoUnsent => Some(Kind::Mongo),
327 _ => Some(Kind::Database),
328 }
329 }
330}
331
332impl Error {
333 /// An error of `kind` with `message` and code `0`.
334 pub fn new(kind: Kind, message: impl Into<String>) -> Self {
335 Self {
336 kind,
337 message: message.into(),
338 code: 0,
339 attribute: None,
340 previous: None,
341 raw: None,
342 driver: None,
343 marks: Marks(0),
344 }
345 }
346
347 /// An error of `kind` whose message is bytes (PHP messages are: one can
348 /// quote a string that is not UTF-8).
349 pub fn from_bytes(kind: Kind, message: Vec<u8>) -> Self {
350 match String::from_utf8(message) {
351 Ok(message) => Self::new(kind, message),
352 Err(e) => {
353 let raw = e.into_bytes();
354 Self { raw: Some(raw.clone()), ..Self::new(kind, String::from_utf8_lossy(&raw).into_owned()) }
355 }
356 }
357 }
358
359 /// The same error with a code. PHP: `Utopia\Database\Exception` takes an
360 /// `int|string` code and turns a non-numeric string into `0`; pass the
361 /// integer it ends up as.
362 pub fn with_code(mut self, code: i64) -> Self {
363 self.code = code;
364 self
365 }
366
367 /// The integer a string code becomes (`Utopia\Database\Exception`'s
368 /// constructor): a numeric string is cast to an integer (`"12"` is 12,
369 /// `" 1.9"` is 1, `"1e3"` is 1000, beyond `i64` it saturates), anything
370 /// else is 0.
371 ///
372 /// ```
373 /// use utopia_database::Error;
374 ///
375 /// assert_eq!(Error::string_code(b"42"), 42);
376 /// assert_eq!(Error::string_code(b"1.5"), 1);
377 /// assert_eq!(Error::string_code(b"HY000"), 0);
378 /// ```
379 ///
380 /// PHP: `Utopia\Database\Exception::__construct` with a string `$code`
381 /// (`is_numeric($code) ? (int) $code : 0`).
382 pub fn string_code(code: &[u8]) -> i64 {
383 if php_std::value::numeric_bytes_ex(code).is_some() { php_std::format::str_to_int(code) } else { 0 }
384 }
385
386 /// The same error with a string code: kept as [`Error::state`], and as
387 /// the integer [`Error::string_code`] turns it into.
388 pub fn with_string_code(mut self, code: &[u8]) -> Self {
389 self.driver.get_or_insert_default().state = Some(String::from_utf8_lossy(code).into_owned());
390 self.with_code(Self::string_code(code))
391 }
392
393 /// The string code the error was built with, such as a SQLSTATE
394 /// (`$state`); `None` for an integer code.
395 pub fn state(&self) -> Option<&str> {
396 self.driver.as_ref().and_then(|d| d.state.as_deref())
397 }
398
399 /// The same error with the driver's own error code
400 /// (`PDOException::$errorInfo[1]`), which [`crate::connection::is_lost`]
401 /// reads.
402 pub fn with_driver_code(mut self, code: i64) -> Self {
403 self.driver.get_or_insert_default().code = Some(code);
404 self
405 }
406
407 /// The driver's own error code (`$errorInfo[1]`), when the error carries
408 /// one.
409 pub fn driver_code(&self) -> Option<i64> {
410 self.driver.as_ref().and_then(|d| d.code)
411 }
412
413 /// The same error with the server's error labels (a MongoDB error's
414 /// `TransientTransactionError`, `UnknownTransactionCommitResult`, ...).
415 pub fn with_labels(mut self, labels: Vec<String>) -> Self {
416 self.driver.get_or_insert_default().labels = labels;
417 self
418 }
419
420 /// The server's error labels (`getErrorLabels()`); empty when the error
421 /// carries none.
422 pub fn labels(&self) -> &[String] {
423 self.driver.as_ref().map_or(&[], |d| d.labels.as_slice())
424 }
425
426 /// The same error wrapping `previous`.
427 pub fn with_previous(mut self, previous: Error) -> Self {
428 self.previous = Some(Box::new(previous));
429 self
430 }
431
432 /// An [`Kind::Order`] error about `attribute`.
433 pub fn order(message: impl Into<String>, attribute: Option<String>) -> Self {
434 Self { attribute, ..Self::new(Kind::Order, message) }
435 }
436
437 /// The kind (PHP class) of the error.
438 pub fn kind(&self) -> Kind {
439 self.kind
440 }
441
442 /// The PHP class of the error.
443 pub fn php_class(&self) -> &'static str {
444 self.kind.php_class()
445 }
446
447 /// Whether the error is of `kind` or of a kind extending it
448 /// (`instanceof`).
449 pub fn is_a(&self, kind: Kind) -> bool {
450 let mut k = Some(self.kind);
451 while let Some(current) = k {
452 if current == kind {
453 return true;
454 }
455 k = current.parent();
456 }
457 false
458 }
459
460 /// Whether the error is an engine `\Error` (`TypeError`, `ValueError`,
461 /// `DivisionByZeroError`, `Error`) rather than an `\Exception`: code
462 /// that catches `Exception` lets it through.
463 pub fn is_engine_error(&self) -> bool {
464 matches!(self.kind, Kind::TypeError | Kind::ValueError | Kind::DivisionByZero | Kind::Error)
465 }
466
467 /// The message (`getMessage()`), lossy when [`Error::message_bytes`]
468 /// is not UTF-8.
469 pub fn message(&self) -> &str {
470 &self.message
471 }
472
473 /// The message (`getMessage()`) byte for byte.
474 pub fn message_bytes(&self) -> &[u8] {
475 self.raw.as_deref().unwrap_or(self.message.as_bytes())
476 }
477
478 /// The code (`getCode()`).
479 pub fn code(&self) -> i64 {
480 self.code
481 }
482
483 /// The attribute of an [`Kind::Order`] error (`getAttribute()`).
484 pub fn attribute(&self) -> Option<&str> {
485 self.attribute.as_deref()
486 }
487
488 /// The wrapped error (`getPrevious()`).
489 pub fn previous(&self) -> Option<&Error> {
490 self.previous.as_deref()
491 }
492
493 /// Records `mark` on the error.
494 pub(crate) fn mark(&mut self, mark: Mark) {
495 self.marks.0 |= mark as u8;
496 }
497
498 /// Whether the error carries `mark`.
499 pub(crate) fn is_marked(&self, mark: Mark) -> bool {
500 self.marks.0 & mark as u8 != 0
501 }
502
503 /// Removes `mark`, answering whether the error carried it.
504 pub(crate) fn take_mark(&mut self, mark: Mark) -> bool {
505 let had = self.is_marked(mark);
506 self.marks.0 &= !(mark as u8);
507 had
508 }
509}
510
511impl fmt::Display for Error {
512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513 f.write_str(&self.message)
514 }
515}
516
517impl std::error::Error for Error {
518 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
519 self.previous.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
520 }
521}
522
523impl From<php_std::EngineError> for Error {
524 fn from(e: php_std::EngineError) -> Self {
525 let kind = match e.class {
526 "TypeError" => Kind::TypeError,
527 "ValueError" => Kind::ValueError,
528 "JsonException" => Kind::Json,
529 "Error" => Kind::Error,
530 "InvalidArgumentException" => Kind::InvalidArgument,
531 _ => Kind::Exception,
532 };
533 Error::new(kind, e.message)
534 }
535}
536
537/// `Result` with [`Error`].
538pub type Result<T, E = Error> = std::result::Result<T, E>;
539
540/// The message of every unique index violation (`Exception\Unique::MESSAGE`).
541pub const UNIQUE_MESSAGE: &str = "Unique index violation";
542
543/// Shorthands for the error of each kind.
544macro_rules! constructors {
545 ($($name:ident => $kind:ident),* $(,)?) => {
546 impl Error {
547 $(
548 #[doc = concat!("A [`Kind::", stringify!($kind), "`] error.")]
549 pub fn $name(message: impl Into<String>) -> Self {
550 Self::new(Kind::$kind, message)
551 }
552 )*
553 }
554 };
555}
556
557constructors! {
558 database => Database,
559 authorization => Authorization,
560 schema => Schema,
561 contention => Contention,
562 mismatch => Mismatch,
563 refused => Refused,
564 unconfirmed => Unconfirmed,
565 exception => Exception,
566 character => Character,
567 conflict => Conflict,
568 dependency => Dependency,
569 duplicate => Duplicate,
570 index => Index,
571 limit => Limit,
572 not_found => NotFound,
573 operator => Operator,
574 query => Query,
575 relationship => Relationship,
576 restricted => Restricted,
577 structure => Structure,
578 timeout => Timeout,
579 transaction => Transaction,
580 truncate => Truncate,
581 type_error => Type,
582 unique => Unique,
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 #[test]
590 fn unique_is_a_duplicate() {
591 let e = Error::unique("Unique index violation");
592 assert!(e.is_a(Kind::Unique));
593 assert!(e.is_a(Kind::Duplicate));
594 assert!(e.is_a(Kind::Database));
595 assert!(!e.is_a(Kind::NotFound));
596 assert_eq!(e.php_class(), "Utopia\\Database\\Exception\\Unique");
597 }
598}