Skip to content

Commit e6c54a2

Browse files
authored
Added Unpivot. Fixed some Pivot (#2)
-- Technically, unpivot has some stricter expr requirements (eg instead of expr for ident in col_list it should be <column> for ident in col_list). I haven't been able to navigate to find this stricter definition yet, but maybe we want this fix ASAP.
1 parent 7d0dc15 commit e6c54a2

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/ast/query.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,14 @@ pub enum TableFactor {
319319
/// https://docs.snowflake.com/en/sql-reference/constructs/pivot.html
320320
Pivot {
321321
expr: Expr,
322+
alias: Option<TableAlias>,
323+
val: Ident,
324+
pivot_vals: Vec<Expr>,
325+
},
326+
/// https://docs.snowflake.com/en/sql-reference/constructs/unpivot.html
327+
Unpivot {
328+
expr: Expr,
329+
alias: Option<TableAlias>,
322330
val: Ident,
323331
pivot_vals: Vec<Expr>,
324332
},
@@ -389,6 +397,25 @@ impl fmt::Display for TableFactor {
389397
}
390398
TableFactor::Pivot {
391399
expr,
400+
alias,
401+
val,
402+
pivot_vals,
403+
} => {
404+
write!(f, "({} FOR {} IN (", expr, val)?;
405+
let mut delim = "";
406+
for pivot_val in pivot_vals {
407+
write!(f, "{}{}", delim, pivot_val)?;
408+
delim = ", ";
409+
}
410+
write!(f, "))")?;
411+
if let Some(alias) = alias {
412+
write!(f, " AS {}", alias)?;
413+
}
414+
Ok(())
415+
}
416+
TableFactor::Unpivot {
417+
expr,
418+
alias,
392419
val,
393420
pivot_vals,
394421
} => {
@@ -398,7 +425,11 @@ impl fmt::Display for TableFactor {
398425
write!(f, "{}{}", delim, pivot_val)?;
399426
delim = ", ";
400427
}
401-
write!(f, "))")
428+
write!(f, "))")?;
429+
if let Some(alias) = alias {
430+
write!(f, " AS {}", alias)?;
431+
}
432+
Ok(())
402433
}
403434
TableFactor::NestedJoin(table_reference) => write!(f, "({})", table_reference),
404435
}

src/parser.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2631,6 +2631,7 @@ impl<'a> Parser<'a> {
26312631
alias.replace(outer_alias);
26322632
}
26332633
TableFactor::Pivot { .. } => unreachable!(),
2634+
TableFactor::Unpivot { .. } => unreachable!(),
26342635
TableFactor::NestedJoin(_) => unreachable!(),
26352636
};
26362637
}
@@ -2681,8 +2682,10 @@ impl<'a> Parser<'a> {
26812682
let pivot_vals = self.parse_comma_separated(Parser::parse_expr)?;
26822683
self.expect_token(&Token::RParen)?;
26832684
self.expect_token(&Token::RParen)?;
2685+
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
26842686
Ok(TableFactor::Pivot {
26852687
expr,
2688+
alias,
26862689
val,
26872690
pivot_vals,
26882691
})

0 commit comments

Comments
 (0)