polyglot-sql 0.3.3

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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Exasol SQL Dialect
//!
//! Exasol-specific SQL dialect based on sqlglot patterns.
//!
//! References:
//! - SQL Reference: https://docs.exasol.com/db/latest/sql_references/basiclanguageelements.htm
//! - Data Types: https://docs.exasol.com/db/latest/sql_references/data_types/datatypesoverview.htm
//! - Functions: https://docs.exasol.com/db/latest/sql_references/functions/
//!
//! Key characteristics:
//! - Uppercase normalization for identifiers
//! - Identifiers: double quotes or square brackets
//! - Date functions: ADD_DAYS, ADD_MONTHS, DAYS_BETWEEN, MONTHS_BETWEEN
//! - Bitwise: BIT_AND, BIT_OR, BIT_XOR, BIT_NOT, BIT_LSHIFT, BIT_RSHIFT
//! - Functions: ZEROIFNULL, NULLIFZERO, SYSTIMESTAMP
//! - EVERY for ALL aggregate
//! - No SEMI/ANTI join support
//! - DATE_TRUNC for date truncation
//! - IF...THEN...ELSE...ENDIF syntax

use super::{DialectImpl, DialectType};
use crate::error::Result;
use crate::expressions::{Expression, Function, ListAggFunc, Literal, VarArgFunc};
use crate::generator::GeneratorConfig;
use crate::tokens::TokenizerConfig;

/// Exasol dialect
pub struct ExasolDialect;

impl DialectImpl for ExasolDialect {
    fn dialect_type(&self) -> DialectType {
        DialectType::Exasol
    }

    fn tokenizer_config(&self) -> TokenizerConfig {
        let mut config = TokenizerConfig::default();
        // Exasol uses double quotes for identifiers
        config.identifiers.insert('"', '"');
        // Also supports square brackets
        config.identifiers.insert('[', ']');
        config
    }

    fn generator_config(&self) -> GeneratorConfig {
        use crate::generator::IdentifierQuoteStyle;
        GeneratorConfig {
            identifier_quote: '"',
            identifier_quote_style: IdentifierQuoteStyle::DOUBLE_QUOTE,
            dialect: Some(DialectType::Exasol),
            supports_column_join_marks: true,
            // Exasol uses lowercase for window frame keywords (rows, preceding, following)
            lowercase_window_frame_keywords: true,
            ..Default::default()
        }
    }

    fn transform_expr(&self, expr: Expression) -> Result<Expression> {
        match expr {
            // SYSTIMESTAMP -> SYSTIMESTAMP() (with parentheses in Exasol)
            Expression::Systimestamp(_) => Ok(Expression::Function(Box::new(Function::new(
                "SYSTIMESTAMP".to_string(),
                vec![],
            )))),

            // WeekOfYear -> WEEK
            Expression::WeekOfYear(f) => Ok(Expression::Function(Box::new(Function::new(
                "WEEK".to_string(),
                vec![f.this],
            )))),

            // COALESCE is native, but also support transformations from other forms
            Expression::Nvl(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
                original_name: None,
                expressions: vec![f.this, f.expression],
                inferred_type: None,
            }))),

            Expression::IfNull(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
                original_name: None,
                expressions: vec![f.this, f.expression],
                inferred_type: None,
            }))),

            // Bitwise operations → BIT_* functions
            Expression::BitwiseAnd(op) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_AND".to_string(),
                vec![op.left, op.right],
            )))),

            Expression::BitwiseOr(op) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_OR".to_string(),
                vec![op.left, op.right],
            )))),

            Expression::BitwiseXor(op) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_XOR".to_string(),
                vec![op.left, op.right],
            )))),

            Expression::BitwiseNot(f) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_NOT".to_string(),
                vec![f.this],
            )))),

            Expression::BitwiseLeftShift(op) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_LSHIFT".to_string(),
                vec![op.left, op.right],
            )))),

            Expression::BitwiseRightShift(op) => Ok(Expression::Function(Box::new(Function::new(
                "BIT_RSHIFT".to_string(),
                vec![op.left, op.right],
            )))),

            // Modulo → MOD function
            Expression::Mod(op) => Ok(Expression::Function(Box::new(Function::new(
                "MOD".to_string(),
                vec![op.left, op.right],
            )))),

            // GROUP_CONCAT -> LISTAGG in Exasol (with WITHIN GROUP for ORDER BY)
            Expression::GroupConcat(f) => Ok(Expression::ListAgg(Box::new(ListAggFunc {
                this: f.this,
                separator: f.separator,
                on_overflow: None,
                order_by: f.order_by,
                distinct: f.distinct,
                filter: f.filter,
                inferred_type: None,
            }))),

            // USER (no parens) -> CURRENT_USER
            Expression::Column(col)
                if col.table.is_none() && col.name.name.eq_ignore_ascii_case("USER") =>
            {
                Ok(Expression::CurrentUser(Box::new(
                    crate::expressions::CurrentUser { this: None },
                )))
            }

            // Generic function transformations
            Expression::Function(f) => self.transform_function(*f),

            // Aggregate function transformations
            Expression::AggregateFunction(f) => self.transform_aggregate_function(f),

            // Pass through everything else
            _ => Ok(expr),
        }
    }
}

