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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! SingleStore Dialect
//!
//! SingleStore (formerly MemSQL) specific transformations based on sqlglot patterns.
//! SingleStore is MySQL-compatible with distributed database extensions.

use super::{DialectImpl, DialectType};
use crate::error::Result;
use crate::expressions::{
    AggFunc, BinaryOp, Case, Cast, CollationExpr, DataType, Expression, Function, Paren, VarArgFunc,
};
use crate::generator::GeneratorConfig;
use crate::tokens::TokenizerConfig;

/// SingleStore dialect (MySQL-compatible distributed database)
pub struct SingleStoreDialect;

impl DialectImpl for SingleStoreDialect {
    fn dialect_type(&self) -> DialectType {
        DialectType::SingleStore
    }

    fn tokenizer_config(&self) -> TokenizerConfig {
        let mut config = TokenizerConfig::default();
        // SingleStore uses backticks for identifiers (MySQL-style)
        config.identifiers.insert('`', '`');
        config.nested_comments = false;
        config
    }

    fn generator_config(&self) -> GeneratorConfig {
        use crate::generator::IdentifierQuoteStyle;
        GeneratorConfig {
            identifier_quote: '`',
            identifier_quote_style: IdentifierQuoteStyle::BACKTICK,
            dialect: Some(DialectType::SingleStore),
            ..Default::default()
        }
    }

    fn transform_expr(&self, expr: Expression) -> Result<Expression> {
        match expr {
            // SHOW INDEXES/KEYS -> SHOW INDEX in SingleStore
            Expression::Show(mut s) => {
                // Normalize INDEXES and KEYS to INDEX
                if s.this == "INDEXES" || s.this == "KEYS" {
                    s.this = "INDEX".to_string();
                }
                Ok(Expression::Show(s))
            }

            // SingleStore: Cast followed by COLLATE needs double cast
            // e.g., name :> LONGTEXT COLLATE 'utf8mb4_bin' -> name :> LONGTEXT :> LONGTEXT COLLATE 'utf8mb4_bin'
            Expression::Collation(c) => {
                if let Expression::Cast(inner_cast) = &c.this {
                    // Wrap the cast in another cast with the same type
                    let double_cast = Expression::Cast(Box::new(Cast {
                        this: c.this.clone(),
                        to: inner_cast.to.clone(),
                        trailing_comments: Vec::new(),
                        double_colon_syntax: false,
                        format: None,
                        default: None,
                        inferred_type: None,
                    }));
                    Ok(Expression::Collation(Box::new(CollationExpr {
                        this: double_cast,
                        collation: c.collation.clone(),
                        quoted: c.quoted,
                        double_quoted: c.double_quoted,
                    })))
                } else {
                    Ok(Expression::Collation(c))
                }
            }

            // IFNULL is native in SingleStore (MySQL-style)
            Expression::IfNull(f) => Ok(Expression::IfNull(f)),

            // NVL -> IFNULL in SingleStore
            Expression::Nvl(f) => Ok(Expression::IfNull(f)),

            // TryCast -> not directly supported, use :> operator
            Expression::TryCast(c) => Ok(Expression::TryCast(c)),

            // SafeCast -> TryCast in SingleStore
            Expression::SafeCast(c) => Ok(Expression::TryCast(c)),

            // CountIf -> SUM(CASE WHEN condition THEN 1 ELSE 0 END)
            Expression::CountIf(f) => {
                let case_expr = Expression::Case(Box::new(Case {
                    operand: None,
                    whens: vec![(f.this.clone(), Expression::number(1))],
                    else_: Some(Expression::number(0)),
                    comments: Vec::new(),
                    inferred_type: None,
                }));
                Ok(Expression::Sum(Box::new(AggFunc {
                    ignore_nulls: None,
                    having_max: None,
                    this: case_expr,
                    distinct: f.distinct,
                    filter: f.filter,
                    order_by: Vec::new(),
                    name: None,
                    limit: None,
                    inferred_type: None,
                })))
            }

            // RAND is native in SingleStore
            Expression::Rand(r) => Ok(Expression::Rand(r)),

            // Second -> DATE_FORMAT(..., '%s') :> INT (SingleStore doesn't have native SECOND)
            Expression::Second(f) => {
                let date = f.this;
                // Cast to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%s")],
                )));
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // Hour -> DATE_FORMAT(..., '%k') :> INT (SingleStore uses DATE_FORMAT for HOUR)
            Expression::Hour(f) => {
                let date = f.this;
                // Cast to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%k")],
                )));
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // Minute -> DATE_FORMAT(..., '%i') :> INT (SingleStore doesn't have native MINUTE)
            Expression::Minute(f) => {
                let date = f.this;
                // Cast to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%i")],
                )));
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

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

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

            // Cast transformations
            Expression::Cast(c) => self.transform_cast(*c),

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

