|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import collections |
| 4 | +import traceback |
| 5 | +import typing as t |
| 6 | + |
| 7 | +from fastapi import APIRouter, Depends, HTTPException |
| 8 | +from sqlglot import exp |
| 9 | +from sqlglot.lineage import Node, lineage |
| 10 | +from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY |
| 11 | + |
| 12 | +from sqlmesh.core.context import Context |
| 13 | +from web.server.settings import get_loaded_context |
| 14 | + |
| 15 | +router = APIRouter() |
| 16 | + |
| 17 | + |
| 18 | +def _get_table(node: Node) -> str: |
| 19 | + """Get a node's table/source""" |
| 20 | + if isinstance(node.expression, exp.Table): |
| 21 | + return exp.table_name(node.expression) |
| 22 | + else: |
| 23 | + return node.alias |
| 24 | + |
| 25 | + |
| 26 | +def _process_downstream(downstream: t.List[Node]) -> t.Dict[str, t.List[str]]: |
| 27 | + """Aggregate a list of downstream nodes by table/source""" |
| 28 | + graph = collections.defaultdict(list) |
| 29 | + for node in downstream: |
| 30 | + column = exp.to_column(node.name).name |
| 31 | + table = _get_table(node) |
| 32 | + graph[table].append(column) |
| 33 | + return graph |
| 34 | + |
| 35 | + |
| 36 | +@router.get("/") |
| 37 | +async def column_lineage( |
| 38 | + column: str, |
| 39 | + model: str, |
| 40 | + context: Context = Depends(get_loaded_context), |
| 41 | +) -> t.Dict[str, t.Dict[str, t.Dict[str, t.List[str]]]]: |
| 42 | + """Get a column's lineage""" |
| 43 | + try: |
| 44 | + node = lineage( |
| 45 | + column=column, |
| 46 | + sql=context.models[model].render_query(), |
| 47 | + sources={ |
| 48 | + model: context.models[model].render_query() for model in context.dag.upstream(model) |
| 49 | + }, |
| 50 | + ) |
| 51 | + except Exception: |
| 52 | + raise HTTPException( |
| 53 | + status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=traceback.format_exc() |
| 54 | + ) |
| 55 | + |
| 56 | + graph = {} |
| 57 | + table = model |
| 58 | + for i, node in enumerate(node.walk()): |
| 59 | + if i > 0: |
| 60 | + table = _get_table(node) |
| 61 | + column = exp.to_column(node.name).name |
| 62 | + graph[table] = {column: _process_downstream(node.downstream)} |
| 63 | + return graph |
0 commit comments