Skip to main content

uqa_sql/
error.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Error types surfaced by the SQL compiler and executor.
8
9#[derive(Debug, Clone, thiserror::Error)]
10pub enum SQLError {
11    #[error("{0}")]
12    Parse(String),
13    /// Original parser diagnostics, including its one-based character position.
14    #[error("{0}")]
15    ParseDiagnostic(Box<pg_query::Diagnostic>),
16    #[error("{0}")]
17    Unsupported(String),
18    /// The host configured this SQL session to require an independently owned notification subscription.
19    #[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    /// An owned host callback diagnostic. Its typed cause survives workers,
52    /// routine context, cleanup and cloning without a thread-local side channel.
53    #[error("{0}")]
54    Host(#[source] std::sync::Arc<dyn std::error::Error + Send + Sync>),
55    /// Error raised by (or on behalf of) a user-defined SQL /
56    /// `PL/pgSQL` routine. Carries an explicit `SQLSTATE` so
57    /// `EXCEPTION WHEN <condition>` handlers and `SQLSTATE` /
58    /// `SQLERRM` report the same code `PostgreSQL` would.
59    #[error("{message}")]
60    Routine { sqlstate: String, message: String },
61    /// A primary SQL error with separate `PostgreSQL` diagnostic fields. `SQLERRM` and `Display` expose only the primary message; protocol clients receive detail and hint independently.
62    #[error("{message}")]
63    Diagnostic {
64        sqlstate: String,
65        message: String,
66        detail: Option<String>,
67        hint: Option<String>,
68    },
69    /// Routine traceback, independent of the primary diagnostic and its typed cause.
70    #[error("{source}")]
71    Context { source: Box<Self>, context: String },
72    /// A failed cleanup attached to the original, typed SQL error. The primary
73    /// message and SQLSTATE remain unchanged; DETAIL includes both diagnostics.
74    #[error("{source}")]
75    Cleanup {
76        source: Box<Self>,
77        failures: Vec<(String, Self)>,
78        detail: String,
79    },
80    /// Source position independent of the primary diagnostic and its typed cause.
81    #[error("{source}")]
82    Position { source: Box<Self>, position: u32 },
83    /// A routine-body cursor that cannot be transposed into the submitted SQL.
84    #[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    /// Stable application error code, separate from the five-character SQLSTATE. Ordinary SQL errors do not acquire an application code.
96    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    /// Append an enclosing routine frame after the innermost error context.
108    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    /// `PostgreSQL` CONTEXT, with inner frames before their callers.
148    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    /// The typed primary error, unaffected by an attached routine traceback.
159    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    /// Preserve the innermost reference's source position without changing its typed diagnostic.
170    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    /// Position within `internal_query`, separate from the submitted SQL cursor.
183    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    /// Routine source for an internal diagnostic cursor.
194    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    /// `ParseFuncOrColumn`'s error when no function matches a call: `signature` is the name with its argument types, as `func_signature_string` spells it.
248    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    /// `ParseFuncOrColumn`'s error when more than one function matches a call equally well.
261    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    /// A failed call resolution in `ParseFuncOrColumn`'s terms: `42883` when no function matches and `42725` when no candidate is best, each with its hint.
274    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    /// `PostgreSQL` `SQLSTATE` code for the error, mirroring the
293    /// the current exception-to-state mapping. `None` for
294    /// errors that do not carry a defined `SQLSTATE`.
295    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"), // external_routine_exception
303            SQLError::Parse(_) => Some("42601"), // syntax_error
304            SQLError::ParseDiagnostic(diagnostic) => Some(&diagnostic.sqlstate),
305            SQLError::Unsupported(_) | SQLError::NotificationRequiresSubscription => Some("0A000"), // feature_not_supported
306            SQLError::UnknownTable(_) => Some("42P01"), // undefined_table
307            SQLError::UnknownColumn(_) => Some("42703"), // undefined_column
308            SQLError::AmbiguousColumn(_) => Some("42702"), // ambiguous_column
309            SQLError::UnknownFunction(_) => Some("42883"), // undefined_function
310            SQLError::TypeMismatch(_) | SQLError::TextIndexRequired { .. } => Some("42804"), // datatype_mismatch
311            SQLError::BadArity { .. } => Some("42883"), // undefined_function (PG)
312            SQLError::MissingParam(_) => Some("S1002"), // ERRCODE_INVALID_PARAMETER_VALUE
313            SQLError::VectorDimMismatch { .. } => Some("22023"), // invalid_parameter_value
314            SQLError::Routine { sqlstate, .. } | SQLError::Diagnostic { sqlstate, .. } => {
315                Some(sqlstate)
316            }
317            SQLError::Internal(_) => Some("XX000"), // internal_error
318        }
319    }
320
321    /// `PostgreSQL` DETAIL field, reported separately from the primary message.
322    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    /// `PostgreSQL` HINT field, reported separately from the primary message.
335    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    /// One-based character position in the original submitted SQL.
348    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}