1use super::SQLError;
10use std::fmt::Write as _;
11
12impl SQLError {
13 pub fn with_cleanup(self, cleanup: Self, operation: impl Into<String>) -> Self {
16 let operation = operation.into();
17 let (source, mut failures, mut detail) = match self {
18 Self::Cleanup {
19 source,
20 failures,
21 detail,
22 } => (source, failures, detail),
23 Self::Context { source, context } => {
24 return Self::Context {
25 source: Box::new(source.with_cleanup(cleanup, operation)),
26 context,
27 }
28 }
29 Self::Position { source, position } => {
30 return Self::Position {
31 source: Box::new(source.with_cleanup(cleanup, operation)),
32 position,
33 }
34 }
35 Self::InternalPosition {
36 source,
37 position,
38 query,
39 } => {
40 return Self::InternalPosition {
41 source: Box::new(source.with_cleanup(cleanup, operation)),
42 position,
43 query,
44 }
45 }
46 source => {
47 let detail = source.detail().unwrap_or_default().to_owned();
48 (Box::new(source), Vec::new(), detail)
49 }
50 };
51 if !detail.is_empty() {
52 detail.push('\n');
53 }
54 detail.push_str(&operation);
55 detail.push_str(": ");
56 if let Some(state) = cleanup.sqlstate() {
57 write!(detail, "[{state}] ").expect("writing to a String cannot fail");
58 }
59 detail.push_str(&cleanup.to_string());
60 for (label, value) in [
61 ("DETAIL", cleanup.detail()),
62 ("HINT", cleanup.hint()),
63 ("CONTEXT", cleanup.context()),
64 ("INTERNAL QUERY", cleanup.internal_query()),
65 ] {
66 if let Some(value) = value {
67 write!(detail, "\n{label}: {value}").expect("writing to a String cannot fail");
68 }
69 }
70 if let Some(position) = cleanup.position() {
71 write!(detail, "\nPOSITION: {position}").expect("writing to a String cannot fail");
72 }
73 if let Some(position) = cleanup.internal_position() {
74 write!(detail, "\nINTERNAL POSITION: {position}")
75 .expect("writing to a String cannot fail");
76 }
77 failures.push((operation, cleanup));
78 Self::Cleanup {
79 source,
80 failures,
81 detail,
82 }
83 }
84
85 pub fn cleanup(&self) -> Option<(&str, &Self)> {
87 match self {
88 Self::Cleanup { failures, .. } => failures
89 .last()
90 .map(|(operation, cleanup)| (operation.as_str(), cleanup)),
91 Self::Context { source, .. }
92 | Self::Position { source, .. }
93 | Self::InternalPosition { source, .. } => source.cleanup(),
94 _ => None,
95 }
96 }
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 fn diagnostic(state: &str, message: &str) -> SQLError {
104 SQLError::Diagnostic {
105 sqlstate: state.into(),
106 message: message.into(),
107 detail: Some(format!("{message} detail")),
108 hint: Some(format!("{message} hint")),
109 }
110 }
111
112 #[test]
113 fn cleanup_preserves_typed_primary_and_secondary_diagnostics() {
114 let error = diagnostic("22012", "primary")
115 .with_context("inner")
116 .at_position(Some(7))
117 .with_cleanup(
118 diagnostic("58030", "cleanup")
119 .with_context("cleanup context")
120 .at_position(Some(13)),
121 "close scan",
122 )
123 .with_context("outer")
124 .at_position(Some(19));
125 assert_eq!(error.to_string(), "primary");
126 assert_eq!(error.sqlstate(), Some("22012"));
127 assert_eq!(error.hint(), Some("primary hint"));
128 assert_eq!(error.context(), Some("inner\nouter"));
129 assert_eq!(error.position(), Some(7));
130 assert_eq!(error.primary().detail(), Some("primary detail"));
131 assert_eq!(error.detail(), Some("primary detail\nclose scan: [58030] cleanup\nDETAIL: cleanup detail\nHINT: cleanup hint\nCONTEXT: cleanup context\nPOSITION: 13"));
132 let (operation, cleanup) = error.cleanup().unwrap();
133 assert_eq!(operation, "close scan");
134 assert_eq!(cleanup.sqlstate(), Some("58030"));
135 assert_eq!(cleanup.detail(), Some("cleanup detail"));
136 assert_eq!(cleanup.hint(), Some("cleanup hint"));
137 assert_eq!(cleanup.context(), Some("cleanup context"));
138 assert_eq!(cleanup.position(), Some(13));
139
140 let error = error.with_cleanup(diagnostic("58000", "second cleanup"), "close child");
141 assert_eq!(error.to_string(), "primary");
142 assert_eq!(error.sqlstate(), Some("22012"));
143 let detail = error.detail().unwrap();
144 assert!(detail.contains("close scan: [58030] cleanup"));
145 assert!(detail.contains("close child: [58000] second cleanup"));
146 }
147
148 #[test]
149 fn cleanup_preserves_cancellation_application_code_and_routine_position() {
150 let error = SQLError::Cancelled(uqa_core::QueryCancelled::USER_REQUEST)
151 .with_cleanup(diagnostic("58030", "cleanup"), "close scan");
152 assert!(matches!(error.primary(), SQLError::Cancelled(_)));
153 assert_eq!(error.sqlstate(), Some("57014"));
154 let error = SQLError::NotificationRequiresSubscription
155 .with_cleanup(diagnostic("58030", "cleanup"), "close scan");
156 assert_eq!(error.code(), Some("NOTIFICATION_REQUIRES_SUBSCRIPTION"));
157 let error = diagnostic("22012", "primary")
158 .at_position(Some(3))
159 .with_cleanup(diagnostic("58030", "cleanup"), "close scan")
160 .in_routine_source("routine source", None)
161 .with_context("routine frame");
162 assert_eq!(error.position(), None);
163 assert_eq!(error.internal_position(), Some(3));
164 assert_eq!(error.internal_query(), Some("routine source"));
165 assert_eq!(error.context(), Some("routine frame"));
166 assert_eq!(error.cleanup().unwrap().1.sqlstate(), Some("58030"));
167 }
168
169 #[test]
170 fn multiple_failed_resources_append_to_one_cleanup_collection() {
171 let mut error = diagnostic("22012", "primary")
172 .with_context("routine")
173 .at_position(Some(4));
174 for index in 0..300 {
175 error = error.with_cleanup(
176 diagnostic("58030", "cleanup"),
177 format!("close scan {index}"),
178 );
179 }
180 assert_eq!(error.sqlstate(), Some("22012"));
181 assert_eq!(error.position(), Some(4));
182 assert_eq!(error.context(), Some("routine"));
183 assert_eq!(error.detail().unwrap().matches("primary detail").count(), 1);
184 assert_eq!(error.detail().unwrap().matches("close scan ").count(), 300);
185 let SQLError::Position { source, .. } = error else {
186 panic!("position");
187 };
188 let SQLError::Context { source, .. } = *source else {
189 panic!("context");
190 };
191 let SQLError::Cleanup {
192 source, failures, ..
193 } = *source
194 else {
195 panic!("cleanup");
196 };
197 assert!(matches!(*source, SQLError::Diagnostic { .. }));
198 assert_eq!(failures.len(), 300);
199 }
200}