Skip to content

Commit 0fcafd9

Browse files
support PIVOT table syntax
Signed-off-by: Pawel Leszczynski <[email protected]>
1 parent 4ff3aeb commit 0fcafd9

File tree

4 files changed

+146
-0
lines changed

4 files changed

+146
-0
lines changed

src/ast/query.rs

+41
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,17 @@ pub enum TableFactor {
670670
table_with_joins: Box<TableWithJoins>,
671671
alias: Option<TableAlias>,
672672
},
673+
/// Represents PIVOT operation on a table.
674+
/// For example `FROM monthly_sales PIVOT(sum(amount) FOR MONTH IN ('JAN', 'FEB'))`
675+
Pivot {
676+
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
677+
name: ObjectName,
678+
table_alias: Option<TableAlias>,
679+
aggregate_function: Expr, // Function expression
680+
value_column: Vec<Ident>,
681+
pivot_values: Vec<Value>,
682+
pivot_alias: Option<TableAlias>,
683+
},
673684
}
674685

675686
impl fmt::Display for TableFactor {
@@ -742,6 +753,36 @@ impl fmt::Display for TableFactor {
742753
}
743754
Ok(())
744755
}
756+
TableFactor::Pivot {
757+
name,
758+
table_alias,
759+
aggregate_function,
760+
value_column,
761+
pivot_values,
762+
pivot_alias,
763+
} => {
764+
write!(f, "{}", name)?;
765+
if table_alias.is_some() {
766+
write!(f, " AS {}", table_alias.as_ref().unwrap())?;
767+
}
768+
write!(
769+
f,
770+
" PIVOT({} FOR {} IN (",
771+
aggregate_function,
772+
Expr::CompoundIdentifier(value_column.to_vec())
773+
)?;
774+
for value in pivot_values {
775+
write!(f, "{}", value)?;
776+
if !value.eq(pivot_values.last().unwrap()) {
777+
write!(f, ", ")?;
778+
}
779+
}
780+
write!(f, "))")?;
781+
if pivot_alias.is_some() {
782+
write!(f, " AS {}", pivot_alias.as_ref().unwrap())?;
783+
}
784+
Ok(())
785+
}
745786
}
746787
}
747788
}

src/keywords.rs

