The user wants a system to build a data lineage graph.
The system needs to support three main functionalities:
Extraction: Getting metadata to build the graph.
Impact Analysis: Querying the graph to see dependencies.
Visualizations: Displaying the graph or parts of it.
This is a complex request that spans multiple technologies (SQL parsing, Graph DBs or libraries, Visualization tools). I need to provide a conceptual architecture and a practical implementation example.
Scope & Strategy:
I cannot "build" the entire enterprise software in a single response, but I can provide a robust prototype using Python.
Extraction: Use SQL parsing (specifically sqlfluff or sqlparse to extract table dependencies from queries).
Storage: Use a Python dictionary/networkx graph for the in-memory example, or mention Neo4j for production. I will stick to networkx for a self-contained example.
Impact Analysis: Graph traversal algorithms (BFS/DFS) using NetworkX.
Visualizations: Use pyvis for an interactive HTML graph or matplotlib for static. pyvis is better for "cool" factor and usability.
Step-by-Step Implementation Plan:
Define the Data Model: Nodes (Tables/Columns) and Edges (Derivation/Flow).
Extraction (SQL Parsing):
Need a mock list of SQL queries.
A parser function that takes a CREATE TABLE AS SELECT or INSERT INTO statement and finds Source and Target tables.
Graph Construction:
Initialize networkx.DiGraph.
Add nodes and edges based on parsed SQL.
Impact Analysis:
Upstream (Lineage): Where did this data come from?
Downstream (Impact): If I change this table, what breaks?
Refining the SQL Parsing:
Writing a full SQL parser from scratch is hard. I'll use sqlparse because it's standard, though sqlfluff is more powerful. Actually, for a simple demo, a Regex approach works for basic SELECT ... FROM but is fragile. sqlglot is excellent for this. It's pure Python, fast, and handles dependencies well. I will use sqlglot.
Adding Complexity (Columns):
Column-level lineage is hard. I'll stick to Table-level lineage for the demo to keep it understandable, but mention how to extend it.
The "Story" of the response:
Conceptual Overview: What is it? (DAG).
The Toolkit: What tools to use? (SQLGlot, NetworkX, PyVis/Neo4j).
Code Implementation: The Python script.
Extraction Details: How to parse SQL.
Impact Analysis Logic: How to traverse the graph.
Visualization: How to render it.
Self-Correction during thought process:
Initial thought: Use Neo4j.
Correction: Setting up Neo4j requires Docker or a local install. Too high barrier to entry for a chat response. Stick to NetworkX (in-memory) and PyVis (HTML export). Mention Neo4j as the "Production" path.
Parsing: Regex is bad. Use sqlglot. It identifies sources and targets easily.
Let's write the code mentally:import sqlglot.expressions as expast = sqlglot.parse_one(sql)
Sources: ast.find_all(exp.Table) inside the FROM/JOIN clauses.
Target: ast.find(exp.Insert) or ast.find(exp.Create).
Visuals:
PyVis allows setting colors. I should color the "impacted" nodes Red and the "source" node Green during the impact analysis demo.
Structure of the final output:
High-Level Architecture: The 3 layers (Extract, Compute, Present).
Red: The specific node being analyzed (in Impact mode).
Physics Engine: The hierarchicalRepulsion setting in the visualization code organizes the graph so that parents are always above children, mimicking a data flow diagram.
5. Extending to Production
For a production enterprise environment, replace the Python dictionaries with:
Graph Database: Store nodes and edges in Neo4j. This allows for much faster queries on millions of nodes.
Change: Instead of just graph.add_node("Table"), add nodes for Table.column.
Benefit: You can say "Changing users.email breaks the marketing_report" even if users.id is used elsewhere safely.
Orchestrator Integration: Instead of parsing raw text files, hook this logic into an orchestrator like Airflow or dbt. dbt automatically generates this graph in its manifest.json file.
import sqlglot
import networkx as nx
from pyvis.network import Network
import pandas as pd
class DataLineageGraph:
def __init__(self):
# Directed Graph: Edge goes from Source -> Target
self.graph = nx.DiGraph()
self.sql_catalog = {} # Store SQL for reference
def _extract_lineage(self, sql_script, dialect='snowflake'):
"""
Uses sqlglot to parse SQL and find dependencies.
Returns: list of source tables, target table
"""
try:
# Parse the SQL
parsed = sqlglot.parse_one(sql_script, dialect=dialect)
# 1. Identify Target (The table being created/inserted)
target = None
if isinstance(parsed, sqlglot.exp.Create):
target = parsed.this.name
elif isinstance(parsed, sqlglot.exp.Insert):
target = parsed.this.name
elif isinstance(parsed, sqlglot.exp.Merge):
target = parsed.this.name
if not target:
return [], None
# 2. Identify Sources (Tables in FROM or JOIN clauses)
sources = set()
# Find all table identifiers in the query
for table in parsed.find_all(sqlglot.exp.Table):
# Exclude the target table if it appears in a self-join or specific clauses
# (This logic can be refined based on specific SQL dialects)
sources.add(table.name)
# If the target was accidentally picked up as a source (e.g. INSERT INTO x SELECT * FROM x), remove it
if target in sources:
sources.remove(target)
return list(sources), target
except Exception as e:
print(f"Error parsing SQL: {e}")
return [], None
def add_pipeline_definition(self, sql_script, job_name="etl_job"):
"""
Ingests raw SQL and adds nodes/edges to the graph.
"""
sources, target = self._extract_lineage(sql_script)
if not target:
print(f"No target found in job: {job_name}")
return
# Add Target Node
self.graph.add_node(target, type='target', label=target, title=f"Target: {target}\nJob: {job_name}")
# Add Sources and Edges
for src in sources:
self.graph.add_node(src, type='source', label=src, title=f"Source: {src}")
# Edge direction: Source -> Target (Data flows TO target)
self.graph.add_edge(src, target, title=f"Loaded by {job_name}")
self.sql_catalog[target] = sql_script
print(f"Processed {job_name}: {[src + ' -> ' + target for src in sources]}")
def get_upstream(self, table_name, depth_limit=5):
"""
LINEAGE: Where does this data come from?
"""
if table_name not in self.graph:
return []
# networkx ancestors finds all nodes reachable from source
ancestors = nx.ancestors(self.graph, table_name)
return list(ancestors)
def get_downstream_impact(self, table_name):
"""
IMPACT ANALYSIS: If I break this table, what fails?
"""
if table_name not in self.graph:
return []
# networkx descendants finds all nodes reachable from target
descendants = nx.descendants(self.graph, table_name)
return list(descendants)
def visualize(self, output_file='lineage.html', focus_node=None):
"""
Generates an interactive HTML visualization.
"""
net = Network(height='750px', width='100%', directed=True, bgcolor='#222222', font_color='white')
# Determine nodes to show (if focusing)
if focus_node:
nodes_to_show = set([focus_node])
nodes_to_show.update(self.get_upstream(focus_node))
nodes_to_show.update(self.get_downstream_impact(focus_node))
subgraph = self.graph.subgraph(nodes_to_show)
else:
subgraph = self.graph
# Custom styling
for node in subgraph.nodes():
n = subgraph.nodes[node]
color = '#00ff1e' if n.get('type') == 'source' else '#f7b731'
# Highlight focus node
if node == focus_node:
color = '#ff0055'
net.add_node(node, label=node, color=color, title=n.get('title', node))
for edge in subgraph.edges():
net.add_edge(edge[0], edge[1])
net.set_options("""
{
"physics": {
"hierarchicalRepulsion": {
"centralGravity": 0.0,
"springLength": 200,
"springConstant": 0.01,
"nodeDistance": 200,
"damping": 0.09
},
"minVelocity": 0.75,
"solver": "hierarchicalRepulsion"
}
}
""")
net.save_graph(output_file)
print(f"Visualization saved to {output_file}")
# ==========================================
# 3. Execution Demo
# ==========================================
# Initialize
lineage = DataLineageGraph()
# Mock SQL Scripts (representing a Data Warehouse pipeline)
sql_raw_load = "CREATE TABLE raw_users AS SELECT id, name FROM stg_api_users;"
sql_clean = """
CREATE TABLE clean_users AS
SELECT u.id, u.name, o.order_date
FROM raw_users u
JOIN raw_orders o ON u.id = o.user_id;
"""
sql_agg = """
CREATE TABLE agg_daily_sales AS
SELECT date_trunc('day', order_date) as day, count(*) as sales
FROM clean_users
GROUP BY 1;
"""
sql_mart = """
CREATE TABLE mart_finance AS
SELECT day, sales
FROM agg_daily_sales
UNION ALL
SELECT day, refunds FROM agg_refunds;
"""
sql_refunds = "CREATE TABLE agg_refunds AS SELECT date as day, amount as refunds FROM raw_stripe_data;"
# 1. EXTRACTION: Build the graph
print("--- Building Graph ---")
lineage.add_pipeline_definition(sql_raw_load, "Load Raw Users")
lineage.add_pipeline_definition(sql_clean, "Clean & Join")
lineage.add_pipeline_definition(sql_agg, "Aggregation Logic")
lineage.add_pipeline_definition(sql_mart, "Finance Mart")
lineage.add_pipeline_definition(sql_refunds, "Refunds Load")
# 2. IMPACT ANALYSIS
print("\n--- Impact Analysis: 'raw_users' is down ---")
impacted_tables = lineage.get_downstream_impact('raw_users')
print(f"If raw_users breaks, the following tables will fail or stale: {impacted_tables}")
# 3. VISUALIZATION
print("\n--- Generating Visualization ---")
# We can visualize the whole graph, or just the impact radius
lineage.visualize('full_lineage.html')
# Visualize only the impact radius of 'raw_users'
lineage.visualize('impact_raw_users.html', focus_node='raw_users')