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
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Query {
pub ctes: Vec<Cte>,
pub body: SetExpr,
pub order_by: Vec<OrderByExpr>,
pub limit: Option<Expr>,
pub offset: Option<Expr>,
pub fetch: Option<Fetch>,
}
impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if !self.ctes.is_empty() {
write!(f, "WITH {} ", display_comma_separated(&self.ctes))?;
}
write!(f, "{}", self.body)?;
if !self.order_by.is_empty() {
write!(f, " ORDER BY {}", display_comma_separated(&self.order_by))?;
}
if let Some(ref limit) = self.limit {
write!(f, " LIMIT {}", limit)?;
}
if let Some(ref offset) = self.offset {
write!(f, " OFFSET {}", offset)?;
}
if let Some(ref fetch) = self.fetch {
write!(f, " {}", fetch)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SetExpr {
Select(Box<Select>),
Query(Box<Query>),
SetOperation {
op: SetOperator,
all: bool,
left: Box<SetExpr>,
right: Box<SetExpr>,
},
Values(Values),
ParameterizedValue(Vec<usize>),
}
impl fmt::Display for SetExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SetExpr::Select(s) => write!(f, "{}", s),
SetExpr::Query(q) => write!(f, "({})", q),
SetExpr::Values(v) => write!(f, "{}", v),
SetExpr::SetOperation {
left,
right,
op,
all,
} => {
let all_str = if *all { " ALL" } else { "" };
write!(f, "{} {}{} {}", left, op, all_str, right)
}
SetExpr::ParameterizedValue(params) => write!(
f,
"VALUES({})",
params
.iter()
.map(|i| format!("${}", i))
.collect::<Vec<String>>()
.join(", ")
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SetOperator {
Union,
Except,
Intersect,
}
impl fmt::Display for SetOperator {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
SetOperator::Union => "UNION",
SetOperator::Except => "EXCEPT",
SetOperator::Intersect => "INTERSECT",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Select {
pub distinct: bool,
pub projection: Vec<SelectItem>,
pub from: Vec<TableWithJoins>,
pub selection: Option<Expr>,
pub group_by: Vec<Expr>,
pub having: Option<Expr>,
}
impl fmt::Display for Select {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"SELECT{} {}",
if self.distinct { " DISTINCT" } else { "" },
display_comma_separated(&self.projection)
)?;
if !self.from.is_empty() {
write!(f, " FROM {}", display_comma_separated(&self.from))?;
}
if let Some(ref selection) = self.selection {
write!(f, " WHERE {}", selection)?;
}
if !self.group_by.is_empty() {
write!(f, " GROUP BY {}", display_comma_separated(&self.group_by))?;
}
if let Some(ref having) = self.having {
write!(f, " HAVING {}", having)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Cte {
pub alias: TableAlias,
pub query: Query,
}
impl fmt::Display for Cte {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} AS ({})", self.alias, self.query)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SelectItem {
UnnamedExpr(Expr),
ExprWithAlias { expr: Expr, alias: Ident },
QualifiedWildcard(ObjectName),
Wildcard,
}
impl fmt::Display for SelectItem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self {
SelectItem::UnnamedExpr(expr) => write!(f, "{}", expr),
SelectItem::ExprWithAlias { expr, alias } => write!(f, "{} AS {}", expr, alias),
SelectItem::QualifiedWildcard(prefix) => write!(f, "{}.*", prefix),
SelectItem::Wildcard => write!(f, "*"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TableWithJoins {
pub relation: TableFactor,
pub joins: Vec<Join>,
}
impl fmt::Display for TableWithJoins {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.relation)?;
for join in &self.joins {
write!(f, "{}", join)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TableFactor {
Table {
name: ObjectName,
alias: Option<TableAlias>,
args: Vec<Expr>,
with_hints: Vec<Expr>,
},
Derived {
lateral: bool,
subquery: Box<Query>,
alias: Option<TableAlias>,
},
NestedJoin(Box<TableWithJoins>),
}
impl fmt::Display for TableFactor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TableFactor::Table {
name,
alias,
args,
with_hints,
} => {
write!(f, "{}", name)?;
if !args.is_empty() {
write!(f, "({})", display_comma_separated(args))?;
}
if let Some(alias) = alias {
write!(f, " AS {}", alias)?;
}
if !with_hints.is_empty() {
write!(f, " WITH ({})", display_comma_separated(with_hints))?;
}
Ok(())
}
TableFactor::Derived {
lateral,
subquery,
alias,
} => {
if *lateral {
write!(f, "LATERAL ")?;
}
write!(f, "({})", subquery)?;
if let Some(alias) = alias {
write!(f, " AS {}", alias)?;
}
Ok(())
}
TableFactor::NestedJoin(table_reference) => write!(f, "({})", table_reference),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TableAlias {
pub name: Ident,
pub columns: Vec<Ident>,
}
impl fmt::Display for TableAlias {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)?;
if !self.columns.is_empty() {
write!(f, " ({})", display_comma_separated(&self.columns))?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Join {
pub relation: TableFactor,
pub join_operator: JoinOperator,
}
impl fmt::Display for Join {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn prefix(constraint: &JoinConstraint) -> &'static str {
match constraint {
JoinConstraint::Natural => "NATURAL ",
_ => "",
}
}
fn suffix<'a>(constraint: &'a JoinConstraint) -> impl fmt::Display + 'a {
struct Suffix<'a>(&'a JoinConstraint);
impl<'a> fmt::Display for Suffix<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
JoinConstraint::On(expr) => write!(f, " ON {}", expr),
JoinConstraint::Using(attrs) => {
write!(f, " USING({})", display_comma_separated(attrs))
}
_ => Ok(()),
}
}
}
Suffix(constraint)
}
match &self.join_operator {
JoinOperator::Inner(constraint) => write!(
f,
" {}JOIN {}{}",
prefix(constraint),
self.relation,
suffix(constraint)
),
JoinOperator::LeftOuter(constraint) => write!(
f,
" {}LEFT JOIN {}{}",
prefix(constraint),
self.relation,
suffix(constraint)
),
JoinOperator::RightOuter(constraint) => write!(
f,
" {}RIGHT JOIN {}{}",
prefix(constraint),
self.relation,
suffix(constraint)
),
JoinOperator::FullOuter(constraint) => write!(
f,
" {}FULL JOIN {}{}",
prefix(constraint),
self.relation,
suffix(constraint)
),
JoinOperator::CrossJoin => write!(f, " CROSS JOIN {}", self.relation),
JoinOperator::CrossApply => write!(f, " CROSS APPLY {}", self.relation),
JoinOperator::OuterApply => write!(f, " OUTER APPLY {}", self.relation),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum JoinOperator {
Inner(JoinConstraint),
LeftOuter(JoinConstraint),
RightOuter(JoinConstraint),
FullOuter(JoinConstraint),
CrossJoin,
CrossApply,
OuterApply,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum JoinConstraint {
On(Expr),
Using(Vec<Ident>),
Natural,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OrderByExpr {
pub expr: Expr,
pub asc: Option<bool>,
}
impl fmt::Display for OrderByExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.asc {
Some(true) => write!(f, "{} ASC", self.expr),
Some(false) => write!(f, "{} DESC", self.expr),
None => write!(f, "{}", self.expr),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fetch {
pub with_ties: bool,
pub percent: bool,
pub quantity: Option<Expr>,
}
impl fmt::Display for Fetch {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let extension = if self.with_ties { "WITH TIES" } else { "ONLY" };
if let Some(ref quantity) = self.quantity {
let percent = if self.percent { " PERCENT" } else { "" };
write!(f, "FETCH FIRST {}{} ROWS {}", quantity, percent, extension)
} else {
write!(f, "FETCH FIRST ROWS {}", extension)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Values(pub Vec<Vec<Expr>>);
impl fmt::Display for Values {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "VALUES ")?;
let mut delim = "";
for row in &self.0 {
write!(f, "{}", delim)?;
delim = ", ";
write!(f, "({})", display_comma_separated(row))?;
}
Ok(())
}
}