impl ExasolDialect {
    fn transform_function(&self, f: Function) -> Result<Expression> {
        let name_upper = f.name.to_uppercase();
        match name_upper.as_str() {
            // SYSTIMESTAMP -> SYSTIMESTAMP() (with parentheses in Exasol)
            // Exasol requires parentheses even for no-arg functions
            // Preserve any arguments (like precision)
            "SYSTIMESTAMP" => Ok(Expression::Function(Box::new(Function::new(
                "SYSTIMESTAMP".to_string(),
                f.args,
            )))),

            // ALL → EVERY
            "ALL" => Ok(Expression::Function(Box::new(Function::new(
                "EVERY".to_string(),
                f.args,
            )))),

            // IFNULL/ISNULL/NVL → COALESCE (native in Exasol)
            "IFNULL" | "ISNULL" | "NVL" if f.args.len() == 2 => {
                Ok(Expression::Coalesce(Box::new(VarArgFunc {
                    original_name: None,
                    expressions: f.args,
                    inferred_type: None,
                })))
            }

            // DateDiff → DAYS_BETWEEN (for DAY unit) or other *_BETWEEN functions
            "DATEDIFF" => Ok(Expression::Function(Box::new(Function::new(
                "DAYS_BETWEEN".to_string(),
                f.args,
            )))),

            // DateAdd → ADD_DAYS (for DAY unit) or other ADD_* functions
            "DATEADD" | "DATE_ADD" => Ok(Expression::Function(Box::new(Function::new(
                "ADD_DAYS".to_string(),
                f.args,
            )))),

            // DateSub → Negate and use ADD_DAYS
            "DATESUB" | "DATE_SUB" => {
                // Would need to negate the interval, for now just use ADD_DAYS
                Ok(Expression::Function(Box::new(Function::new(
                    "ADD_DAYS".to_string(),
                    f.args,
                ))))
            }

            // DATE_TRUNC is native
            "DATE_TRUNC" | "TRUNC" => Ok(Expression::Function(Box::new(f))),

            // LEVENSHTEIN → EDIT_DISTANCE
            "LEVENSHTEIN" | "LEVENSHTEIN_DISTANCE" => Ok(Expression::Function(Box::new(
                Function::new("EDIT_DISTANCE".to_string(), f.args),
            ))),

            // REGEXP_EXTRACT → REGEXP_SUBSTR
            "REGEXP_EXTRACT" => Ok(Expression::Function(Box::new(Function::new(
                "REGEXP_SUBSTR".to_string(),
                f.args,
            )))),

            // SHA/SHA1 → HASH_SHA
            "SHA" | "SHA1" => Ok(Expression::Function(Box::new(Function::new(
                "HASH_SHA".to_string(),
                f.args,
            )))),

            // MD5 → HASH_MD5
            "MD5" => Ok(Expression::Function(Box::new(Function::new(
                "HASH_MD5".to_string(),
                f.args,
            )))),

            // SHA256 → HASH_SHA256
            "SHA256" | "SHA2" => {
                // SHA2 in some dialects takes a length parameter
                // HASH_SHA256 in Exasol just takes the value
                let arg = f
                    .args
                    .into_iter()
                    .next()
                    .unwrap_or(Expression::Null(crate::expressions::Null));
                Ok(Expression::Function(Box::new(Function::new(
                    "HASH_SHA256".to_string(),
                    vec![arg],
                ))))
            }

            // SHA512 → HASH_SHA512
            "SHA512" => Ok(Expression::Function(Box::new(Function::new(
                "HASH_SHA512".to_string(),
                f.args,
            )))),

            // VAR_POP is native
            "VAR_POP" | "VARIANCE_POP" => Ok(Expression::Function(Box::new(Function::new(
                "VAR_POP".to_string(),
                f.args,
            )))),

            // APPROX_DISTINCT → APPROXIMATE_COUNT_DISTINCT
            "APPROX_DISTINCT" | "APPROX_COUNT_DISTINCT" => Ok(Expression::Function(Box::new(
                Function::new("APPROXIMATE_COUNT_DISTINCT".to_string(), f.args),
            ))),

            // TO_CHAR is native for date formatting
            // DATE_FORMAT/STRFTIME: convert format codes and CAST value to TIMESTAMP
            "TO_CHAR" | "DATE_FORMAT" | "STRFTIME" => {
                let mut args = f.args;
                if args.len() >= 2 {
                    // Convert format codes from C-style (%Y, %m, etc.) to Exasol format
                    if let Expression::Literal(lit) = &args[1] {
                        if let Literal::String(fmt) = lit.as_ref() {
                            let exasol_fmt = Self::convert_c_format_to_exasol(fmt);
                            args[1] = Expression::Literal(Box::new(Literal::String(exasol_fmt)));
                        }
                    }
                    // CAST string literal values to TIMESTAMP for date formatting functions
                    if matches!(&args[0], Expression::Literal(lit) if matches!(lit.as_ref(), Literal::String(_)))
                        && (f.name.eq_ignore_ascii_case("DATE_FORMAT")
                            || f.name.eq_ignore_ascii_case("STRFTIME"))
                    {
                        args[0] = Expression::Cast(Box::new(crate::expressions::Cast {
                            this: args[0].clone(),
                            to: crate::expressions::DataType::Timestamp {
                                timezone: false,
                                precision: None,
                            },
                            trailing_comments: vec![],
                            double_colon_syntax: false,
                            format: None,
                            default: None,
                            inferred_type: None,
                        }));
                    }
                }
                Ok(Expression::Function(Box::new(Function::new(
                    "TO_CHAR".to_string(),
                    args,
                ))))
            }

            // TO_DATE is native but format specifiers need uppercasing
            "TO_DATE" => {
                if f.args.len() >= 2 {
                    // Uppercase format string if present
                    let mut new_args = f.args.clone();
                    if let Expression::Literal(lit) = &f.args[1] {
                        if let Literal::String(fmt) = lit.as_ref() {
                            new_args[1] = Expression::Literal(Box::new(Literal::String(
                                Self::uppercase_exasol_format(fmt),
                            )));
                        }
                    }
                    Ok(Expression::Function(Box::new(Function::new(
                        "TO_DATE".to_string(),
                        new_args,
                    ))))
                } else {
                    Ok(Expression::Function(Box::new(f)))
                }
            }

            // TIME_TO_STR -> TO_CHAR with format conversion
            "TIME_TO_STR" => {
                if f.args.len() >= 2 {
                    let mut new_args = vec![f.args[0].clone()];
                    if let Expression::Literal(lit) = &f.args[1] {
                        if let Literal::String(fmt) = lit.as_ref() {
                            new_args.push(Expression::Literal(Box::new(Literal::String(
                                Self::convert_strptime_to_exasol_format(fmt),
                            ))));
                        }
                    } else {
                        new_args.push(f.args[1].clone());
                    }
                    Ok(Expression::Function(Box::new(Function::new(
                        "TO_CHAR".to_string(),
                        new_args,
                    ))))
                } else {
                    Ok(Expression::Function(Box::new(Function::new(
                        "TO_CHAR".to_string(),
                        f.args,
                    ))))
                }
            }

            // STR_TO_TIME -> TO_DATE with format conversion
            "STR_TO_TIME" => {
                if f.args.len() >= 2 {
                    let mut new_args = vec![f.args[0].clone()];
                    if let Expression::Literal(lit) = &f.args[1] {
                        if let Literal::String(fmt) = lit.as_ref() {
                            new_args.push(Expression::Literal(Box::new(Literal::String(
                                Self::convert_strptime_to_exasol_format(fmt),
                            ))));
                        }
                    } else {
                        new_args.push(f.args[1].clone());
                    }
                    Ok(Expression::Function(Box::new(Function::new(
                        "TO_DATE".to_string(),
                        new_args,
                    ))))
                } else {
                    Ok(Expression::Function(Box::new(Function::new(
                        "TO_DATE".to_string(),
                        f.args,
                    ))))
                }
            }

            // TO_TIMESTAMP is native
            "TO_TIMESTAMP" => Ok(Expression::Function(Box::new(f))),

            // CONVERT_TZ for timezone conversion
            "CONVERT_TIMEZONE" | "AT_TIME_ZONE" => Ok(Expression::Function(Box::new(
                Function::new("CONVERT_TZ".to_string(), f.args),
            ))),

            // STRPOS/POSITION → INSTR
            "STRPOS" | "POSITION" | "CHARINDEX" | "LOCATE" => Ok(Expression::Function(Box::new(
                Function::new("INSTR".to_string(), f.args),
            ))),

            // WEEK_OF_YEAR → WEEK
            "WEEK_OF_YEAR" | "WEEKOFYEAR" => Ok(Expression::Function(Box::new(Function::new(
                "WEEK".to_string(),
                f.args,
            )))),

            // LAST_DAY is not native, would need complex transformation
            "LAST_DAY" => {
                // Exasol doesn't have LAST_DAY, but we can compute it
                // For now, pass through
                Ok(Expression::Function(Box::new(f)))
            }

            // CURDATE -> CURRENT_DATE
            "CURDATE" => Ok(Expression::CurrentDate(crate::expressions::CurrentDate)),

            // USER / USER() -> CURRENT_USER
            "USER" if f.args.is_empty() => Ok(Expression::CurrentUser(Box::new(
                crate::expressions::CurrentUser { this: None },
            ))),

            // NOW -> CURRENT_TIMESTAMP
            "NOW" => Ok(Expression::CurrentTimestamp(
                crate::expressions::CurrentTimestamp {
                    precision: None,
                    sysdate: false,
                },
            )),

            // Pass through everything else
            _ => Ok(Expression::Function(Box::new(f))),
        }
    }

