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
//! Redshift Dialect
//!
//! Redshift-specific transformations based on sqlglot patterns.
//! Redshift is based on PostgreSQL but has some differences.
use super::{DialectImpl, DialectType};
use crate::error::Result;
use crate::expressions::{
AggFunc, Case, Cast, DataType, Expression, Function, Limit, RegexpFunc, VarArgFunc,
};
use crate::generator::GeneratorConfig;
use crate::tokens::TokenizerConfig;
/// Redshift dialect
pub struct RedshiftDialect;
impl DialectImpl for RedshiftDialect {
fn dialect_type(&self) -> DialectType {
DialectType::Redshift
}
fn tokenizer_config(&self) -> TokenizerConfig {
use crate::tokens::TokenType;
let mut config = TokenizerConfig::default();
// Redshift uses double quotes for identifiers (like PostgreSQL)
config.identifiers.insert('"', '"');
// Redshift does NOT support nested comments
config.nested_comments = false;
// MINUS is an alias for EXCEPT in Redshift
config
.keywords
.insert("MINUS".to_string(), TokenType::Except);
config
}
fn generator_config(&self) -> GeneratorConfig {
use crate::generator::IdentifierQuoteStyle;
GeneratorConfig {
identifier_quote: '"',
identifier_quote_style: IdentifierQuoteStyle::DOUBLE_QUOTE,
dialect: Some(DialectType::Redshift),
supports_column_join_marks: true,
locking_reads_supported: false,
tz_to_with_time_zone: true,
..Default::default()
}
}
fn transform_expr(&self, expr: Expression) -> Result<Expression> {
match expr {
// IFNULL -> COALESCE in Redshift
Expression::IfNull(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: vec![f.this, f.expression],
inferred_type: None,
}))),
// NVL is native in Redshift, but we standardize to COALESCE for consistency
Expression::Nvl(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: vec![f.this, f.expression],
inferred_type: None,
}))),
// TryCast -> TRY_CAST (Redshift supports TRY_CAST via CONVERT)
Expression::TryCast(c) => Ok(Expression::TryCast(c)),
// SafeCast -> TRY_CAST in Redshift
Expression::SafeCast(c) => Ok(Expression::TryCast(c)),
// ILIKE is native in Redshift (inherited from PostgreSQL)
Expression::ILike(op) => Ok(Expression::ILike(op)),
// 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,
})))
}
// EXPLODE is not supported in Redshift
Expression::Explode(_) => Ok(expr),
// ExplodeOuter is not supported in Redshift
Expression::ExplodeOuter(_) => Ok(expr),
// UNNEST is supported in Redshift (but limited)
Expression::Unnest(_) => Ok(expr),
// RAND -> RANDOM in Redshift (like PostgreSQL)
Expression::Rand(r) => {
let _ = r.seed;
Ok(Expression::Random(crate::expressions::Random))
}
// DateAdd -> DATEADD(unit, count, date) in Redshift
Expression::DateAdd(f) => {
let unit_str = match f.unit {
crate::expressions::IntervalUnit::Year => "YEAR",
crate::expressions::IntervalUnit::Quarter => "QUARTER",
crate::expressions::IntervalUnit::Month => "MONTH",
crate::expressions::IntervalUnit::Week => "WEEK",
crate::expressions::IntervalUnit::Day => "DAY",
crate::expressions::IntervalUnit::Hour => "HOUR",
crate::expressions::IntervalUnit::Minute => "MINUTE",
crate::expressions::IntervalUnit::Second => "SECOND",
crate::expressions::IntervalUnit::Millisecond => "MILLISECOND",
crate::expressions::IntervalUnit::Microsecond => "MICROSECOND",
crate::expressions::IntervalUnit::Nanosecond => "NANOSECOND",
};
let unit = Expression::Identifier(crate::expressions::Identifier {
name: unit_str.to_string(),
quoted: false,
trailing_comments: Vec::new(),
span: None,
});
Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
vec![unit, f.interval, f.this],
))))
}
// 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),
// CONVERT -> CAST in Redshift
Expression::Convert(c) => Ok(Expression::Cast(Box::new(Cast {
this: c.this,
to: c.to,
trailing_comments: Vec::new(),
double_colon_syntax: false,
format: None,
default: None,
inferred_type: None,
}))),
// SELECT TOP n -> SELECT ... LIMIT n in Redshift (PostgreSQL-style)
Expression::Select(mut select) => {
if let Some(top) = select.top.take() {
// Only convert simple TOP (not TOP PERCENT or WITH TIES)
if !top.percent && !top.with_ties {
// Convert TOP to LIMIT
select.limit = Some(Limit {
this: top.this,
percent: false,
comments: Vec::new(),
});
} else {
// Restore TOP if it has PERCENT or WITH TIES (not supported as LIMIT)
select.top = Some(top);
}
}
Ok(Expression::Select(select))
}
// Pass through everything else
_ => Ok(expr),
}
}
}
impl RedshiftDialect {
fn transform_function(&self, f: Function) -> Result<Expression> {
let name_upper = f.name.to_uppercase();
match name_upper.as_str() {
// IFNULL -> COALESCE
"IFNULL" if f.args.len() == 2 => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
}))),
// NVL -> COALESCE (supports 2+ args)
"NVL" if f.args.len() >= 2 => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
}))),
// ISNULL -> COALESCE
"ISNULL" if f.args.len() == 2 => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
}))),
// GETDATE is native to Redshift
"GETDATE" => Ok(Expression::Function(Box::new(Function::new(
"GETDATE".to_string(),
vec![],
)))),
// NOW -> GETDATE in Redshift
"NOW" => Ok(Expression::Function(Box::new(Function::new(
"GETDATE".to_string(),
vec![],
)))),
// RAND -> RANDOM in Redshift
"RAND" => Ok(Expression::Random(crate::expressions::Random)),
// GROUP_CONCAT -> LISTAGG in Redshift
"GROUP_CONCAT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// STRING_AGG -> LISTAGG in Redshift
"STRING_AGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// LISTAGG is native in Redshift
"LISTAGG" => Ok(Expression::Function(Box::new(f))),
// SUBSTR -> SUBSTRING
"SUBSTR" => Ok(Expression::Function(Box::new(Function::new(
"SUBSTRING".to_string(),
f.args,
)))),
// LEN is native in Redshift
"LEN" => Ok(Expression::Function(Box::new(f))),
// LENGTH -> LEN in Redshift
"LENGTH" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
"LEN".to_string(),
f.args,
)))),
// CHARINDEX is native in Redshift
"CHARINDEX" => Ok(Expression::Function(Box::new(f))),
// POSITION -> CHARINDEX in Redshift (with swapped args)
"POSITION" if f.args.len() == 2 => {
let mut args = f.args;
let substring = args.remove(0);
let string = args.remove(0);
// CHARINDEX(substring, string)
Ok(Expression::Function(Box::new(Function::new(
"CHARINDEX".to_string(),
vec![substring, string],
))))
}
// STRPOS -> CHARINDEX in Redshift
"STRPOS" if f.args.len() == 2 => {
let args = f.args;
// STRPOS(string, substring) -> CHARINDEX(substring, string)
let string = args[0].clone();
let substring = args[1].clone();
Ok(Expression::Function(Box::new(Function::new(
"CHARINDEX".to_string(),
vec![substring, string],
))))
}
// INSTR -> CHARINDEX in Redshift
"INSTR" if f.args.len() >= 2 => {
let mut args = f.args;
let string = args.remove(0);
let substring = args.remove(0);
// INSTR(string, substring) -> CHARINDEX(substring, string)
Ok(Expression::Function(Box::new(Function::new(
"CHARINDEX".to_string(),
vec![substring, string],
))))
}
// LOCATE -> CHARINDEX in Redshift
"LOCATE" if f.args.len() >= 2 => {
let mut args = f.args;
let substring = args.remove(0);
let string = args.remove(0);
// LOCATE(substring, string) -> CHARINDEX(substring, string)
Ok(Expression::Function(Box::new(Function::new(
"CHARINDEX".to_string(),
vec![substring, string],
))))
}
// ARRAY_LENGTH -> ARRAY_UPPER / custom in Redshift
// Redshift doesn't have ARRAY_LENGTH, arrays are limited
"ARRAY_LENGTH" => Ok(Expression::Function(Box::new(f))),
// SIZE -> not directly supported
"SIZE" => Ok(Expression::Function(Box::new(f))),
// TO_DATE -> TO_DATE (native in Redshift)
"TO_DATE" => Ok(Expression::Function(Box::new(f))),
// TO_TIMESTAMP -> TO_TIMESTAMP (native in Redshift)
"TO_TIMESTAMP" => Ok(Expression::Function(Box::new(f))),
// DATE_FORMAT -> TO_CHAR in Redshift
"DATE_FORMAT" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
Function::new("TO_CHAR".to_string(), f.args),
))),
// strftime -> TO_CHAR in Redshift
"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(
"TO_CHAR".to_string(),
vec![date, format],
))))
}
// TO_CHAR is native in Redshift
"TO_CHAR" => Ok(Expression::Function(Box::new(f))),
// LEVENSHTEIN -> not directly supported
"LEVENSHTEIN" => Ok(Expression::Function(Box::new(f))),
// JSON_EXTRACT -> JSON_EXTRACT_PATH_TEXT in Redshift
"JSON_EXTRACT" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
Function::new("JSON_EXTRACT_PATH_TEXT".to_string(), f.args),
))),
// JSON_EXTRACT_SCALAR -> JSON_EXTRACT_PATH_TEXT in Redshift
"JSON_EXTRACT_SCALAR" if f.args.len() >= 2 => Ok(Expression::Function(Box::new(
Function::new("JSON_EXTRACT_PATH_TEXT".to_string(), f.args),
))),
// GET_JSON_OBJECT -> JSON_EXTRACT_PATH_TEXT in Redshift
"GET_JSON_OBJECT" if f.args.len() == 2 => Ok(Expression::Function(Box::new(
Function::new("JSON_EXTRACT_PATH_TEXT".to_string(), f.args),
))),
// COLLECT_LIST -> not directly supported (limited array support)
"COLLECT_LIST" => Ok(Expression::Function(Box::new(f))),
// COLLECT_SET -> not directly supported
"COLLECT_SET" => Ok(Expression::Function(Box::new(f))),
// RLIKE -> REGEXP_MATCHES in Redshift (or SIMILAR TO)
"RLIKE" if f.args.len() == 2 => {
// Redshift uses ~ for regex matching
let mut args = f.args;
let string = args.remove(0);
let pattern = args.remove(0);
Ok(Expression::RegexpLike(Box::new(RegexpFunc {
this: string,
pattern,
flags: None,
})))
}
// REGEXP -> RegexpLike
"REGEXP" if f.args.len() == 2 => {
let mut args = f.args;
let string = args.remove(0);
let pattern = args.remove(0);
Ok(Expression::RegexpLike(Box::new(RegexpFunc {
this: string,
pattern,
flags: None,
})))
}
// REGEXP_LIKE -> native in Redshift (PostgreSQL-compatible)
"REGEXP_LIKE" => Ok(Expression::Function(Box::new(f))),
// ADD_MONTHS -> DATEADD in Redshift
"ADD_MONTHS" if f.args.len() == 2 => {
let mut args = f.args;
let date = args.remove(0);
let months = args.remove(0);
// DATEADD(month, num_months, date)
Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
vec![Expression::identifier("month"), months, date],
))))
}
// DATEDIFF is native in Redshift
"DATEDIFF" => Ok(Expression::Function(Box::new(f))),
// DATE_DIFF -> DATEDIFF in Redshift
"DATE_DIFF" => Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
f.args,
)))),
// DATEADD is native in Redshift
"DATEADD" => Ok(Expression::Function(Box::new(f))),
// DATE_ADD -> DATEADD in Redshift
"DATE_ADD" => Ok(Expression::Function(Box::new(Function::new(
"DATEADD".to_string(),
f.args,
)))),
// SPLIT_TO_ARRAY is native in Redshift
"SPLIT_TO_ARRAY" => Ok(Expression::Function(Box::new(f))),
// STRING_TO_ARRAY -> SPLIT_TO_ARRAY in Redshift
"STRING_TO_ARRAY" if f.args.len() >= 1 => Ok(Expression::Function(Box::new(
Function::new("SPLIT_TO_ARRAY".to_string(), f.args),
))),
// SPLIT -> SPLIT_TO_ARRAY in Redshift
"SPLIT" if f.args.len() >= 1 => Ok(Expression::Function(Box::new(Function::new(
"SPLIT_TO_ARRAY".to_string(),
f.args,
)))),
// STRTOL is native in Redshift (string to long/base conversion)
"STRTOL" => Ok(Expression::Function(Box::new(f))),
// FROM_BASE -> STRTOL in Redshift
"FROM_BASE" if f.args.len() == 2 => Ok(Expression::Function(Box::new(Function::new(
"STRTOL".to_string(),
f.args,
)))),
// CONVERT_TIMEZONE(target_tz, timestamp) -> CONVERT_TIMEZONE('UTC', target_tz, timestamp)
"CONVERT_TIMEZONE" if f.args.len() == 2 => {
let mut new_args = vec![Expression::string("UTC")];
new_args.extend(f.args);
Ok(Expression::Function(Box::new(Function::new(
"CONVERT_TIMEZONE".to_string(),
new_args,
))))
}
// 3-arg form stays as-is
"CONVERT_TIMEZONE" => Ok(Expression::Function(Box::new(f))),
// CONVERT(type, expr) -> CAST(expr AS type)
"CONVERT" if f.args.len() == 2 => {
let type_expr = &f.args[0];
let value_expr = f.args[1].clone();
// Extract type name from the first argument (it's likely a Column or Identifier)
let type_name = match type_expr {
Expression::Column(c) => c.name.name.clone(),
Expression::Identifier(i) => i.name.clone(),
_ => return Ok(Expression::Function(Box::new(f))), // Can't handle, pass through
};
// Map type name to DataType
let data_type = match type_name.to_uppercase().as_str() {
"INT" | "INTEGER" => DataType::Int {
length: None,
integer_spelling: false,
},
"BIGINT" => DataType::BigInt { length: None },
"SMALLINT" => DataType::SmallInt { length: None },
"TINYINT" => DataType::TinyInt { length: None },
"VARCHAR" => DataType::VarChar {
length: None,
parenthesized_length: false,
},
"CHAR" => DataType::Char { length: None },
"FLOAT" | "REAL" => DataType::Float {
precision: None,
scale: None,
real_spelling: false,
},
"DOUBLE" => DataType::Double {
precision: None,
scale: None,
},
"BOOLEAN" | "BOOL" => DataType::Boolean,
"DATE" => DataType::Date,
"TIMESTAMP" => DataType::Timestamp {
precision: None,
timezone: false,
},
"TEXT" => DataType::Text,
"DECIMAL" | "NUMERIC" => DataType::Decimal {
precision: None,
scale: None,
},
_ => return Ok(Expression::Function(Box::new(f))), // Unknown type, pass through
};
Ok(Expression::Cast(Box::new(Cast {
this: value_expr,
to: data_type,
trailing_comments: Vec::new(),
double_colon_syntax: false,
format: None,
default: None,
inferred_type: None,
})))
}
// 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,
})))
}
// ANY_VALUE is native in Redshift
"ANY_VALUE" => Ok(Expression::AggregateFunction(f)),
// GROUP_CONCAT -> LISTAGG in Redshift
"GROUP_CONCAT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// STRING_AGG -> LISTAGG in Redshift
"STRING_AGG" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("LISTAGG".to_string(), f.args),
))),
// LISTAGG is native in Redshift
"LISTAGG" => Ok(Expression::AggregateFunction(f)),
// STDDEV is native in Redshift
"STDDEV" => Ok(Expression::AggregateFunction(f)),
// VARIANCE is native in Redshift
"VARIANCE" => Ok(Expression::AggregateFunction(f)),
// MEDIAN is native in Redshift
"MEDIAN" => Ok(Expression::AggregateFunction(f)),
// Pass through everything else
_ => Ok(Expression::AggregateFunction(f)),
}
}
fn transform_cast(&self, c: Cast) -> Result<Expression> {
// Redshift type mappings are handled in the generator
Ok(Expression::Cast(Box::new(c)))
}
}