utopia-database 0.1.0

Document database: collections, attributes, indexes, documents, queries, permissions, relationships and tenancy over pluggable adapters (PostgreSQL, MariaDB, MySQL, SQLite, in-memory, Redis, Pool, Mirror).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! The errors database operations fail with.

use std::fmt;

/// What a database operation failed with: a kind (one per PHP exception
/// class), a message, and the integer code PHP's exception carries.
///
/// PHP: `Utopia\Database\Exception` and its subclasses in
/// `Utopia\Database\Exception\*`, plus the driver and engine exceptions that
/// escape the library unmapped (`PDOException`, `TypeError`, ...). The kind is
/// the class ([`Error::php_class`]); `instanceof` is [`Error::is_a`] (a
/// [`Kind::Unique`] error is also a [`Kind::Duplicate`] one, as `Unique`
/// extends `Duplicate`).
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    kind: Kind,
    message: String,
    code: i64,
    /// The attribute an [`Kind::Order`] error is about (`getAttribute()`).
    attribute: Option<String>,
    /// The exception this one wraps (`getPrevious()`).
    previous: Option<Box<Error>>,
    /// The message as PHP has it, when it is not UTF-8 (`message` is then
    /// its lossy form).
    raw: Option<Vec<u8>>,
    /// What a driver reported, when it did (boxed: most errors carry none).
    driver: Option<Box<Driver>>,
    /// What the database recorded about this failure (PHP keeps it in
    /// `WeakMap`s keyed by the exception object); never compared.
    marks: Marks,
}

/// The facts a database records about a failure it let through: PHP's
/// `$committedFailures`, `$transactionFailures` and `$unconfirmedCommits`
/// `WeakMap`s of `Trait\Transactions`, carried by the error itself.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Marks(u8);

impl PartialEq for Marks {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

/// A fact [`Marks`] records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Mark {
    /// Raised after its outermost transaction committed (`$committedFailures`).
    Committed = 1,
    /// Let through by an adapter transaction (`$transactionFailures`).
    Transaction = 2,
    /// The `Unconfirmed` failure of a commit, not one its callback threw
    /// (`$unconfirmedCommits`).
    UnconfirmedCommit = 4,
}

/// The codes a driver error carries besides the integer code.
#[derive(Debug, Clone, PartialEq, Default)]
struct Driver {
    /// The string code (a SQLSTATE such as `HY000`) the error was built
    /// with (`$state`).
    state: Option<String>,
    /// The driver's own error code of a [`Kind::Pdo`] error
    /// (`PDOException::$errorInfo[1]`, such as MySQL's `2006`).
    code: Option<i64>,
    /// The server's error labels of a [`Kind::Mongo`] error
    /// (`Utopia\Mongo\Exception::getErrorLabels()`).
    labels: Vec<String>,
}

