kumosql-sql 0.2.0

BigQuery/GoogleSQL lexer, parser, AST, printer, formatter, complexity scoring, read-only validation, Dataform SQLX handling and script analysis for KumoSQL-Rust
Documentation
//! Errors raised by the lexer, parser, formatter, validator and SQLX helpers.

use crate::token::Span;
use kumosql_core::KumoError;

/// Every error this crate returns.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SqlError {
    /// The text could not be tokenized (an unterminated string, comment or quoted name).
    #[error("lex error: {message} at line {line}, column {column}")]
    Lex {
        message: String,
        span: Span,
        line: usize,
        column: usize,
    },
    /// The tokens do not form valid GoogleSQL.
    #[error("parse error: {message} at line {line}, column {column}")]
    Parse {
        message: String,
        span: Span,
        line: usize,
        column: usize,
    },
    /// A Dataform SQLX file or block is malformed.
    #[error("SQLX error: {0}")]
    Sqlx(String),
    /// A rewrite lost or duplicated a masked SQLX interpolation.
    #[error("SQLX restoration error: {0}")]
    SqlxRestoration(String),
    /// Input refused by a validator (read-only query check, table path check, preferences).
    #[error("{0}")]
    Validation(String),
    /// The formatter or complexity scorer could not handle the input.
    #[error("{0}")]
    Format(String),
}

impl SqlError {
    /// A lex error at `span` of `source`, with a 1-based line and column.
    pub fn lex(source: &str, span: Span, message: impl Into<String>) -> Self {
        let (line, column) = line_column(source, span.start);
        SqlError::Lex {
            message: message.into(),
            span,
            line,
            column,
        }
    }

    /// A parse error at `span` of `source`, with a 1-based line and column.
    pub fn parse(source: &str, span: Span, message: impl Into<String>) -> Self {
        let (line, column) = line_column(source, span.start);
        SqlError::Parse {
            message: message.into(),
            span,
            line,
            column,
        }
    }

    /// Where the error happened, for lex and parse errors.
    pub fn span(&self) -> Option<Span> {
        match self {
            SqlError::Lex { span, .. } | SqlError::Parse { span, .. } => Some(*span),
            _ => None,
        }
    }

    /// The message without position information, never quoting SQL text.
    pub fn message(&self) -> String {
        match self {
            SqlError::Lex { message, .. } | SqlError::Parse { message, .. } => message.clone(),
            other => other.to_string(),
        }
    }
}

/// 1-based line and column (in characters) of byte `offset` in `source`.
pub fn line_column(source: &str, offset: usize) -> (usize, usize) {
    let offset = offset.min(source.len());
    let mut line = 1;
    let mut column = 1;
    for (index, ch) in source.char_indices() {
        if index >= offset {
            break;
        }
        if ch == '\n' {
            line += 1;
            column = 1;
        } else {
            column += 1;
        }
    }
    (line, column)
}

impl From<SqlError> for KumoError {
    fn from(error: SqlError) -> Self {
        match error {
            SqlError::Lex { .. } | SqlError::Parse { .. } => KumoError::Parse(error.to_string()),
            SqlError::Sqlx(message) | SqlError::SqlxRestoration(message) => {
                KumoError::Sqlx(message)
            }
            SqlError::Validation(message) | SqlError::Format(message) => {
                KumoError::Validation(message)
            }
        }
    }
}

/// Result alias used throughout the crate.
pub type Result<T> = std::result::Result<T, SqlError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn line_column_counts_from_one() {
        assert_eq!(line_column("ab\ncd", 0), (1, 1));
        assert_eq!(line_column("ab\ncd", 4), (2, 2));
        assert_eq!(line_column("ab", 99), (1, 3));
    }

    #[test]
    fn converts_into_core_error() {
        let err = SqlError::parse("select", Span::new(0, 6), "boom");
        let core: KumoError = err.into();
        assert!(matches!(core, KumoError::Parse(_)));
        let core: KumoError = SqlError::Sqlx("x".into()).into();
        assert!(matches!(core, KumoError::Sqlx(_)));
    }
}