Edit on GitHub

sqlglot.optimizer.qualify_columns

  1from __future__ import annotations
  2
  3import itertools
  4import typing as t
  5
  6from sqlglot import alias, exp
  7from sqlglot._typing import E
  8from sqlglot.dialects.dialect import Dialect, DialectType
  9from sqlglot.errors import OptimizeError
 10from sqlglot.helper import seq_get
 11from sqlglot.optimizer.scope import Scope, traverse_scope, walk_in_scope
 12from sqlglot.schema import Schema, ensure_schema
 13
 14
 15def qualify_columns(
 16    expression: exp.Expression,
 17    schema: t.Dict | Schema,
 18    expand_alias_refs: bool = True,
 19    infer_schema: t.Optional[bool] = None,
 20) -> exp.Expression:
 21    """
 22    Rewrite sqlglot AST to have fully qualified columns.
 23
 24    Example:
 25        >>> import sqlglot
 26        >>> schema = {"tbl": {"col": "INT"}}
 27        >>> expression = sqlglot.parse_one("SELECT col FROM tbl")
 28        >>> qualify_columns(expression, schema).sql()
 29        'SELECT tbl.col AS col FROM tbl'
 30
 31    Args:
 32        expression: expression to qualify
 33        schema: Database schema
 34        expand_alias_refs: whether or not to expand references to aliases
 35        infer_schema: whether or not to infer the schema if missing
 36    Returns:
 37        sqlglot.Expression: qualified expression
 38    """
 39    schema = ensure_schema(schema)
 40    infer_schema = schema.empty if infer_schema is None else infer_schema
 41
 42    for scope in traverse_scope(expression):
 43        resolver = Resolver(scope, schema, infer_schema=infer_schema)
 44        _pop_table_column_aliases(scope.ctes)
 45        _pop_table_column_aliases(scope.derived_tables)
 46        using_column_tables = _expand_using(scope, resolver)
 47
 48        if schema.empty and expand_alias_refs:
 49            _expand_alias_refs(scope, resolver)
 50
 51        _qualify_columns(scope, resolver)
 52
 53        if not schema.empty and expand_alias_refs:
 54            _expand_alias_refs(scope, resolver)
 55
 56        if not isinstance(scope.expression, exp.UDTF):
 57            _expand_stars(scope, resolver, using_column_tables)
 58            _qualify_outputs(scope)
 59        _expand_group_by(scope)
 60        _expand_order_by(scope, resolver)
 61
 62    return expression
 63
 64
 65def validate_qualify_columns(expression: E) -> E:
 66    """Raise an `OptimizeError` if any columns aren't qualified"""
 67    unqualified_columns = []
 68    for scope in traverse_scope(expression):
 69        if isinstance(scope.expression, exp.Select):
 70            unqualified_columns.extend(scope.unqualified_columns)
 71            if scope.external_columns and not scope.is_correlated_subquery and not scope.pivots:
 72                column = scope.external_columns[0]
 73                raise OptimizeError(
 74                    f"""Column '{column}' could not be resolved{f" for table: '{column.table}'" if column.table else ''}"""
 75                )
 76
 77    if unqualified_columns:
 78        raise OptimizeError(f"Ambiguous columns: {unqualified_columns}")
 79    return expression
 80
 81
 82def _pop_table_column_aliases(derived_tables: t.List[exp.CTE | exp.Subquery]) -> None:
 83    """
 84    Remove table column aliases.
 85
 86    (e.g. SELECT ... FROM (SELECT ...) AS foo(col1, col2)
 87    """
 88    for derived_table in derived_tables:
 89        table_alias = derived_table.args.get("alias")
 90        if table_alias:
 91            table_alias.args.pop("columns", None)
 92
 93
 94def _expand_using(scope: Scope, resolver: Resolver) -> t.Dict[str, t.Any]:
 95    joins = list(scope.find_all(exp.Join))
 96    names = {join.alias_or_name for join in joins}
 97    ordered = [key for key in scope.selected_sources if key not in names]
 98
 99    # Mapping of automatically joined column names to an ordered set of source names (dict).
