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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// use super::pos::PosMarker;

use fancy_regex::Regex;

use super::parser::segments::base::Segment;
use crate::core::parser::markers::PositionMarker;

type CheckTuple = (String, usize, usize);

pub trait SqlError {
    fn fixable(&self) -> bool;
    fn rule_code(&self) -> Option<String>;
    fn identifier(&self) -> String;
    /// Get a tuple representing this error. Mostly for testing.
    fn check_tuple(&self) -> CheckTuple;
}

#[derive(Debug, PartialEq, Clone)]
pub struct SQLBaseError {
    pub fatal: bool,
    pub ignore: bool,
    pub warning: bool,
    pub line_no: usize,
    pub line_pos: usize,
}

impl SQLBaseError {
    pub fn new(fatal: bool, ignore: bool, warning: bool, line_no: usize, line_pos: usize) -> Self {
        Self { fatal, ignore, warning, line_no, line_pos }
    }
}

impl SqlError for SQLBaseError {
    fn fixable(&self) -> bool {
        false
    }

    fn rule_code(&self) -> Option<String> {
        None
    }

    fn identifier(&self) -> String {
        "base".to_string()
    }

    fn check_tuple(&self) -> CheckTuple {
        ("".to_string(), self.line_no, self.line_pos)
    }
}

// impl SQLBaseError {
// /// Should this error be considered fixable?
// fn fixable(&self) -> bool {
//     false
// }

// /// Fetch the code of the rule which cause this error.
// /// NB: This only returns a real code for some subclasses of
// /// error, (the ones with a `rule` attribute), but otherwise
// /// returns a placeholder value which can be used instead.
// fn rule_code(&self) -> String {
//     // TODO
//     "".to_string()
// }
// }
//     /// Fetch a description of this violation.
//     /// NB: For violations which don't directly implement a rule
//     /// this attempts to return the error message linked to whatever
//     /// caused the violation. Optionally some errors may have their
//     /// description set directly.
//     fn desc(&self) -> String {
//         // TODO
//         "".to_string()
//     }
//
//     /// Return a dict of properties.
//     /// This is useful in the API for outputting violations.
//     fn get_info_dict(&self) -> () {
//         // TODO
//         ()
//     }
//
//     /// Get a tuple representing this error. Mostly for testing.
//     fn check_tuple(&self) -> CheckTuple {
//         // TODO
//         ("".to_string(), 0, 0)
//     }
//
//     /// Return hashable source signature for deduplication.
//     fn source_signature(&self) -> () {
//         // TODO
//         ()
//     }
//
//     /// Ignore this violation if it matches the iterable.
//     fn ignore_if_in(&self, ignore_iterable: Vec<String>) {
//         // TODO
//     }
//
//     /// Warning only for this violation if it matches the iterable.
//     /// Designed for rule codes so works with L001, L00X but also TMP or PRS
//     /// for templating and parsing errors.
//     fn warning_if_in(&self, warning_iterable: Vec<String>) {
//         // TODO
//     }
// }
//
// struct SQLTemplaterError {
//     pos: Option<PosMarker>,
// }
//
// impl SQLTemplaterError {
//     /// An error which occurred during templating.
//     /// Args:
//     ///     pos (:obj:`PosMarker`, optional): The position which the error
//     ///         occurred at.
//     fn new(pos: Option<PosMarker>) -> SQLTemplaterError {
//         SQLTemplaterError { pos }
//     }
// }
//
// #[derive(Debug)]
// struct SQLFluffSkipFile;
//
// impl Error for SQLFluffSkipFile {}
//
// impl fmt::Display for SQLFluffSkipFile {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "An error returned from a templater to skip a file.")
//     }
// }
//
// #[derive(Debug)]
// struct SQLLexError {
//     pos: PosMarker,
// }
//
// impl Error for SQLLexError {}
//
// impl fmt::Display for SQLLexError {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "An error which occurred during lexing.")
//     }
// }
//
// #[derive(Debug)]
// struct SQLParseError {
//     segment: BaseSegment,
// }
//
// impl Error for SQLParseError {}
//
// impl fmt::Display for SQLParseError {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "An error which occurred during parsing.")
//     }
// }
//
#[derive(Debug, PartialEq, Eq)]
pub struct SQLLintError {
    // segment: Box<dyn Segment>,
    // rule: ErasedRule,
    // fixes: Vec<LintFix>,
    pub description: String,
}

impl From<SQLLintError> for SQLBaseError {
    fn from(value: SQLLintError) -> Self {
        Self { fatal: false, ignore: false, warning: true, line_no: todo!(), line_pos: todo!() }
    }
}

//
// impl Error for SQLLintError {}
//
// impl fmt::Display for SQLLintError {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "An error which occurred during linting.")
//     }
// }
//
// #[derive(Debug)]
// struct SQLFluffUserError;
//
// impl Error for SQLFluffUserError {}
//
// impl fmt::Display for SQLFluffUserError {
//     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//         write!(f, "An error which should be fed back to the user.")
//     }
// }

#[derive(Debug, PartialEq, Clone)]
pub struct SQLTemplaterError {}

impl SqlError for SQLTemplaterError {
    fn fixable(&self) -> bool {
        false
    }

    fn rule_code(&self) -> Option<String> {
        None
    }

    fn identifier(&self) -> String {
        "templater".to_string()
    }

    fn check_tuple(&self) -> CheckTuple {
        ("".to_string(), 0, 0)
    }
}

/// An error which should be fed back to the user.
#[derive(Debug)]
pub struct SQLFluffUserError {
    value: String,
}

impl SQLFluffUserError {
    pub fn new(value: String) -> SQLFluffUserError {
        SQLFluffUserError { value }
    }
}

// Not from SQLFluff but translates Python value error
#[derive(Debug)]
pub struct ValueError {
    value: String,
}

impl ValueError {
    pub fn new(value: String) -> ValueError {
        ValueError { value }
    }
}

#[derive(Debug)]
pub struct SQLParseError {
    pub description: String,
    pub segment: Option<Box<dyn Segment>>,
}

impl SQLParseError {
    pub fn matches(&self, regexp: &str) -> bool {
        let value = &self.description;
        let regex = Regex::new(regexp).expect("Invalid regex pattern");

        if let Ok(true) = regex.is_match(value) {
            true
        } else {
            let msg =
                format!("Regex pattern did not match.\nRegex: {:?}\nInput: {:?}", regexp, value);

            if regexp == value {
                panic!("{}\nDid you mean to escape the regex?", msg);
            } else {
                panic!("{}", msg);
            }
        }
    }
}

impl From<SQLParseError> for SQLBaseError {
    fn from(value: SQLParseError) -> Self {
        let (mut line_no, mut line_pos) = Default::default();

        let pos_marker = value.segment.and_then(|segment| segment.get_position_marker());

        if let Some(pos_marker) = pos_marker {
            (line_no, line_pos) = pos_marker.source_position();
        }

        Self { fatal: true, ignore: false, warning: false, line_no, line_pos }
    }
}

#[derive(PartialEq, Eq, Debug)]
pub struct SQLLexError {
    message: String,
    position_marker: PositionMarker,
}

impl SQLLexError {
    pub fn new(message: String, position_marker: PositionMarker) -> SQLLexError {
        SQLLexError { message, position_marker }
    }
}

#[derive(Debug)]
pub struct SQLFluffSkipFile {
    value: String,
}

impl SQLFluffSkipFile {
    pub fn new(value: String) -> SQLFluffSkipFile {
        SQLFluffSkipFile { value }
    }
}