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
//! Vertica Dialect
//!
//! Vertica (OpenText Analytics Database) is a columnar MPP analytic database whose
//! SQL surface is largely PostgreSQL-compatible.
//! Reference: https://docs.vertica.com/latest/en/sql-reference/
//! Semantics cross-checked against https://github.com/luisdelatorre012/vertica-sqlglot-dialect
//!
//! Key characteristics:
//! - Double-quote identifiers, case-insensitive (folded to lowercase)
//! - `::` casts, ILIKE, `||` concatenation, LIMIT/OFFSET
//! - MINUS is an alias for EXCEPT
//! - All integer types are 64-bit (INT, SMALLINT, TINYINT are BIGINT)
//! - REAL / FLOAT are DOUBLE PRECISION
//! - LONG VARCHAR / LONG VARBINARY types
//! - NVL, NVL2, DECODE, ZEROIFNULL, LISTAGG, DATEDIFF(unit, a, b), TIMESTAMPADD
//! - GETDATE() / SYSDATE are statement-start timestamps
//! - No QUALIFY, TRY_CAST or semi/anti join syntax
//! - No nested comments
use super::{DialectImpl, DialectType};
#[cfg(feature = "transpile")]
use crate::error::Result;
#[cfg(feature = "transpile")]
use crate::expressions::{
AggFunc, Case, Expression, Function, Identifier, IntervalUnit, ListAggFunc, Literal, VarArgFunc,
};
#[cfg(feature = "generate")]
use crate::generator::GeneratorConfig;
use crate::tokens::TokenizerConfig;
/// Vertica dialect
pub struct VerticaDialect;
impl DialectImpl for VerticaDialect {
fn dialect_type(&self) -> DialectType {
DialectType::Vertica
}
fn tokenizer_config(&self) -> TokenizerConfig {
use crate::tokens::TokenType;
let mut config = TokenizerConfig::default();
// Vertica uses double quotes for identifiers (PostgreSQL-style)
config.identifiers.insert('"', '"');
// Vertica does NOT support nested comments
config.nested_comments = false;
// `//` is integer division
config.double_slash_int_div = true;
// MINUS is an alias for EXCEPT in Vertica
config
.keywords
.insert("MINUS".to_string(), TokenType::Except);
config
}
#[cfg(feature = "generate")]
fn generator_config(&self) -> GeneratorConfig {
use crate::generator::{IdentifierQuoteStyle, LimitFetchStyle};
GeneratorConfig {
identifier_quote: '"',
identifier_quote_style: IdentifierQuoteStyle::DOUBLE_QUOTE,
dialect: Some(DialectType::Vertica),
single_string_interval: true,
locking_reads_supported: true,
limit_fetch_style: LimitFetchStyle::Limit,
nvl2_supported: true,
supports_median: true,
aggregate_filter_supported: false,
..Default::default()
}
}
#[cfg(feature = "transpile")]
fn transform_expr(&self, expr: Expression) -> Result<Expression> {
match expr {
// IFNULL -> COALESCE in Vertica
Expression::IfNull(f) => Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: vec![f.this, f.expression],
inferred_type: None,
}))),
// Coalesce with original_name (e.g., IFNULL parsed as Coalesce) -> clear original_name
Expression::Coalesce(mut f) => {
f.original_name = None;
Ok(Expression::Coalesce(f))
}
Expression::TryCast(_) | Expression::SafeCast(_) => {
Err(crate::error::Error::unsupported(
"safe casts: Vertica ::! does not suppress constant cast failures",
"vertica",
))
}
// 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 -> RANDOM in Vertica
Expression::Rand(r) => {
let _ = r.seed;
Ok(Expression::Random(crate::expressions::Random))
}
// DAYOFWEEK_ISO has no shared generator form
Expression::DayOfWeekIso(f) => Ok(Expression::Function(Box::new(Function::new(
"DAYOFWEEK_ISO".to_string(),
vec![f.this],
)))),
// DATE_ADD / DATEADD -> TIMESTAMPADD(unit, n, ts); Vertica has no DATEADD
Expression::DateAdd(f) => Ok(timestamp_add(
interval_unit_name(&f.unit),
f.interval,
f.this,
)),
// APPROX_COUNT_DISTINCT -> APPROXIMATE_COUNT_DISTINCT
Expression::ApproxDistinct(mut f) | Expression::ApproxCountDistinct(mut f) => {
if !f.order_by.is_empty()
|| f.limit.is_some()
|| f.having_max.is_some()
|| f.ignore_nulls.is_some()
{
return Err(crate::error::Error::unsupported(
"approximate distinct aggregate modifiers",
"vertica",
));
}
if let Some(filter) = f.filter.take() {
f.this = Expression::Case(Box::new(Case {
operand: None,
whens: vec![(filter, f.this)],
else_: None,
comments: Vec::new(),
inferred_type: None,
}));
}
// DISTINCT is redundant for an approximate distinct count.
f.distinct = false;
f.name = None;
Ok(Expression::ApproxDistinct(f))
}
// GROUP_CONCAT / STRING_AGG -> LISTAGG
Expression::GroupConcat(f) => Ok(Expression::ListAgg(Box::new(ListAggFunc {
source_dialect: None,
this: f.this,
separator: f.separator,
on_overflow: None,
max_length: None,
order_by: f.order_by,
distinct: f.distinct,
filter: f.filter,
inferred_type: None,
}))),
Expression::StringAgg(f) => Ok(Expression::ListAgg(Box::new(ListAggFunc {
source_dialect: None,
this: f.this,
separator: f.separator,
on_overflow: None,
max_length: None,
order_by: f.order_by,
distinct: f.distinct,
filter: f.filter,
inferred_type: None,
}))),
// Generic function transformations
Expression::Function(f) => self.transform_function(*f),
// Pass through everything else
_ => Ok(expr),
}
}
}
#[cfg(feature = "transpile")]
impl VerticaDialect {
fn transform_function(&self, f: Function) -> Result<Expression> {
let name_upper = f.name.to_uppercase();
match name_upper.as_str() {
// IFNULL / ISNULL -> COALESCE
"IFNULL" | "ISNULL" if f.args.len() == 2 => {
Ok(Expression::Coalesce(Box::new(VarArgFunc {
original_name: None,
expressions: f.args,
inferred_type: None,
})))
}
// SYSDATE is a synonym for GETDATE (statement-start timestamp)
"SYSDATE" if f.args.is_empty() => Ok(Expression::Function(Box::new(Function::new(
"GETDATE".to_string(),
vec![],
)))),
// TIMESTAMPDIFF(unit, a, b) is a synonym for DATEDIFF(unit, a, b)
"TIMESTAMPDIFF" if f.args.len() == 3 => {
let mut args = f.args;
upper_unit(&mut args[0]);
Ok(Expression::Function(Box::new(Function::new(
"DATEDIFF".to_string(),
args,
))))
}
// APPROX_COUNT_DISTINCT -> APPROXIMATE_COUNT_DISTINCT
"APPROX_COUNT_DISTINCT" if !f.args.is_empty() => Ok(Expression::Function(Box::new(
Function::new("APPROXIMATE_COUNT_DISTINCT".to_string(), f.args),
))),
// DATEADD(unit, n, ts) -> TIMESTAMPADD(unit, n, ts)
"DATEADD" | "DATE_ADD" if f.args.len() == 3 => {
let mut args = f.args;
let ts = args.pop().unwrap();
let n = args.pop().unwrap();
let unit = args.pop().unwrap();
let unit = match unit {
Expression::Literal(lit) => match *lit {
Literal::String(s) => {
Expression::Identifier(Identifier::new(s.to_ascii_uppercase()))
}
other => Expression::Literal(Box::new(other)),
},
other => other,
};
Ok(Expression::Function(Box::new(Function::new(
"TIMESTAMPADD".to_string(),
vec![unit, n, ts],
))))
}
// TIMESTAMPADD(unit, n, ts): normalize the unit keyword to upper case
"TIMESTAMPADD" if f.args.len() == 3 => {
let mut f = f;
upper_unit(&mut f.args[0]);
Ok(Expression::Function(Box::new(f)))
}
// CHARINDEX(substr, str[, start]) -> INSTR(str, substr[, start])
"CHARINDEX" if f.args.len() >= 2 => {
let mut args = f.args;
let substr = args.remove(0);
let string = args.remove(0);
let mut new_args = vec![string, substr];
new_args.extend(args);
Ok(Expression::Function(Box::new(Function::new(
"INSTR".to_string(),
new_args,
))))
}
// LEN -> LENGTH
"LEN" if f.args.len() == 1 => Ok(Expression::Function(Box::new(Function::new(
"LENGTH".to_string(),
f.args,
)))),
// Pass through everything else
_ => Ok(Expression::Function(Box::new(f))),
}
}
}
#[cfg(feature = "transpile")]
fn interval_unit_name(unit: &IntervalUnit) -> &'static str {
match unit {
IntervalUnit::Year => "YEAR",
IntervalUnit::Quarter => "QUARTER",
IntervalUnit::Month => "MONTH",
IntervalUnit::Week => "WEEK",
IntervalUnit::Day => "DAY",
IntervalUnit::Hour => "HOUR",
IntervalUnit::Minute => "MINUTE",
IntervalUnit::Second => "SECOND",
IntervalUnit::Millisecond => "MILLISECOND",
IntervalUnit::Microsecond => "MICROSECOND",
IntervalUnit::Nanosecond => "NANOSECOND",
}
}
#[cfg(feature = "transpile")]
fn timestamp_add(unit: &str, amount: Expression, ts: Expression) -> Expression {
Expression::Function(Box::new(Function::new(
"TIMESTAMPADD".to_string(),
vec![Expression::Identifier(Identifier::new(unit)), amount, ts],
)))
}
/// Upper-case a bare datetime unit keyword (`day` -> `DAY`), leaving expressions alone.
#[cfg(feature = "transpile")]
fn upper_unit(unit: &mut Expression) {
match unit {
Expression::Identifier(id) if !id.quoted => id.name = id.name.to_ascii_uppercase(),
Expression::Column(col) if col.table.is_none() && !col.name.quoted => {
*unit = Expression::Identifier(Identifier::new(col.name.name.to_ascii_uppercase()));
}
_ => {}
}
}