100    column_tables: t.Dict[str, t.Dict[str, t.Any]] = {}
101
102    for join in joins:
103        using = join.args.get("using")
104
105        if not using:
106            continue
107
108        join_table = join.alias_or_name
109
110        columns = {}
111
112        for k in scope.selected_sources:
113            if k in ordered:
114                for column in resolver.get_source_columns(k):
115                    if column not in columns:
116                        columns[column] = k
117
118        source_table = ordered[-1]
119        ordered.append(join_table)
120        join_columns = resolver.get_source_columns(join_table)
121        conditions = []
122
123        for identifier in using:
124            identifier = identifier.name
125            table = columns.get(identifier)
126
127            if not table or identifier not in join_columns:
128                if columns and join_columns:
129                    raise OptimizeError(f"Cannot automatically join: {identifier}")
130
131            table = table or source_table
132            conditions.append(
133                exp.condition(
134                    exp.EQ(
135                        this=exp.column(identifier, table=table),
136                        expression=exp.column(identifier, table=join_table),
137                    )
138                )
139            )
140
141            # Set all values in the dict to None, because we only care about the key ordering
142            tables = column_tables.setdefault(identifier, {})
143            if table not in tables:
144                tables[table] = None
145            if join_table not in tables:
146                tables[join_table] = None
147
148        join.args.pop("using")
149        join.set("on", exp.and_(*conditions, copy=False))
150
151    if column_tables:
152        for column in scope.columns:
153            if not column.table and column.name in column_tables:
154                tables = column_tables[column.name]
155                coalesce = [exp.column(column.name, table=table) for table in tables]
156                replacement = exp.Coalesce(this=coalesce[0], expressions=coalesce[1:])
157
158                # Ensure selects keep their output name
159                if isinstance(column.parent, exp.Select):
160                    replacement = alias(replacement, alias=column.name, copy=False)
161
162                scope.replace(column, replacement)
163
164    return column_tables
165
166
167def _expand_alias_refs(scope: Scope, resolver: Resolver) -> None:
168    expression = scope.expression
169
170    if not isinstance(expression, exp.Select):
171        return
172
173    alias_to_expression: t.Dict[str, exp.Expression] = {}
174
175    def replace_columns(node: t.Optional[exp.Expression], resolve_table: bool = False) -> None:
176        if not node:
177            return
178
179        for column, *_ in walk_in_scope(node):
180            if not isinstance(column, exp.Column):
181                continue
182            table = resolver.get_table(column.name) if resolve_table and not column.table else None
183            alias_expr = alias_to_expression.get(column.name)
184            double_agg = (
185                (alias_expr.find(exp.AggFunc) and column.find_ancestor(exp.AggFunc))
186                if alias_expr
187                else False
188            )
189
190            if table and (not alias_expr or double_agg):
191                column.set("table", table)
192            elif not column.table and alias_expr and not double_agg:
193                column.replace(alias_expr.copy())
194
195    for projection in scope.selects:
196        replace_columns(projection)
197
198        if isinstance(projection, exp.Alias):
199            alias_to_expression[projection.alias] = projection.this
200
201    replace_columns(expression.args.get("where"))
202    replace_columns(expression.args.get("group"))
203    replace_columns(expression.args.get("having"), resolve_table=True)
204    replace_columns(expression.args.get("qualify"), resolve_table=True)
205    scope.clear_cache()
206
207
208def _expand_group_by(scope: Scope):
209    expression = scope.expression
210    group = expression.args.get("group")
211    if not group:
212        return
213
214    group.set("expressions", _expand_positional_references(scope, group.expressions))
215    expression.set("group", group)
216
217    # group by expressions cannot be simplified, for example
218    # select x + 1 + 1 FROM y GROUP BY x + 1 + 1
219    # the projection must exactly match the group by key
220    groups = set(group.expressions)
221    group.meta["final"] = True
222
223    for e in expression.selects:
224        for node, *_ in e.walk():
225            if node in groups:
226                e.meta["final"] = True
227                break
228
229    having = expression.args.get("having")
230    if having:
231        for node, *_ in having.walk():
232            if node in groups:
233                having.meta["final"] = True
234                break
235
236
237def _expand_order_by(scope: Scope, resolver: Resolver):
238    order = scope.expression.args.get("order")
239    if not order:
240        return
241
242    ordereds = order.expressions
243    for ordered, new_expression in zip(
244        ordereds,
245        _expand_positional_references(scope, (o.this for o in ordereds)),
246    ):
247        for agg in ordered.find_all(exp.AggFunc):
248            for col in agg.find_all(exp.Column):
249                if not col.table:
250                    col.set("table", resolver.get_table(col.name))
251
252        ordered.set("this", new_expression)
253
254    if scope.expression.args.get("group"):
255        selects = {s.this: exp.column(s.alias_or_name) for s in scope.selects}
256
257        for ordered in ordereds:
258            ordered.set("this", selects.get(ordered.this, ordered.this))
259
260
261def _expand_positional_references(scope: Scope, expressions: t.Iterable[E]) -> t.List[E]:
262    new_nodes = []
263    for node in expressions:
264        if node.is_int:
265            try:
266                select = scope.selects[int(node.name) - 1]
267            except IndexError:
268                raise OptimizeError(f"Unknown output column: {node.name}")
269            if isinstance(select, exp.Alias):
270                select = select.this
271            new_nodes.append(select.copy())
272            scope.clear_cache()
273        else:
274            new_nodes.append(node)
275
276    return new_nodes
277
278
279def _qualify_columns(scope: Scope, resolver: Resolver) -> None:
280    """Disambiguate columns, ensuring each column specifies a source"""
281    for column in scope.columns:
282        column_table = column.table
283        column_name = column.name
284
285        if column_table and column_table in scope.sources:
286            source_columns = resolver.get_source_columns(column_table)
287            if source_columns and column_name not in source_columns and "*" not in source_columns:
288                raise OptimizeError(f"Unknown column: {column_name}")
289
290        if not column_table:
291            if scope.pivots and not column.find_ancestor(exp.Pivot):
292                # If the column is under the Pivot expression, we need to qualify it
293                # using the name of the pivoted source instead of the pivot's alias
294                column.set("table", exp.to_identifier(scope.pivots[0].alias))
295                continue
296
297            column_table = resolver.get_table(column_name)
298
299            # column_table can be a '' because bigquery unnest has no table alias
300            if column_table:
301                column.set("table", column_table)
302        elif column_table not in scope.sources and (
303            not scope.parent or column_table not in scope.parent.sources
304        ):
305            # structs are used like tables (e.g. "struct"."field"), so they need to be qualified
306            # separately and represented as dot(dot(...(<table>.<column>, field1), field2, ...))
307
308            root, *parts = column.parts
309
310            if root.name in scope.sources:
311                # struct is already qualified, but we still need to change the AST representation
312                column_table = root
313                root, *parts = parts
314            else:
315                column_table = resolver.get_table(root.name)
316
317            if column_table:
318                column.replace(exp.Dot.build([exp.column(root, table=column_table), *parts]))
319
320    for pivot in scope.pivots:
321        for column in pivot.find_all(exp.Column):
322            if not column.table and column.name in resolver.all_columns:
323                column_table = resolver.get_table(column.name)
324                if column_table:
325                    column.set("table", column_table)
326
327
328def _expand_stars(
329    scope: Scope, resolver: Resolver, using_column_tables: t.Dict[str, t.Any]
330) -> None:
331    """Expand stars to lists of column selections"""
332
333    new_selections = []
334    except_columns: t.Dict[int, t.Set[str]] = {}
335    replace_columns: t.Dict[int, t.Dict[str, str]] = {}
336    coalesced_columns = set()
337
338    # TODO: handle optimization of multiple PIVOTs (and possibly UNPIVOTs) in the future
339    pivot_columns = None
340    pivot_output_columns = None
341    pivot = t.cast(t.Optional[exp.Pivot], seq_get(scope.pivots, 0))
342
343    has_pivoted_source = pivot and not pivot.args.get("unpivot")
344    if pivot and has_pivoted_source:
345        pivot_columns = set(col.output_name for col in pivot.find_all(exp.Column))
346
347        pivot_output_columns = [col.output_name for col in pivot.args.get("columns", [])]
348        if not pivot_output_columns:
349            pivot_output_columns = [col.alias_or_name for col in pivot.expressions]
350
351    for expression in scope.selects:
352        if isinstance(expression, exp.Star):
353            tables = list(scope.selected_sources)
354            _add_except_columns(expression, tables, except_columns)
355            _add_replace_columns(expression, tables, replace_columns)
356        elif expression.is_star:
357            tables = [expression.table]
358            _add_except_columns(expression.this, tables, except_columns)
359            _add_replace_columns(expression.this, tables, replace_columns)
360        else:
361            new_selections.append(expression)
362            continue
363
364        for table in tables:
365            if table not in scope.sources:
366                raise OptimizeError(f"Unknown table: {table}")
367
368            columns = resolver.get_source_columns(table, only_visible=True)
369
370            # The _PARTITIONTIME and _PARTITIONDATE pseudo-columns are not returned by a SELECT * statement
371            # https://cloud.google.com/bigquery/docs/querying-partitioned-tables#query_an_ingestion-time_partitioned_table
372            if resolver.schema.dialect == "bigquery":
373                columns = [
374                    name
375                    for name in columns
376                    if name.upper() not in ("_PARTITIONTIME", "_PARTITIONDATE")
377                ]
378
379            if columns and "*" not in columns:
380                if pivot and has_pivoted_source and pivot_columns and pivot_output_columns:
381                    implicit_columns = [col for col in columns if col not in pivot_columns]
382                    new_selections.extend(
383                        exp.alias_(exp.column(name, table=pivot.alias), name, copy=False)
384                        for name in implicit_columns + pivot_output_columns
385                    )
386                    continue
387
388                table_id = id(table)
389                for name in columns:
390                    if name in using_column_tables and table in using_column_tables[name]:
391                        if name in coalesced_columns:
392                            continue
393
394                        coalesced_columns.add(name)
395                        tables = using_column_tables[name]
396                        coalesce = [exp.column(name, table=table) for table in tables]
397
398                        new_selections.append(
399                            alias(
400                                exp.Coalesce(this=coalesce[0], expressions=coalesce[1:]),
401                                alias=name,
402                                copy=False,
403                            )
404                        )
405                    elif name not in except_columns.get(table_id, set()):
406                        alias_ = replace_columns.get(table_id, {}).get(name, name)
407                        column = exp.column(name, table=table)
408                        new_selections.append(
409                            alias(column, alias_, copy=False) if alias_ != name else column
410                        )
411            else:
412                return
413
414    scope.expression.set("expressions", new_selections)
415
416
417def _add_except_columns(
418    expression: exp.Expression, tables, except_columns: t.Dict[int, t.Set[str]]
419) -> None:
420    except_ = expression.args.get("except")
421
422    if not except_:
423        return
424
425    columns = {e.name for e in except_}
426
427    for table in tables:
428        except_columns[id(table)] = columns
429
430
431def _add_replace_columns(
432    expression: exp.Expression, tables, replace_columns: t.Dict[int, t.Dict[str, str]]
433) -> None:
434    replace = expression.args.get("replace")
435
436    if not replace:
437        return
438
439    columns = {e.this.name: e.alias for e in replace}
440
441    for table in tables:
442        replace_columns[id(table)] = columns
443
444
445def _qualify_outputs(scope: Scope):
446    """Ensure all output columns are aliased"""
447    new_selections = []
448
449    for i, (selection, aliased_column) in enumerate(
450        itertools.zip_longest(scope.selects, scope.outer_column_list)
451    ):
452        if isinstance(selection, exp.Subquery):
453            if not selection.output_name:
454                selection.set("alias", exp.TableAlias(this=exp.to_identifier(f"_col_{i}")))
455        elif not isinstance(selection, exp.Alias) and not selection.is_star:
456            selection = alias(
457                selection,
458                alias=selection.output_name or f"_col_{i}",
459            )
460        if aliased_column:
461            selection.set("alias", exp.to_identifier(aliased_column))
462
463        new_selections.append(selection)
464
465    scope.expression.set("expressions", new_selections)
466
467
468def quote_identifiers(expression: E, dialect: DialectType = None, identify: bool = True) -> E:
469    """Makes sure all identifiers that need to be quoted are quoted."""
470    return expression.transform(
471        Dialect.get_or_raise(dialect).quote_identifier, identify=identify, copy=False
472    )
473
474
475class Resolver:
476    """
477    Helper for resolving columns.
478
479    This is a class so we can lazily load some things and easily share them across functions.
480    """
481
482    def __init__(self, scope: Scope, schema: Schema, infer_schema: bool = True):
483        self.scope = scope
484        self.schema = schema
485        self._source_columns = None
486        self._unambiguous_columns: t.Optional[t.Dict[str, str]] = None
487        self._all_columns = None
488        self._infer_schema = infer_schema
489
490    def get_table(self, column_name: str) -> t.Optional[exp.Identifier]:
491        """
492        Get the table for a column name.
493
494        Args:
495            column_name: The column name to find the table for.
496        Returns:
497            The table name if it can be found/inferred.
498        """
499        if self._unambiguous_columns is None:
500            self._unambiguous_columns = self._get_unambiguous_columns(
501                self._get_all_source_columns()
502            )
503
504        table_name = self._unambiguous_columns.get(column_name)
505
506        if not table_name and self._infer_schema:
507            sources_without_schema = tuple(
508                source
509                for source, columns in self._get_all_source_columns().items()
510                if not columns or "*" in columns
511            )
512            if len(sources_without_schema) == 1:
513                table_name = sources_without_schema[0]
514
515        if table_name not in self.scope.selected_sources:
516            return exp.to_identifier(table_name)
517
518        node, _ = self.scope.selected_sources.get(table_name)
519
520        if isinstance(node, exp.Subqueryable):
521            while node and node.alias != table_name:
522                node = node.parent
523
524        node_alias = node.args.get("alias")
525        if node_alias:
526            return exp.to_identifier(node_alias.this)
527
528        return exp.to_identifier(table_name)
529
530    @property
531    def all_columns(self):
532        """All available columns of all sources in this scope"""
533        if self._all_columns is None:
534            self._all_columns = {
535                column for columns in self._get_all_source_columns().values() for column in columns
536            }
537        return self._all_columns
538
539    def get_source_columns(self, name, only_visible=False):
540        """Resolve the source columns for a given source `name`"""
541        if name not in self.scope.sources:
542            raise OptimizeError(f"Unknown table: {name}")
543
544        source = self.scope.sources[name]
545
546        # If referencing a table, return the columns from the schema
547        if isinstance(source, exp.Table):
548            return self.schema.column_names(source, only_visible)
549
550        if isinstance(source, Scope) and isinstance(source.expression, exp.Values):
551            return source.expression.alias_column_names
552
553        # Otherwise, if referencing another scope, return that scope's named selects
554        return source.expression.named_selects
555
556    def _get_all_source_columns(self):
557        if self._source_columns is None:
558            self._source_columns = {
559                k: self.get_source_columns(k)
560                for k in itertools.chain(self.scope.selected_sources, self.scope.lateral_sources)
561            }
562        return self._source_columns
563
564    def _get_unambiguous_columns(self, source_columns):
565        """
566        Find all the unambiguous columns in sources.
567
568        Args:
569            source_columns (dict): Mapping of names to source columns
570        Returns:
571            dict: Mapping of column name to source name
572        """
573        if not source_columns:
574            return {}
575
576        source_columns = list(source_columns.items())
577
578        first_table, first_columns = source_columns[0]
579        unambiguous_columns = {col: first_table for col in self._find_unique_columns(first_columns)}
580        all_columns = set(unambiguous_columns)
581
582        for table, columns in source_columns[1:]:
583            unique = self._find_unique_columns(columns)
584            ambiguous = set(all_columns).intersection(unique)
585            all_columns.update(columns)
586            for column in ambiguous:
587                unambiguous_columns.pop(column, None)
588            for column in unique.difference(ambiguous):
589                unambiguous_columns[column] = table
590
591        return unambiguous_columns
592
593    @staticmethod
594    def _find_unique_columns(columns):
595        """
596        Find the unique columns in a list of columns.
597
598        Example:
599            >>> sorted(Resolver._find_unique_columns(["a", "b", "b", "c"]))
600            ['a', 'c']
601
602        This is necessary because duplicate column names are ambiguous.
603        """
604        counts = {}
605        for column in columns:
606            counts[column] = counts.get(column, 0) + 1
607        return {column for column, count in counts.items() if count == 1}
def qualify_columns( expression: sqlglot.expressions.Expression, schema: Union[Dict, sqlglot.schema.Schema], expand_alias_refs: bool = True, infer_schema: Optional[bool] = None) -> sqlglot.expressions.Expression:
16def qualify_columns(
17    expression: exp.Expression,
18    schema: t.Dict | Schema,
19    expand_alias_refs: bool = True,
20    infer_schema: t.Optional[bool] = None,
21) -> exp.Expression:
22    """
23    Rewrite sqlglot AST to have fully qualified columns.
24
25    Example:
26        >>> import sqlglot
27        >>> schema = {"tbl": {"col": "INT"}}
28        >>> expression = sqlglot.parse_one("SELECT col FROM tbl")
29        >>> qualify_columns(expression, schema).sql()
30        'SELECT tbl.col AS col FROM tbl'
31
32    Args:
33        expression: expression to qualify
34        schema: Database schema
35        expand_alias_refs: whether or not to expand references to aliases
36        infer_schema: whether or not to infer the schema if missing
37    Returns:
38        sqlglot.Expression: qualified expression
39    """
40    schema = ensure_schema(schema)
41    infer_schema = schema.empty if infer_schema is None else infer_schema
42
43    for scope in traverse_scope(expression):
44        resolver = Resolver(scope, schema, infer_schema=infer_schema)
45        _pop_table_column_aliases(scope.ctes)
46        _pop_table_column_aliases(scope.derived_tables)
47        using_column_tables = _expand_using(scope, resolver)
48
49        if schema.empty and expand_alias_refs:
50            _expand_alias_refs(scope, resolver)
51
52        _qualify_columns(scope, resolver)
53
54        if not schema.empty and expand_alias_refs:
55            _expand_alias_refs(scope, resolver)
56
57        if not isinstance(scope.expression, exp.UDTF):
58            _expand_stars(scope, resolver, using_column_tables)
59            _qualify_outputs(scope)
60        _expand_group_by(scope)
61        _expand_order_by(scope, resolver)
62
63    return expression

