summaryrefslogtreecommitdiffstats
path: root/sqlglot/optimizer/expand_laterals.py
blob: 59f3fec9e0c401ac478c6358326965a3f1a6fa4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from __future__ import annotations

import typing as t

from sqlglot import exp


def expand_laterals(expression: exp.Expression) -> exp.Expression:
    """
    Expand lateral column alias references.

    This assumes `qualify_columns` as already run.

    Example:
        >>> import sqlglot
        >>> sql = "SELECT x.a + 1 AS b, b + 1 AS c FROM x"
        >>> expression = sqlglot.parse_one(sql)
        >>> expand_laterals(expression).sql()
        'SELECT x.a + 1 AS b, x.a + 1 + 1 AS c FROM x'

    Args:
        expression: expression to optimize
    Returns:
        optimized expression
    """
    for select in expression.find_all(exp.Select):
        alias_to_expression: t.Dict[str, exp.Expression] = {}
        for projection in select.expressions:
            for column in projection.find_all(exp.Column):
                if not column.table and column.name in alias_to_expression:
                    column.replace(alias_to_expression[column.name].copy())
                if isinstance(projection, exp.Alias):
                    alias_to_expression[projection.alias] = projection.this
    return expression