Skip to content

Commit

Permalink
Feat: make table_name more robust by quoting unsafe parts (#1820)
Browse files Browse the repository at this point in the history
* Feat: make table_name more robust by quoting unsafe parts

* Docstring fixup
  • Loading branch information
georgesittas authored Jun 23, 2023
1 parent 91ebaf5 commit 2367bfc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 7 additions & 3 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5705,11 +5705,12 @@ def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
}


def table_name(table: Table | str) -> str:
def table_name(table: Table | str, dialect: DialectType = None) -> str:
"""Get the full name of a table as a string.
Args:
table: table expression node or string.
table: Table expression node or string.
dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
Expand All @@ -5725,7 +5726,10 @@ def table_name(table: Table | str) -> str:
if not table:
raise ValueError(f"Cannot parse {table}")

return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)
return ".".join(
part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
for part in table.parts
)


def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
Expand Down
4 changes: 4 additions & 0 deletions tests/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@ def test_table_name(self):
self.assertEqual(exp.table_name(parse_one("a.b", into=exp.Table)), "a.b")
self.assertEqual(exp.table_name(parse_one("a.b.c", into=exp.Table)), "a.b.c")
self.assertEqual(exp.table_name("a.b.c"), "a.b.c")
self.assertEqual(
exp.table_name(parse_one("foo.`{bar,er}`", read="databricks"), dialect="databricks"),
"foo.`{bar,er}`",
)

def test_table(self):
self.assertEqual(exp.table_("a", alias="b"), parse_one("select * from a b").find(exp.Table))
Expand Down

0 comments on commit 2367bfc

Please sign in to comment.