Rewrite sqlglot AST to have fully qualified columns.

Example:
>>> import sqlglot
>>> schema = {"tbl": {"col": "INT"}}
>>> expression = sqlglot.parse_one("SELECT col FROM tbl")
>>> qualify_columns(expression, schema).sql()
'SELECT tbl.col AS col FROM tbl'
Arguments:
  • expression: expression to qualify
  • schema: Database schema
  • expand_alias_refs: whether or not to expand references to aliases
  • infer_schema: whether or not to infer the schema if missing
Returns:

sqlglot.Expression: qualified expression

def validate_qualify_columns(expression: ~E) -> ~E:
66def validate_qualify_columns(expression: E) -> E:
67    """Raise an `OptimizeError` if any columns aren't qualified"""
68    unqualified_columns = []
69    for scope in traverse_scope(expression):
70        if isinstance(scope.expression, exp.Select):
71            unqualified_columns.extend(scope.unqualified_columns)
72            if scope.external_columns and not scope.is_correlated_subquery and not scope.pivots:
73                column = scope.external_columns[0]
74                raise OptimizeError(
75                    f"""Column '{column}' could not be resolved{f" for table: '{column.table}'" if column.table else ''}"""
76                )
77
78    if unqualified_columns:
79        raise OptimizeError(f"Ambiguous columns: {unqualified_columns}")
80    return expression

