Skip to main content

ic_dbms_api/
error.rs

1//! Error type returned by every endpoint of an ic-dbms canister.
2
3use candid::CandidType;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6#[cfg(feature = "sql")]
7use wasm_dbms_api::prelude::SqlError;
8use wasm_dbms_api::prelude::{
9    DbmsError, MemoryError, MigrationError, QueryError, TableError, TransactionError,
10};
11
12use crate::acl::AclError;
13
14/// Error returned by every endpoint of an ic-dbms canister.
15///
16/// Engine errors are wrapped in [`IcDbmsError::Dbms`]; access control
17/// failures, which the engine knows nothing about, are
18/// [`IcDbmsError::Acl`]. With the `sql` feature, errors raised while
19/// parsing, planning or running a SQL statement are `IcDbmsError::Sql`.
20#[derive(Debug, Error, CandidType, Serialize, Deserialize)]
21pub enum IcDbmsError {
22    /// The canister access control list refused the call.
23    #[error("Access control error: {0}")]
24    Acl(#[from] AclError),
25    /// The database engine reported an error.
26    #[error("{0}")]
27    Dbms(#[from] DbmsError),
28    /// The SQL front-end rejected or failed to run a statement.
29    #[cfg(feature = "sql")]
30    #[cfg_attr(docsrs, doc(cfg(feature = "sql")))]
31    #[error("SQL error: {0}")]
32    Sql(#[from] SqlError),
33}
34
35impl From<MemoryError> for IcDbmsError {
36    fn from(error: MemoryError) -> Self {
37        Self::Dbms(DbmsError::from(error))
38    }
39}
40
41impl From<MigrationError> for IcDbmsError {
42    fn from(error: MigrationError) -> Self {
43        Self::Dbms(DbmsError::from(error))
44    }
45}
46
47impl From<QueryError> for IcDbmsError {
48    fn from(error: QueryError) -> Self {
49        Self::Dbms(DbmsError::from(error))
50    }
51}
52
53impl From<TableError> for IcDbmsError {
54    fn from(error: TableError) -> Self {
55        Self::Dbms(DbmsError::from(error))
56    }
57}
58
59impl From<TransactionError> for IcDbmsError {
60    fn from(error: TransactionError) -> Self {
61        Self::Dbms(DbmsError::from(error))
62    }
63}
64
65/// Result type returned by every endpoint of an ic-dbms canister.
66pub type IcDbmsResult<T> = Result<T, IcDbmsError>;
67
68#[cfg(test)]
69mod test {
70
71    use super::*;
72    use crate::acl::{AclError, AclPermission};
73
74    #[test]
75    fn test_should_display_dbms_error_transparently() {
76        let error = IcDbmsError::Dbms(DbmsError::Memory(MemoryError::OutOfBounds));
77        assert_eq!(
78            error.to_string(),
79            "Memory error: Stable memory access out of bounds"
80        );
81        let error = IcDbmsError::Dbms(DbmsError::Query(QueryError::UnknownColumn(
82            "foo".to_string(),
83        )));
84        assert_eq!(error.to_string(), "Query error: Unknown column: foo");
85        let error = IcDbmsError::Dbms(DbmsError::Validation("invalid email".to_string()));
86        assert_eq!(error.to_string(), "Validation error: invalid email");
87    }
88
89    #[test]
90    fn test_should_display_acl_error() {
91        let error = IcDbmsError::Acl(AclError::AccessDenied {
92            required: AclPermission::Admin.into(),
93            table: None,
94        });
95        assert_eq!(
96            error.to_string(),
97            "Access control error: access denied: the caller lacks the Admin permission"
98        );
99    }
100
101    #[test]
102    fn test_should_convert_from_engine_errors() {
103        let error: IcDbmsError = MemoryError::OutOfBounds.into();
104        assert!(matches!(
105            error,
106            IcDbmsError::Dbms(DbmsError::Memory(MemoryError::OutOfBounds))
107        ));
108        let error: IcDbmsError = QueryError::UnknownColumn("col".to_string()).into();
109        assert!(matches!(error, IcDbmsError::Dbms(DbmsError::Query(_))));
110        let error: IcDbmsError = TableError::TableNotFound.into();
111        assert!(matches!(error, IcDbmsError::Dbms(DbmsError::Table(_))));
112        let error: IcDbmsError = TransactionError::NoActiveTransaction.into();
113        assert!(matches!(
114            error,
115            IcDbmsError::Dbms(DbmsError::Transaction(_))
116        ));
117        let error: IcDbmsError = DbmsError::Sanitize("x".to_string()).into();
118        assert!(matches!(error, IcDbmsError::Dbms(DbmsError::Sanitize(_))));
119    }
120
121    #[test]
122    fn test_should_convert_from_acl_error() {
123        let error: IcDbmsError = AclError::LastAdmin.into();
124        assert!(matches!(error, IcDbmsError::Acl(AclError::LastAdmin)));
125    }
126
127    #[test]
128    fn test_should_candid_roundtrip() {
129        let error = IcDbmsError::Acl(AclError::AnonymousPrincipal);
130        let bytes = candid::encode_one(&error).expect("encode");
131        let decoded: IcDbmsError = candid::decode_one(&bytes).expect("decode");
132        assert!(matches!(
133            decoded,
134            IcDbmsError::Acl(AclError::AnonymousPrincipal)
135        ));
136    }
137
138    #[cfg(feature = "sql")]
139    #[test]
140    fn test_should_wrap_sql_error() {
141        use wasm_dbms_api::prelude::SqlError;
142
143        let error: IcDbmsError = SqlError::MissingWhereClause.into();
144        assert!(matches!(
145            error,
146            IcDbmsError::Sql(SqlError::MissingWhereClause)
147        ));
148        assert_eq!(
149            error.to_string(),
150            "SQL error: UPDATE and DELETE require a WHERE clause"
151        );
152    }
153
154    #[cfg(feature = "sql")]
155    #[test]
156    fn test_should_candid_roundtrip_sql_error() {
157        use wasm_dbms_api::prelude::SqlError;
158
159        let error = IcDbmsError::Sql(SqlError::UnknownTable("ghosts".to_string()));
160        let bytes = candid::encode_one(&error).expect("encode");
161        let decoded: IcDbmsError = candid::decode_one(&bytes).expect("decode");
162        assert!(matches!(
163            decoded,
164            IcDbmsError::Sql(SqlError::UnknownTable(table)) if table == "ghosts"
165        ));
166    }
167}