Edit on GitHub

# sqlglot.lineage

View Source

      1from __future__ import annotations
      2
      3import json
      4import typing as t
      5from dataclasses import dataclass, field
      6
      7from sqlglot import Schema, exp, maybe_parse
      8from sqlglot.errors import SqlglotError
      9from sqlglot.optimizer import Scope, build_scope, qualify
     10
     11if t.TYPE_CHECKING:
     12    from sqlglot.dialects.dialect import DialectType
     13
     14
     15@dataclass(frozen=True)
     16class Node:
     17    name: str
     18    expression: exp.Expression
     19    source: exp.Expression
     20    downstream: t.List[Node] = field(default_factory=list)
     21    alias: str = ""
     22
     23    def walk(self) -> t.Iterator[Node]:
     24        yield self
     25
     26        for d in self.downstream:
     27            if isinstance(d, Node):
     28                yield from d.walk()
     29            else:
     30                yield d
     31
     32    def to_html(self, **opts) -> LineageHTML:
     33        return LineageHTML(self, **opts)
     34
     35
     36def lineage(
     37    column: str | exp.Column,
     38    sql: str | exp.Expression,
     39    schema: t.Optional[t.Dict | Schema] = None,
     40    sources: t.Optional[t.Dict[str, str | exp.Subqueryable]] = None,
     41    dialect: DialectType = None,
     42    **kwargs,
     43) -> Node:
     44    """Build the lineage graph for a column of a SQL query.
     45
     46    Args:
     47        column: The column to build the lineage for.
     48        sql: The SQL string or expression.
     49        schema: The schema of tables.
     50        sources: A mapping of queries which will be used to continue building lineage.
     51        dialect: The dialect of input SQL.
     52        **kwargs: Qualification optimizer kwargs.
     53
     54    Returns:
     55        A lineage node.
     56    """
     57
     58    expression = maybe_parse(sql, dialect=dialect)
     59
     60    if sources:
     61        expression = exp.expand(
     62            expression,
     63            {
     64                k: t.cast(exp.Subqueryable, maybe_parse(v, dialect=dialect))
     65                for k, v in sources.items()
     66            },
     67        )
     68
     69    qualified = qualify.qualify(
     70        expression,
     71        dialect=dialect,
     72        schema=schema,
     73        **{"validate_qualify_columns": False, "identify": False, **kwargs},  # type: ignore
     74    )
     75
     76    scope = build_scope(qualified)
     77
     78    if not scope:
     79        raise SqlglotError("Cannot build lineage, sql must be SELECT")
     80
     81    def to_node(
     82        column: str | int,
     83        scope: Scope,
     84        scope_name: t.Optional[str] = None,
     85        upstream: t.Optional[Node] = None,
     86        alias: t.Optional[str] = None,
     87    ) -> Node:
     88        aliases = {
     89            dt.alias: dt.comments[0].split()[1]
     90            for dt in scope.derived_tables
     91            if dt.comments and dt.comments[0].startswith("source: ")
     92        }
     93
     94        # Find the specific select clause that is the source of the column we want.
     95        # This can either be a specific, named select or a generic `*` clause.
     96        select = (
     97            scope.expression.selects[column]
     98            if isinstance(column, int)
     99            else next(
    100                (select for select in scope.expression.selects if select.alias_or_name == column),
    101                exp.Star() if scope.expression.is_star else None,
    102            )
    103        )
    104
    105        if not select:
    106            raise ValueError(f"Could not find {column} in {scope.expression}")
    107
    108        if isinstance(scope.expression, exp.Union):
    109            upstream = upstream or Node(name="UNION", source=scope.expression, expression=select)
    110
    111            index = (
    112                column
    113                if isinstance(column, int)
    114                else next(
    115                    i
    116                    for i, select in enumerate(scope.expression.selects)
    117                    if select.alias_or_name == column
    118                )
    119            )
    120
    121            for s in scope.union_scopes:
    122                to_node(index, scope=s, upstream=upstream)
    123
    124            return upstream
    125
    126        if isinstance(scope.expression, exp.Select):
    127            # For better ergonomics in our node labels, replace the full select with
    128            # a version that has only the column we care about.
    129            #   "x", SELECT x, y FROM foo
    130            #     => "x", SELECT x FROM foo
    131            source = t.cast(exp.Expression, scope.expression.select(select, append=False))
    132        else:
    133            source = scope.expression
    134
    135        # Create the node for this step in the lineage chain, and attach it to the previous one.
    136        node = Node(
    137            name=f"{scope_name}.{column}" if scope_name else str(column),
    138            source=source,
    139            expression=select,
    140            alias=alias or "",
    141        )
    142        if upstream:
    143            upstream.downstream.append(node)
    144
    145        # Find all columns that went into creating this one to list their lineage nodes.
    146        for c in set(select.find_all(exp.Column)):
    147            table = c.table
    148            source = scope.sources.get(table)
    149
    150            if isinstance(source, Scope):
    151                # The table itself came from a more specific scope. Recurse into that one using the unaliased column name.
    152                to_node(
    153                    c.name, scope=source, scope_name=table, upstream=node, alias=aliases.get(table)
    154                )
    155            else:
    156                # The source is not a scope - we've reached the end of the line. At this point, if a source is not found
    157                # it means this column's lineage is unknown. This can happen if the definition of a source used in a query
    158                # is not passed into the `sources` map.
    159                source = source or exp.Placeholder()
    160                node.downstream.append(Node(name=c.sql(), source=source, expression=source))
    161
    162        return node
    163
    164    return to_node(column if isinstance(column, str) else column.name, scope)
    165
    166
    167class LineageHTML:
    168    """Node to HTML generator using vis.js.
    169
    170    https://visjs.github.io/vis-network/docs/network/
    171    """
    172
    173    def __init__(
    174        self,
    175        node: Node,
    176        dialect: DialectType = None,
    177        imports: bool = True,
    178        **opts: t.Any,
    179    ):
    180        self.node = node
    181        self.imports = imports
    182
    183        self.options = {
    184            "height": "500px",
    185            "width": "100%",
    186            "layout": {
    187                "hierarchical": {
    188                    "enabled": True,
    189                    "nodeSpacing": 200,
    190                    "sortMethod": "directed",
    191                },
    192            },
    193            "interaction": {
    194                "dragNodes": False,
    195                "selectable": False,
    196            },
    197            "physics": {
    198                "enabled": False,
    199            },
    200            "edges": {
    201                "arrows": "to",
    202            },
    203            "nodes": {
    204                "font": "20px monaco",
    205                "shape": "box",
    206                "widthConstraint": {
    207                    "maximum": 300,
    208                },
    209            },
    210            **opts,
    211        }
    212
    213        self.nodes = {}
    214        self.edges = []
    215
    216        for node in node.walk():
    217            if isinstance(node.expression, exp.Table):
    218                label = f"FROM {node.expression.this}"
    219                title = f"<pre>SELECT {node.name} FROM {node.expression.this}</pre>"
    220                group = 1
    221            else:
    222                label = node.expression.sql(pretty=True, dialect=dialect)
    223                source = node.source.transform(
    224                    lambda n: exp.Tag(this=n, prefix="<b>", postfix="</b>")
    225                    if n is node.expression
    226                    else n,
    227                    copy=False,
    228                ).sql(pretty=True, dialect=dialect)
    229                title = f"<pre>{source}</pre>"
    230                group = 0
    231
    232            node_id = id(node)
    233
    234            self.nodes[node_id] = {
    235                "id": node_id,
    236                "label": label,
    237                "title": title,
    238                "group": group,
    239            }
    240
    241            for d in node.downstream:
    242                self.edges.append({"from": node_id, "to": id(d)})
    243
    244    def __str__(self):
    245        nodes = json.dumps(list(self.nodes.values()))
    246        edges = json.dumps(self.edges)
    247        options = json.dumps(self.options)
    248        imports = (
    249            """<script type="text/javascript" src="https://unpkg.com/vis-data@latest/peer/umd/vis-data.min.js"></script>
    250  <script type="text/javascript" src="https://unpkg.com/vis-network@latest/peer/umd/vis-network.min.js"></script>
    251  <link rel="stylesheet" type="text/css" href="https://unpkg.com/vis-network/styles/vis-network.min.css" />"""
    252            if self.imports
    253            else ""
    254        )
    255
    256        return f"""<div>
    257  <div id="sqlglot-lineage"></div>
    258  {imports}
    259  <script type="text/javascript">
    260    var nodes = new vis.DataSet({nodes})
    261    nodes.forEach(row => row["title"] = new DOMParser().parseFromString(row["title"], "text/html").body.childNodes[0])
    262
    263    new vis.Network(
    264        document.getElementById("sqlglot-lineage"),
    265        {{
    266            nodes: nodes,
    267            edges: new vis.DataSet({edges})
    268        }},
    269        {options},
    270    )
    271  </script>
    272</div>"""
    273
    274    def _repr_html_(self) -> str:
    275        return self.__str__()

