use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
kind: Kind,
message: String,
code: i64,
attribute: Option<String>,
previous: Option<Box<Error>>,
raw: Option<Vec<u8>>,
driver: Option<Box<Driver>>,
marks: Marks,
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Marks(u8);
impl PartialEq for Marks {
fn eq(&self, _: &Self) -> bool {
true
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Mark {
Committed = 1,
Transaction = 2,
UnconfirmedCommit = 4,
}
#[derive(Debug, Clone, PartialEq, Default)]
struct Driver {
state: Option<String>,
code: Option<i64>,
labels: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Database,
Authorization,
Schema,
Contention,
Mismatch,
Refused,
Unconfirmed,
Character,
Conflict,
Dependency,
Duplicate,
Index,
Limit,
NotFound,
Operator,
Order,
Query,
Relationship,
Restricted,
Structure,
Timeout,
Transaction,
Truncate,
Type,
Unique,
Pdo,
TypeError,
ValueError,
Json,
DivisionByZero,
Exception,
DateMalformedIntervalString,
Error,
Runtime,
Redis,
Mongo,
MongoUnsent,
MongoUnexpectedValue,
DateMalformedString,
InvalidArgument,
BadMethodCall,
QueryValidation,
CacheUnavailable,
}
impl 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",
}
}
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))
}
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 {
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),
}
}
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()) }
}
}
}
pub fn with_code(mut self, code: i64) -> Self {
self.code = code;
self
}
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 }
}
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))
}
pub fn state(&self) -> Option<&str> {
self.driver.as_ref().and_then(|d| d.state.as_deref())
}
pub fn with_driver_code(mut self, code: i64) -> Self {
self.driver.get_or_insert_default().code = Some(code);
self
}
pub fn driver_code(&self) -> Option<i64> {
self.driver.as_ref().and_then(|d| d.code)
}
pub fn with_labels(mut self, labels: Vec<String>) -> Self {
self.driver.get_or_insert_default().labels = labels;
self
}
pub fn labels(&self) -> &[String] {
self.driver.as_ref().map_or(&[], |d| d.labels.as_slice())
}
pub fn with_previous(mut self, previous: Error) -> Self {
self.previous = Some(Box::new(previous));
self
}
pub fn order(message: impl Into<String>, attribute: Option<String>) -> Self {
Self { attribute, ..Self::new(Kind::Order, message) }
}
pub fn kind(&self) -> Kind {
self.kind
}
pub fn php_class(&self) -> &'static str {
self.kind.php_class()
}
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
}
pub fn is_engine_error(&self) -> bool {
matches!(self.kind, Kind::TypeError | Kind::ValueError | Kind::DivisionByZero | Kind::Error)
}
pub fn message(&self) -> &str {
&self.message
}
pub fn message_bytes(&self) -> &[u8] {
self.raw.as_deref().unwrap_or(self.message.as_bytes())
}
pub fn code(&self) -> i64 {
self.code
}
pub fn attribute(&self) -> Option<&str> {
self.attribute.as_deref()
}
pub fn previous(&self) -> Option<&Error> {
self.previous.as_deref()
}
pub(crate) fn mark(&mut self, mark: Mark) {
self.marks.0 |= mark as u8;
}
pub(crate) fn is_marked(&self, mark: Mark) -> bool {
self.marks.0 & mark as u8 != 0
}
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)
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub const UNIQUE_MESSAGE: &str = "Unique index violation";
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");
}
}