sqlglot.optimizer.qualify_columns API documentation

Edit on GitHub

# sqlglot.optimizer.qualify_columns

View Source

      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, t.Tuple[exp.Expression, int]] = {}
    174
    175    def replace_columns(
    176        node: t.Optional[exp.Expression], resolve_table: bool = False, literal_index: bool = False
    177    ) -> None:
    178        if not node:
    179            return
    180
    181        for column, *_ in walk_in_scope(node):
    182            if not isinstance(column, exp.Column):
    183                continue
    184            table = resolver.get_table(column.name) if resolve_table and not column.table else None
    185            alias_expr, i = alias_to_expression.get(column.name, (None, 1))
    186            double_agg = (
    187                (alias_expr.find(exp.AggFunc) and column.find_ancestor(exp.AggFunc))
    188                if alias_expr
    189                else False
    190            )
    191
    192            if table and (not alias_expr or double_agg):
    193                column.set("table", table)
    194            elif not column.table and alias_expr and not double_agg:
    195                if isinstance(alias_expr, exp.Literal) and (literal_index or resolve_table):
    196                    if literal_index:
    197                        column.replace(exp.Literal.number(i))
    198                else:
    199                    column.replace(alias_expr.copy())
    200
    201    for i, projection in enumerate(scope.expression.selects):
    202        replace_columns(projection)
    203
    204        if isinstance(projection, exp.Alias):
    205            alias_to_expression[projection.alias] = (projection.this, i + 1)
    206
    207    replace_columns(expression.args.get("where"))
    208    replace_columns(expression.args.get("group"), literal_index=True)
    209    replace_columns(expression.args.get("having"), resolve_table=True)
    210    replace_columns(expression.args.get("qualify"), resolve_table=True)
    211    scope.clear_cache()
    212
    213
    214def _expand_group_by(scope: Scope):
    215    expression = scope.expression
    216    group = expression.args.get("group")
    217    if not group:
    218        return
    219
    220    group.set("expressions", _expand_positional_references(scope, group.expressions))
    221    expression.set("group", group)
    222
    223
    224def _expand_order_by(scope: Scope, resolver: Resolver):
    225    order = scope.expression.args.get("order")
    226    if not order:
    227        return
    228
    229    ordereds = order.expressions
    230    for ordered, new_expression in zip(
    231        ordereds,
    232        _expand_positional_references(scope, (o.this for o in ordereds)),
    233    ):
    234        for agg in ordered.find_all(exp.AggFunc):
    235            for col in agg.find_all(exp.Column):
    236                if not col.table:
    237                    col.set("table", resolver.get_table(col.name))
    238
    239        ordered.set("this", new_expression)
    240
    241    if scope.expression.args.get("group"):
    242        selects = {s.this: exp.column(s.alias_or_name) for s in scope.expression.selects}
    243
    244        for ordered in ordereds:
    245            ordered = ordered.this
    246
    247            ordered.replace(
    248                exp.to_identifier(_select_by_pos(scope, ordered).alias)
    249                if ordered.is_int
    250                else selects.get(ordered, ordered)
    251            )
    252
    253
    254def _expand_positional_references(scope: Scope, expressions: t.Iterable[E]) -> t.List[E]:
    255    new_nodes = []
    256    for node in expressions:
    257        if node.is_int:
    258            select = _select_by_pos(scope, t.cast(exp.Literal, node)).this
    259
    260            if isinstance(select, exp.Literal):
    261                new_nodes.append(node)
    262            else:
    263                new_nodes.append(select.copy())
    264                scope.clear_cache()
    265        else:
    266            new_nodes.append(node)
    267
    268    return new_nodes
    269
    270
    271def _select_by_pos(scope: Scope, node: exp.Literal) -> exp.Alias:
    272    try:
    273        return scope.expression.selects[int(node.this) - 1].assert_is(exp.Alias)
    274    except IndexError:
    275        raise OptimizeError(f"Unknown output column: {node.name}")
    276
    277
    278def _qualify_columns(scope: Scope, resolver: Resolver) -> None:
    279    """Disambiguate columns, ensuring each column specifies a source"""
    280    for column in scope.columns:
    281        column_table = column.table
    282        column_name = column.name
    283
    284        if column_table and column_table in scope.sources:
    285            source_columns = resolver.get_source_columns(column_table)
    286            if source_columns and column_name not in source_columns and "*" not in source_columns:
    287                raise OptimizeError(f"Unknown column: {column_name}")
    288
    289        if not column_table:
    290            if scope.pivots and not column.find_ancestor(exp.Pivot):
    291                # If the column is under the Pivot expression, we need to qualify it
    292                # using the name of the pivoted source instead of the pivot's alias
    293                column.set("table", exp.to_identifier(scope.pivots[0].alias))
    294                continue
    295
    296            column_table = resolver.get_table(column_name)
    297
    298            # column_table can be a '' because bigquery unnest has no table alias
    299            if column_table:
    300                column.set("table", column_table)
    301        elif column_table not in scope.sources and (
    302            not scope.parent or column_table not in scope.parent.sources
    303        ):
    304            # structs are used like tables (e.g. "struct"."field"), so they need to be qualified
    305            # separately and represented as dot(dot(...(<table>.<column>, field1), field2, ...))
    306
    307            root, *parts = column.parts
    308
    309            if root.name in scope.sources:
    310                # struct is already qualified, but we still need to change the AST representation
    311                column_table = root
    312                root, *parts = parts
    313            else:
    314                column_table = resolver.get_table(root.name)
    315
    316            if column_table:
    317                column.replace(exp.Dot.build([exp.column(root, table=column_table), *parts]))
    318
    319    for pivot in scope.pivots:
    320        for column in pivot.find_all(exp.Column):
    321            if not column.table and column.name in resolver.all_columns:
    322                column_table = resolver.get_table(column.name)
    323                if column_table:
    324                    column.set("table", column_table)
    325
    326
    327def _expand_stars(
    328    scope: Scope, resolver: Resolver, using_column_tables: t.Dict[str, t.Any]
    329) -> None:
    330    """Expand stars to lists of column selections"""
    331
    332    new_selections = []
    333    except_columns: t.Dict[int, t.Set[str]] = {}
    334    replace_columns: t.Dict[int, t.Dict[str, str]] = {}
    335    coalesced_columns = set()
    336
    337    # TODO: handle optimization of multiple PIVOTs (and possibly UNPIVOTs) in the future
    338    pivot_columns = None
    339    pivot_output_columns = None
    340    pivot = t.cast(t.Optional[exp.Pivot], seq_get(scope.pivots, 0))
    341
    342    has_pivoted_source = pivot and not pivot.args.get("unpivot")
    343    if pivot and has_pivoted_source:
    344        pivot_columns = set(col.output_name for col in pivot.find_all(exp.Column))
    345
    346        pivot_output_columns = [col.output_name for col in pivot.args.get("columns", [])]
    347        if not pivot_output_columns:
    348            pivot_output_columns = [col.alias_or_name for col in pivot.expressions]
    349
    350    for expression in scope.expression.selects:
    351        if isinstance(expression, exp.Star):
    352            tables = list(scope.selected_sources)
    353            _add_except_columns(expression, tables, except_columns)
    354            _add_replace_columns(expression, tables, replace_columns)
    355        elif expression.is_star:
    356            tables = [expression.table]
    357            _add_except_columns(expression.this, tables, except_columns)
    358            _add_replace_columns(expression.this, tables, replace_columns)
    359        else:
    360            new_selections.append(expression)
    361            continue
    362
    363        for table in tables:
    364            if table not in scope.sources:
    365                raise OptimizeError(f"Unknown table: {table}")
    366
    367            columns = resolver.get_source_columns(table, only_visible=True)
    368
    369            # The _PARTITIONTIME and _PARTITIONDATE pseudo-columns are not returned by a SELECT * statement
    370            # https://cloud.google.com/bigquery/docs/querying-partitioned-tables#query_an_ingestion-time_partitioned_table
    371            if resolver.schema.dialect == "bigquery":
    372                columns = [
    373                    name
    374                    for name in columns
    375                    if name.upper() not in ("_PARTITIONTIME", "_PARTITIONDATE")
    376                ]
    377
    378            if columns and "*" not in columns:
    379                if pivot and has_pivoted_source and pivot_columns and pivot_output_columns:
    380                    implicit_columns = [col for col in columns if col not in pivot_columns]
    381                    new_selections.extend(
    382                        exp.alias_(exp.column(name, table=pivot.alias), name, copy=False)
    383                        for name in implicit_columns + pivot_output_columns
    384                    )
    385                    continue
    386
    387                table_id = id(table)
    388                for name in columns:
    389                    if name in using_column_tables and table in using_column_tables[name]:
    390                        if name in coalesced_columns:
    391                            continue
    392
    393                        coalesced_columns.add(name)
    394                        tables = using_column_tables[name]
    395                        coalesce = [exp.column(name, table=table) for table in tables]
    396
    397                        new_selections.append(
    398                            alias(
    399                                exp.Coalesce(this=coalesce[0], expressions=coalesce[1:]),
    400                                alias=name,
    401                                copy=False,
    402                            )
    403                        )
    404                    elif name not in except_columns.get(table_id, set()):
    405                        alias_ = replace_columns.get(table_id, {}).get(name, name)
    406                        column = exp.column(name, table=table)
    407                        new_selections.append(
    408                            alias(column, alias_, copy=False) if alias_ != name else column
    409                        )
    410            else:
    411                return
    412
    413    scope.expression.set("expressions", new_selections)
    414
    415
    416def _add_except_columns(
    417    expression: exp.Expression, tables, except_columns: t.Dict[int, t.Set[str]]
    418) -> None:
    419    except_ = expression.args.get("except")
    420
    421    if not except_:
    422        return
    423
    424    columns = {e.name for e in except_}
    425
    426    for table in tables:
    427        except_columns[id(table)] = columns
    428
    429
    430def _add_replace_columns(
    431    expression: exp.Expression, tables, replace_columns: t.Dict[int, t.Dict[str, str]]
    432) -> None:
    433    replace = expression.args.get("replace")
    434
    435    if not replace:
    436        return
    437
    438    columns = {e.this.name: e.alias for e in replace}
    439
    440    for table in tables:
    441        replace_columns[id(table)] = columns
    442
    443
    444def _qualify_outputs(scope: Scope):
    445    """Ensure all output columns are aliased"""
    446    new_selections = []
    447
    448    for i, (selection, aliased_column) in enumerate(
    449        itertools.zip_longest(scope.expression.selects, scope.outer_column_list)
    450    ):
    451        if isinstance(selection, exp.Subquery):
    452            if not selection.output_name:
    453                selection.set("alias", exp.TableAlias(this=exp.to_identifier(f"_col_{i}")))
    454        elif not isinstance(selection, exp.Alias) and not selection.is_star:
    455            selection = alias(
    456                selection,
    457                alias=selection.output_name or f"_col_{i}",
    458            )
    459        if aliased_column:
    460            selection.set("alias", exp.to_identifier(aliased_column))
    461
    462        new_selections.append(selection)
    463
    464    scope.expression.set("expressions", new_selections)
    465
    466
    467def quote_identifiers(expression: E, dialect: DialectType = None, identify: bool = True) -> E:
    468    """Makes sure all identifiers that need to be quoted are quoted."""
    469    return expression.transform(
    470        Dialect.get_or_raise(dialect).quote_identifier, identify=identify, copy=False
    471    )
    472
    473
    474class Resolver:
    475    """
    476    Helper for resolving columns.
    477
    478    This is a class so we can lazily load some things and easily share them across functions.
    479    """
    480
    481    def __init__(self, scope: Scope, schema: Schema, infer_schema: bool = True):
    482        self.scope = scope
    483        self.schema = schema
    484        self._source_columns = None
    485        self._unambiguous_columns: t.Optional[t.Dict[str, str]] = None
    486        self._all_columns = None
    487        self._infer_schema = infer_schema
    488
    489    def get_table(self, column_name: str) -> t.Optional[exp.Identifier]:
    490        """
    491        Get the table for a column name.
    492
    493        Args:
    494            column_name: The column name to find the table for.
    495        Returns:
    496            The table name if it can be found/inferred.
    497        """
    498        if self._unambiguous_columns is None:
    499            self._unambiguous_columns = self._get_unambiguous_columns(
    500                self._get_all_source_columns()
    501            )
    502
    503        table_name = self._unambiguous_columns.get(column_name)
    504
    505        if not table_name and self._infer_schema:
    506            sources_without_schema = tuple(
    507                source
    508                for source, columns in self._get_all_source_columns().items()
    509                if not columns or "*" in columns
    510            )
    511            if len(sources_without_schema) == 1:
    512                table_name = sources_without_schema[0]
    513
    514        if table_name not in self.scope.selected_sources:
    515            return exp.to_identifier(table_name)
    516
    517        node, _ = self.scope.selected_sources.get(table_name)
    518
    519        if isinstance(node, exp.Subqueryable):
    520            while node and node.alias != table_name:
    521                node = node.parent
    522
    523        node_alias = node.args.get("alias")
    524        if node_alias:
    525            return exp.to_identifier(node_alias.this)
    526
    527        return exp.to_identifier(table_name)
    528
    529    @property
    530    def all_columns(self):
    531        """All available columns of all sources in this scope"""
    532        if self._all_columns is None:
    533            self._all_columns = {
    534                column for columns in self._get_all_source_columns().values() for column in columns
    535            }
    536        return self._all_columns
    537
    538    def get_source_columns(self, name, only_visible=False):
    539        """Resolve the source columns for a given source `name`"""
    540        if name not in self.scope.sources:
    541            raise OptimizeError(f"Unknown table: {name}")
    542
    543        source = self.scope.sources[name]
    544
    545        # If referencing a table, return the columns from the schema
    546        if isinstance(source, exp.Table):
    547            return self.schema.column_names(source, only_visible)
    548
    549        if isinstance(source, Scope) and isinstance(source.expression, exp.Values):
    550            return source.expression.alias_column_names
    551
    552        # Otherwise, if referencing another scope, return that scope's named selects
    553        return source.expression.named_selects
    554
    555    def _get_all_source_columns(self):
    556        if self._source_columns is None:
    557            self._source_columns = {
    558                k: self.get_source_columns(k)
    559                for k in itertools.chain(self.scope.selected_sources, self.scope.lateral_sources)
    560            }
    561        return self._source_columns
    562
    563    def _get_unambiguous_columns(self, source_columns):
    564        """
    565        Find all the unambiguous columns in sources.
    566
    567        Args:
    568            source_columns (dict): Mapping of names to source columns
    569        Returns:
    570            dict: Mapping of column name to source name
    571        """
    572        if not source_columns:
    573            return {}
    574
    575        source_columns = list(source_columns.items())
    576
    577        first_table, first_columns = source_columns[0]
    578        unambiguous_columns = {col: first_table for col in self._find_unique_columns(first_columns)}
    579        all_columns = set(unambiguous_columns)
    580
    581        for table, columns in source_columns[1:]:
    582            unique = self._find_unique_columns(columns)
    583            ambiguous = set(all_columns).intersection(unique)
    584            all_columns.update(columns)
    585            for column in ambiguous:
    586                unambiguous_columns.pop(column, None)
    587            for column in unique.difference(ambiguous):
    588                unambiguous_columns[column] = table
    589
    590        return unambiguous_columns
    591
    592    @staticmethod
    593    def _find_unique_columns(columns):
    594        """
    595        Find the unique columns in a list of columns.
    596
    597        Example:
    598            >>> sorted(Resolver._find_unique_columns(["a", "b", "b", "c"]))
    599            ['a', 'c']
    600
    601        This is necessary because duplicate column names are ambiguous.
    602        """
    603        counts = {}
    604        for column in columns:
    605            counts[column] = counts.get(column, 0) + 1
    606        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: View Source

    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: View Source

    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: View Source

    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    )

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

class Resolver: View Source

    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}

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) View Source

    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

scope
schema
def get_table(self, column_name: str) -> Optional[sqlglot.expressions.Identifier]: View Source

    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)

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): View Source

    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

Resolve the source columns for a given source `name`