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    /// Error raised by (or on behalf of) a user-defined SQL /
52    /// `PL/pgSQL` routine. Carries an explicit `SQLSTATE` so
53    /// `EXCEPTION WHEN <condition>` handlers and `SQLSTATE` /
54    /// `SQLERRM` report the same code `PostgreSQL` would.
55    #[error("{message}")]
56    Routine { sqlstate: String, message: String },
57    /// A primary SQL error with separate `PostgreSQL` diagnostic fields. `SQLERRM` and `Display` expose only the primary message; protocol clients receive detail and hint independently.
58    #[error("{message}")]
59    Diagnostic {
60        sqlstate: String,
61        message: String,
62        detail: Option<String>,
63        hint: Option<String>,
64    },
65    /// Routine traceback, independent of the primary diagnostic and its typed cause.
66    #[error("{source}")]
67    Context { source: Box<Self>, context: String },
68    #[error("internal error: {0}")]
69    Internal(String),
70}
71
72impl SQLError {
73    /// Stable application error code, separate from the five-character SQLSTATE. Ordinary SQL errors do not acquire an application code.
74    pub const fn code(&self) -> Option<&'static str> {
75        match self {
76            Self::NotificationRequiresSubscription => Some("NOTIFICATION_REQUIRES_SUBSCRIPTION"),
77            Self::Context { source, .. } => source.code(),
78            _ => None,
79        }
80    }
81
82    /// Append an enclosing routine frame after the innermost error context.
83    pub fn with_context(self, frame: impl AsRef<str>) -> Self {
84        match self {
85            Self::Context {
86                source,
87                mut context,
88            } => {
89                context.push('\n');
90                context.push_str(frame.as_ref());
91                Self::Context { source, context }
92            }
93            source => Self::Context {
94                source: Box::new(source),
95                context: frame.as_ref().to_owned(),
96            },
97        }
98    }
99
100    /// `PostgreSQL` CONTEXT, with inner frames before their callers.
101    pub fn context(&self) -> Option<&str> {
102        match self {
103            Self::Context { context, .. } => Some(context),
104            _ => None,
105        }
106    }
107
108    /// The typed primary error, unaffected by an attached routine traceback.
109    pub fn primary(&self) -> &Self {
110        match self {
111            Self::Context { source, .. } => source.primary(),
112            _ => self,
113        }
114    }
115
116    /// `ParseFuncOrColumn`'s error when no function matches a call: `signature` is the name with its argument types, as `func_signature_string` spells it.
117    pub fn undefined_function_call(signature: &str) -> Self {
118        Self::Diagnostic {
119            sqlstate: "42883".into(),
120            message: format!("function {signature} does not exist"),
121            detail: None,
122            hint: Some(
123                "No function matches the given name and argument types. You might need to add explicit type casts."
124                    .into(),
125            ),
126        }
127    }
128
129    /// `ParseFuncOrColumn`'s error when more than one function matches a call equally well.
130    pub fn ambiguous_function_call(signature: &str) -> Self {
131        Self::Diagnostic {
132            sqlstate: "42725".into(),
133            message: format!("function {signature} is not unique"),
134            detail: None,
135            hint: Some(
136                "Could not choose a best candidate function. You might need to add explicit type casts."
137                    .into(),
138            ),
139        }
140    }
141
142    /// A failed call resolution in `ParseFuncOrColumn`'s terms: `42883` when no function matches and `42725` when no candidate is best, each with its hint.
143    pub fn function_call_resolution(sqlstate: &str, signature: &str, suffix: &str) -> Self {
144        match (sqlstate, suffix) {
145            ("42883", "does not exist") => Self::undefined_function_call(signature),
146            ("42725", "is not unique") => Self::ambiguous_function_call(signature),
147            _ => Self::Routine {
148                sqlstate: sqlstate.into(),
149                message: format!("function {signature} {suffix}"),
150            },
151        }
152    }
153
154    pub fn unknown_qualified_column(qualifier: &str, column: &str) -> Self {
155        Self::Routine {
156            sqlstate: "42703".into(),
157            message: format!("column {qualifier}.{column} does not exist"),
158        }
159    }
160
161    /// `PostgreSQL` `SQLSTATE` code for the error, mirroring the
162    /// the current exception-to-state mapping. `None` for
163    /// errors that do not carry a defined `SQLSTATE`.
164    pub fn sqlstate(&self) -> Option<&str> {
165        match self {
166            SQLError::Context { source, .. } => source.sqlstate(),
167            SQLError::Cancelled(cancelled) => Some(cancelled.sqlstate()),
168            SQLError::Parse(_) => Some("42601"), // syntax_error
169            SQLError::ParseDiagnostic(diagnostic) => Some(&diagnostic.sqlstate),
170            SQLError::Unsupported(_) | SQLError::NotificationRequiresSubscription => Some("0A000"), // feature_not_supported
171            SQLError::UnknownTable(_) => Some("42P01"), // undefined_table
172            SQLError::UnknownColumn(_) => Some("42703"), // undefined_column
173            SQLError::AmbiguousColumn(_) => Some("42702"), // ambiguous_column
174            SQLError::UnknownFunction(_) => Some("42883"), // undefined_function
175            SQLError::TypeMismatch(_) | SQLError::TextIndexRequired { .. } => Some("42804"), // datatype_mismatch
176            SQLError::BadArity { .. } => Some("42883"), // undefined_function (PG)
177            SQLError::MissingParam(_) => Some("S1002"), // ERRCODE_INVALID_PARAMETER_VALUE
178            SQLError::VectorDimMismatch { .. } => Some("22023"), // invalid_parameter_value
179            SQLError::Routine { sqlstate, .. } | SQLError::Diagnostic { sqlstate, .. } => {
180                Some(sqlstate)
181            }
182            SQLError::Internal(_) => Some("XX000"), // internal_error
183        }
184    }
185
186    /// `PostgreSQL` DETAIL field, reported separately from the primary message.
187    pub fn detail(&self) -> Option<&str> {
188        match self {
189            SQLError::Context { source, .. } => source.detail(),
190            SQLError::Diagnostic { detail, .. } => detail.as_deref(),
191            SQLError::ParseDiagnostic(diagnostic) => diagnostic.detail.as_deref(),
192            _ => None,
193        }
194    }
195
196    /// `PostgreSQL` HINT field, reported separately from the primary message.
197    pub fn hint(&self) -> Option<&str> {
198        match self {
199            SQLError::Context { source, .. } => source.hint(),
200            SQLError::Diagnostic { hint, .. } => hint.as_deref(),
201            SQLError::ParseDiagnostic(diagnostic) => diagnostic.hint.as_deref(),
202            _ => None,
203        }
204    }
205
206    /// One-based character position in the submitted SQL, only when supplied by the parser.
207    pub fn position(&self) -> Option<u32> {
208        match self {
209            Self::Context { source, .. } => source.position(),
210            Self::ParseDiagnostic(diagnostic) => u32::try_from(diagnostic.cursor_position)
211                .ok()
212                .filter(|position| *position != 0),
213            _ => None,
214        }
215    }
216}
217
218pub type Result<T> = std::result::Result<T, SQLError>;
219
220impl From<pg_query::Error> for SQLError {
221    fn from(value: pg_query::Error) -> Self {
222        match value {
223            pg_query::Error::ParseDiagnostic(diagnostic) => Self::ParseDiagnostic(diagnostic),
224            pg_query::Error::Parse(message) => Self::Parse(message),
225            other => Self::Parse(other.to_string()),
226        }
227    }
228}
229
230impl From<uqa_core::memory::MemoryError> for SQLError {
231    fn from(error: uqa_core::memory::MemoryError) -> Self {
232        Self::Routine {
233            sqlstate: "53200".into(),
234            message: error.to_string(),
235        }
236    }
237}
238
239impl From<uqa_core::ValueRetentionError> for SQLError {
240    fn from(error: uqa_core::ValueRetentionError) -> Self {
241        match error {
242            uqa_core::ValueRetentionError::Memory(error) => error.into(),
243            uqa_core::ValueRetentionError::Cancelled(error) => error.into(),
244            error @ uqa_core::ValueRetentionError::Malformed { .. } => Self::Routine {
245                sqlstate: "XX001".into(),
246                message: error.to_string(),
247            },
248        }
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::SQLError;
255
256    #[test]
257    fn routine_frames_preserve_primary_fields_and_typed_cancellation() {
258        let error = SQLError::Diagnostic {
259            sqlstate: "22012".into(),
260            message: "division by zero".into(),
261            detail: Some("original detail".into()),
262            hint: Some("original hint".into()),
263        }
264        .with_context("inner routine")
265        .with_context("outer routine");
266        assert_eq!(error.to_string(), "division by zero");
267        assert_eq!(error.sqlstate(), Some("22012"));
268        assert_eq!(error.detail(), Some("original detail"));
269        assert_eq!(error.hint(), Some("original hint"));
270        assert_eq!(error.context(), Some("inner routine\nouter routine"));
271        assert!(matches!(error.primary(), SQLError::Diagnostic { .. }));
272
273        let cancelled = SQLError::Cancelled(uqa_core::QueryCancelled::USER_REQUEST)
274            .with_context("interrupted routine");
275        assert_eq!(cancelled.sqlstate(), Some("57014"));
276        assert!(matches!(cancelled.primary(), SQLError::Cancelled(_)));
277    }
278}