/// The kinds of [`Error`], one per PHP exception class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// `Utopia\Database\Exception`: any other failure.
    Database,
    /// `Exception\Authorization`: the roles lack a permission.
    Authorization,
    /// `Exception\Schema`: a schema definition or a document breaks the rules
    /// of its collection's schema (the parent of [`Kind::Structure`],
    /// [`Kind::Type`], [`Kind::Character`], [`Kind::Truncate`],
    /// [`Kind::Index`], [`Kind::Dependency`], [`Kind::Limit`] and
    /// [`Kind::Relationship`]).
    Schema,
    /// `Exception\Contention`: the engine aborted a statement over a lock
    /// conflict (a [`Kind::Transaction`]).
    Contention,
    /// `Exception\Mismatch`: a resource exists with another definition (a
    /// [`Kind::Duplicate`]).
    Mismatch,
    /// `Exception\Refused`: an adapter reported, without an error, that it
    /// did not apply a schema change.
    Refused,
    /// `Exception\Unconfirmed`: a commit could not be confirmed, so its
    /// writes may or may not be stored.
    Unconfirmed,
    /// `Exception\Character`: a value has characters the adapter cannot store.
    Character,
    /// `Exception\Conflict`: the document changed after the request started.
    Conflict,
    /// `Exception\Dependency`: an attribute is used by an index.
    Dependency,
    /// `Exception\Duplicate`: a collection, attribute, index or document exists.
    Duplicate,
    /// `Exception\Index`: an invalid index.
    Index,
    /// `Exception\Limit`: a limit (attributes, indexes, size, bounds) is reached.
    Limit,
    /// `Exception\NotFound`: a collection, attribute, index or document is missing.
    NotFound,
    /// `Exception\Operator`: an operator cannot apply.
    Operator,
    /// `Exception\Order`: an order or cursor attribute is unusable.
    Order,
    /// `Exception\Query`: an invalid query.
    Query,
    /// `Exception\Relationship`: an invalid relationship operation.
    Relationship,
    /// `Exception\Restricted`: an `onDelete: restrict` relationship blocks a delete.
    Restricted,
    /// `Exception\Structure`: a document does not match its collection.
    Structure,
    /// `Exception\Timeout`: the statement exceeded the configured timeout.
    Timeout,
    /// `Exception\Transaction`: a transaction could not start, commit or roll back.
    Transaction,
    /// `Exception\Truncate`: a value is longer than its column.
    Truncate,
    /// `Exception\Type`: a value of the wrong type for its column.
    Type,
    /// `Exception\Unique`: a unique index is violated (a [`Kind::Duplicate`]).
    Unique,
    /// `PDOException`: a driver error the adapter does not map.
    Pdo,
    /// `TypeError`, raised by the engine on a wrong argument type.
    TypeError,
    /// `ValueError`, raised by the engine on a wrong argument value.
    ValueError,
    /// `JsonException`.
    Json,
    /// `DivisionByZeroError`, raised by the engine on a division or modulo by zero.
    DivisionByZero,
    /// `Exception`: PHP's base exception, thrown by library code with `new \Exception`.
    Exception,
    /// `DateMalformedIntervalStringException`: `DateInterval` rejected an
    /// interval string (`DateTime::addSeconds` with `PHP_INT_MIN` seconds).
    DateMalformedIntervalString,
    /// `Error`: an engine error (using an object as an array, a string
    /// offset that cannot be assigned or unset, ...).
    Error,
    /// `RuntimeException`: raised by a caller's callback (a transaction's
    /// body, an `onNext`) and passed through.
    Runtime,
    /// `RedisException`: a Redis command of the Redis adapter failed outside
    /// a transaction wrapper (phpredis's exception, passed through).
    Redis,
    /// `Utopia\Mongo\Exception`: a MongoDB failure the Mongo adapter does
    /// not map (passed through from utopia-php/mongo).
    Mongo,
    /// `Utopia\Mongo\UnsentException`: a MongoDB command that never reached
    /// the server (passed through from utopia-php/mongo).
    MongoUnsent,
    /// `MongoDB\Driver\Exception\UnexpectedValueException`: PHP's MongoDB
    /// extension refused to encode a command (a key holding a null byte, a
    /// string that is not UTF-8).
    MongoUnexpectedValue,
    /// `DateMalformedStringException`: `new DateTime($value)` rejected a
    /// date string.
    DateMalformedString,
    /// `InvalidArgumentException`: an invalid argument (the integer
    /// arithmetic of [`crate::validator::big_int::BigInt`], a profiler
    /// capacity below 1, an invalid hook argument).
    InvalidArgument,
    /// `BadMethodCallException`: a call the object cannot serve (a query
    /// builder without an executor).
    BadMethodCall,
    /// `Utopia\Query\Exception\ValidationException`: a statement the query
    /// library's builder refused, passed through where PHP's adapter does
    /// not wrap it in a [`Kind::Query`] error (an upsert's statement).
    QueryValidation,
    /// `Utopia\Cache\Exception\Unavailable`: the cache could not confirm
    /// an operation (a versioned record that kept changing or is invalid,
    /// a flush that failed), passed through from utopia-php/cache.
    CacheUnavailable,
}

