use littlegraph_core::{Error as CoreError, Neo4jStoreError, TransactionErrorKind};
use pyo3::create_exception;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
create_exception!(_littlegraph, LittleGraphError, PyException);
create_exception!(_littlegraph, InterfaceError, LittleGraphError);
create_exception!(_littlegraph, DatabaseClosedError, InterfaceError);
create_exception!(_littlegraph, DatabaseWorkerError, InterfaceError);
create_exception!(_littlegraph, ForkedProcessError, InterfaceError);
create_exception!(_littlegraph, TransactionActiveError, InterfaceError);
create_exception!(_littlegraph, TransactionClosedError, InterfaceError);
create_exception!(
_littlegraph,
TransactionAccessedConcurrentlyError,
InterfaceError
);
create_exception!(_littlegraph, DataError, LittleGraphError);
create_exception!(_littlegraph, ParameterTypeError, DataError);
create_exception!(_littlegraph, ParameterValueError, DataError);
create_exception!(_littlegraph, UnsupportedValueError, DataError);
create_exception!(_littlegraph, DatabaseError, LittleGraphError);
create_exception!(_littlegraph, QueryError, LittleGraphError);
create_exception!(_littlegraph, CypherSyntaxError, QueryError);
create_exception!(_littlegraph, UnsupportedQueryError, QueryError);
create_exception!(_littlegraph, QueryValidationError, QueryError);
create_exception!(_littlegraph, QueryExecutionError, QueryError);
create_exception!(_littlegraph, ProcedureError, QueryError);
create_exception!(_littlegraph, AccessModeError, QueryError);
create_exception!(_littlegraph, TransactionError, LittleGraphError);
create_exception!(_littlegraph, TransactionRollbackOnlyError, TransactionError);
create_exception!(_littlegraph, InvalidSavepointError, TransactionError);
create_exception!(_littlegraph, TransactionTimeoutError, TransactionError);
create_exception!(_littlegraph, TransactionCancelledError, TransactionError);
create_exception!(
_littlegraph,
TransactionResourceLimitError,
TransactionError
);
create_exception!(_littlegraph, TransactionConflictError, TransactionError);
create_exception!(_littlegraph, StoragePoisonedError, TransactionError);
macro_rules! add_exceptions {
($module:expr, $($exception:ty),+ $(,)?) => {
$(
$module.add(stringify!($exception), $module.py().get_type::<$exception>())?;
)+
};
}
pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
add_exceptions!(
module,
LittleGraphError,
InterfaceError,
DatabaseClosedError,
DatabaseWorkerError,
ForkedProcessError,
TransactionActiveError,
TransactionClosedError,
TransactionAccessedConcurrentlyError,
DataError,
ParameterTypeError,
ParameterValueError,
UnsupportedValueError,
DatabaseError,
QueryError,
CypherSyntaxError,
UnsupportedQueryError,
QueryValidationError,
QueryExecutionError,
ProcedureError,
AccessModeError,
TransactionError,
TransactionRollbackOnlyError,
InvalidSavepointError,
TransactionTimeoutError,
TransactionCancelledError,
TransactionResourceLimitError,
TransactionConflictError,
StoragePoisonedError,
);
Ok(())
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum ErrorClass {
Database,
Worker,
Forked,
ParameterType,
ParameterValue,
UnsupportedValue,
Syntax,
UnsupportedQuery,
QueryValidation,
QueryExecution,
Procedure,
AccessMode,
TransactionRollbackOnly,
InvalidSavepoint,
TransactionTimeout,
TransactionCancelled,
TransactionResourceLimit,
TransactionConflict,
StoragePoisoned,
Transaction,
}
#[derive(Debug)]
pub(crate) struct BindingError {
pub(crate) class: ErrorClass,
pub(crate) code: &'static str,
pub(crate) message: String,
pub(crate) path: Option<String>,
}
impl BindingError {
pub(crate) fn worker(message: impl Into<String>) -> Self {
Self {
class: ErrorClass::Worker,
code: "Database.WorkerUnavailable",
message: message.into(),
path: None,
}
}
pub(crate) fn forked() -> Self {
Self {
class: ErrorClass::Forked,
code: "Interface.ForkedProcess",
message: "database handles cannot be used after fork; reopen the database in the child process".to_owned(),
path: None,
}
}
pub(crate) fn parameter_type(message: impl Into<String>) -> Self {
Self::new(ErrorClass::ParameterType, "Data.ParameterType", message)
}
pub(crate) fn parameter_value(message: impl Into<String>) -> Self {
Self::new(ErrorClass::ParameterValue, "Data.ParameterValue", message)
}
pub(crate) fn unsupported_value(message: impl Into<String>) -> Self {
Self::new(
ErrorClass::UnsupportedValue,
"Data.UnsupportedValue",
message,
)
}
pub(crate) fn resource_limit(message: impl Into<String>) -> Self {
Self::new(
ErrorClass::TransactionResourceLimit,
"Transaction.ResourceLimit",
message,
)
}
fn new(class: ErrorClass, code: &'static str, message: impl Into<String>) -> Self {
Self {
class,
code,
message: message.into(),
path: None,
}
}
pub(crate) fn into_pyerr(self, py: Python<'_>) -> PyErr {
let error = match self.class {
ErrorClass::Database => PyErr::new::<DatabaseError, _>(self.message.clone()),
ErrorClass::Worker => PyErr::new::<DatabaseWorkerError, _>(self.message.clone()),
ErrorClass::Forked => PyErr::new::<ForkedProcessError, _>(self.message.clone()),
ErrorClass::ParameterType => PyErr::new::<ParameterTypeError, _>(self.message.clone()),
ErrorClass::ParameterValue => {
PyErr::new::<ParameterValueError, _>(self.message.clone())
}
ErrorClass::UnsupportedValue => {
PyErr::new::<UnsupportedValueError, _>(self.message.clone())
}
ErrorClass::Syntax => PyErr::new::<CypherSyntaxError, _>(self.message.clone()),
ErrorClass::UnsupportedQuery => {
PyErr::new::<UnsupportedQueryError, _>(self.message.clone())
}
ErrorClass::QueryValidation => {
PyErr::new::<QueryValidationError, _>(self.message.clone())
}
ErrorClass::QueryExecution => {
PyErr::new::<QueryExecutionError, _>(self.message.clone())
}
ErrorClass::Procedure => PyErr::new::<ProcedureError, _>(self.message.clone()),
ErrorClass::AccessMode => PyErr::new::<AccessModeError, _>(self.message.clone()),
ErrorClass::TransactionRollbackOnly => {
PyErr::new::<TransactionRollbackOnlyError, _>(self.message.clone())
}
ErrorClass::InvalidSavepoint => {
PyErr::new::<InvalidSavepointError, _>(self.message.clone())
}
ErrorClass::TransactionTimeout => {
PyErr::new::<TransactionTimeoutError, _>(self.message.clone())
}
ErrorClass::TransactionCancelled => {
PyErr::new::<TransactionCancelledError, _>(self.message.clone())
}
ErrorClass::TransactionResourceLimit => {
PyErr::new::<TransactionResourceLimitError, _>(self.message.clone())
}
ErrorClass::TransactionConflict => {
PyErr::new::<TransactionConflictError, _>(self.message.clone())
}
ErrorClass::StoragePoisoned => {
PyErr::new::<StoragePoisonedError, _>(self.message.clone())
}
ErrorClass::Transaction => PyErr::new::<TransactionError, _>(self.message.clone()),
};
let value = error.value(py);
let _ = value.setattr("code", self.code);
let _ = value.setattr("message", &self.message);
if let Some(path) = self.path {
let _ = value.setattr("path", path);
}
error
}
}
impl From<CoreError> for BindingError {
fn from(error: CoreError) -> Self {
if let CoreError::Transaction(kind) = &error {
let class = match kind {
TransactionErrorKind::RollbackOnly => ErrorClass::TransactionRollbackOnly,
TransactionErrorKind::InvalidSavepoint => ErrorClass::InvalidSavepoint,
TransactionErrorKind::TimedOut => ErrorClass::TransactionTimeout,
TransactionErrorKind::Cancelled => ErrorClass::TransactionCancelled,
TransactionErrorKind::ResourceLimit => ErrorClass::TransactionResourceLimit,
TransactionErrorKind::Conflict => ErrorClass::TransactionConflict,
TransactionErrorKind::StoragePoisoned => ErrorClass::StoragePoisoned,
_ => ErrorClass::Transaction,
};
return Self::new(class, transaction_code(*kind), error.to_string());
}
let class = match &error {
CoreError::Parse(_) => ErrorClass::Syntax,
CoreError::UnsupportedQueryFeature(_) | CoreError::UnsupportedWriteQuery(_) => {
ErrorClass::UnsupportedQuery
}
CoreError::Validation(_)
| CoreError::InvalidGraphReference(_)
| CoreError::DataLoad(_) => ErrorClass::QueryValidation,
CoreError::UnknownProcedure { .. }
| CoreError::DeferredProcedure { .. }
| CoreError::InvalidProcedureCall { .. }
| CoreError::UnsupportedProcedureMode { .. } => ErrorClass::Procedure,
CoreError::AccessMode => ErrorClass::AccessMode,
CoreError::Execution(_) | CoreError::Console(_) | CoreError::Json(_) => {
ErrorClass::QueryExecution
}
CoreError::Neo4jStore(_) | CoreError::Io(_) => ErrorClass::Database,
_ => ErrorClass::QueryExecution,
};
let code = match &error {
CoreError::Neo4jStore(store) => match store {
Neo4jStoreError::NotADirectory { .. } => "Database.NotADirectory",
Neo4jStoreError::MissingFile { .. } => "Database.MissingStoreFile",
Neo4jStoreError::Read { source, .. }
if source.kind() == std::io::ErrorKind::NotFound =>
{
"Database.NotFound"
}
Neo4jStoreError::DatabaseLocked { .. } | Neo4jStoreError::DatabaseLock { .. } => {
"Database.Locked"
}
Neo4jStoreError::UnsupportedFormat { .. }
| Neo4jStoreError::UnsupportedWritableStore { .. } => "Database.UnsupportedStore",
_ => "Database.Storage",
},
CoreError::Io(_) => "Database.Io",
CoreError::Parse(_) => "Query.Syntax",
CoreError::UnsupportedQueryFeature(_) | CoreError::UnsupportedWriteQuery(_) => {
"Query.Unsupported"
}
CoreError::Validation(_)
| CoreError::InvalidGraphReference(_)
| CoreError::DataLoad(_) => "Query.Validation",
CoreError::UnknownProcedure { .. }
| CoreError::DeferredProcedure { .. }
| CoreError::InvalidProcedureCall { .. }
| CoreError::UnsupportedProcedureMode { .. } => "Query.Procedure",
CoreError::AccessMode => "Query.AccessMode",
_ => "Query.Execution",
};
let path = match &error {
CoreError::Neo4jStore(store) => store_path(store),
_ => None,
};
Self {
class,
code,
message: error.to_string(),
path,
}
}
}
fn store_path(error: &Neo4jStoreError) -> Option<String> {
let path = match error {
Neo4jStoreError::NotADirectory { path }
| Neo4jStoreError::MissingFile { path }
| Neo4jStoreError::Read { path, .. }
| Neo4jStoreError::Write { path, .. }
| Neo4jStoreError::DatabaseLocked { path }
| Neo4jStoreError::DatabaseLock { path, .. }
| Neo4jStoreError::InvalidJournal { path, .. }
| Neo4jStoreError::UnsupportedWritableStore { path, .. }
| Neo4jStoreError::CommitRecovery { path, .. }
| Neo4jStoreError::Truncated { path, .. }
| Neo4jStoreError::InvalidMetadata { path, .. }
| Neo4jStoreError::InvalidPageLayout { path, .. }
| Neo4jStoreError::RecordOutOfBounds { path, .. }
| Neo4jStoreError::RecordRead { path, .. }
| Neo4jStoreError::RecordWrite { path, .. }
| Neo4jStoreError::InvalidRecord { path, .. }
| Neo4jStoreError::UnsupportedFormat { path, .. } => path,
_ => return None,
};
Some(path.to_string_lossy().into_owned())
}
#[allow(dead_code)]
pub(crate) fn transaction_code(kind: TransactionErrorKind) -> &'static str {
match kind {
TransactionErrorKind::AlreadyActive => "Transaction.AlreadyActive",
TransactionErrorKind::NotActive => "Transaction.NotActive",
TransactionErrorKind::RollbackOnly => "Transaction.RollbackOnly",
TransactionErrorKind::InvalidSavepoint => "Transaction.InvalidSavepoint",
TransactionErrorKind::TimedOut => "Transaction.TimedOut",
TransactionErrorKind::Cancelled => "Transaction.Cancelled",
TransactionErrorKind::ResourceLimit => "Transaction.ResourceLimit",
TransactionErrorKind::Conflict => "Transaction.Conflict",
TransactionErrorKind::StoragePoisoned => "Transaction.StoragePoisoned",
_ => "Transaction.Unknown",
}
}