Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support trailing commas in BigQuery dialect #557

Merged
merged 1 commit into from Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/parser.rs
Expand Up @@ -1621,6 +1621,33 @@ impl<'a> Parser<'a> {
}
}

/// Parse a comma-separated list of 1+ SelectItem
pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError> {
let mut values = vec![];
loop {
values.push(self.parse_select_item()?);
if !self.consume_token(&Token::Comma) {
break;
} else if dialect_of!(self is BigQueryDialect) {
// BigQuery allows trailing commas.
// e.g. `SELECT 1, 2, FROM t`
// https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#trailing_commas
match self.peek_token() {
Token::Word(kw)
if keywords::RESERVED_FOR_COLUMN_ALIAS
.iter()
.any(|d| kw.keyword == *d) =>
{
break
}
Token::RParen | Token::EOF => break,
_ => continue,
}
}
}
Ok(values)
}

/// Parse a comma-separated list of 1+ items accepted by `F`
pub fn parse_comma_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError>
where
Expand Down Expand Up @@ -3468,7 +3495,7 @@ impl<'a> Parser<'a> {
None
};

let projection = self.parse_comma_separated(Parser::parse_select_item)?;
let projection = self.parse_projection()?;

let into = if self.parse_keyword(Keyword::INTO) {
let temporary = self
Expand Down
15 changes: 15 additions & 0 deletions tests/sqlparser_bigquery.rs
Expand Up @@ -94,6 +94,21 @@ fn parse_table_identifiers() {
test_table_ident("abc5.GROUP", vec![Ident::new("abc5"), Ident::new("GROUP")]);
}

#[test]
fn parse_trailing_comma() {
for (sql, canonical) in [
("SELECT a,", "SELECT a"),
("SELECT a, b,", "SELECT a, b"),
("SELECT a, b AS c,", "SELECT a, b AS c"),
("SELECT a, b AS c, FROM t", "SELECT a, b AS c FROM t"),
("SELECT a, b, FROM t", "SELECT a, b FROM t"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests look good to me.

("SELECT a, b, LIMIT 1", "SELECT a, b LIMIT 1"),
("SELECT a, (SELECT 1, )", "SELECT a, (SELECT 1)"),
] {
bigquery().one_statement_parses_to(sql, canonical);
}
}

#[test]
fn parse_cast_type() {
let sql = r#"SELECT SAFE_CAST(1 AS INT64)"#;
Expand Down