1use crate::token::Span;
4use kumosql_core::KumoError;
5
6#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
8pub enum SqlError {
9 #[error("lex error: {message} at line {line}, column {column}")]
11 Lex {
12 message: String,
13 span: Span,
14 line: usize,
15 column: usize,
16 },
17 #[error("parse error: {message} at line {line}, column {column}")]
19 Parse {
20 message: String,
21 span: Span,
22 line: usize,
23 column: usize,
24 },
25 #[error("SQLX error: {0}")]
27 Sqlx(String),
28 #[error("SQLX restoration error: {0}")]
30 SqlxRestoration(String),
31 #[error("{0}")]
33 Validation(String),
34 #[error("{0}")]
36 Format(String),
37}
38
39impl SqlError {
40 pub fn lex(source: &str, span: Span, message: impl Into<String>) -> Self {
42 let (line, column) = line_column(source, span.start);
43 SqlError::Lex {
44 message: message.into(),
45 span,
46 line,
47 column,
48 }
49 }
50
51 pub fn parse(source: &str, span: Span, message: impl Into<String>) -> Self {
53 let (line, column) = line_column(source, span.start);
54 SqlError::Parse {
55 message: message.into(),
56 span,
57 line,
58 column,
59 }
60 }
61
62 pub fn span(&self) -> Option<Span> {
64 match self {
65 SqlError::Lex { span, .. } | SqlError::Parse { span, .. } => Some(*span),
66 _ => None,
67 }
68 }
69
70 pub fn message(&self) -> String {
72 match self {
73 SqlError::Lex { message, .. } | SqlError::Parse { message, .. } => message.clone(),
74 other => other.to_string(),
75 }
76 }
77}
78
79pub fn line_column(source: &str, offset: usize) -> (usize, usize) {
81 let offset = offset.min(source.len());
82 let mut line = 1;
83 let mut column = 1;
84 for (index, ch) in source.char_indices() {
85 if index >= offset {
86 break;
87 }
88 if ch == '\n' {
89 line += 1;
90 column = 1;
91 } else {
92 column += 1;
93 }
94 }
95 (line, column)
96}
97
98impl From<SqlError> for KumoError {
99 fn from(error: SqlError) -> Self {
100 match error {
101 SqlError::Lex { .. } | SqlError::Parse { .. } => KumoError::Parse(error.to_string()),
102 SqlError::Sqlx(message) | SqlError::SqlxRestoration(message) => {
103 KumoError::Sqlx(message)
104 }
105 SqlError::Validation(message) | SqlError::Format(message) => {
106 KumoError::Validation(message)
107 }
108 }
109 }
110}
111
112pub type Result<T> = std::result::Result<T, SqlError>;
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn line_column_counts_from_one() {
121 assert_eq!(line_column("ab\ncd", 0), (1, 1));
122 assert_eq!(line_column("ab\ncd", 4), (2, 2));
123 assert_eq!(line_column("ab", 99), (1, 3));
124 }
125
126 #[test]
127 fn converts_into_core_error() {
128 let err = SqlError::parse("select", Span::new(0, 6), "boom");
129 let core: KumoError = err.into();
130 assert!(matches!(core, KumoError::Parse(_)));
131 let core: KumoError = SqlError::Sqlx("x".into()).into();
132 assert!(matches!(core, KumoError::Sqlx(_)));
133 }
134}