Skip to main content

kumosql_sql/
error.rs

1//! Errors raised by the lexer, parser, formatter, validator and SQLX helpers.
2
3use crate::token::Span;
4use kumosql_core::KumoError;
5
6/// Every error this crate returns.
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
8pub enum SqlError {
9    /// The text could not be tokenized (an unterminated string, comment or quoted name).
10    #[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    /// The tokens do not form valid GoogleSQL.
18    #[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    /// A Dataform SQLX file or block is malformed.
26    #[error("SQLX error: {0}")]
27    Sqlx(String),
28    /// A rewrite lost or duplicated a masked SQLX interpolation.
29    #[error("SQLX restoration error: {0}")]
30    SqlxRestoration(String),
31    /// Input refused by a validator (read-only query check, table path check, preferences).
32    #[error("{0}")]
33    Validation(String),
34    /// The formatter or complexity scorer could not handle the input.
35    #[error("{0}")]
36    Format(String),
37}
38
39impl SqlError {
40    /// A lex error at `span` of `source`, with a 1-based line and column.
41    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    /// A parse error at `span` of `source`, with a 1-based line and column.
52    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    /// Where the error happened, for lex and parse errors.
63    pub fn span(&self) -> Option<Span> {
64        match self {
65            SqlError::Lex { span, .. } | SqlError::Parse { span, .. } => Some(*span),
66            _ => None,
67        }
68    }
69
70    /// The message without position information, never quoting SQL text.
71    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
79/// 1-based line and column (in characters) of byte `offset` in `source`.
80pub 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
112/// Result alias used throughout the crate.
113pub 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}