summaryrefslogtreecommitdiffstats
path: root/sqlglot/optimizer/qualify_columns.py
diff options
context:
space:
mode:
Diffstat (limited to 'sqlglot/optimizer/qualify_columns.py')
-rw-r--r--sqlglot/optimizer/qualify_columns.py22
1 files changed, 21 insertions, 1 deletions
diff --git a/sqlglot/optimizer/qualify_columns.py b/sqlglot/optimizer/qualify_columns.py
index e793e31..66b3170 100644
--- a/sqlglot/optimizer/qualify_columns.py
+++ b/sqlglot/optimizer/qualify_columns.py
@@ -37,6 +37,7 @@ def qualify_columns(expression, schema):
_qualify_outputs(scope)
_expand_group_by(scope, resolver)
_expand_order_by(scope)
+
return expression
@@ -213,6 +214,21 @@ def _qualify_columns(scope, resolver):
# column_table can be a '' because bigquery unnest has no table alias
if column_table:
column.set("table", column_table)
+ elif column_table not in scope.sources:
+ # structs are used like tables (e.g. "struct"."field"), so they need to be qualified
+ # separately and represented as dot(dot(...(<table>.<column>, field1), field2, ...))
+
+ root, *parts = column.parts
+
+ if root.name in scope.sources:
+ # struct is already qualified, but we still need to change the AST representation
+ column_table = root
+ root, *parts = parts
+ else:
+ column_table = resolver.get_table(root.name)
+
+ if column_table:
+ column.replace(exp.Dot.build([exp.column(root, table=column_table), *parts]))
columns_missing_from_scope = []
# Determine whether each reference in the order by clause is to a column or an alias.
@@ -373,10 +389,14 @@ class Resolver:
if isinstance(node, exp.Subqueryable):
while node and node.alias != table_name:
node = node.parent
+
node_alias = node.args.get("alias")
if node_alias:
return node_alias.this
- return exp.to_identifier(table_name)
+
+ return exp.to_identifier(
+ table_name, quoted=node.this.quoted if isinstance(node, exp.Table) else None
+ )
@property
def all_columns(self):