uqa_sql/catalog/
errors.rs1use crate::SQLError;
9
10pub fn storage_error(action: &str, err: &(dyn std::error::Error + 'static)) -> SQLError {
11 let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
12 while let Some(error) = source {
13 if let Some(error) = error.downcast_ref::<SQLError>() {
14 if matches!(error, SQLError::Diagnostic { .. }) {
16 return error.clone();
17 }
18 return SQLError::Routine {
19 sqlstate: error.sqlstate().unwrap_or("XX000").into(),
20 message: error.to_string(),
21 };
22 }
23 source = error.source();
24 }
25 SQLError::Internal(format!("{action} failed in storage backend: {err}"))
26}
27
28pub fn dml_storage_error(action: &str, err: impl std::fmt::Display) -> SQLError {
29 SQLError::Internal(format!("{action} failed in storage backend: {err}"))
30}
31
32pub fn dml_storage_error_with_control(
34 action: &str,
35 error: SQLError,
36 control: &uqa_core::memory::ProductionControl<'_>,
37) -> SQLError {
38 match error {
39 SQLError::Internal(message) => match control.format(format_args!(
40 "{action} failed in storage backend: {message}"
41 )) {
42 Ok(message) => SQLError::Internal(message.into_parts().0),
43 Err(error) => error.into(),
44 },
45 error => error,
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52 #[derive(Debug)]
53 struct CatalogFailure(SQLError);
54 impl std::fmt::Display for CatalogFailure {
55 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 formatter.write_str("catalog lookup failed")
57 }
58 }
59 impl std::error::Error for CatalogFailure {
60 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
61 Some(&self.0)
62 }
63 }
64 #[test]
65 fn catalog_error_chain_preserves_the_embedded_sql_diagnostic() {
66 let original = SQLError::Routine {
67 sqlstate: "42501".into(),
68 message: "permission denied for schema secret".into(),
69 };
70 let expected = original.to_string();
71 let error = storage_error("column type coercion", &CatalogFailure(original));
72 assert_eq!(error.sqlstate(), Some("42501"));
73 assert_eq!(error.to_string(), expected);
74 }
75 #[test]
76 fn catalog_error_chain_keeps_diagnostic_detail_and_hint() {
77 let original = SQLError::Diagnostic {
78 sqlstate: "42501".into(),
79 message: "permission denied to create \"pg_catalog.t\"".into(),
80 detail: Some("System catalog modifications are currently disallowed.".into()),
81 hint: None,
82 };
83 let error = storage_error("CREATE TABLE", &CatalogFailure(original));
84 assert!(matches!(
85 error,
86 SQLError::Diagnostic { sqlstate, detail: Some(detail), .. }
87 if sqlstate == "42501" && detail == "System catalog modifications are currently disallowed."
88 ));
89 }
90 #[test]
91 fn plain_catalog_errors_retain_the_operation_context() {
92 let error = std::io::Error::other("unavailable");
93 assert!(
94 matches!(storage_error("column type coercion", &error), SQLError::Internal(message) if message == "column type coercion failed in storage backend: unavailable")
95 );
96 }
97}