Skip to content

Commit 18231ca

Browse files
authored
fix(mysql): parse quoted constraint names. (#7519)
sqlglot's `_parse_unique_key` checks whether the current token matches a `CONSTRAINT_PARSERS` keyword to decide if it should stop parsing the index name. The check used `self._curr.text.upper()` without considering the token type, so backtick-quoted identifiers like `` `Unique` ``, `` `Index` ``, and `` `Key` `` were mistaken for constraint keywords and rejected. MySQL allows any identifier as an index name when it is quoted. The tokenizer already classifies these as `TokenType.IDENTIFIER`, so the fix adds a `token_type != TokenType.IDENTIFIER` guard to the existing check. Quoted names skip the keyword lookup entirely and fall through to `_parse_id_var` as intended.
1 parent 998b42b commit 18231ca

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

sqlglot/parser.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7262,7 +7262,11 @@ def _parse_unnamed_constraint(
72627262
return result
72637263

72647264
def _parse_unique_key(self) -> exp.Expr | None:
7265-
if self._curr and self._curr.text.upper() in self.CONSTRAINT_PARSERS:
7265+
if (
7266+
self._curr
7267+
and self._curr.token_type != TokenType.IDENTIFIER
7268+
and self._curr.text.upper() in self.CONSTRAINT_PARSERS
7269+
):
72667270
return None
72677271
return self._parse_id_var(any_token=False)
72687272

tests/dialects/test_mysql.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,18 @@ def test_ddl(self):
144144
"CREATE TABLE IF NOT EXISTS industry_info (a BIGINT(20) NOT NULL AUTO_INCREMENT, b BIGINT(20) NOT NULL, c VARCHAR(1000), PRIMARY KEY (a), UNIQUE KEY d (b), KEY e (b))",
145145
"CREATE TABLE IF NOT EXISTS industry_info (a BIGINT(20) NOT NULL AUTO_INCREMENT, b BIGINT(20) NOT NULL, c VARCHAR(1000), PRIMARY KEY (a), UNIQUE d (b), INDEX e (b))",
146146
)
147+
self.validate_identity(
148+
"CREATE TABLE t (a INT, b INT, UNIQUE KEY `Unique` (a, b))",
149+
"CREATE TABLE t (a INT, b INT, UNIQUE `Unique` (a, b))",
150+
)
151+
self.validate_identity(
152+
"CREATE TABLE t (a INT, UNIQUE KEY `Index` (a))",
153+
"CREATE TABLE t (a INT, UNIQUE `Index` (a))",
154+
)
155+
self.validate_identity(
156+
"CREATE TABLE t (a INT, UNIQUE KEY `Key` (a))",
157+
"CREATE TABLE t (a INT, UNIQUE `Key` (a))",
158+
)
147159
self.validate_identity(
148160
"CREATE TABLE test (ts TIMESTAMP, ts_tz TIMESTAMPTZ, ts_ltz TIMESTAMPLTZ)",
149161
"CREATE TABLE test (ts TIMESTAMP, ts_tz TIMESTAMP, ts_ltz TIMESTAMP)",

0 commit comments

Comments
 (0)