Skip to content

Commit 77b71e9

Browse files
hdimerLucaCappelletti94
authored andcommitted
Escape closing brackets in bracket-quoted identifiers
A bracket-quoted identifier whose value contains ] (e.g. [a]]b], value a]b) serialized back to [a]b], which no longer re-parses. Double each ] on display, mirroring the tokenizer folding ]] into ]. Redshift nested quoted identifiers (["a]b"]) store the value as a complete double-quoted string whose inner ] is literal, so those are left unchanged. Fixes apache#2409 Signed-off-by: Haim Dimer <[email protected]>
1 parent 88ffee6 commit 77b71e9

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎src/ast/mod.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,18 @@ pub(crate) fn fmt_ident(
384384
quote_style: Option<char>,
385385
) -> fmt::Result {
386386
match quote_style {
387-
Some('[') => write!(f, "[{value}]"),
387+
Some('[') => {
388+
// Redshift nested quoted identifiers (e.g. `["a]b"]`) store the
389+
// value as a complete double-quoted string whose inner `]` is
390+
// literal, so leave those unchanged. Otherwise double each `]`,
391+
// mirroring the tokenizer folding `]]` into `]`, so the
392+
// identifier round-trips (#2409).
393+
if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
394+
write!(f, "[{value}]")
395+
} else {
396+
write!(f, "[{}]", value.replace(']', "]]"))
397+
}
398+
}
388399
Some(q) => {
389400
let escaped = value::escape_quoted_string(value, q);
390401
write!(f, "{q}{escaped}{q}")

‎tests/sqlparser_mssql.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,18 @@ fn parse_table_name_in_square_brackets() {
937937
);
938938
}
939939

940+
#[test]
941+
fn parse_bracket_identifier_with_escaped_closing_bracket() {
942+
// A bracket-quoted identifier whose value contains `]` must serialize
943+
// with the bracket doubled so it round-trips. See #2409.
944+
let select = ms().verified_only_select("SELECT [a]]b]");
945+
assert_eq!(
946+
&Expr::Identifier(Ident::with_quote('[', "a]b")),
947+
expr_from_projection(&select.projection[0]),
948+
);
949+
ms().verified_stmt("SELECT [a]]b] FROM [c]]d]");
950+
}
951+
940952
#[test]
941953
fn parse_for_clause() {
942954
ms_and_generic().verified_stmt("SELECT a FROM t FOR JSON PATH");

0 commit comments

Comments
 (0)