1use std::error::Error as StdError;
7use std::fmt;
8
9use crate::catalog::CatalogError;
10use crate::error::ParserError;
11use crate::executor::ExecutorError;
12use crate::planner::PlannerError;
13use crate::storage::StorageError;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct ErrorLocation {
18 pub line: u64,
19 pub column: u64,
20}
21
22impl ErrorLocation {
23 pub fn is_known(&self) -> bool {
25 self.line > 0 || self.column > 0
26 }
27}
28
29impl fmt::Display for ErrorLocation {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 write!(f, "line {}, column {}", self.line, self.column)
32 }
33}
34
35#[derive(Debug)]
47pub enum SqlError {
48 Parse {
50 message: String,
51 location: ErrorLocation,
52 code: &'static str,
53 },
54
55 Plan {
57 message: String,
58 location: ErrorLocation,
59 code: &'static str,
60 },
61
62 Execution { message: String, code: &'static str },
64
65 Storage {
67 message: String,
68 code: &'static str,
69 source: Option<alopex_core::Error>,
70 },
71
72 Catalog {
74 message: String,
75 location: ErrorLocation,
76 code: &'static str,
77 },
78}
79
80impl SqlError {
81 pub fn code(&self) -> &'static str {
83 match self {
84 Self::Parse { code, .. }
85 | Self::Plan { code, .. }
86 | Self::Execution { code, .. }
87 | Self::Storage { code, .. }
88 | Self::Catalog { code, .. } => code,
89 }
90 }
91
92 pub fn message(&self) -> &str {
94 match self {
95 Self::Parse { message, .. }
96 | Self::Plan { message, .. }
97 | Self::Execution { message, .. }
98 | Self::Storage { message, .. }
99 | Self::Catalog { message, .. } => message,
100 }
101 }
102
103 pub fn location(&self) -> ErrorLocation {
105 match self {
106 Self::Parse { location, .. }
107 | Self::Plan { location, .. }
108 | Self::Catalog { location, .. } => *location,
109 Self::Execution { .. } | Self::Storage { .. } => ErrorLocation::default(),
110 }
111 }
112
113 pub fn message_with_location(&self) -> String {
115 let code = self.code();
116 let message = self.message();
117 let location = self.location();
118
119 match self {
120 Self::Storage { .. } => format!("error[{code}]: storage error: {message}"),
121 _ if location.is_known() => format!(
122 "error[{code}]: {message} at line {}, column {}",
123 location.line, location.column
124 ),
125 _ => format!("error[{code}]: {message}"),
126 }
127 }
128}
129
130impl fmt::Display for SqlError {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 f.write_str(&self.message_with_location())
133 }
134}
135
136impl StdError for SqlError {
137 fn source(&self) -> Option<&(dyn StdError + 'static)> {
138 match self {
139 Self::Storage {
140 source: Some(source),
141 ..
142 } => Some(source),
143 _ => None,
144 }
145 }
146}
147
148impl From<alopex_core::Error> for SqlError {
149 fn from(e: alopex_core::Error) -> Self {
150 let code = match e {
151 alopex_core::Error::TxnConflict => "ALOPEX-S001",
152 alopex_core::Error::TxnClosed => "ALOPEX-S002",
153 alopex_core::Error::TxnReadOnly => "ALOPEX-S003",
154 _ => "ALOPEX-S999",
155 };
156
157 Self::Storage {
158 message: e.to_string(),
159 code,
160 source: Some(e),
161 }
162 }
163}
164
165impl From<ParserError> for SqlError {
166 fn from(value: ParserError) -> Self {
167 match value {
168 ParserError::UnexpectedToken {
169 line,
170 column,
171 expected,
172 found,
173 } => Self::Parse {
174 message: format!("unexpected token: expected {expected}, found {found}"),
175 location: ErrorLocation { line, column },
176 code: "ALOPEX-P001",
177 },
178 ParserError::ExpectedToken {
179 line,
180 column,
181 expected,
182 found,
183 } => Self::Parse {
184 message: format!("expected {expected} but found {found}"),
185 location: ErrorLocation { line, column },
186 code: "ALOPEX-P002",
187 },
188 ParserError::UnterminatedString { line, column } => Self::Parse {
189 message: "unterminated string literal".to_string(),
190 location: ErrorLocation { line, column },
191 code: "ALOPEX-P003",
192 },
193 ParserError::InvalidNumber {
194 line,
195 column,
196 value,
197 } => Self::Parse {
198 message: format!("invalid number literal '{value}'"),
199 location: ErrorLocation { line, column },
200 code: "ALOPEX-P004",
201 },
202 ParserError::InvalidVector { line, column } => Self::Parse {
203 message: "invalid vector literal".to_string(),
204 location: ErrorLocation { line, column },
205 code: "ALOPEX-P005",
206 },
207 ParserError::RecursionLimitExceeded { depth } => Self::Parse {
208 message: format!("recursion limit exceeded (depth: {depth})"),
209 location: ErrorLocation::default(),
210 code: "ALOPEX-P006",
211 },
212 ParserError::InternalParserDefect { message } => Self::Parse {
213 message: format!(
214 "internal parser defect (this is a parser bug, not invalid SQL): {message}"
215 ),
216 location: ErrorLocation::default(),
217 code: "ALOPEX-P007",
218 },
219 }
220 }
221}
222
223impl From<PlannerError> for SqlError {
224 fn from(value: PlannerError) -> Self {
225 match value {
226 PlannerError::TableNotFound { name, line, column } => Self::Catalog {
227 message: format!("table '{name}' not found"),
228 location: ErrorLocation { line, column },
229 code: "ALOPEX-C001",
230 },
231 PlannerError::TableAlreadyExists { name } => Self::Catalog {
232 message: format!("table '{name}' already exists"),
233 location: ErrorLocation::default(),
234 code: "ALOPEX-C002",
235 },
236 PlannerError::ColumnNotFound {
237 column,
238 table,
239 line,
240 col,
241 } => Self::Catalog {
242 message: format!("column '{column}' not found in table '{table}'"),
243 location: ErrorLocation { line, column: col },
244 code: "ALOPEX-C003",
245 },
246 PlannerError::AmbiguousColumn {
247 column,
248 tables,
249 line,
250 col,
251 } => Self::Catalog {
252 message: format!("ambiguous column '{column}' found in tables: {tables:?}"),
253 location: ErrorLocation { line, column: col },
254 code: "ALOPEX-C004",
255 },
256 PlannerError::IndexAlreadyExists { name } => Self::Catalog {
257 message: format!("index '{name}' already exists"),
258 location: ErrorLocation::default(),
259 code: "ALOPEX-C005",
260 },
261 PlannerError::IndexNotFound { name } => Self::Catalog {
262 message: format!("index '{name}' not found"),
263 location: ErrorLocation::default(),
264 code: "ALOPEX-C006",
265 },
266 PlannerError::TypeMismatch {
267 expected,
268 found,
269 line,
270 column,
271 } => Self::Plan {
272 message: format!("type mismatch: expected {expected}, found {found}"),
273 location: ErrorLocation { line, column },
274 code: "ALOPEX-T001",
275 },
276 PlannerError::InvalidOperator {
277 op,
278 type_name,
279 line,
280 column,
281 } => Self::Plan {
282 message: format!("invalid operator '{op}' for type '{type_name}'"),
283 location: ErrorLocation { line, column },
284 code: "ALOPEX-T002",
285 },
286 PlannerError::NullConstraintViolation { column, line, col } => Self::Plan {
287 message: format!("null constraint violation for column '{column}'"),
288 location: ErrorLocation { line, column: col },
289 code: "ALOPEX-T003",
290 },
291 PlannerError::VectorDimensionMismatch {
292 expected,
293 found,
294 line,
295 column,
296 } => Self::Plan {
297 message: format!("vector dimension mismatch: expected {expected}, found {found}"),
298 location: ErrorLocation { line, column },
299 code: "ALOPEX-T004",
300 },
301 PlannerError::InvalidMetric {
302 value,
303 line,
304 column,
305 } => Self::Plan {
306 message: format!("invalid metric '{value}' (valid: cosine, l2, inner)"),
307 location: ErrorLocation { line, column },
308 code: "ALOPEX-T005",
309 },
310 PlannerError::ColumnValueCountMismatch {
311 columns,
312 values,
313 line,
314 column,
315 } => Self::Plan {
316 message: format!("column count ({columns}) does not match value count ({values})"),
317 location: ErrorLocation { line, column },
318 code: "ALOPEX-T006",
319 },
320 PlannerError::UnsupportedFeature {
321 feature,
322 version,
323 line,
324 column,
325 } => Self::Plan {
326 message: format!("feature '{feature}' is not supported (expected in {version})"),
327 location: ErrorLocation { line, column },
328 code: "ALOPEX-F001",
329 },
330 PlannerError::InvalidExpression { message } => Self::Plan {
331 message,
332 location: ErrorLocation::default(),
333 code: "ALOPEX-T007",
334 },
335 PlannerError::InvalidPragma { name, reason } => Self::Plan {
336 message: format!("invalid PRAGMA '{name}': {reason}"),
337 location: ErrorLocation::default(),
338 code: "ALOPEX-F002",
339 },
340 }
341 }
342}
343
344impl From<StorageError> for SqlError {
345 fn from(value: StorageError) -> Self {
346 match value {
347 StorageError::TransactionConflict => Self::Storage {
348 message: "transaction conflict".to_string(),
349 code: "ALOPEX-S001",
350 source: Some(alopex_core::Error::TxnConflict),
351 },
352 StorageError::TransactionReadOnly => Self::Storage {
353 message: "transaction is read-only".to_string(),
354 code: "ALOPEX-S003",
355 source: Some(alopex_core::Error::TxnReadOnly),
356 },
357 StorageError::TransactionClosed => Self::Storage {
358 message: "transaction is closed".to_string(),
359 code: "ALOPEX-S002",
360 source: Some(alopex_core::Error::TxnClosed),
361 },
362 StorageError::KvError(core_error) => Self::from(core_error),
363 other => Self::Storage {
364 message: other.to_string(),
365 code: "ALOPEX-S999",
366 source: None,
367 },
368 }
369 }
370}
371
372impl From<CatalogError> for SqlError {
373 fn from(value: CatalogError) -> Self {
374 match value {
375 CatalogError::Kv(core_error) => Self::from(StorageError::from(core_error)),
376 other => Self::Catalog {
377 message: format!("catalog persistence error: {other}"),
378 location: ErrorLocation::default(),
379 code: "ALOPEX-C999",
380 },
381 }
382 }
383}
384
385impl From<ExecutorError> for SqlError {
386 fn from(value: ExecutorError) -> Self {
387 match value {
388 ExecutorError::Planner(planner_error) => Self::from(planner_error),
389 ExecutorError::Core(core_error) => Self::from(core_error),
390 ExecutorError::Storage(storage_error) => Self::from(storage_error),
391 ExecutorError::TransactionConflict => Self::Execution {
392 message: "transaction conflict".to_string(),
393 code: "ALOPEX-E001",
394 },
395 ExecutorError::ReadOnlyTransaction { operation } => Self::Execution {
396 message: format!("read-only transaction: cannot execute {operation}"),
397 code: "ALOPEX-E002",
398 },
399 ExecutorError::TableNotFound(name) => Self::Catalog {
400 message: format!("table '{name}' not found"),
401 location: ErrorLocation::default(),
402 code: "ALOPEX-C001",
403 },
404 ExecutorError::TableAlreadyExists(name) => Self::Catalog {
405 message: format!("table '{name}' already exists"),
406 location: ErrorLocation::default(),
407 code: "ALOPEX-C002",
408 },
409 ExecutorError::IndexNotFound(name) => Self::Catalog {
410 message: format!("index '{name}' not found"),
411 location: ErrorLocation::default(),
412 code: "ALOPEX-C006",
413 },
414 ExecutorError::IndexAlreadyExists(name) => Self::Catalog {
415 message: format!("index '{name}' already exists"),
416 location: ErrorLocation::default(),
417 code: "ALOPEX-C005",
418 },
419 ExecutorError::ColumnNotFound(column) => Self::Catalog {
420 message: format!("column '{column}' not found"),
421 location: ErrorLocation::default(),
422 code: "ALOPEX-C003",
423 },
424 other => Self::Execution {
425 message: other.to_string(),
426 code: "ALOPEX-E999",
427 },
428 }
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[test]
437 fn from_parser_error_preserves_location() {
438 let parser_error = ParserError::UnexpectedToken {
439 line: 12,
440 column: 34,
441 expected: "SELECT".into(),
442 found: "SELEC".into(),
443 };
444
445 let unified: SqlError = parser_error.into();
446 assert_eq!(unified.code(), "ALOPEX-P001");
447 assert_eq!(
448 unified.location(),
449 ErrorLocation {
450 line: 12,
451 column: 34
452 }
453 );
454 }
455
456 #[test]
457 fn from_planner_error_preserves_code() {
458 let planner_error = PlannerError::TableNotFound {
459 name: "users".into(),
460 line: 1,
461 column: 8,
462 };
463
464 let unified: SqlError = planner_error.into();
465 assert_eq!(unified.code(), "ALOPEX-C001");
466 assert_eq!(unified.location(), ErrorLocation { line: 1, column: 8 });
467 }
468
469 #[test]
470 fn message_with_location_format() {
471 let parser_error = ParserError::InvalidNumber {
472 line: 3,
473 column: 7,
474 value: "12x".into(),
475 };
476
477 let unified: SqlError = parser_error.into();
478 assert_eq!(
479 unified.message_with_location(),
480 "error[ALOPEX-P004]: invalid number literal '12x' at line 3, column 7"
481 );
482 }
483
484 #[test]
485 fn from_executor_core_error_maps_to_storage_and_preserves_source() {
486 let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnConflict).into();
487 assert_eq!(unified.code(), "ALOPEX-S001");
488 assert!(unified.source().is_some());
489 assert_eq!(
490 unified.message_with_location(),
491 "error[ALOPEX-S001]: storage error: transaction conflict"
492 );
493 }
494
495 #[test]
496 fn from_executor_core_readonly_maps_to_storage_and_preserves_source() {
497 let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnReadOnly).into();
498 assert_eq!(unified.code(), "ALOPEX-S003");
499 assert!(unified.source().is_some());
500 assert_eq!(
501 unified.message_with_location(),
502 "error[ALOPEX-S003]: storage error: transaction is read-only"
503 );
504 }
505
506 #[test]
507 fn from_executor_readonly_transaction_maps_to_execution_code() {
508 let unified: SqlError = ExecutorError::ReadOnlyTransaction {
509 operation: "INSERT".to_string(),
510 }
511 .into();
512 assert_eq!(unified.code(), "ALOPEX-E002");
513 assert_eq!(
514 unified.message_with_location(),
515 "error[ALOPEX-E002]: read-only transaction: cannot execute INSERT"
516 );
517 }
518}