Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,10 +474,23 @@ pub struct Array {

/// `true` for `ARRAY[..]`, `false` for `[..]`
pub named: bool,

/// The declared element type of a typed array literal, e.g. `INT64` in
/// `ARRAY<INT64>[1, 2, 3]` (BigQuery). `None` for an untyped `[..]` /
/// `ARRAY[..]`.
pub element_type: Option<DataType>,
}

impl fmt::Display for Array {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(element_type) = &self.element_type {
return write!(
f,
"ARRAY<{}>[{}]",
element_type,
display_comma_separated(&self.elem)
);
}
write!(
f,
"{}[{}]",
Expand Down
3 changes: 2 additions & 1 deletion src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1727,7 +1727,8 @@ impl Spanned for Array {
fn span(&self) -> Span {
let Array {
elem,
named: _, // bool
named: _, // bool
element_type: _, // DataType, not spanned
} = self;

union_spans(elem.iter().map(|i| i.span()))
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/bigquery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ impl Dialect for BigQueryDialect {
true
}

// See https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#array_type
fn supports_array_typed_literal(&self) -> bool {
true
}

/// See <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_expression_star>
fn supports_select_expr_star(&self) -> bool {
true
Expand Down
7 changes: 7 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,13 @@ pub trait Dialect: Debug + Any {
false
}

/// Return true if the dialect supports a typed array literal, where the
/// element type is given in angle brackets before the elements, e.g.
/// `ARRAY<INT64>[1, 2, 3]` (BigQuery).
fn supports_array_typed_literal(&self) -> bool {
false
}

/// Return true if the dialect supports empty projections in SELECT statements
///
/// Example
Expand Down
23 changes: 22 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1616,6 +1616,23 @@ impl<'a> Parser<'a> {
self.expect_token(&Token::LBracket)?;
Ok(Some(self.parse_array_expr(true)?))
}
// Typed array literal, e.g. `ARRAY<INT64>[1, 2, 3]` (BigQuery).
Keyword::ARRAY
if self.dialect.supports_array_typed_literal()
&& self.peek_token_ref().token == Token::Lt =>
{
self.expect_token(&Token::Lt)?;
let (element_type, trailing_bracket) = self.parse_data_type_helper()?;
self.expect_closing_angle_bracket(trailing_bracket)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unmatched angle bracket is swallowed

Low Severity

The typed array path calls expect_closing_angle_bracket and drops its return value. When that helper consumes >>, the leftover > is never reported, so an extra closing bracket is accepted and the literal still parses. Typed STRUCT literals check this leftover flag and error instead.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b346f24. Configure here.

self.expect_token(&Token::LBracket)?;
let elem = self.parse_comma_separated0(Parser::parse_expr, Token::RBracket)?;
self.expect_token(&Token::RBracket)?;
Ok(Some(Expr::Array(Array {
elem,
named: true,
element_type: Some(element_type),
})))
}
Keyword::ARRAY
if self.peek_token_ref().token == Token::LParen
&& !dialect_of!(self is ClickHouseDialect | DatabricksDialect) =>
Expand Down Expand Up @@ -3132,7 +3149,11 @@ impl<'a> Parser<'a> {
pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError> {
let exprs = self.parse_comma_separated0(Parser::parse_expr, Token::RBracket)?;
self.expect_token(&Token::RBracket)?;
Ok(Expr::Array(Array { elem: exprs, named }))
Ok(Expr::Array(Array {
elem: exprs,
named,
element_type: None,
}))
}

/// Parse the `ON OVERFLOW` clause for `LISTAGG`.
Expand Down
39 changes: 39 additions & 0 deletions tests/sqlparser_bigquery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3127,3 +3127,42 @@ fn parse_bigquery_create_vector_index() {
}
bigquery().verified_stmt("CREATE VECTOR INDEX emb ON t(embedding)");
}

#[test]
fn parse_typed_array_literal() {
// Typed array literal `ARRAY<T>[...]`: the element type is carried on the
// `Array` node and round-trips. Scalar, empty, nested struct and nested
// array element types are all supported.
for sql in [
"SELECT ARRAY<INT64>[1, 2, 3]",
"SELECT ARRAY<STRING>['a', 'b']",
"SELECT ARRAY<INT64>[]",
"SELECT ARRAY<STRUCT<a INT64, b STRING>>[(1, 'x'), (2, 'y')]",
"SELECT ARRAY<ARRAY<INT64>>[ARRAY<INT64>[1], ARRAY<INT64>[2]]",
] {
bigquery().verified_stmt(sql);
}

// The element type is recorded on the AST.
let Statement::Query(query) = bigquery().verified_stmt("SELECT ARRAY<INT64>[1, 2, 3]") else {
panic!("expected a query");
};
let SelectItem::UnnamedExpr(Expr::Array(array)) =
&query.body.as_select().unwrap().projection[0]
else {
panic!("expected an array expression");
};
assert!(array.named);
assert_eq!(array.element_type, Some(DataType::Int64));

// Untyped arrays keep `element_type` as `None`.
let Statement::Query(query) = bigquery().verified_stmt("SELECT [1, 2, 3]") else {
panic!("expected a query");
};
let SelectItem::UnnamedExpr(Expr::Array(array)) =
&query.body.as_select().unwrap().projection[0]
else {
panic!("expected an array expression");
};
assert_eq!(array.element_type, None);
}
1 change: 1 addition & 0 deletions tests/sqlparser_clickhouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ fn parse_array_expr() {
Expr::value(Value::SingleQuotedString("2".to_string())),
],
named: false,
element_type: None,
}),
expr_from_projection(only(&select.projection))
)
Expand Down
5 changes: 5 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13777,13 +13777,15 @@ fn test_map_syntax() {
key: Box::new(Expr::Array(Array {
elem: vec![number_expr("1"), number_expr("2"), number_expr("3")],
named: false,
element_type: None,
})),
value: Box::new(Expr::value(number("10.0"))),
},
MapEntry {
key: Box::new(Expr::Array(Array {
elem: vec![number_expr("4"), number_expr("5"), number_expr("6")],
named: false,
element_type: None,
})),
value: Box::new(Expr::value(number("20.0"))),
},
Expand Down Expand Up @@ -13847,20 +13849,23 @@ fn test_map_syntax() {
value: Box::new(Expr::Array(Array {
elem: vec![number_expr("1"), null_expr(), number_expr("3")],
named: false,
element_type: None,
})),
},
MapEntry {
key: Box::new(number_expr("2")),
value: Box::new(Expr::Array(Array {
elem: vec![number_expr("4"), null_expr(), number_expr("6")],
named: false,
element_type: None,
})),
},
MapEntry {
key: Box::new(number_expr("3")),
value: Box::new(Expr::Array(Array {
elem: vec![number_expr("7"), number_expr("8"), number_expr("9")],
named: false,
element_type: None,
})),
},
],
Expand Down
9 changes: 6 additions & 3 deletions tests/sqlparser_duckdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,8 @@ fn test_duckdb_struct_literal() {
(Value::SingleQuotedString("abc".to_string())).with_empty_span()
)),
},],)],
named: false
named: false,
element_type: None,
}),
expr_from_projection(&select.projection[1])
);
Expand All @@ -452,7 +453,8 @@ fn test_duckdb_struct_literal() {
Ident::from("t"),
Ident::from("str_col")
])],
named: false
named: false,
element_type: None,
})),
},
],),
Expand Down Expand Up @@ -691,7 +693,8 @@ fn test_array_index() {
Expr::Value((Value::SingleQuotedString("b".to_owned())).with_empty_span()),
Expr::Value((Value::SingleQuotedString("c".to_owned())).with_empty_span())
],
named: false
named: false,
element_type: None,
})),
access_chain: vec![AccessExpr::Subscript(Subscript::Index {
index: Expr::value(number("3"))
Expand Down
17 changes: 13 additions & 4 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2524,6 +2524,7 @@ fn parse_pg_regex_match_ops() {
Expr::Value(single_quoted_string("x").with_empty_span()),
],
named: true,
element_type: None,
})),
is_some: false,
}),
Expand Down Expand Up @@ -2565,6 +2566,7 @@ fn parse_pg_like_match_ops() {
right: Box::new(Expr::Array(Array {
elem: vec![Expr::Value(single_quoted_string("a_c%").with_empty_span())],
named: true,
element_type: None,
})),
}),
select.projection[0]
Expand Down Expand Up @@ -2645,8 +2647,10 @@ fn parse_array_index_expr() {
elem: vec![Expr::Array(Array {
elem: vec![num[2].clone(), num[3].clone(),],
named: true,
element_type: None,
})],
named: true,
element_type: None,
})),
data_type: DataType::Array(ArrayElemTypeDef::SquareBracket(
Box::new(DataType::Array(ArrayElemTypeDef::SquareBracket(
Expand Down Expand Up @@ -2675,7 +2679,8 @@ fn parse_array_index_expr() {
assert_eq!(
&Expr::Array(sqlparser::ast::Array {
elem: vec![],
named: true
named: true,
element_type: None,
}),
expr_from_projection(only(&select.projection)),
);
Expand Down Expand Up @@ -3657,6 +3662,7 @@ fn test_json() {
Expr::Value((Value::SingleQuotedString("b".to_string())).with_empty_span()),
],
named: true,
element_type: None,
})),
}),
select.projection[0],
Expand Down Expand Up @@ -3712,7 +3718,8 @@ fn test_json() {
Expr::Value((Value::SingleQuotedString("b".to_string())).with_empty_span()),
Expr::Value((Value::SingleQuotedString("c".to_string())).with_empty_span())
],
named: true
named: true,
element_type: None,
}))
},
select.selection.unwrap(),
Expand All @@ -3729,7 +3736,8 @@ fn test_json() {
Expr::Value((Value::SingleQuotedString("b".to_string())).with_empty_span()),
Expr::Value((Value::SingleQuotedString("c".to_string())).with_empty_span())
],
named: true
named: true,
element_type: None,
}))
},
select.selection.unwrap(),
Expand Down Expand Up @@ -3909,7 +3917,8 @@ fn test_composite_value() {
(Value::SingleQuotedString("i".to_string())).with_empty_span()
),
],
named: true
named: true,
element_type: None,
}
)))],
clauses: vec![],
Expand Down
Loading