diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index 854c30d078..1c0af58a0d 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -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 @@ -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: diff --git a/tests/test_expressions.py b/tests/test_expressions.py index e7a37f31c0..f83addbb80 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -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))