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

Fix: make exp.to_column more lenient #3292

Merged
merged 1 commit into from
Apr 9, 2024
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: 8 additions & 5 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6666,7 +6666,7 @@ def to_table(

def to_column(
sql_path: str | Column,
quoted: bool = False,
quoted: t.Optional[bool] = None,
dialect: DialectType = None,
copy: bool = True,
**kwargs,
Expand All @@ -6688,16 +6688,19 @@ def to_column(
if isinstance(sql_path, Column):
return maybe_copy(sql_path, copy=copy)

column = maybe_parse(sql_path, into=Column, dialect=dialect)
try:
col = maybe_parse(sql_path, into=Column, dialect=dialect)
except ParseError:
return column(*reversed(sql_path.split(".")), quoted=quoted, **kwargs)

for k, v in kwargs.items():
column.set(k, v)
col.set(k, v)

if quoted:
for i in column.find_all(Identifier):
for i in col.find_all(Identifier):
i.set("quoted", True)

return column
return col


def alias_(
Expand Down
1 change: 1 addition & 0 deletions tests/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,7 @@ def test_to_column(self):
self.assertEqual(table_and_column.name, "column_name")
self.assertEqual(table_and_column.args.get("table"), exp.to_identifier("table_name"))

self.assertEqual(exp.to_column("foo bar").sql(), '"foo bar"')
self.assertEqual(exp.to_column("`column_name`", dialect="spark").sql(), '"column_name"')
self.assertEqual(exp.to_column("column_name", quoted=True).sql(), '"column_name"')
self.assertEqual(
Expand Down
Loading