Skip to content

Commit

Permalink
Fix: selecting from table with same name as cte
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed Jun 11, 2023
1 parent b3f9078 commit 55a14a3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlglot/optimizer/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ def _traverse_tables(scope):
table_name = expression.name
source_name = expression.alias_or_name

if table_name in scope.sources:
if table_name in scope.sources and not expression.db:
# This is a reference to a parent source (e.g. a CTE), not an actual table, unless
# it is pivoted, because then we get back a new table and hence a new source.
pivots = expression.args.get("pivots")
Expand Down
9 changes: 9 additions & 0 deletions tests/test_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ def test_normalize(self):
self.check_file("normalize", normalize)

def test_qualify_columns(self):
self.assertEqual(
optimizer.qualify_columns.qualify_columns(
parse_one("WITH x AS (SELECT a FROM db.y) SELECT z FROM db.x"),
schema={"db": {"x": {"z": "int"}, "y": {"a": "int"}}},
infer_schema=False,
).sql(),
"WITH x AS (SELECT y.a AS a FROM db.y) SELECT x.z AS z FROM db.x",
)

self.assertEqual(
optimizer.qualify_columns.qualify_columns(
parse_one("select y from x"),
Expand Down

0 comments on commit 55a14a3

Please sign in to comment.