Skip to content

Commit 8bee742

Browse files
committed
Handle derived tables with set operations
This commit adds support for derived tables (i.e., subqueries) that incorporate set operations, like: SELECT * FROM (((SELECT 1) UNION (SELECT 2)) t1 AS NATURAL JOIN t2) This introduces a bit of complexity around determining whether a left paren starts a subquery, starts a nested join, or belongs to an already-started subquery. The details are explained in a comment within the patch.
1 parent 1998910 commit 8bee742

File tree

2 files changed

+99
-23
lines changed

2 files changed

+99
-23
lines changed

src/sqlparser.rs

Lines changed: 70 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ pub enum IsOptional {
4040
}
4141
use IsOptional::*;
4242

43+
pub enum IsLateral {
44+
Lateral,
45+
NotLateral,
46+
}
47+
use IsLateral::*;
48+
4349
impl From<TokenizerError> for ParserError {
4450
fn from(e: TokenizerError) -> Self {
4551
ParserError::TokenizerError(format!("{:?}", e))
@@ -1668,30 +1674,55 @@ impl Parser {
16681674

16691675
/// A table name or a parenthesized subquery, followed by optional `[AS] alias`
16701676
pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError> {
1671-
let lateral = self.parse_keyword("LATERAL");
1677+
if self.parse_keyword("LATERAL") {
1678+
// LATERAL must always be followed by a subquery.
1679+
if !self.consume_token(&Token::LParen) {
1680+
self.expected("subquery after LATERAL", self.peek_token())?;
1681+
}
1682+
return self.parse_derived_table_factor(Lateral);
1683+
}
1684+
16721685
if self.consume_token(&Token::LParen) {
1673-
if self.parse_keyword("SELECT")
1674-
|| self.parse_keyword("WITH")
1675-
|| self.parse_keyword("VALUES")
1676-
{
1677-
self.prev_token();
1678-
let subquery = Box::new(self.parse_query()?);
1679-
self.expect_token(&Token::RParen)?;
1680-
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
1681-
Ok(TableFactor::Derived {
1682-
lateral,
1683-
subquery,
1684-
alias,
1685-
})
1686-
} else if lateral {
1687-
parser_err!("Expected subquery after LATERAL, found nested join".to_string())
1688-
} else {
1689-
let table_reference = self.parse_table_and_joins()?;
1690-
self.expect_token(&Token::RParen)?;
1691-
Ok(TableFactor::NestedJoin(Box::new(table_reference)))
1686+
let index = self.index;
1687+
// A left paren introduces either a derived table (i.e., a subquery)
1688+
// or a nested join. It's nearly impossible to determine ahead of
1689+
// time which it is... so we just try to parse both.
1690+
//
1691+
// Here's an example that demonstrates the complexity:
1692+
// /-------------------------------------------------------\
1693+
// | /-----------------------------------\ |
1694+
// SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
1695+
// ^ ^ ^ ^
1696+
// | | | |
1697+
// | | | |
1698+
// | | | (4) belongs to a SQLSetExpr::Query inside the subquery
1699+
// | | (3) starts a derived table (subquery)
1700+
// | (2) starts a nested join
1701+
// (1) an additional set of parens around a nested join
1702+
//
1703+
match self.parse_derived_table_factor(NotLateral) {
1704+
// The recently consumed '(' started a derived table, and we've
1705+
// parsed the subquery, followed by the closing ')', and the
1706+
// alias of the derived table. In the example above this is
1707+
// case (3), and the next token would be `NATURAL`.
1708+
Ok(table_factor) => Ok(table_factor),
1709+
Err(_) => {
1710+
// The '(' we've recently consumed does not start a derived
1711+
// table. For valid input this can happen either when the
1712+
// token following the paren can't start a query (e.g. `foo`
1713+
// in `FROM (foo NATURAL JOIN bar)`, or when the '(' we've
1714+
// consumed is followed by another '(' that starts a
1715+
// derived table, like (3), or another nested join (2).
1716+
//
1717+
// Ignore the error and back up to where we were before.
1718+
// Either we'll be able to parse a valid nested join, or
1719+
// we won't, and we'll return that error instead.
1720+
self.index = index;
1721+
let table_and_joins = self.parse_table_and_joins()?;
1722+
self.expect_token(&Token::RParen)?;
1723+
Ok(TableFactor::NestedJoin(Box::new(table_and_joins)))
1724+
}
16921725
}
1693-
} else if lateral {
1694-
self.expected("subquery after LATERAL", self.peek_token())
16951726
} else {
16961727
let name = self.parse_object_name()?;
16971728
// Postgres, MSSQL: table-valued functions:
@@ -1721,6 +1752,23 @@ impl Parser {
17211752
}
17221753
}
17231754

1755+
pub fn parse_derived_table_factor(
1756+
&mut self,
1757+
lateral: IsLateral,
1758+
) -> Result<TableFactor, ParserError> {
1759+
let subquery = Box::new(self.parse_query()?);
1760+
self.expect_token(&Token::RParen)?;
1761+
let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
1762+
Ok(TableFactor::Derived {
1763+
lateral: match lateral {
1764+
Lateral => true,
1765+
NotLateral => false,
1766+
},
1767+
subquery,
1768+
alias,
1769+
})
1770+
}
1771+
17241772
fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
17251773
if natural {
17261774
Ok(JoinConstraint::Natural)

tests/sqlparser_common.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1848,6 +1848,32 @@ fn parse_derived_tables() {
18481848
let sql = "SELECT * FROM t NATURAL JOIN (((SELECT 1)))";
18491849
let _ = verified_only_select(sql);
18501850
// TODO: add assertions
1851+
1852+
let sql = "SELECT * FROM (((SELECT 1) UNION (SELECT 2)) AS t1 NATURAL JOIN t2)";
1853+
let select = verified_only_select(sql);
1854+
let from = only(select.from);
1855+
assert_eq!(
1856+
from.relation,
1857+
TableFactor::NestedJoin(Box::new(TableWithJoins {
1858+
relation: TableFactor::Derived {
1859+
lateral: false,
1860+
subquery: Box::new(verified_query("(SELECT 1) UNION (SELECT 2)")),
1861+
alias: Some(TableAlias {
1862+
name: "t1".into(),
1863+
columns: vec![],
1864+
})
1865+
},
1866+
joins: vec![Join {
1867+
relation: TableFactor::Table {
1868+
name: SQLObjectName(vec!["t2".into()]),
1869+
alias: None,
1870+
args: vec![],
1871+
with_hints: vec![],
1872+
},
1873+
join_operator: JoinOperator::Inner(JoinConstraint::Natural),
1874+
}],
1875+
}))
1876+
)
18511877
}
18521878

18531879
#[test]
@@ -2360,7 +2386,9 @@ fn lateral_derived() {
23602386
let sql = "SELECT * FROM a LEFT JOIN LATERAL (b CROSS JOIN c)";
23612387
let res = parse_sql_statements(sql);
23622388
assert_eq!(
2363-
ParserError::ParserError("Expected subquery after LATERAL, found nested join".to_string()),
2389+
ParserError::ParserError(
2390+
"Expected SELECT or a subquery in the query body, found: b".to_string()
2391+
),
23642392
res.unwrap_err()
23652393
);
23662394
}

0 commit comments

Comments
 (0)