    fn transform_aggregate_function(
        &self,
        f: Box<crate::expressions::AggregateFunction>,
    ) -> Result<Expression> {
        let name_upper = f.name.to_uppercase();
        match name_upper.as_str() {
            // ALL → EVERY
            "ALL" | "EVERY" => Ok(Expression::Function(Box::new(Function::new(
                "EVERY".to_string(),
                f.args,
            )))),

            // GROUP_CONCAT / STRING_AGG → LISTAGG (native with WITHIN GROUP)
            "GROUP_CONCAT" | "STRING_AGG" => Ok(Expression::Function(Box::new(Function::new(
                "LISTAGG".to_string(),
                f.args,
            )))),

            // LISTAGG is native
            "LISTAGG" => Ok(Expression::AggregateFunction(f)),

            // APPROX_DISTINCT → APPROXIMATE_COUNT_DISTINCT
            "APPROX_DISTINCT" | "APPROX_COUNT_DISTINCT" => Ok(Expression::Function(Box::new(
                Function::new("APPROXIMATE_COUNT_DISTINCT".to_string(), f.args),
            ))),

            // Pass through everything else
            _ => Ok(Expression::AggregateFunction(f)),
        }
    }

    /// Convert strptime format string to Exasol format string
    /// Exasol TIME_MAPPING (reverse of Python sqlglot):
    /// %Y -> YYYY, %y -> YY, %m -> MM, %d -> DD, %H -> HH, %M -> MI, %S -> SS, %a -> DY
    fn convert_strptime_to_exasol_format(format: &str) -> String {
        let mut result = String::new();
        let chars: Vec<char> = format.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            if chars[i] == '%' && i + 1 < chars.len() {
                let spec = chars[i + 1];
                let exasol_spec = match spec {
                    'Y' => "YYYY",
                    'y' => "YY",
                    'm' => "MM",
                    'd' => "DD",
                    'H' => "HH",
                    'M' => "MI",
                    'S' => "SS",
                    'a' => "DY",    // abbreviated weekday name
                    'A' => "DAY",   // full weekday name
                    'b' => "MON",   // abbreviated month name
                    'B' => "MONTH", // full month name
                    'I' => "H12",   // 12-hour format
                    'u' => "ID",    // ISO weekday (1-7)
                    'V' => "IW",    // ISO week number
                    'G' => "IYYY",  // ISO year
                    'W' => "UW",    // Week number (Monday as first day)
                    'U' => "UW",    // Week number (Sunday as first day)
                    'z' => "Z",     // timezone offset
                    _ => {
                        // Unknown specifier, keep as-is
                        result.push('%');
                        result.push(spec);
                        i += 2;
                        continue;
                    }
                };
                result.push_str(exasol_spec);
                i += 2;
            } else {
                result.push(chars[i]);
                i += 1;
            }
        }
        result
    }

    /// Convert C-style / MySQL format codes to Exasol format codes.
    /// Handles both standard strptime codes and MySQL-specific codes (%i, %T).
    fn convert_c_format_to_exasol(format: &str) -> String {
        let mut result = String::new();
        let chars: Vec<char> = format.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            if chars[i] == '%' && i + 1 < chars.len() {
                let spec = chars[i + 1];
                let exasol_spec = match spec {
                    'Y' => "YYYY",
                    'y' => "YY",
                    'm' => "MM",
                    'd' => "DD",
                    'H' => "HH",
                    'M' => "MI", // strptime minutes
                    'i' => "MI", // MySQL minutes
                    'S' | 's' => "SS",
                    'T' => "HH:MI:SS", // MySQL %T = time (HH:MM:SS)
                    'a' => "DY",       // abbreviated weekday name
                    'A' => "DAY",      // full weekday name
                    'b' => "MON",      // abbreviated month name
                    'B' => "MONTH",    // full month name
                    'I' => "H12",      // 12-hour format
                    'u' => "ID",       // ISO weekday (1-7)
                    'V' => "IW",       // ISO week number
                    'G' => "IYYY",     // ISO year
                    'W' => "UW",       // Week number
                    'U' => "UW",       // Week number
                    'z' => "Z",        // timezone offset
                    _ => {
                        // Unknown specifier, keep as-is
                        result.push('%');
                        result.push(spec);
                        i += 2;
                        continue;
                    }
                };
                result.push_str(exasol_spec);
                i += 2;
            } else {
                result.push(chars[i]);
                i += 1;
            }
        }
        result
    }

    /// Uppercase Exasol format specifiers (DD, MM, YYYY, etc.)
    /// Converts lowercase format strings like 'dd-mm-yyyy' to 'DD-MM-YYYY'
    fn uppercase_exasol_format(format: &str) -> String {
        // Exasol format specifiers are always uppercase
        format.to_uppercase()
    }
}

// Note: Exasol type mappings (handled in generator if needed):
// - BLOB, LONGBLOB, etc. → VARCHAR
// - TEXT → LONG VARCHAR
// - VARBINARY → VARCHAR
// - TINYINT → SMALLINT
// - MEDIUMINT → INT
// - DECIMAL32/64/128/256 → DECIMAL
// - DATETIME → TIMESTAMP
// - TIMESTAMPTZ/TIMESTAMPLTZ/TIMESTAMPNTZ → TIMESTAMP
//
// Exasol also supports:
// - TIMESTAMP WITH LOCAL TIME ZONE (fixed precision of 3)
// - IF...THEN...ELSE...ENDIF syntax for conditionals