polyglot-sql 0.7.0

SQL parsing, validating, formatting, and dialect translation library
Documentation
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Error types for polyglot-sql

use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

/// The result type for polyglot operations
pub type Result<T> = std::result::Result<T, Error>;

/// Errors that can occur during SQL parsing and generation
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// Error during tokenization
    #[error("Tokenization error at line {line}, column {column}: {message}")]
    Tokenize {
        message: String,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    },

    /// Error during parsing
    #[error("Parse error at line {line}, column {column}: {message}")]
    Parse {
        message: String,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    },

    /// Error during SQL generation
    #[error("Generation error: {0}")]
    Generate(String),

    /// Unsupported feature for the target dialect
    #[error("Unsupported: {feature} is not supported in {dialect}")]
    Unsupported { feature: String, dialect: String },

    /// Invalid SQL syntax
    #[error("Syntax error at line {line}, column {column}: {message}")]
    Syntax {
        message: String,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    },

    /// Invalid input for an operation after parsing has completed.
    #[error("Invalid input: {0}")]
    InvalidInput(String),

    /// A requested output column could not be resolved.
    #[error("Cannot resolve {target}: {reason}")]
    ColumnResolution {
        target: ColumnResolutionTarget,
        reason: ColumnResolutionReason,
    },

    /// Internal error (should not happen in normal usage)
    #[error("Internal error: {0}")]
    Internal(String),
}

impl Error {
    /// Create a tokenization error
    pub fn tokenize(
        message: impl Into<String>,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    ) -> Self {
        Error::Tokenize {
            message: message.into(),
            line,
            column,
            start,
            end,
        }
    }

    /// Create a parse error with position information
    pub fn parse(
        message: impl Into<String>,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    ) -> Self {
        Error::Parse {
            message: message.into(),
            line,
            column,
            start,
            end,
        }
    }

    /// Get the line number if available
    pub fn line(&self) -> Option<usize> {
        match self {
            Error::Tokenize { line, .. }
            | Error::Parse { line, .. }
            | Error::Syntax { line, .. } => Some(*line),
            _ => None,
        }
    }

    /// Get the column number if available
    pub fn column(&self) -> Option<usize> {
        match self {
            Error::Tokenize { column, .. }
            | Error::Parse { column, .. }
            | Error::Syntax { column, .. } => Some(*column),
            _ => None,
        }
    }

    /// Get the start byte offset if available
    pub fn start(&self) -> Option<usize> {
        match self {
            Error::Tokenize { start, .. }
            | Error::Parse { start, .. }
            | Error::Syntax { start, .. } => Some(*start),
            _ => None,
        }
    }

    /// Get the end byte offset if available
    pub fn end(&self) -> Option<usize> {
        match self {
            Error::Tokenize { end, .. } | Error::Parse { end, .. } | Error::Syntax { end, .. } => {
                Some(*end)
            }
            _ => None,
        }
    }

    /// Create a generation error
    pub fn generate(message: impl Into<String>) -> Self {
        Error::Generate(message.into())
    }

    /// Create an unsupported feature error
    pub fn unsupported(feature: impl Into<String>, dialect: impl Into<String>) -> Self {
        Error::Unsupported {
            feature: feature.into(),
            dialect: dialect.into(),
        }
    }

    /// Create a syntax error
    pub fn syntax(
        message: impl Into<String>,
        line: usize,
        column: usize,
        start: usize,
        end: usize,
    ) -> Self {
        Error::Syntax {
            message: message.into(),
            line,
            column,
            start,
            end,
        }
    }

    /// Create an invalid-input error.
    pub fn invalid_input(message: impl Into<String>) -> Self {
        Error::InvalidInput(message.into())
    }

    /// Create a structured column-resolution error.
    pub fn column_resolution(
        target: ColumnResolutionTarget,
        reason: ColumnResolutionReason,
    ) -> Self {
        Error::ColumnResolution { target, reason }
    }

    /// Create an internal error
    pub fn internal(message: impl Into<String>) -> Self {
        Error::Internal(message.into())
    }
}

/// The output-column selector that failed to resolve.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ColumnResolutionTarget {
    /// Resolve an output column by name.
    Name { name: String },
    /// Resolve an output column by zero-based ordinal.
    Ordinal { ordinal: usize },
}

impl fmt::Display for ColumnResolutionTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Name { name } => write!(f, "column '{name}'"),
            Self::Ordinal { ordinal } => write!(f, "output ordinal {ordinal}"),
        }
    }
}

/// Why an output-column selector could not be resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ColumnResolutionReason {
    /// The output shape is known and does not contain the requested column.
    NotFound,
    /// An unresolved wildcard prevents the output position from being known.
    Indeterminate,
    /// More than one output position matches the requested name.
    Ambiguous,
}

impl fmt::Display for ColumnResolutionReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFound => f.write_str("not found"),
            Self::Indeterminate => {
                f.write_str("indeterminate because an output wildcard could not be expanded")
            }
            Self::Ambiguous => f.write_str("ambiguous"),
        }
    }
}