@dataclass(frozen=True)
class Node: View Source

    16@dataclass(frozen=True)
    17class Node:
    18    name: str
    19    expression: exp.Expression
    20    source: exp.Expression
    21    downstream: t.List[Node] = field(default_factory=list)
    22    alias: str = ""
    23
    24    def walk(self) -> t.Iterator[Node]:
    25        yield self
    26
    27        for d in self.downstream:
    28            if isinstance(d, Node):
    29                yield from d.walk()
    30            else:
    31                yield d
    32
    33    def to_html(self, **opts) -> LineageHTML:
    34        return LineageHTML(self, **opts)

Node( name: str, expression: sqlglot.expressions.Expression, source: sqlglot.expressions.Expression, downstream: List[Node] = <factory>, alias: str = '')
name: str
expression: sqlglot.expressions.Expression
source: sqlglot.expressions.Expression
downstream: List[Node]
alias: str = ''
def walk(self) -> Iterator[Node]: View Source

    24    def walk(self) -> t.Iterator[Node]:
    25        yield self
    26
    27        for d in self.downstream:
    28            if isinstance(d, Node):
    29                yield from d.walk()
    30            else:
    31                yield d

def to_html(self, **opts) -> LineageHTML: View Source

    33    def to_html(self, **opts) -> LineageHTML:
    34        return LineageHTML(self, **opts)

