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