/// Severity level for validation errors
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ValidationSeverity {
    /// An error that prevents the query from being valid
    Error,
    /// A warning about potential issues
    Warning,
}

/// A single validation error or warning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// The error/warning message
    pub message: String,
    /// Line number where the error occurred (1-based)
    pub line: Option<usize>,
    /// Column number where the error occurred (1-based)
    pub column: Option<usize>,
    /// Severity of the validation issue
    pub severity: ValidationSeverity,
    /// Error code (e.g., "E001", "W001")
    pub code: String,
    /// Start byte offset of the error range
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<usize>,
    /// End byte offset of the error range (exclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<usize>,
}

impl ValidationError {
    /// Create a new validation error
    pub fn error(message: impl Into<String>, code: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            line: None,
            column: None,
            severity: ValidationSeverity::Error,
            code: code.into(),
            start: None,
            end: None,
        }
    }

    /// Create a new validation warning
    pub fn warning(message: impl Into<String>, code: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            line: None,
            column: None,
            severity: ValidationSeverity::Warning,
            code: code.into(),
            start: None,
            end: None,
        }
    }

    /// Set the line number
    pub fn with_line(mut self, line: usize) -> Self {
        self.line = Some(line);
        self
    }

    /// Set the column number
    pub fn with_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }

    /// Set both line and column
    pub fn with_location(mut self, line: usize, column: usize) -> Self {
        self.line = Some(line);
        self.column = Some(column);
        self
    }

    /// Set the start/end byte offsets
    pub fn with_span(mut self, start: Option<usize>, end: Option<usize>) -> Self {
        self.start = start;
        self.end = end;
        self
    }
}

/// Result of validating SQL
#[derive(Debug, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether the SQL is valid (no errors, warnings are allowed)
    pub valid: bool,
    /// List of validation errors and warnings
    pub errors: Vec<ValidationError>,
}

impl ValidationResult {
    /// Create a successful validation result
    pub fn success() -> Self {
        Self {
            valid: true,
            errors: Vec::new(),
        }
    }

    /// Create a validation result with errors
    pub fn with_errors(errors: Vec<ValidationError>) -> Self {
        let has_errors = errors
            .iter()
            .any(|e| e.severity == ValidationSeverity::Error);
        Self {
            valid: !has_errors,
            errors,
        }
    }

    /// Add an error to the result
    pub fn add_error(&mut self, error: ValidationError) {
        if error.severity == ValidationSeverity::Error {
            self.valid = false;
        }
        self.errors.push(error);
    }
}

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

    #[test]
    fn test_parse_error_has_position() {
        let err = Error::parse("test message", 5, 10, 20, 25);
        assert_eq!(err.line(), Some(5));
        assert_eq!(err.column(), Some(10));
        assert_eq!(err.start(), Some(20));
        assert_eq!(err.end(), Some(25));
        assert!(err.to_string().contains("line 5"));
        assert!(err.to_string().contains("column 10"));
        assert!(err.to_string().contains("test message"));
    }

    #[test]
    fn test_tokenize_error_has_position() {
        let err = Error::tokenize("bad token", 3, 7, 15, 20);
        assert_eq!(err.line(), Some(3));
        assert_eq!(err.column(), Some(7));
        assert_eq!(err.start(), Some(15));
        assert_eq!(err.end(), Some(20));
    }

    #[test]
    fn test_generate_error_has_no_position() {
        let err = Error::generate("gen error");
        assert_eq!(err.line(), None);
        assert_eq!(err.column(), None);
        assert_eq!(err.start(), None);
        assert_eq!(err.end(), None);
    }

    #[test]
    fn test_parse_error_position_from_parser() {
        // Parse invalid SQL and verify the error carries position info
        use crate::dialects::{Dialect, DialectType};
        let d = Dialect::get(DialectType::Generic);
        let result = d.parse("SELECT 1 + 2)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.line().is_some(),
            "Parse error should have line: {:?}",
            err
        );
        assert!(
            err.column().is_some(),
            "Parse error should have column: {:?}",
            err
        );
        assert_eq!(err.line(), Some(1));
    }

    #[test]
    fn test_parse_error_has_span_offsets() {
        use crate::dialects::{Dialect, DialectType};
        let d = Dialect::get(DialectType::Generic);
        let result = d.parse("SELECT 1 + 2)");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.start().is_some(),
            "Parse error should have start offset: {:?}",
            err
        );
        assert!(
            err.end().is_some(),
            "Parse error should have end offset: {:?}",
            err
        );
        // The ')' is at byte offset 12
        assert_eq!(err.start(), Some(12));
        assert_eq!(err.end(), Some(13));
    }

    #[test]
    fn test_validation_error_with_span() {
        let err = ValidationError::error("test", "E001")
            .with_location(1, 5)
            .with_span(Some(4), Some(10));
        assert_eq!(err.start, Some(4));
        assert_eq!(err.end, Some(10));
        assert_eq!(err.line, Some(1));
        assert_eq!(err.column, Some(5));
    }
}