1#[derive(Debug, Clone, thiserror::Error)]
10pub enum SQLError {
11 #[error("{0}")]
12 Parse(String),
13 #[error("{0}")]
15 ParseDiagnostic(Box<pg_query::Diagnostic>),
16 #[error("{0}")]
17 Unsupported(String),
18 #[error("LISTEN and UNLISTEN require a notification subscription")]
20 NotificationRequiresSubscription,
21 #[error("relation \"{0}\" does not exist")]
22 UnknownTable(String),
23 #[error("column \"{0}\" does not exist")]
24 UnknownColumn(String),
25 #[error("column reference \"{0}\" is ambiguous")]
26 AmbiguousColumn(String),
27 #[error("unknown function: {0}")]
28 UnknownFunction(String),
29 #[error("type mismatch: {0}")]
30 TypeMismatch(String),
31 #[error("invalid argument count for `{name}`: expected {expected}, got {actual}")]
32 BadArity {
33 name: String,
34 expected: String,
35 actual: usize,
36 },
37 #[error("No value supplied for parameter ${0}")]
38 MissingParam(usize),
39 #[error("vector dimension mismatch: expected {expected}, got {actual}")]
40 VectorDimMismatch { expected: usize, actual: usize },
41 #[error(
42 "{function_name}: column `{table}.{field}` has no text index; create one with CREATE INDEX ... ON {table} USING gin ({field})"
43 )]
44 TextIndexRequired {
45 function_name: String,
46 table: String,
47 field: String,
48 },
49 #[error("{0}")]
50 Cancelled(#[from] uqa_core::QueryCancelled),
51 #[error("{0}")]
54 Host(#[source] std::sync::Arc<dyn std::error::Error + Send + Sync>),
55 #[error("{message}")]
60 Routine { sqlstate: String, message: String },
61 #[error("{message}")]
63 Diagnostic {
64 sqlstate: String,
65 message: String,
66 detail: Option<String>,
67 hint: Option<String>,
68 },
69 #[error("{source}")]
71 Context { source: Box<Self>, context: String },
72 #[error("{source}")]
75 Cleanup {
76 source: Box<Self>,
77 failures: Vec<(String, Self)>,
78 detail: String,
79 },
80 #[error("{source}")]
82 Position { source: Box<Self>, position: u32 },
83 #[error("{source}")]
85 InternalPosition {
86 source: Box<Self>,
87 position: u32,
88 query: String,
89 },
90 #[error("internal error: {0}")]
91 Internal(String),
92}
93
94impl SQLError {
95 pub const fn code(&self) -> Option<&'static str> {
97 match self {
98 Self::NotificationRequiresSubscription => Some("NOTIFICATION_REQUIRES_SUBSCRIPTION"),
99 Self::Context { source, .. }
100 | Self::Cleanup { source, .. }
101 | Self::Position { source, .. }
102 | Self::InternalPosition { source, .. } => source.code(),
103 _ => None,
104 }
105 }
106
107 pub fn with_context(self, frame: impl AsRef<str>) -> Self {
109 match self {
110 Self::Cleanup {
111 source,
112 failures,
113 detail,
114 } => Self::Cleanup {
115 source: Box::new(source.with_context(frame)),
116 failures,
117 detail,
118 },
119 Self::InternalPosition {
120 source,
121 position,
122 query,
123 } => Self::InternalPosition {
124 source: Box::new(source.with_context(frame)),
125 position,
126 query,
127 },
128 Self::Position { source, position } => Self::Position {
129 source: Box::new(source.with_context(frame)),
130 position,
131 },
132 Self::Context {
133 source,
134 mut context,
135 } => {
136 context.push('\n');
137 context.push_str(frame.as_ref());
138 Self::Context { source, context }
139 }
140 source => Self::Context {
141 source: Box::new(source),
142 context: frame.as_ref().to_owned(),
143 },
144 }
145 }
146
147 pub fn context(&self) -> Option<&str> {
149 match self {
150 Self::Context { context, .. } => Some(context),
151 Self::Cleanup { source, .. }
152 | Self::Position { source, .. }
153 | Self::InternalPosition { source, .. } => source.context(),
154 _ => None,
155 }
156 }
157
158 pub fn primary(&self) -> &Self {
160 match self {
161 Self::Context { source, .. }
162 | Self::Cleanup { source, .. }
163 | Self::Position { source, .. }
164 | Self::InternalPosition { source, .. } => source.primary(),
165 _ => self,
166 }
167 }
168
169 pub fn at_position(self, position: Option<u32>) -> Self {
171 match position.filter(|position| *position != 0) {
172 Some(position) if self.position().is_none() && self.internal_position().is_none() => {
173 Self::Position {
174 source: Box::new(self),
175 position,
176 }
177 }
178 _ => self,
179 }
180 }
181
182 pub fn internal_position(&self) -> Option<u32> {
184 match self {
185 Self::InternalPosition { position, .. } => Some(*position),
186 Self::Context { source, .. }
187 | Self::Cleanup { source, .. }
188 | Self::Position { source, .. } => source.internal_position(),
189 _ => None,
190 }
191 }
192
193 pub fn internal_query(&self) -> Option<&str> {
195 match self {
196 Self::InternalPosition { query, .. } => Some(query),
197 Self::Context { source, .. }
198 | Self::Cleanup { source, .. }
199 | Self::Position { source, .. } => source.internal_query(),
200 _ => None,
201 }
202 }
203
204 pub(crate) fn in_routine_source(
205 self,
206 body: &str,
207 origin: Option<&crate::ast::RoutineBodyOrigin>,
208 ) -> Self {
209 let Some(position) = self.position() else {
210 return self;
211 };
212 let source = self.without_position();
213 match origin.and_then(|origin| origin.position(position)) {
214 Some(position) => source.at_position(Some(position)),
215 None => Self::InternalPosition {
216 source: Box::new(source),
217 position,
218 query: body.to_owned(),
219 },
220 }
221 }
222
223 fn without_position(self) -> Self {
224 match self {
225 Self::Position { source, .. } => source.without_position(),
226 Self::Context { source, context } => Self::Context {
227 source: Box::new(source.without_position()),
228 context,
229 },
230 Self::Cleanup {
231 source,
232 failures,
233 detail,
234 } => Self::Cleanup {
235 source: Box::new(source.without_position()),
236 failures,
237 detail,
238 },
239 Self::ParseDiagnostic(mut diagnostic) => {
240 diagnostic.cursor_position = 0;
241 Self::ParseDiagnostic(diagnostic)
242 }
243 _ => self,
244 }
245 }
246
247 pub fn undefined_function_call(signature: &str) -> Self {
249 Self::Diagnostic {
250 sqlstate: "42883".into(),
251 message: format!("function {signature} does not exist"),
252 detail: None,
253 hint: Some(
254 "No function matches the given name and argument types. You might need to add explicit type casts."
255 .into(),
256 ),
257 }
258 }
259
260 pub fn ambiguous_function_call(signature: &str) -> Self {
262 Self::Diagnostic {
263 sqlstate: "42725".into(),
264 message: format!("function {signature} is not unique"),
265 detail: None,
266 hint: Some(
267 "Could not choose a best candidate function. You might need to add explicit type casts."
268 .into(),
269 ),
270 }
271 }
272
273 pub fn function_call_resolution(sqlstate: &str, signature: &str, suffix: &str) -> Self {
275 match (sqlstate, suffix) {
276 ("42883", "does not exist") => Self::undefined_function_call(signature),
277 ("42725", "is not unique") => Self::ambiguous_function_call(signature),
278 _ => Self::Routine {
279 sqlstate: sqlstate.into(),
280 message: format!("function {signature} {suffix}"),
281 },
282 }
283 }
284
285 pub fn unknown_qualified_column(qualifier: &str, column: &str) -> Self {
286 Self::Routine {
287 sqlstate: "42703".into(),
288 message: format!("column {qualifier}.{column} does not exist"),
289 }
290 }
291
292 pub fn sqlstate(&self) -> Option<&str> {
296 match self {
297 SQLError::Context { source, .. }
298 | SQLError::Cleanup { source, .. }
299 | SQLError::Position { source, .. }
300 | SQLError::InternalPosition { source, .. } => source.sqlstate(),
301 SQLError::Cancelled(cancelled) => Some(cancelled.sqlstate()),
302 SQLError::Host(_) => Some("38000"), SQLError::Parse(_) => Some("42601"), SQLError::ParseDiagnostic(diagnostic) => Some(&diagnostic.sqlstate),
305 SQLError::Unsupported(_) | SQLError::NotificationRequiresSubscription => Some("0A000"), SQLError::UnknownTable(_) => Some("42P01"), SQLError::UnknownColumn(_) => Some("42703"), SQLError::AmbiguousColumn(_) => Some("42702"), SQLError::UnknownFunction(_) => Some("42883"), SQLError::TypeMismatch(_) | SQLError::TextIndexRequired { .. } => Some("42804"), SQLError::BadArity { .. } => Some("42883"), SQLError::MissingParam(_) => Some("S1002"), SQLError::VectorDimMismatch { .. } => Some("22023"), SQLError::Routine { sqlstate, .. } | SQLError::Diagnostic { sqlstate, .. } => {
315 Some(sqlstate)
316 }
317 SQLError::Internal(_) => Some("XX000"), }
319 }
320
321 pub fn detail(&self) -> Option<&str> {
323 match self {
324 SQLError::Context { source, .. }
325 | SQLError::Position { source, .. }
326 | SQLError::InternalPosition { source, .. } => source.detail(),
327 SQLError::Diagnostic { detail, .. } => detail.as_deref(),
328 SQLError::Cleanup { detail, .. } => Some(detail),
329 SQLError::ParseDiagnostic(diagnostic) => diagnostic.detail.as_deref(),
330 _ => None,
331 }
332 }
333
334 pub fn hint(&self) -> Option<&str> {
336 match self {
337 SQLError::Context { source, .. }
338 | SQLError::Cleanup { source, .. }
339 | SQLError::Position { source, .. }
340 | SQLError::InternalPosition { source, .. } => source.hint(),
341 SQLError::Diagnostic { hint, .. } => hint.as_deref(),
342 SQLError::ParseDiagnostic(diagnostic) => diagnostic.hint.as_deref(),
343 _ => None,
344 }
345 }
346
347 pub fn position(&self) -> Option<u32> {
349 match self {
350 Self::Context { source, .. } | Self::Cleanup { source, .. } => source.position(),
351 Self::Position { position, .. } => Some(*position),
352 Self::ParseDiagnostic(diagnostic) => u32::try_from(diagnostic.cursor_position)
353 .ok()
354 .filter(|position| *position != 0),
355 _ => None,
356 }
357 }
358}
359
360mod cleanup;
361
362pub type Result<T> = std::result::Result<T, SQLError>;
363
364impl From<pg_query::Error> for SQLError {
365 fn from(value: pg_query::Error) -> Self {
366 match value {
367 pg_query::Error::ParseDiagnostic(diagnostic) => Self::ParseDiagnostic(diagnostic),
368 pg_query::Error::Parse(message) => Self::Parse(message),
369 other => Self::Parse(other.to_string()),
370 }
371 }
372}
373
374impl From<uqa_core::memory::MemoryError> for SQLError {
375 fn from(error: uqa_core::memory::MemoryError) -> Self {
376 Self::Routine {
377 sqlstate: "53200".into(),
378 message: error.to_string(),
379 }
380 }
381}
382
383impl From<uqa_core::ValueRetentionError> for SQLError {
384 fn from(error: uqa_core::ValueRetentionError) -> Self {
385 match error {
386 uqa_core::ValueRetentionError::Memory(error) => error.into(),
387 uqa_core::ValueRetentionError::Cancelled(error) => error.into(),
388 error @ uqa_core::ValueRetentionError::Malformed { .. } => Self::Routine {
389 sqlstate: "XX001".into(),
390 message: error.to_string(),
391 },
392 }
393 }
394}
395
396#[cfg(test)]
397mod tests {
398 #[test]
399 fn host_cause_survives_clone_context_position_and_cleanup() {
400 #[derive(Debug, thiserror::Error)]
401 #[error("host diagnostic")]
402 struct Failure(u32);
403 let error = super::SQLError::Host(std::sync::Arc::new(Failure(73)))
404 .with_context("routine frame")
405 .at_position(Some(11))
406 .with_cleanup(
407 super::SQLError::Internal("cleanup failed".into()),
408 "close host state",
409 );
410 let cloned = error.clone();
411 drop(error);
412 let super::SQLError::Host(source) = cloned.primary() else {
413 panic!("typed host cause lost")
414 };
415 assert_eq!(source.downcast_ref::<Failure>().unwrap().0, 73);
416 assert_eq!(
417 std::error::Error::source(cloned.primary())
418 .unwrap()
419 .downcast_ref::<std::sync::Arc<dyn std::error::Error + Send + Sync>>()
420 .unwrap()
421 .downcast_ref::<Failure>()
422 .unwrap()
423 .0,
424 73
425 );
426 assert_eq!(cloned.sqlstate(), Some("38000"));
427 assert_eq!(cloned.to_string(), "host diagnostic");
428 assert_eq!(cloned.context(), Some("routine frame"));
429 assert_eq!(cloned.position(), Some(11));
430 assert!(cloned.detail().unwrap().contains("cleanup failed"));
431 }
432
433 #[test]
434 fn source_positions_preserve_typed_errors_and_nested_context() {
435 let error = super::SQLError::Diagnostic {
436 sqlstate: "42P10".into(),
437 message: "invalid reference".into(),
438 detail: Some("invalid join type".into()),
439 hint: Some("hint".into()),
440 }
441 .with_context("inner")
442 .at_position(Some(17))
443 .with_context("outer")
444 .at_position(Some(29));
445 assert_eq!(error.position(), Some(17));
446 assert_eq!(error.context(), Some("inner\nouter"));
447 assert_eq!(error.sqlstate(), Some("42P10"));
448 assert_eq!(error.to_string(), "invalid reference");
449 assert_eq!(error.detail(), Some("invalid join type"));
450 assert_eq!(error.hint(), Some("hint"));
451 assert!(matches!(
452 error.primary(),
453 super::SQLError::Diagnostic { .. }
454 ));
455 let cancelled =
456 super::SQLError::Cancelled(uqa_core::QueryCancelled::USER_REQUEST).at_position(Some(3));
457 assert!(matches!(cancelled.primary(), super::SQLError::Cancelled(_)));
458 let subscription = super::SQLError::NotificationRequiresSubscription.at_position(Some(2));
459 assert_eq!(
460 subscription.code(),
461 Some("NOTIFICATION_REQUIRES_SUBSCRIPTION")
462 );
463 }
464
465 use super::SQLError;
466
467 #[test]
468 fn routine_frames_preserve_primary_fields_and_typed_cancellation() {
469 let error = SQLError::Diagnostic {
470 sqlstate: "22012".into(),
471 message: "division by zero".into(),
472 detail: Some("original detail".into()),
473 hint: Some("original hint".into()),
474 }
475 .with_context("inner routine")
476 .with_context("outer routine");
477 assert_eq!(error.to_string(), "division by zero");
478 assert_eq!(error.sqlstate(), Some("22012"));
479 assert_eq!(error.detail(), Some("original detail"));
480 assert_eq!(error.hint(), Some("original hint"));
481 assert_eq!(error.context(), Some("inner routine\nouter routine"));
482 assert!(matches!(error.primary(), SQLError::Diagnostic { .. }));
483
484 let cancelled = SQLError::Cancelled(uqa_core::QueryCancelled::USER_REQUEST)
485 .with_context("interrupted routine");
486 assert_eq!(cancelled.sqlstate(), Some("57014"));
487 assert!(matches!(cancelled.primary(), SQLError::Cancelled(_)));
488 }
489}