Skip to main content

alopex_sql/
unified_error.rs

1//! SQL 実行パイプライン(Parse/Plan/Execute)を横断する統一エラー型。
2//!
3//! 公開 API としては「安定した形」を維持するため、内部エラー型(Parser/Planner/Executor)を
4//! そのまま公開せず、`message / code / location` を持つフィールド形式のエラーを提供する。
5
6use 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/// エラー位置情報(1-based、未知の場合は 0)。
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct ErrorLocation {
18    pub line: u64,
19    pub column: u64,
20}
21
22impl ErrorLocation {
23    /// 位置情報が有効か判定する。
24    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/// 統一 SQL エラー型(公開 API)。
36///
37/// # Examples
38///
39/// ```
40/// use alopex_sql::SqlError;
41/// use alopex_sql::StorageError;
42///
43/// let err = SqlError::from(StorageError::TransactionConflict);
44/// assert_eq!(err.code(), "ALOPEX-S001");
45/// ```
46#[derive(Debug)]
47pub enum SqlError {
48    /// パースエラー。
49    Parse {
50        message: String,
51        location: ErrorLocation,
52        code: &'static str,
53    },
54
55    /// プランニングエラー(型エラー等)。
56    Plan {
57        message: String,
58        location: ErrorLocation,
59        code: &'static str,
60    },
61
62    /// 実行エラー。
63    Execution { message: String, code: &'static str },
64
65    /// ストレージエラー(REQ-4-3: `source` を保持してエラーチェーンを維持)。
66    Storage {
67        message: String,
68        code: &'static str,
69        source: Option<alopex_core::Error>,
70    },
71
72    /// カタログエラー(テーブル/インデックス等の参照・整合性)。
73    Catalog {
74        message: String,
75        location: ErrorLocation,
76        code: &'static str,
77    },
78}
79
80impl SqlError {
81    /// エラーコード(例: `ALOPEX-C001`)。
82    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    /// ユーザー向けメッセージ(位置情報は含めない)。
93    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    /// 位置情報(未知の場合は `{ line: 0, column: 0 }`)。
104    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    /// span 情報付きメッセージを生成する(位置情報がない場合は位置部分を省略)。
114    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::SetOperationColumnCountMismatch {
336                left,
337                right,
338                line,
339                column,
340            } => Self::Plan {
341                message: format!("set operation column count mismatch: left {left}, right {right}"),
342                location: ErrorLocation { line, column },
343                code: "ALOPEX-T008",
344            },
345            PlannerError::CteColumnCountMismatch {
346                cte,
347                declared,
348                actual,
349                line,
350                column,
351            } => Self::Plan {
352                message: format!(
353                    "common table expression '{cte}' declares {declared} column names but its query returns {actual} columns"
354                ),
355                location: ErrorLocation { line, column },
356                code: "ALOPEX-T009",
357            },
358            PlannerError::DuplicateCteColumn {
359                cte,
360                name,
361                line,
362                column,
363            } => Self::Plan {
364                message: format!(
365                    "common table expression '{cte}' declares column '{name}' more than once"
366                ),
367                location: ErrorLocation { line, column },
368                code: "ALOPEX-T010",
369            },
370            PlannerError::InvalidPragma { name, reason } => Self::Plan {
371                message: format!("invalid PRAGMA '{name}': {reason}"),
372                location: ErrorLocation::default(),
373                code: "ALOPEX-F002",
374            },
375        }
376    }
377}
378
379impl From<StorageError> for SqlError {
380    fn from(value: StorageError) -> Self {
381        match value {
382            StorageError::TransactionConflict => Self::Storage {
383                message: "transaction conflict".to_string(),
384                code: "ALOPEX-S001",
385                source: Some(alopex_core::Error::TxnConflict),
386            },
387            StorageError::TransactionReadOnly => Self::Storage {
388                message: "transaction is read-only".to_string(),
389                code: "ALOPEX-S003",
390                source: Some(alopex_core::Error::TxnReadOnly),
391            },
392            StorageError::TransactionClosed => Self::Storage {
393                message: "transaction is closed".to_string(),
394                code: "ALOPEX-S002",
395                source: Some(alopex_core::Error::TxnClosed),
396            },
397            StorageError::KvError(core_error) => Self::from(core_error),
398            other => Self::Storage {
399                message: other.to_string(),
400                code: "ALOPEX-S999",
401                source: None,
402            },
403        }
404    }
405}
406
407impl From<CatalogError> for SqlError {
408    fn from(value: CatalogError) -> Self {
409        match value {
410            CatalogError::Kv(core_error) => Self::from(StorageError::from(core_error)),
411            other => Self::Catalog {
412                message: format!("catalog persistence error: {other}"),
413                location: ErrorLocation::default(),
414                code: "ALOPEX-C999",
415            },
416        }
417    }
418}
419
420impl From<ExecutorError> for SqlError {
421    fn from(value: ExecutorError) -> Self {
422        match value {
423            ExecutorError::Planner(planner_error) => Self::from(planner_error),
424            ExecutorError::Core(core_error) => Self::from(core_error),
425            ExecutorError::Storage(storage_error) => Self::from(storage_error),
426            ExecutorError::TransactionConflict => Self::Execution {
427                message: "transaction conflict".to_string(),
428                code: "ALOPEX-E001",
429            },
430            ExecutorError::ReadOnlyTransaction { operation } => Self::Execution {
431                message: format!("read-only transaction: cannot execute {operation}"),
432                code: "ALOPEX-E002",
433            },
434            ExecutorError::ResourceExhausted { message } => Self::Execution {
435                message: format!("resource exhausted: {message}"),
436                code: "ALOPEX-E003",
437            },
438            ExecutorError::TableNotFound(name) => Self::Catalog {
439                message: format!("table '{name}' not found"),
440                location: ErrorLocation::default(),
441                code: "ALOPEX-C001",
442            },
443            ExecutorError::TableAlreadyExists(name) => Self::Catalog {
444                message: format!("table '{name}' already exists"),
445                location: ErrorLocation::default(),
446                code: "ALOPEX-C002",
447            },
448            ExecutorError::IndexNotFound(name) => Self::Catalog {
449                message: format!("index '{name}' not found"),
450                location: ErrorLocation::default(),
451                code: "ALOPEX-C006",
452            },
453            ExecutorError::IndexAlreadyExists(name) => Self::Catalog {
454                message: format!("index '{name}' already exists"),
455                location: ErrorLocation::default(),
456                code: "ALOPEX-C005",
457            },
458            ExecutorError::ColumnNotFound(column) => Self::Catalog {
459                message: format!("column '{column}' not found"),
460                location: ErrorLocation::default(),
461                code: "ALOPEX-C003",
462            },
463            other => Self::Execution {
464                message: other.to_string(),
465                code: "ALOPEX-E999",
466            },
467        }
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[test]
476    fn from_parser_error_preserves_location() {
477        let parser_error = ParserError::UnexpectedToken {
478            line: 12,
479            column: 34,
480            expected: "SELECT".into(),
481            found: "SELEC".into(),
482        };
483
484        let unified: SqlError = parser_error.into();
485        assert_eq!(unified.code(), "ALOPEX-P001");
486        assert_eq!(
487            unified.location(),
488            ErrorLocation {
489                line: 12,
490                column: 34
491            }
492        );
493    }
494
495    #[test]
496    fn from_planner_error_preserves_code() {
497        let planner_error = PlannerError::TableNotFound {
498            name: "users".into(),
499            line: 1,
500            column: 8,
501        };
502
503        let unified: SqlError = planner_error.into();
504        assert_eq!(unified.code(), "ALOPEX-C001");
505        assert_eq!(unified.location(), ErrorLocation { line: 1, column: 8 });
506    }
507
508    #[test]
509    fn cte_column_errors_preserve_public_codes_and_locations() {
510        let count_mismatch: SqlError = PlannerError::CteColumnCountMismatch {
511            cte: "items".into(),
512            declared: 2,
513            actual: 1,
514            line: 3,
515            column: 6,
516        }
517        .into();
518        assert_eq!(count_mismatch.code(), "ALOPEX-T009");
519        assert_eq!(
520            count_mismatch.location(),
521            ErrorLocation { line: 3, column: 6 }
522        );
523
524        let duplicate: SqlError = PlannerError::DuplicateCteColumn {
525            cte: "items".into(),
526            name: "identifier".into(),
527            line: 4,
528            column: 7,
529        }
530        .into();
531        assert_eq!(duplicate.code(), "ALOPEX-T010");
532        assert_eq!(duplicate.location(), ErrorLocation { line: 4, column: 7 });
533    }
534
535    #[test]
536    fn message_with_location_format() {
537        let parser_error = ParserError::InvalidNumber {
538            line: 3,
539            column: 7,
540            value: "12x".into(),
541        };
542
543        let unified: SqlError = parser_error.into();
544        assert_eq!(
545            unified.message_with_location(),
546            "error[ALOPEX-P004]: invalid number literal '12x' at line 3, column 7"
547        );
548    }
549
550    #[test]
551    fn from_executor_core_error_maps_to_storage_and_preserves_source() {
552        let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnConflict).into();
553        assert_eq!(unified.code(), "ALOPEX-S001");
554        assert!(unified.source().is_some());
555        assert_eq!(
556            unified.message_with_location(),
557            "error[ALOPEX-S001]: storage error: transaction conflict"
558        );
559    }
560
561    #[test]
562    fn from_executor_core_readonly_maps_to_storage_and_preserves_source() {
563        let unified: SqlError = ExecutorError::Core(alopex_core::Error::TxnReadOnly).into();
564        assert_eq!(unified.code(), "ALOPEX-S003");
565        assert!(unified.source().is_some());
566        assert_eq!(
567            unified.message_with_location(),
568            "error[ALOPEX-S003]: storage error: transaction is read-only"
569        );
570    }
571
572    #[test]
573    fn from_executor_readonly_transaction_maps_to_execution_code() {
574        let unified: SqlError = ExecutorError::ReadOnlyTransaction {
575            operation: "INSERT".to_string(),
576        }
577        .into();
578        assert_eq!(unified.code(), "ALOPEX-E002");
579        assert_eq!(
580            unified.message_with_location(),
581            "error[ALOPEX-E002]: read-only transaction: cannot execute INSERT"
582        );
583    }
584
585    #[test]
586    fn from_executor_resource_exhausted_maps_to_stable_execution_code() {
587        let unified: SqlError = ExecutorError::ResourceExhausted {
588            message: "recursive CTE 'numbers' reached row limit 100000".to_string(),
589        }
590        .into();
591
592        assert_eq!(unified.code(), "ALOPEX-E003");
593        assert_eq!(
594            unified.message_with_location(),
595            "error[ALOPEX-E003]: resource exhausted: recursive CTE 'numbers' reached row limit 100000"
596        );
597    }
598}