summaryrefslogtreecommitdiffstats
path: root/sqlglot/optimizer
diff options
context:
space:
mode:
Diffstat (limited to 'sqlglot/optimizer')
-rw-r--r--sqlglot/optimizer/qualify_columns.py21
-rw-r--r--sqlglot/optimizer/scope.py2
2 files changed, 14 insertions, 9 deletions
diff --git a/sqlglot/optimizer/qualify_columns.py b/sqlglot/optimizer/qualify_columns.py
index 36ba028..ebee92a 100644
--- a/sqlglot/optimizer/qualify_columns.py
+++ b/sqlglot/optimizer/qualify_columns.py
@@ -211,21 +211,26 @@ def _qualify_columns(scope, resolver):
if column_table:
column.set("table", exp.to_identifier(column_table))
+ columns_missing_from_scope = []
# Determine whether each reference in the order by clause is to a column or an alias.
for ordered in scope.find_all(exp.Ordered):
for column in ordered.find_all(exp.Column):
- column_table = column.table
- column_name = column.name
+ if not column.table and column.parent is not ordered and column.name in resolver.all_columns:
+ columns_missing_from_scope.append(column)
- if column_table or column.parent is ordered or column_name not in resolver.all_columns:
- continue
+ # Determine whether each reference in the having clause is to a column or an alias.
+ for having in scope.find_all(exp.Having):
+ for column in having.find_all(exp.Column):
+ if not column.table and column.find_ancestor(exp.AggFunc) and column.name in resolver.all_columns:
+ columns_missing_from_scope.append(column)
- column_table = resolver.get_table(column_name)
+ for column in columns_missing_from_scope:
+ column_table = resolver.get_table(column.name)
- if column_table is None:
- raise OptimizeError(f"Ambiguous column: {column_name}")
+ if column_table is None:
+ raise OptimizeError(f"Ambiguous column: {column.name}")
- column.set("table", exp.to_identifier(column_table))
+ column.set("table", exp.to_identifier(column_table))
def _expand_stars(scope, resolver):
diff --git a/sqlglot/optimizer/scope.py b/sqlglot/optimizer/scope.py
index b7eb6c2..5a75ee2 100644
--- a/sqlglot/optimizer/scope.py
+++ b/sqlglot/optimizer/scope.py
@@ -232,7 +232,7 @@ class Scope:
self._columns = []
for column in columns + external_columns:
- ancestor = column.find_ancestor(exp.Qualify, exp.Order, exp.Hint)
+ ancestor = column.find_ancestor(exp.Qualify, exp.Order, exp.Having, exp.Hint)
if (
not ancestor
or column.table