Skip to content

Commit

Permalink
fix: allow string aliases closes #2788
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed Jan 7, 2024
1 parent 963e2dc commit d31ae0d
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions sqlglot/dialects/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ class Parser(parser.Parser):
}

LOG_DEFAULTS_TO_LN = True
STRING_ALIASES = True

def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
this = self._parse_id_var()
Expand Down
1 change: 1 addition & 0 deletions sqlglot/dialects/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ class Parser(parser.Parser):
**parser.Parser.FUNCTIONS,
"EDITDIST3": exp.Levenshtein.from_arg_list,
}
STRING_ALIASES = True

class Generator(generator.Generator):
JOIN_HINTS = False
Expand Down
1 change: 1 addition & 0 deletions sqlglot/dialects/tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ class Parser(parser.Parser):
LOG_DEFAULTS_TO_LN = True

ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
STRING_ALIASES = True

def _parse_projections(self) -> t.List[exp.Expression]:
"""
Expand Down
7 changes: 6 additions & 1 deletion sqlglot/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,9 @@ class Parser(metaclass=_Parser):
# Whether the TRIM function expects the characters to trim as its first argument
TRIM_PATTERN_FIRST = False

# Whether or not string aliases are supported `SELECT COUNT(*) 'count'`
STRING_ALIASES = False

# Whether query modifiers such as LIMIT are attached to the UNION node (vs its right operand)
MODIFIERS_ATTACHED_TO_UNION = True
UNION_MODIFIERS = {"order", "limit", "offset"}
Expand Down Expand Up @@ -4905,7 +4908,9 @@ def _parse_alias(
self._match_r_paren(aliases)
return aliases

alias = self._parse_id_var(any_token)
alias = self._parse_id_var(any_token) or (
self.STRING_ALIASES and self._parse_string_as_identifier()
)

if alias:
return self.expression(exp.Alias, comments=comments, this=this, alias=alias)
Expand Down
22 changes: 22 additions & 0 deletions tests/dialects/test_dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1683,6 +1683,28 @@ def test_limit(self):
)

def test_alias(self):
self.validate_all(
'SELECT 1 AS "foo"',
read={
"mysql": "SELECT 1 'foo'",
"sqlite": "SELECT 1 'foo'",
"tsql": "SELECT 1 'foo'",
},
)

for dialect in (
"presto",
"hive",
"postgres",
"clickhouse",
"bigquery",
"snowflake",
"duckdb",
):
with self.subTest(f"string alias: {dialect}"):
with self.assertRaises(ParseError):
parse_one("SELECT 1 'foo'", dialect=dialect)

self.validate_all(
"SELECT a AS b FROM x GROUP BY b",
write={
Expand Down

0 comments on commit d31ae0d

Please sign in to comment.