Raise an OptimizeError if any columns aren't qualified

def quote_identifiers( expression: ~E, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, identify: bool = True) -> ~E:
469def quote_identifiers(expression: E, dialect: DialectType = None, identify: bool = True) -> E:
470    """Makes sure all identifiers that need to be quoted are quoted."""
471    return expression.transform(
472        Dialect.get_or_raise(dialect).quote_identifier, identify=identify, copy=False
473    )

Makes sure all identifiers that need to be quoted are quoted.

class Resolver:
476class Resolver:
477    """
478    Helper for resolving columns.
479
480    This is a class so we can lazily load some things and easily share them across functions.
481    """
482
483    def __init__(self, scope: Scope, schema: Schema, infer_schema: bool = True):
484        self.scope = scope
485        self.schema = schema
486        self._source_columns = None
487        self._unambiguous_columns: t.Optional[t.Dict[str, str]] = None
488        self._all_columns = None
489        self._infer_schema = infer_schema
490
491    def get_table(self, column_name: str) -> t.Optional[exp.Identifier]:
492        """
493        Get the table for a column name.
494
495        Args:
496            column_name: The column name to find the table for.
497        Returns:
498            The table name if it can be found/inferred.
499        """
500        if self._unambiguous_columns is None:
501            self._unambiguous_columns = self._get_unambiguous_columns(
502                self._get_all_source_columns()
503            )
504
505        table_name = self._unambiguous_columns.get(column_name)
506
507        if not table_name and self._infer_schema:
508            sources_without_schema = tuple(
509                source
510                for source, columns in self._get_all_source_columns().items()
511                if not columns or "*" in columns
512            )
513            if len(sources_without_schema) == 1:
514                table_name = sources_without_schema[0]
515
516        if table_name not in self.scope.selected_sources:
517            return exp.to_identifier(table_name)
518
519        node, _ = self.scope.selected_sources.get(table_name)
520
521        if isinstance(node, exp.Subqueryable):
522            while node and node.alias != table_name:
523                node = node.parent
524
525        node_alias = node.args.get("alias")
526        if node_alias:
527            return exp.to_identifier(node_alias.this)
528
529        return exp.to_identifier(table_name)
530
531    @property
532    def all_columns(self):
533        """All available columns of all sources in this scope"""
534        if self._all_columns is None:
535            self._all_columns = {
536                column for columns in self._get_all_source_columns().values() for column in columns
537            }
538        return self._all_columns
539
540    def get_source_columns(self, name, only_visible=False):
541        """Resolve the source columns for a given source `name`"""
542        if name not in self.scope.sources:
543            raise OptimizeError(f"Unknown table: {name}")
544
545        source = self.scope.sources[name]
546
547        # If referencing a table, return the columns from the schema
548        if isinstance(source, exp.Table):
549            return self.schema.column_names(source, only_visible)
550
551        if isinstance(source, Scope) and isinstance(source.expression, exp.Values):
552            return source.expression.alias_column_names
553
554        # Otherwise, if referencing another scope, return that scope's named selects
555        return source.expression.named_selects
556
557    def _get_all_source_columns(self):
558        if self._source_columns is None:
559            self._source_columns = {
560                k: self.get_source_columns(k)
561                for k in itertools.chain(self.scope.selected_sources, self.scope.lateral_sources)
562            }
563        return self._source_columns
564
565    def _get_unambiguous_columns(self, source_columns):
566        """
567        Find all the unambiguous columns in sources.
568
569        Args:
570            source_columns (dict): Mapping of names to source columns
571        Returns:
572            dict: Mapping of column name to source name
573        """
574        if not source_columns:
575            return {}
576
577        source_columns = list(source_columns.items())
578
579        first_table, first_columns = source_columns[0]
580        unambiguous_columns = {col: first_table for col in self._find_unique_columns(first_columns)}
581        all_columns = set(unambiguous_columns)
582
583        for table, columns in source_columns[1:]:
584            unique = self._find_unique_columns(columns)
585            ambiguous = set(all_columns).intersection(unique)
586            all_columns.update(columns)
587            for column in ambiguous:
588                unambiguous_columns.pop(column, None)
589            for column in unique.difference(ambiguous):
590                unambiguous_columns[column] = table
591
592        return unambiguous_columns
593
594    @staticmethod
595    def _find_unique_columns(columns):
596        """
597        Find the unique columns in a list of columns.
598
599        Example:
600            >>> sorted(Resolver._find_unique_columns(["a", "b", "b", "c"]))
601            ['a', 'c']
602
603        This is necessary because duplicate column names are ambiguous.
604        """
605        counts = {}
606        for column in columns:
607            counts[column] = counts.get(column, 0) + 1
608        return {column for column, count in counts.items() if count == 1}