def lineage( column: str | sqlglot.expressions.Column, sql: str | sqlglot.expressions.Expression, schema: Union[Dict, sqlglot.schema.Schema, NoneType] = None, sources: Optional[Dict[str, str | sqlglot.expressions.Subqueryable]] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Node: View Source

     37def lineage(
     38    column: str | exp.Column,
     39    sql: str | exp.Expression,
     40    schema: t.Optional[t.Dict | Schema] = None,
     41    sources: t.Optional[t.Dict[str, str | exp.Subqueryable]] = None,
     42    dialect: DialectType = None,
     43    **kwargs,
     44) -> Node:
     45    """Build the lineage graph for a column of a SQL query.
     46
     47    Args:
     48        column: The column to build the lineage for.
     49        sql: The SQL string or expression.
     50        schema: The schema of tables.
     51        sources: A mapping of queries which will be used to continue building lineage.
     52        dialect: The dialect of input SQL.
     53        **kwargs: Qualification optimizer kwargs.
     54
     55    Returns:
     56        A lineage node.
     57    """
     58
     59    expression = maybe_parse(sql, dialect=dialect)
     60
     61    if sources:
     62        expression = exp.expand(
     63            expression,
     64            {
     65                k: t.cast(exp.Subqueryable, maybe_parse(v, dialect=dialect))
     66                for k, v in sources.items()
     67            },
     68        )
     69
     70    qualified = qualify.qualify(
     71        expression,
     72        dialect=dialect,
     73        schema=schema,
     74        **{"validate_qualify_columns": False, "identify": False, **kwargs},  # type: ignore
     75    )
     76
     77    scope = build_scope(qualified)
     78
     79    if not scope:
     80        raise SqlglotError("Cannot build lineage, sql must be SELECT")
     81
     82    def to_node(
     83        column: str | int,
     84        scope: Scope,
     85        scope_name: t.Optional[str] = None,
     86        upstream: t.Optional[Node] = None,
     87        alias: t.Optional[str] = None,
     88    ) -> Node:
     89        aliases = {
     90            dt.alias: dt.comments[0].split()[1]
     91            for dt in scope.derived_tables
     92            if dt.comments and dt.comments[0].startswith("source: ")
     93        }
     94
     95        # Find the specific select clause that is the source of the column we want.
     96        # This can either be a specific, named select or a generic `*` clause.
     97        select = (
     98            scope.expression.selects[column]
     99            if isinstance(column, int)
    100            else next(
    101                (select for select in scope.expression.selects if select.alias_or_name == column),
    102                exp.Star() if scope.expression.is_star else None,
    103            )
    104        )
    105
    106        if not select:
    107            raise ValueError(f"Could not find {column} in {scope.expression}")
    108
    109        if isinstance(scope.expression, exp.Union):
    110            upstream = upstream or Node(name="UNION", source=scope.expression, expression=select)
    111
    112            index = (
    113                column
    114                if isinstance(column, int)
    115                else next(
    116                    i
    117                    for i, select in enumerate(scope.expression.selects)
    118                    if select.alias_or_name == column
    119                )
    120            )
    121
    122            for s in scope.union_scopes:
    123                to_node(index, scope=s, upstream=upstream)
    124
    125            return upstream
    126
    127        if isinstance(scope.expression, exp.Select):
    128            # For better ergonomics in our node labels, replace the full select with
    129            # a version that has only the column we care about.
    130            #   "x", SELECT x, y FROM foo
    131            #     => "x", SELECT x FROM foo
    132            source = t.cast(exp.Expression, scope.expression.select(select, append=False))
    133        else:
    134            source = scope.expression
    135
    136        # Create the node for this step in the lineage chain, and attach it to the previous one.
    137        node = Node(
    138            name=f"{scope_name}.{column}" if scope_name else str(column),
    139            source=source,
    140            expression=select,
    141            alias=alias or "",
    142        )
    143        if upstream:
    144            upstream.downstream.append(node)
    145
    146        # Find all columns that went into creating this one to list their lineage nodes.
    147        for c in set(select.find_all(exp.Column)):
    148            table = c.table
    149            source = scope.sources.get(table)
    150
    151            if isinstance(source, Scope):
    152                # The table itself came from a more specific scope. Recurse into that one using the unaliased column name.
    153                to_node(
    154                    c.name, scope=source, scope_name=table, upstream=node, alias=aliases.get(table)
    155                )
    156            else:
    157                # The source is not a scope - we've reached the end of the line. At this point, if a source is not found
    158                # it means this column's lineage is unknown. This can happen if the definition of a source used in a query
    159                # is not passed into the `sources` map.
    160                source = source or exp.Placeholder()
    161                node.downstream.append(Node(name=c.sql(), source=source, expression=source))
    162
    163        return node
    164
    165    return to_node(column if isinstance(column, str) else column.name, scope)

Build the lineage graph for a column of a SQL query.

###### Arguments:

- column: The column to build the lineage for.
- sql: The SQL string or expression.
- schema: The schema of tables.
- sources: A mapping of queries which will be used to continue building lineage.
- dialect: The dialect of input SQL.
- **kwargs: Qualification optimizer kwargs.

###### Returns:

> A lineage node.

class LineageHTML: View Source

    168class LineageHTML:
    169    """Node to HTML generator using vis.js.
    170
    171    https://visjs.github.io/vis-network/docs/network/
    172    """
    173
    174    def __init__(
    175        self,
    176        node: Node,
    177        dialect: DialectType = None,
    178        imports: bool = True,
    179        **opts: t.Any,
    180    ):
    181        self.node = node
    182        self.imports = imports
    183
    184        self.options = {
    185            "height": "500px",
    186            "width": "100%",
    187            "layout": {
    188                "hierarchical": {
    189                    "enabled": True,
    190                    "nodeSpacing": 200,
    191                    "sortMethod": "directed",
    192                },
    193            },
    194            "interaction": {
    195                "dragNodes": False,
    196                "selectable": False,
    197            },
    198            "physics": {
    199                "enabled": False,
    200            },
    201            "edges": {
    202                "arrows": "to",
    203            },
    204            "nodes": {
    205                "font": "20px monaco",
    206                "shape": "box",
    207                "widthConstraint": {
    208                    "maximum": 300,
    209                },
    210            },
    211            **opts,
    212        }
    213
    214        self.nodes = {}
    215        self.edges = []
    216
    217        for node in node.walk():
    218            if isinstance(node.expression, exp.Table):
    219                label = f"FROM {node.expression.this}"
    220                title = f"<pre>SELECT {node.name} FROM {node.expression.this}</pre>"
    221                group = 1
    222            else:
    223                label = node.expression.sql(pretty=True, dialect=dialect)
    224                source = node.source.transform(
    225                    lambda n: exp.Tag(this=n, prefix="<b>", postfix="</b>")
    226                    if n is node.expression
    227                    else n,
    228                    copy=False,
    229                ).sql(pretty=True, dialect=dialect)
    230                title = f"<pre>{source}</pre>"
    231                group = 0
    232
    233            node_id = id(node)
    234
    235            self.nodes[node_id] = {
    236                "id": node_id,
    237                "label": label,
    238                "title": title,
    239                "group": group,
    240            }
    241
    242            for d in node.downstream:
    243                self.edges.append({"from": node_id, "to": id(d)})
    244
    245    def __str__(self):
    246        nodes = json.dumps(list(self.nodes.values()))
    247        edges = json.dumps(self.edges)
    248        options = json.dumps(self.options)
    249        imports = (
    250            """<script type="text/javascript" src="https://unpkg.com/vis-data@latest/peer/umd/vis-data.min.js"></script>
    251  <script type="text/javascript" src="https://unpkg.com/vis-network@latest/peer/umd/vis-network.min.js"></script>
    252  <link rel="stylesheet" type="text/css" href="https://unpkg.com/vis-network/styles/vis-network.min.css" />"""
    253            if self.imports
    254            else ""
    255        )
    256
    257        return f"""<div>
    258  <div id="sqlglot-lineage"></div>
    259  {imports}
    260  <script type="text/javascript">
    261    var nodes = new vis.DataSet({nodes})
    262    nodes.forEach(row => row["title"] = new DOMParser().parseFromString(row["title"], "text/html").body.childNodes[0])
    263
    264    new vis.Network(
    265        document.getElementById("sqlglot-lineage"),
    266        {{
    267            nodes: nodes,
    268            edges: new vis.DataSet({edges})
    269        }},
    270        {options},
    271    )
    272  </script>
    273</div>"""
    274
    275    def _repr_html_(self) -> str:
    276        return self.__str__()

Node to HTML generator using vis.js.

https://visjs.github.io/vis-network/docs/network/

LineageHTML( node: Node, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, imports: bool = True, **opts: Any) View Source

    174    def __init__(
    175        self,
    176        node: Node,
    177        dialect: DialectType = None,
    178        imports: bool = True,
    179        **opts: t.Any,
    180    ):
    181        self.node = node
    182        self.imports = imports
    183
    184        self.options = {
    185            "height": "500px",
    186            "width": "100%",
    187            "layout": {
    188                "hierarchical": {
    189                    "enabled": True,
    190                    "nodeSpacing": 200,
    191                    "sortMethod": "directed",
    192                },
    193            },
    194            "interaction": {
    195                "dragNodes": False,
    196                "selectable": False,
    197            },
    198            "physics": {
    199                "enabled": False,
    200            },
    201            "edges": {
    202                "arrows": "to",
    203            },
    204            "nodes": {
    205                "font": "20px monaco",
    206                "shape": "box",
    207                "widthConstraint": {
    208                    "maximum": 300,
    209                },
    210            },
    211            **opts,
    212        }
    213
    214        self.nodes = {}
    215        self.edges = []
    216
    217        for node in node.walk():
    218            if isinstance(node.expression, exp.Table):
    219                label = f"FROM {node.expression.this}"
    220                title = f"<pre>SELECT {node.name} FROM {node.expression.this}</pre>"
    221                group = 1
    222            else:
    223                label = node.expression.sql(pretty=True, dialect=dialect)
    224                source = node.source.transform(
    225                    lambda n: exp.Tag(this=n, prefix="<b>", postfix="</b>")
    226                    if n is node.expression
    227                    else n,
    228                    copy=False,
    229                ).sql(pretty=True, dialect=dialect)
    230                title = f"<pre>{source}</pre>"
    231                group = 0
    232
    233            node_id = id(node)
    234
    235            self.nodes[node_id] = {
    236                "id": node_id,
    237                "label": label,
    238                "title": title,
    239                "group": group,
    240            }
    241
    242            for d in node.downstream:
    243                self.edges.append({"from": node_id, "to": id(d)})

node
imports
options
nodes
edges