impl Kind {
    /// The PHP class of errors of this kind.
    pub fn php_class(self) -> &'static str {
        match self {
            Kind::Database => "Utopia\\Database\\Exception",
            Kind::Authorization => "Utopia\\Database\\Exception\\Authorization",
            Kind::Schema => "Utopia\\Database\\Exception\\Schema",
            Kind::Contention => "Utopia\\Database\\Exception\\Contention",
            Kind::Mismatch => "Utopia\\Database\\Exception\\Mismatch",
            Kind::Refused => "Utopia\\Database\\Exception\\Refused",
            Kind::Unconfirmed => "Utopia\\Database\\Exception\\Unconfirmed",
            Kind::Character => "Utopia\\Database\\Exception\\Character",
            Kind::Conflict => "Utopia\\Database\\Exception\\Conflict",
            Kind::Dependency => "Utopia\\Database\\Exception\\Dependency",
            Kind::Duplicate => "Utopia\\Database\\Exception\\Duplicate",
            Kind::Index => "Utopia\\Database\\Exception\\Index",
            Kind::Limit => "Utopia\\Database\\Exception\\Limit",
            Kind::NotFound => "Utopia\\Database\\Exception\\NotFound",
            Kind::Operator => "Utopia\\Database\\Exception\\Operator",
            Kind::Order => "Utopia\\Database\\Exception\\Order",
            Kind::Query => "Utopia\\Database\\Exception\\Query",
            Kind::Relationship => "Utopia\\Database\\Exception\\Relationship",
            Kind::Restricted => "Utopia\\Database\\Exception\\Restricted",
            Kind::Structure => "Utopia\\Database\\Exception\\Structure",
            Kind::Timeout => "Utopia\\Database\\Exception\\Timeout",
            Kind::Transaction => "Utopia\\Database\\Exception\\Transaction",
            Kind::Truncate => "Utopia\\Database\\Exception\\Truncate",
            Kind::Type => "Utopia\\Database\\Exception\\Type",
            Kind::Unique => "Utopia\\Database\\Exception\\Unique",
            Kind::Pdo => "PDOException",
            Kind::TypeError => "TypeError",
            Kind::ValueError => "ValueError",
            Kind::Json => "JsonException",
            Kind::DivisionByZero => "DivisionByZeroError",
            Kind::Exception => "Exception",
            Kind::DateMalformedIntervalString => "DateMalformedIntervalStringException",
            Kind::Error => "Error",
            Kind::Runtime => "RuntimeException",
            Kind::Redis => "RedisException",
            Kind::Mongo => "Utopia\\Mongo\\Exception",
            Kind::MongoUnsent => "Utopia\\Mongo\\UnsentException",
            Kind::MongoUnexpectedValue => "MongoDB\\Driver\\Exception\\UnexpectedValueException",
            Kind::DateMalformedString => "DateMalformedStringException",
            Kind::InvalidArgument => "InvalidArgumentException",
            Kind::BadMethodCall => "BadMethodCallException",
            Kind::QueryValidation => "Utopia\\Query\\Exception\\ValidationException",
            Kind::CacheUnavailable => "Utopia\\Cache\\Exception\\Unavailable",
        }
    }

    /// The kind of errors of the PHP class `class` (the inverse of
    /// [`Kind::php_class`]); `None` for a class no kind stands for.
    pub fn from_php_class(class: &str) -> Option<Kind> {
        const ALL: [Kind; 43] = [
            Kind::Database,
            Kind::Authorization,
            Kind::Schema,
            Kind::Contention,
            Kind::Mismatch,
            Kind::Refused,
            Kind::Unconfirmed,
            Kind::Character,
            Kind::Conflict,
            Kind::Dependency,
            Kind::Duplicate,
            Kind::Index,
            Kind::Limit,
            Kind::NotFound,
            Kind::Operator,
            Kind::Order,
            Kind::Query,
            Kind::Relationship,
            Kind::Restricted,
            Kind::Structure,
            Kind::Timeout,
            Kind::Transaction,
            Kind::Truncate,
            Kind::Type,
            Kind::Unique,
            Kind::Pdo,
            Kind::TypeError,
            Kind::ValueError,
            Kind::Json,
            Kind::DivisionByZero,
            Kind::Exception,
            Kind::DateMalformedIntervalString,
            Kind::Error,
            Kind::Runtime,
            Kind::Redis,
            Kind::Mongo,
            Kind::MongoUnsent,
            Kind::MongoUnexpectedValue,
            Kind::DateMalformedString,
            Kind::InvalidArgument,
            Kind::BadMethodCall,
            Kind::QueryValidation,
            Kind::CacheUnavailable,
        ];
        let class = class.strip_prefix('\\').unwrap_or(class);
        ALL.into_iter().find(|k| k.php_class().eq_ignore_ascii_case(class))
    }

    /// The kind this kind's PHP class extends, if it extends another
    /// database exception: `Unique` and `Mismatch` extend
    /// [`Kind::Duplicate`], `Contention` extends [`Kind::Transaction`],
    /// `Order` and `Operator` extend [`Kind::Query`], the schema violations
    /// extend [`Kind::Schema`], and every other `Exception\*` extends
    /// [`Kind::Database`].
    pub fn parent(self) -> Option<Kind> {
        match self {
            Kind::Unique | Kind::Mismatch => Some(Kind::Duplicate),
            Kind::Contention => Some(Kind::Transaction),
            Kind::Order | Kind::Operator => Some(Kind::Query),
            Kind::Structure
            | Kind::Type
            | Kind::Character
            | Kind::Truncate
            | Kind::Index
            | Kind::Dependency
            | Kind::Limit
            | Kind::Relationship => Some(Kind::Schema),
            Kind::Database
            | Kind::Pdo
            | Kind::TypeError
            | Kind::ValueError
            | Kind::Json
            | Kind::DivisionByZero
            | Kind::Exception
            | Kind::DateMalformedIntervalString
            | Kind::Error
            | Kind::Runtime
            | Kind::Redis
            | Kind::Mongo
            | Kind::MongoUnexpectedValue
            | Kind::DateMalformedString
            | Kind::InvalidArgument
            | Kind::BadMethodCall
            | Kind::QueryValidation
            | Kind::CacheUnavailable => None,
            Kind::MongoUnsent => Some(Kind::Mongo),
            _ => Some(Kind::Database),
        }
    }
}