Helper for resolving columns.

This is a class so we can lazily load some things and easily share them across functions.

Resolver( scope: sqlglot.optimizer.scope.Scope, schema: sqlglot.schema.Schema, infer_schema: bool = True)
483    def __init__(self, scope: Scope, schema: Schema, infer_schema: bool = True):
484        self.scope = scope
485        self.schema = schema
486        self._source_columns = None
487        self._unambiguous_columns: t.Optional[t.Dict[str, str]] = None
488        self._all_columns = None
489        self._infer_schema = infer_schema
scope
schema
def get_table(self, column_name: str) -> Optional[sqlglot.expressions.Identifier]:
491    def get_table(self, column_name: str) -> t.Optional[exp.Identifier]:
492        """
493        Get the table for a column name.
494
495        Args:
496            column_name: The column name to find the table for.
497        Returns:
498            The table name if it can be found/inferred.
499        """
500        if self._unambiguous_columns is None:
501            self._unambiguous_columns = self._get_unambiguous_columns(
502                self._get_all_source_columns()
503            )
504
505        table_name = self._unambiguous_columns.get(column_name)
506
507        if not table_name and self._infer_schema:
508            sources_without_schema = tuple(
509                source
510                for source, columns in self._get_all_source_columns().items()
511                if not columns or "*" in columns
512            )
513            if len(sources_without_schema) == 1:
514                table_name = sources_without_schema[0]
515
516        if table_name not in self.scope.selected_sources:
517            return exp.to_identifier(table_name)
518
519        node, _ = self.scope.selected_sources.get(table_name)
520
521        if isinstance(node, exp.Subqueryable):
522            while node and node.alias != table_name:
523                node = node.parent
524
525        node_alias = node.args.get("alias")
526        if node_alias:
527            return exp.to_identifier(node_alias.this)
528
529        return exp.to_identifier(table_name)

Get the table for a column name.

Arguments:
  • column_name: The column name to find the table for.
Returns:

The table name if it can be found/inferred.

all_columns

All available columns of all sources in this scope

def get_source_columns(self, name, only_visible=False):
540    def get_source_columns(self, name, only_visible=False):
541        """Resolve the source columns for a given source `name`"""
542        if name not in self.scope.sources:
543            raise OptimizeError(f"Unknown table: {name}")
544
545        source = self.scope.sources[name]
546
547        # If referencing a table, return the columns from the schema
548        if isinstance(source, exp.Table):
549            return self.schema.column_names(source, only_visible)
550
551        if isinstance(source, Scope) and isinstance(source.expression, exp.Values):
552            return source.expression.alias_column_names
553
554        # Otherwise, if referencing another scope, return that scope's named selects
555        return source.expression.named_selects

Resolve the source columns for a given source name