1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use thiserror::Error;

/// Koron errors.
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum ParseError {
    #[error("malformed query: {message}")]
    MalformedQuery { message: String },
    #[error("statement not supported: {message}")]
    Unsupported { message: String },
    #[error("internal: {message}")]
    Internal { message: String },
}

macro_rules! impl_malformed_from {
    ($err:ty) => {
        impl From<$err> for ParseError {
            fn from(e: $err) -> Self {
                Self::MalformedQuery {
                    message: e.to_string(),
                }
            }
        }
    };
}

impl_malformed_from!(sqlparser::parser::ParserError);

impl From<String> for ParseError {
    fn from(e: String) -> Self {
        Self::Internal { message: e }
    }
}

/// Constructs a `ParseError::Unsupported{message: $msg}`.
#[macro_export]
macro_rules! unsupported {
    ($msg:literal) => {{
        ParseError::Unsupported { message: $msg }
    }};
    ($msg:expr) => {{
        ParseError::Unsupported { message: $msg }
    }};
}

/// Constructs a `ParseError::Internal{message: $msg}`.
#[macro_export]
macro_rules! internal {
    ($msg:literal) => {{
        ParseError::Internal { message: $msg }
    }};
    ($msg:expr) => {{
        ParseError::Internal { message: $msg }
    }};
}

/// Constructs a `ParseError::MalformedQuery{message: $msg}`.
#[macro_export]
macro_rules! malformed_query {
    ($msg:literal) => {{
        ParseError::MalformedQuery { message: $msg }
    }};
    ($msg:expr) => {{
        ParseError::MalformedQuery { message: $msg }
    }};
}

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

    #[test]
    fn to_string() {
        let mut error = internal!("test.".to_string());
        assert_eq!(error.to_string(), "internal: test.".to_string());

        error = malformed_query!("test.".to_string());
        assert_eq!(error.to_string(), "malformed query: test.".to_string());

        error = unsupported!("test.".to_string());
        assert_eq!(
            error.to_string(),
            "statement not supported: test.".to_string()
        );
    }
}