impl Error {
    /// An error of `kind` with `message` and code `0`.
    pub fn new(kind: Kind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            code: 0,
            attribute: None,
            previous: None,
            raw: None,
            driver: None,
            marks: Marks(0),
        }
    }

    /// An error of `kind` whose message is bytes (PHP messages are: one can
    /// quote a string that is not UTF-8).
    pub fn from_bytes(kind: Kind, message: Vec<u8>) -> Self {
        match String::from_utf8(message) {
            Ok(message) => Self::new(kind, message),
            Err(e) => {
                let raw = e.into_bytes();
                Self { raw: Some(raw.clone()), ..Self::new(kind, String::from_utf8_lossy(&raw).into_owned()) }
            }
        }
    }

    /// The same error with a code. PHP: `Utopia\Database\Exception` takes an
    /// `int|string` code and turns a non-numeric string into `0`; pass the
    /// integer it ends up as.
    pub fn with_code(mut self, code: i64) -> Self {
        self.code = code;
        self
    }

    /// The integer a string code becomes (`Utopia\Database\Exception`'s
    /// constructor): a numeric string is cast to an integer (`"12"` is 12,
    /// `" 1.9"` is 1, `"1e3"` is 1000, beyond `i64` it saturates), anything
    /// else is 0.
    ///
    /// ```
    /// use utopia_database::Error;
    ///
    /// assert_eq!(Error::string_code(b"42"), 42);
    /// assert_eq!(Error::string_code(b"1.5"), 1);
    /// assert_eq!(Error::string_code(b"HY000"), 0);
    /// ```
    ///
    /// PHP: `Utopia\Database\Exception::__construct` with a string `$code`
    /// (`is_numeric($code) ? (int) $code : 0`).
    pub fn string_code(code: &[u8]) -> i64 {
        if php_std::value::numeric_bytes_ex(code).is_some() { php_std::format::str_to_int(code) } else { 0 }
    }

    /// The same error with a string code: kept as [`Error::state`], and as
    /// the integer [`Error::string_code`] turns it into.
    pub fn with_string_code(mut self, code: &[u8]) -> Self {
        self.driver.get_or_insert_default().state = Some(String::from_utf8_lossy(code).into_owned());
        self.with_code(Self::string_code(code))
    }

    /// The string code the error was built with, such as a SQLSTATE
    /// (`$state`); `None` for an integer code.
    pub fn state(&self) -> Option<&str> {
        self.driver.as_ref().and_then(|d| d.state.as_deref())
    }

    /// The same error with the driver's own error code
    /// (`PDOException::$errorInfo[1]`), which [`crate::connection::is_lost`]
    /// reads.
    pub fn with_driver_code(mut self, code: i64) -> Self {
        self.driver.get_or_insert_default().code = Some(code);
        self
    }

    /// The driver's own error code (`$errorInfo[1]`), when the error carries
    /// one.
    pub fn driver_code(&self) -> Option<i64> {
        self.driver.as_ref().and_then(|d| d.code)
    }

    /// The same error with the server's error labels (a MongoDB error's
    /// `TransientTransactionError`, `UnknownTransactionCommitResult`, ...).
    pub fn with_labels(mut self, labels: Vec<String>) -> Self {
        self.driver.get_or_insert_default().labels = labels;
        self
    }

    /// The server's error labels (`getErrorLabels()`); empty when the error
    /// carries none.
    pub fn labels(&self) -> &[String] {
        self.driver.as_ref().map_or(&[], |d| d.labels.as_slice())
    }

    /// The same error wrapping `previous`.
    pub fn with_previous(mut self, previous: Error) -> Self {
        self.previous = Some(Box::new(previous));
        self
    }

    /// An [`Kind::Order`] error about `attribute`.
    pub fn order(message: impl Into<String>, attribute: Option<String>) -> Self {
        Self { attribute, ..Self::new(Kind::Order, message) }
    }

    /// The kind (PHP class) of the error.
    pub fn kind(&self) -> Kind {
        self.kind
    }

    /// The PHP class of the error.
    pub fn php_class(&self) -> &'static str {
        self.kind.php_class()
    }

    /// Whether the error is of `kind` or of a kind extending it
    /// (`instanceof`).
    pub fn is_a(&self, kind: Kind) -> bool {
        let mut k = Some(self.kind);
        while let Some(current) = k {
            if current == kind {
                return true;
            }
            k = current.parent();
        }
        false
    }

    /// Whether the error is an engine `\Error` (`TypeError`, `ValueError`,
    /// `DivisionByZeroError`, `Error`) rather than an `\Exception`: code
    /// that catches `Exception` lets it through.
    pub fn is_engine_error(&self) -> bool {
        matches!(self.kind, Kind::TypeError | Kind::ValueError | Kind::DivisionByZero | Kind::Error)
    }

    /// The message (`getMessage()`), lossy when [`Error::message_bytes`]
    /// is not UTF-8.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The message (`getMessage()`) byte for byte.
    pub fn message_bytes(&self) -> &[u8] {
        self.raw.as_deref().unwrap_or(self.message.as_bytes())
    }

    /// The code (`getCode()`).
    pub fn code(&self) -> i64 {
        self.code
    }

    /// The attribute of an [`Kind::Order`] error (`getAttribute()`).
    pub fn attribute(&self) -> Option<&str> {
        self.attribute.as_deref()
    }

    /// The wrapped error (`getPrevious()`).
    pub fn previous(&self) -> Option<&Error> {
        self.previous.as_deref()
    }

    /// Records `mark` on the error.
    pub(crate) fn mark(&mut self, mark: Mark) {
        self.marks.0 |= mark as u8;
    }

    /// Whether the error carries `mark`.
    pub(crate) fn is_marked(&self, mark: Mark) -> bool {
        self.marks.0 & mark as u8 != 0
    }

    /// Removes `mark`, answering whether the error carried it.
    pub(crate) fn take_mark(&mut self, mark: Mark) -> bool {
        let had = self.is_marked(mark);
        self.marks.0 &= !(mark as u8);
        had
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.previous.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
    }
}