impl SingleStoreDialect {
    fn transform_function(&self, f: Function) -> Result<Expression> {
        let name_upper = f.name.to_uppercase();
        match name_upper.as_str() {
            // NVL -> IFNULL
            "NVL" if f.args.len() == 2 => Ok(Expression::Function(Box::new(Function::new(
                "IFNULL".to_string(),
                f.args,
            )))),

            // COALESCE is native in SingleStore
            "COALESCE" => Ok(Expression::Coalesce(Box::new(VarArgFunc {
                original_name: None,
                expressions: f.args,
                inferred_type: None,
            }))),

            // NOW is native in SingleStore - preserve as function
            "NOW" => Ok(Expression::Function(Box::new(f))),

            // GETDATE -> NOW
            "GETDATE" => Ok(Expression::Function(Box::new(Function::new(
                "NOW".to_string(),
                f.args,
            )))),

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

            // STRING_AGG -> GROUP_CONCAT
            "STRING_AGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
                Function::new("GROUP_CONCAT".to_string(), f.args),
            ))),

            // LISTAGG -> GROUP_CONCAT
            "LISTAGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
                "GROUP_CONCAT".to_string(),
                f.args,
            )))),

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

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

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

            // LEN -> LENGTH
            "LEN" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
                "LENGTH".to_string(),
                f.args,
            )))),

            // CHARINDEX -> INSTR (with swapped args)
            "CHARINDEX" if f.args.len() >= 2 => {
                let mut args = f.args;
                let substring = args.remove(0);
                let string = args.remove(0);
                Ok(Expression::Function(Box::new(Function::new(
                    "INSTR".to_string(),
                    vec![string, substring],
                ))))
            }

            // STRPOS -> INSTR
            "STRPOS" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
                "INSTR".to_string(),
                f.args,
            )))),

            // CURTIME -> CURRENT_TIME
            "CURTIME" => Ok(Expression::CurrentTime(crate::expressions::CurrentTime {
                precision: None,
            })),

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

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

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

            // strftime -> DATE_FORMAT
            "STRFTIME" if f.args.len() >= 2 => {
                let mut args = f.args;
                let format = args.remove(0);
                let date = args.remove(0);
                Ok(Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![date, format],
                ))))
            }

            // TO_CHAR is native in SingleStore - preserve as function
            "TO_CHAR" => Ok(Expression::Function(Box::new(f))),

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

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

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

            // JSON_EXTRACT -> JSON_EXTRACT_JSON
            "JSON_EXTRACT" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
                Function::new("JSON_EXTRACT_JSON".to_string(), f.args),
            ))),

            // GET_JSON_OBJECT -> JSON_EXTRACT_STRING
            "GET_JSON_OBJECT" if f.args.len() == 2 => Ok(Expression::Function(Box::new(
                Function::new("JSON_EXTRACT_STRING".to_string(), f.args),
            ))),

            // REGEXP_LIKE -> RLIKE
            "REGEXP_LIKE" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
                Function::new("RLIKE".to_string(), f.args),
            ))),

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

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

            // DATE_BIN -> TIME_BUCKET
            "DATE_BIN" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(Function::new(
                "TIME_BUCKET".to_string(),
                f.args,
            )))),

            // TIME_FORMAT -> DATE_FORMAT with cast to TIME(6)
            // TIME_FORMAT(date, fmt) -> DATE_FORMAT(date :> TIME(6), fmt)
            "TIME_FORMAT" if f.args.len() == 2 => {
                let mut args = f.args;
                let date = args.remove(0);
                let format = args.remove(0);
                // Cast date to TIME(6)
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                Ok(Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, format],
                ))))
            }

            // DAYNAME -> DATE_FORMAT with '%W'
            "DAYNAME" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                Ok(Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![date, Expression::string("%W")],
                ))))
            }

            // MONTHNAME -> DATE_FORMAT with '%M'
            "MONTHNAME" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                Ok(Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![date, Expression::string("%M")],
                ))))
            }

            // HOUR -> DATE_FORMAT with '%k' :> INT
            "HOUR" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                // Cast date to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                // DATE_FORMAT(... :> TIME(6), '%k')
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%k")],
                )));
                // Cast result to INT
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // MINUTE -> DATE_FORMAT with '%i' :> INT
            "MINUTE" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                // Cast date to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                // DATE_FORMAT(... :> TIME(6), '%i')
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%i")],
                )));
                // Cast result to INT
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // SECOND -> DATE_FORMAT with '%s' :> INT
            "SECOND" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                // Cast date to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                // DATE_FORMAT(... :> TIME(6), '%s')
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%s")],
                )));
                // Cast result to INT
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // MICROSECOND -> DATE_FORMAT with '%f' :> INT
            "MICROSECOND" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                // Cast date to TIME(6) first
                let cast_to_time = Expression::Cast(Box::new(Cast {
                    this: date,
                    to: DataType::Time {
                        precision: Some(6),
                        timezone: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                }));
                // DATE_FORMAT(... :> TIME(6), '%f')
                let date_format = Expression::Function(Box::new(Function::new(
                    "DATE_FORMAT".to_string(),
                    vec![cast_to_time, Expression::string("%f")],
                )));
                // Cast result to INT
                Ok(Expression::Cast(Box::new(Cast {
                    this: date_format,
                    to: DataType::Int {
                        length: None,
                        integer_spelling: false,
                    },
                    trailing_comments: Vec::new(),
                    double_colon_syntax: false,
                    format: None,
                    default: None,
                    inferred_type: None,
                })))
            }

            // WEEKDAY -> (DAYOFWEEK(...) + 5) % 7
            "WEEKDAY" if f.args.len() == 1 => {
                let date = f.args.into_iter().next().unwrap();
                // DAYOFWEEK(date)
                let dayofweek = Expression::Function(Box::new(Function::new(
                    "DAYOFWEEK".to_string(),
                    vec![date],
                )));
                // (DAYOFWEEK(date) + 5) - wrap in explicit parentheses
                let add_five =
                    Expression::Add(Box::new(BinaryOp::new(dayofweek, Expression::number(5))));
                let add_five_paren = Expression::Paren(Box::new(Paren {
                    this: add_five,
                    trailing_comments: Vec::new(),
                }));
                // (DAYOFWEEK(date) + 5) % 7
                Ok(Expression::Mod(Box::new(BinaryOp::new(
                    add_five_paren,
                    Expression::number(7),
                ))))
            }

            // 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() {
            // COUNT_IF -> SUM(CASE WHEN...)
            "COUNT_IF" if !f.args.is_empty() => {
                let condition = f.args.into_iter().next().unwrap();
                let case_expr = Expression::Case(Box::new(Case {
                    operand: None,
                    whens: vec![(condition, Expression::number(1))],
                    else_: Some(Expression::number(0)),
                    comments: Vec::new(),
                    inferred_type: None,
                }));
                Ok(Expression::Sum(Box::new(AggFunc {
                    ignore_nulls: None,
                    having_max: None,
                    this: case_expr,
                    distinct: f.distinct,
                    filter: f.filter,
                    order_by: Vec::new(),
                    name: None,
                    limit: None,
                    inferred_type: None,
                })))
            }

            // APPROX_COUNT_DISTINCT is native in SingleStore
            "APPROX_COUNT_DISTINCT" => Ok(Expression::AggregateFunction(f)),

            // HLL -> APPROX_COUNT_DISTINCT
            "HLL" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
                "APPROX_COUNT_DISTINCT".to_string(),
                f.args,
            )))),

            // VARIANCE -> VAR_SAMP
            "VARIANCE" if !f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
                "VAR_SAMP".to_string(),
                f.args,
            )))),

            // VAR_POP is native in SingleStore
            "VAR_POP" => Ok(Expression::AggregateFunction(f)),

            // VAR_SAMP is native in SingleStore
            "VAR_SAMP" => Ok(Expression::AggregateFunction(f)),

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

    fn transform_cast(&self, c: Cast) -> Result<Expression> {
        // SingleStore type mappings are handled in the generator
        Ok(Expression::Cast(Box::new(c)))
    }
}