+2
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ define_keywords!(
431431
PERCENTILE_DISC,
432432
PERCENT_RANK,
433433
PERIOD,
434+
PIVOT,
434435
PLACING,
435436
PLANS,
436437
PORTION,
@@ -647,6 +648,7 @@ pub const RESERVED_FOR_TABLE_ALIAS: &[Keyword] = &[
647648
Keyword::SORT,
648649
Keyword::HAVING,
649650
Keyword::ORDER,
651+
Keyword::PIVOT,
650652
Keyword::TOP,
651653
Keyword::LATERAL,
652654
Keyword::VIEW,

src/parser.rs

+46
Original file line numberDiff line numberDiff line change
@@ -5672,6 +5672,9 @@ impl<'a> Parser<'a> {
56725672
| TableFactor::Table { alias, .. }
56735673
| TableFactor::UNNEST { alias, .. }
56745674
| TableFactor::TableFunction { alias, .. }
5675+
| TableFactor::Pivot {
5676+
pivot_alias: alias, ..
5677+
}
56755678
| TableFactor::NestedJoin { alias, .. } => {
56765679
// but not `FROM (mytable AS alias1) AS alias2`.
56775680
if let Some(inner_alias) = alias {
@@ -5729,13 +5732,21 @@ impl<'a> Parser<'a> {
57295732
})
57305733
} else {
57315734
let name = self.parse_object_name()?;
5735+
57325736
// Postgres, MSSQL: table-valued functions:
57335737
let args = if self.consume_token(&Token::LParen) {
57345738
Some(self.parse_optional_args()?)
57355739
} else {
57365740
None
57375741
};
5742+
57385743
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5744+
5745+
// Pivot
5746+
if self.parse_keyword(Keyword::PIVOT) {
5747+
return self.parse_pivot_table_factor(name, alias);
5748+
}
5749+
57395750
// MSSQL-specific table hints:
57405751
let mut with_hints = vec![];
57415752
if self.parse_keyword(Keyword::WITH) {
@@ -5773,6 +5784,41 @@ impl<'a> Parser<'a> {
57735784
})
57745785
}
57755786

5787+
pub fn parse_pivot_table_factor(
5788+
&mut self,
5789+
name: ObjectName,
5790+
table_alias: Option<TableAlias>,
5791+
) -> Result<TableFactor, ParserError> {
5792+
self.expect_token(&Token::LParen)?;
5793+
let function_name = match self.next_token().token {
5794+
Token::Word(w) => Ok(w.value),
5795+
_ => self.expected("a function name", self.peek_token()),
5796+
}?;
5797+
let function = self
5798+
.parse_function(ObjectName(vec![Ident::new(function_name)]))
5799+
.unwrap();
5800+
self.expect_keyword(Keyword::FOR)?;
5801+
let mut value_column = vec![self.parse_identifier()?];
5802+
while self.next_token().token.eq(&Token::Period) {
5803+
value_column.push(self.parse_identifier()?);
5804+
}
5805+
self.prev_token(); // not a period
5806+
self.expect_keyword(Keyword::IN)?;
5807+
self.expect_token(&Token::LParen)?;
5808+
let pivot_values = self.parse_comma_separated(Parser::parse_value)?;
5809+
self.expect_token(&Token::RParen)?;
5810+
self.expect_token(&Token::RParen)?;
5811+
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5812+
Ok(TableFactor::Pivot {
5813+
name,
5814+
table_alias,
5815+
aggregate_function: function,
5816+
value_column,
5817+
pivot_values,
5818+
pivot_alias: alias,
5819+
})
5820+
}
5821+
57765822
pub fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
57775823
if natural {
57785824
Ok(JoinConstraint::Natural)

tests/sqlparser_common.rs

+57
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use matches::assert_matches;
2222

2323
use sqlparser::ast::SelectItem::UnnamedExpr;
24+
use sqlparser::ast::TableFactor::Pivot;
2425
use sqlparser::ast::*;
2526
use sqlparser::dialect::{
2627
AnsiDialect, BigQueryDialect, ClickHouseDialect, GenericDialect, HiveDialect, MsSqlDialect,
@@ -6718,6 +6719,62 @@ fn parse_with_recursion_limit() {
67186719
assert!(matches!(res, Ok(_)), "{res:?}");
67196720
}
67206721

6722+
#[test]
6723+
fn parse_pivot_table() {
6724+
let sql = concat!(
6725+
"SELECT * FROM monthly_sales AS a ",
6726+
"PIVOT(SUM(a.amount) FOR a.MONTH IN ('JAN', 'FEB', 'MAR', 'APR')) AS p (c, d) ",
6727+
"ORDER BY EMPID"
6728+
);
6729+
6730+
assert_eq!(
6731+
verified_only_select(sql).from[0].relation,
6732+
Pivot {
6733+
name: ObjectName(vec![Ident::new("monthly_sales")]),
6734+
table_alias: Some(TableAlias {
6735+
name: Ident::new("a"),
6736+
columns: vec![]
6737+
}),
6738+
aggregate_function: Expr::Function(Function {
6739+
name: ObjectName(vec![Ident::new("SUM")]),
6740+
args: (vec![FunctionArg::Unnamed(FunctionArgExpr::Expr(
6741+
Expr::CompoundIdentifier(vec![Ident::new("a"), Ident::new("amount"),])
6742+
))]),
6743+
over: None,
6744+
distinct: false,
6745+
special: false,
6746+
}),
6747+
value_column: vec![Ident::new("a"), Ident::new("MONTH")],
6748+
pivot_values: vec![
6749+
Value::SingleQuotedString("JAN".to_string()),
6750+
Value::SingleQuotedString("FEB".to_string()),
6751+
Value::SingleQuotedString("MAR".to_string()),
6752+
Value::SingleQuotedString("APR".to_string()),
6753+
],
6754+
pivot_alias: Some(TableAlias {
6755+
name: Ident {
6756+
value: "p".to_string(),
6757+
quote_style: None
6758+
},
6759+
columns: vec![Ident::new("c"), Ident::new("d")],
6760+
}),
6761+
}
6762+
);
6763+
6764+
let sql_without_table_alias = concat!(
6765+
"SELECT * FROM monthly_sales ",
6766+
"PIVOT(SUM(a.amount) FOR a.MONTH IN ('JAN', 'FEB', 'MAR', 'APR')) AS p (c, d) ",
6767+
"ORDER BY EMPID"
6768+
);
6769+
assert_matches!(
6770+
verified_only_select(sql_without_table_alias).from[0].relation,
6771+
Pivot {
6772+
table_alias: None, // parsing should succeed with empty alias
6773+
..
6774+
}
6775+
);
6776+
}
6777+
67216778
/// Makes a predicate that looks like ((user_id = $id) OR user_id = $2...)
67226779
fn make_where_clause(num: usize) -> String {
67236780
use std::fmt::Write;

0 commit comments

Comments
 (0)