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("{message}")]
56 Routine { sqlstate: String, message: String },
57 #[error("{message}")]
59 Diagnostic {
60 sqlstate: String,
61 message: String,
62 detail: Option<String>,
63 hint: Option<String>,
64 },
65 #[error("{source}")]
67 Context { source: Box<Self>, context: String },
68 #[error("internal error: {0}")]
69 Internal(String),
70}
71
72impl SQLError {
73 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 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 pub fn context(&self) -> Option<&str> {
102 match self {
103 Self::Context { context, .. } => Some(context),
104 _ => None,
105 }
106 }
107
108 pub fn primary(&self) -> &Self {
110 match self {
111 Self::Context { source, .. } => source.primary(),
112 _ => self,
113 }
114 }
115
116 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 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 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 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"), SQLError::ParseDiagnostic(diagnostic) => Some(&diagnostic.sqlstate),
170 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, .. } => {
180 Some(sqlstate)
181 }
182 SQLError::Internal(_) => Some("XX000"), }
184 }
185
186 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 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 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}