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 }
336 }
337}
338
339impl From<StorageError> for SqlError {
340 fn from(value: StorageError) -> Self {
341 match value {
342 StorageError::TransactionConflict => Self::Storage {
343 message: "transaction conflict".to_string(),
344 code: "ALOPEX-S001",
345 source: Some(alopex_core::Error::TxnConflict),
346 },
347 StorageError::TransactionReadOnly => Self::Storage {
348 message: "transaction is read-only".to_string(),
349 code: "ALOPEX-S003",
350 source: Some(alopex_core::Error::TxnReadOnly),
351 },
352 StorageError::TransactionClosed => Self::Storage {
353 message: "transaction is closed".to_string(),
354 code: "ALOPEX-S002",
355 source: Some(alopex_core::Error::TxnClosed),
356 },
357 StorageError::KvError(core_error) => Self::from(core_error),
358 other => Self::Storage {
359 message: other.to_string(),
360 code: "ALOPEX-S999",
361 source: None,
362 },
363 }
364 }
365}
366
367impl From<CatalogError> for SqlError {
368 fn from(value: CatalogError) -> Self {
369 match value {
370 CatalogError::Kv(core_error) => Self::from(StorageError::from(core_error)),
371 other => Self::Catalog {
372 message: format!("catalog persistence error: {other}"),
373 location: ErrorLocation::default(),
374 code: "ALOPEX-C999",
375 },
376 }
377 }
378}
379
380impl From<ExecutorError> for SqlError {
381 fn from(value: ExecutorError) -> Self {
382 match value {
383 ExecutorError::Planner(planner_error) => Self::from(planner_error),
384 ExecutorError::Core(core_error) => Self::from(core_error),
385 ExecutorError::Storage(storage_error) => Self::from(storage_error),
386 ExecutorError::TransactionConflict => Self::Execution {
387 message: "transaction conflict".to_string(),
388 code: "ALOPEX-E001",
389 },
390 ExecutorError::ReadOnlyTransaction { operation } => Self::Execution {
391 message: format!("read-only transaction: cannot execute {operation}"),
392 code: "ALOPEX-E002",
393 },
394 ExecutorError::TableNotFound(name) => Self::Catalog {
395 message: format!("table '{name}' not found"),
396 location: ErrorLocation::default(),
397 code: "ALOPEX-C001",
398 },
399 ExecutorError::TableAlreadyExists(name) => Self::Catalog {
400 message: format!("table '{name}' already exists"),
401 location: ErrorLocation::default(),
402 code: "ALOPEX-C002",
403 },
404 ExecutorError::IndexNotFound(name) => Self::Catalog {
405 message: format!("index '{name}' not found"),
406 location: ErrorLocation::default(),
407 code: "ALOPEX-C006",
408 },
409 ExecutorError::IndexAlreadyExists(name) => Self::Catalog {
410 message: format!("index '{name}' already exists"),
411 location: ErrorLocation::default(),
412 code: "ALOPEX-C005",
413 },
414 ExecutorError::ColumnNotFound(column) => Self::Catalog {
415 message: format!("column '{column}' not found"),
416 location: ErrorLocation::default(),
417 code: "ALOPEX-C003",
418 },
419 other => Self::Execution {
420 message: other.to_string(),
421 code: "ALOPEX-E999",
422 },
423 }
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430
431 #[test]
432 fn from_parser_error_preserves_location() {
433 let parser_error = ParserError::UnexpectedToken {
434 line: 12,
435 column: 34,
436 expected: "SELECT".into(),
437 found: "SELEC".into(),
438 };
439
440 let unified: SqlError = parser_error.into();
441 assert_eq!(unified.code(), "ALOPEX-P001");
442 assert_eq!(
443 unified.location(),
444 ErrorLocation {
445 line: 12,
446 column: 34
447 }
448 );
449 }
450
451 #[test]
452 fn from_planner_error_preserves_code() {
453 let planner_error = PlannerError::TableNotFound {
454 name: "users".into(),
455 line: 1,
456 column: 8,
457 };
458
459 let unified: SqlError = planner_error.into();
460 assert_eq!(unified.code(), "ALOPEX-C001");
461 assert_eq!(unified.location(), ErrorLocation { line: 1, column: 8 });
462 }
463
464 #[test]
465 fn message_with_location_format() {
466 let parser_error = ParserError::InvalidNumber {
467 line: 3,
468 column: 7,
469 value: "12x".into(),
470 };
471
472 let unified: SqlError = parser_error.into();
473 assert_eq!(
474 unified.message_with_location(),
475 "error[ALOPEX-P004]: invalid number literal '12x' at line 3, column 7"
476 );
477 }
478
479 #[test]
480 fn from_executor_core_error_maps_to_storage_and_preserves_source() {
481 let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnConflict).into();
482 assert_eq!(unified.code(), "ALOPEX-S001");
483 assert!(unified.source().is_some());
484 assert_eq!(
485 unified.message_with_location(),
486 "error[ALOPEX-S001]: storage error: transaction conflict"
487 );
488 }
489
490 #[test]
491 fn from_executor_core_readonly_maps_to_storage_and_preserves_source() {
492 let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnReadOnly).into();
493 assert_eq!(unified.code(), "ALOPEX-S003");
494 assert!(unified.source().is_some());
495 assert_eq!(
496 unified.message_with_location(),
497 "error[ALOPEX-S003]: storage error: transaction is read-only"
498 );
499 }
500
501 #[test]
502 fn from_executor_readonly_transaction_maps_to_execution_code() {
503 let unified: SqlError = ExecutorError::ReadOnlyTransaction {
504 operation: "INSERT".to_string(),
505 }
506 .into();
507 assert_eq!(unified.code(), "ALOPEX-E002");
508 assert_eq!(
509 unified.message_with_location(),
510 "error[ALOPEX-E002]: read-only transaction: cannot execute INSERT"
511 );
512 }
513}