impl From<php_std::EngineError> for Error {
    fn from(e: php_std::EngineError) -> Self {
        let kind = match e.class {
            "TypeError" => Kind::TypeError,
            "ValueError" => Kind::ValueError,
            "JsonException" => Kind::Json,
            "Error" => Kind::Error,
            "InvalidArgumentException" => Kind::InvalidArgument,
            _ => Kind::Exception,
        };
        Error::new(kind, e.message)
    }
}

/// `Result` with [`Error`].
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// The message of every unique index violation (`Exception\Unique::MESSAGE`).
pub const UNIQUE_MESSAGE: &str = "Unique index violation";

/// Shorthands for the error of each kind.
macro_rules! constructors {
    ($($name:ident => $kind:ident),* $(,)?) => {
        impl Error {
            $(
                #[doc = concat!("A [`Kind::", stringify!($kind), "`] error.")]
                pub fn $name(message: impl Into<String>) -> Self {
                    Self::new(Kind::$kind, message)
                }
            )*
        }
    };
}

constructors! {
    database => Database,
    authorization => Authorization,
    schema => Schema,
    contention => Contention,
    mismatch => Mismatch,
    refused => Refused,
    unconfirmed => Unconfirmed,
    exception => Exception,
    character => Character,
    conflict => Conflict,
    dependency => Dependency,
    duplicate => Duplicate,
    index => Index,
    limit => Limit,
    not_found => NotFound,
    operator => Operator,
    query => Query,
    relationship => Relationship,
    restricted => Restricted,
    structure => Structure,
    timeout => Timeout,
    transaction => Transaction,
    truncate => Truncate,
    type_error => Type,
    unique => Unique,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unique_is_a_duplicate() {
        let e = Error::unique("Unique index violation");
        assert!(e.is_a(Kind::Unique));
        assert!(e.is_a(Kind::Duplicate));
        assert!(e.is_a(Kind::Database));
        assert!(!e.is_a(Kind::NotFound));
        assert_eq!(e.php_class(), "Utopia\\Database\\Exception\\Unique");
    }
}