id: sql-column-impact-analysis
namespace: company.team
inputs:
- id: column_change
type: SELECT
displayName: Proposed source change
description: The source column a team wants to drop, rename or retype. The flow
finds everything downstream that would break.
values:
- raw.orders.amount
- raw.orders.status
- raw.customers.email
- raw.customers.signup_at
defaults: raw.orders.amount
- id: dialect
type: STRING
displayName: SQL dialect
defaults: duckdb
- id: notify_slack
type: BOOL
displayName: Notify Slack
description: Post a failure alert to Slack. Needs the SLACK_WEBHOOK_URL secret.
defaults: false
triggers:
- id: on_schema_change_request
type: io.kestra.plugin.core.trigger.Webhook
disabled: true
description: >
Call from the schema change process with {"column": "raw.orders.amount"}.
Replace the key first.
key: replace-with-a-long-random-key
tasks:
- id: analyze
type: io.kestra.plugin.scripts.python.Script
description: >
Parse every model with sqlglot, build column-level lineage through all
models, then follow the proposed column downstream. Columns used only in
WHERE, JOIN or GROUP BY are tracked too, because removing a filter column
breaks a model without changing any output lineage. Exposures (dashboards,
exports) declare which model columns they read.
containerImage: python:3.12-slim
beforeCommands:
- pip install -q --root-user-action=ignore sqlglot==25.24.5
env:
CHANGE: "{{ trigger.body.column ?? inputs.column_change }}"
DIALECT: "{{ inputs.dialect }}"
# Demo project. Replace with a git.Clone of your models in a WorkingDirectory.
inputFiles:
sources.json: |
{"raw": {"orders": {"order_id": "int", "customer_id": "int", "amount": "double", "status": "text", "created_at": "timestamp"},
"customers": {"customer_id": "int", "email": "text", "country": "text", "signup_at": "timestamp"}}}
exposures.json: |
[{"name": "Revenue dashboard", "owner": "finance@example.invalid", "columns": ["analytics.fct_revenue.revenue", "analytics.fct_revenue.country"]},
{"name": "CRM export", "owner": "growth@example.invalid", "columns": ["analytics.dim_customers.country", "analytics.dim_customers.orders"]}]
models/stg_orders.sql: |
select order_id, customer_id, amount as amount_usd, cast(created_at as date) as order_date
from raw.orders
where status <> 'TEST'
models/stg_customers.sql: |
select customer_id, lower(email) as email, country
from raw.customers
models/fct_revenue.sql: |
select c.country, o.order_date, sum(o.amount_usd) as revenue, count(distinct o.customer_id) as buyers
from analytics.stg_orders o
join analytics.stg_customers c on c.customer_id = o.customer_id
group by 1, 2
models/dim_customers.sql: |
select c.customer_id, c.country, count(o.order_id) as orders
from analytics.stg_customers c
left join analytics.stg_orders o on o.customer_id = c.customer_id
group by 1, 2
outputFiles:
- impact.md
script: |
import glob, json, os, re
import sqlglot
from sqlglot import exp
from sqlglot.lineage import lineage
from sqlglot.optimizer.qualify import qualify
dialect, change = os.environ["DIALECT"], os.environ["CHANGE"]
schema = json.load(open("sources.json"))
parts = change.split(".")
if len(parts) != 3 or parts[2] not in schema.get(parts[0], {}).get(parts[1], {}):
raise SystemExit("unknown source column " + change + ": use db.table.column as listed in sources.json")
models = {os.path.basename(p)[:-4]: open(p).read() for p in glob.glob("models/*.sql")}
# Order models so each one is parsed after the models it reads.
refs = {m: set(re.findall(r"analytics\.(\w+)", sql)) for m, sql in models.items()}
order, done = [], set()
while len(order) < len(models):
ready = [m for m in models if m not in done and refs[m] <= done]
if not ready:
raise SystemExit("cycle between models: " + ", ".join(sorted(set(models) - done)))
for m in sorted(ready):
order.append(m); done.add(m)
q = qualify(sqlglot.parse_one(models[m], dialect=dialect), schema=schema, dialect=dialect)
schema.setdefault("analytics", {})[m] = {s.alias_or_name: "text" for s in q.selects}
edges = {} # "db.table.col" -> set of downstream "analytics.model.col"
filter_use = {} # "db.table.col" -> set of models that use it outside the select list
for m in order:
sql = models[m]
q = qualify(sqlglot.parse_one(sql, dialect=dialect), schema=schema, dialect=dialect)
tables = {t.alias_or_name: f"{t.db}.{t.name}" for t in q.find_all(exp.Table)}
for col in [s.alias_or_name for s in q.selects]:
for node in lineage(col, sql, schema=schema, dialect=dialect).walk():
if not node.downstream and isinstance(node.source, exp.Table):
src = f"{node.source.db}.{node.source.name}.{node.name.split('.')[-1]}"
edges.setdefault(src, set()).add(f"analytics.{m}.{col}")
# Columns in WHERE, JOIN, GROUP BY or HAVING: if one disappears, the whole model fails.
for c in q.find_all(exp.Column):
if c.table in tables and c.find_ancestor(exp.Where, exp.Join, exp.Group, exp.Having):
filter_use.setdefault(f"{tables[c.table]}.{c.name}", set()).add(m)
# Walk downstream until nothing new is affected.
affected, broken_models, frontier = set(), set(), [change]
while frontier:
col = frontier.pop()
for m in filter_use.get(col, set()) - broken_models:
broken_models.add(m)
frontier += [f"analytics.{m}.{c}" for c in schema["analytics"][m] if f"analytics.{m}.{c}" not in affected]
affected |= {f"analytics.{m}.{c}" for c in schema["analytics"][m]}
for child in edges.get(col, ()):
if child not in affected:
affected.add(child); frontier.append(child)
exposures = json.load(open("exposures.json"))
hit = [{"name": e["name"], "owner": e["owner"], "columns": sorted(set(e["columns"]) & affected)} for e in exposures]
hit = [h for h in hit if h["columns"]]
models_hit = sorted({a.split(".")[1] for a in affected})
verdict = "BREAKS_EXPOSURE" if hit else ("MODELS_TO_UPDATE" if affected else "SAFE")
lines = [f"# Impact of changing `{change}`", "", f"Verdict: **{verdict}**", "",
f"Downstream columns ({len(affected)}): " + (", ".join(f"`{a}`" for a in sorted(affected)) or "none"), "",
f"Models used in a filter, join or group by: " + (", ".join(sorted(broken_models)) or "none"), "",
"Exposures: " + ("; ".join(f"{h['name']} ({h['owner']}) via {', '.join(h['columns'])}" for h in hit) or "none")]
open("impact.md", "w").write("\n".join(lines) + "\n")
print("\n".join(lines))
print("::" + json.dumps({"outputs": {
"verdict": verdict, "affected_count": len(affected), "affected": ", ".join(sorted(affected)),
"models": ", ".join(models_hit), "filter_models": ", ".join(sorted(broken_models)),
"exposures": "; ".join(f"{h['name']} ({h['owner']})" for h in hit)}}) + "::")
- id: publish_impact
type: io.kestra.plugin.core.namespace.UploadFiles
namespace: "{{ flow.namespace }}"
filesMap:
"schema-changes/{{ (trigger.body.column ?? inputs.column_change) | replace({'.': '_'}) }}.md": "{{ outputs.analyze.outputFiles['impact.md'] }}"
- id: decision
type: io.kestra.plugin.core.flow.Switch
value: "{{ outputs.analyze.vars.verdict }}"
cases:
SAFE:
- id: approve
type: io.kestra.plugin.core.log.Log
message: "Nothing downstream reads {{ trigger.body.column ??
inputs.column_change }}. The change is safe."
MODELS_TO_UPDATE:
- id: list_work
type: io.kestra.plugin.core.log.Log
level: WARN
message: "No exposure breaks, but these models must change in the same release:
{{ outputs.analyze.vars.models }} ({{
outputs.analyze.vars.affected_count }} columns: {{
outputs.analyze.vars.affected }})."
defaults:
- id: block_change
type: io.kestra.plugin.core.execution.Fail
description: An exposure reads an affected column, so its owner must agree
before the change ships.
errorMessage: "Changing {{ trigger.body.column ?? inputs.column_change }} breaks
{{ outputs.analyze.vars.exposures }}. Affected: {{
outputs.analyze.vars.affected }}. Models used in a filter or join: {{
outputs.analyze.vars.filter_models }}."
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
runIf: '{{ inputs.notify_slack }}'
description: A blocked change or an analysis that could not run must reach the
people who own the dashboards.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'SQL column impact analysis failed for ' ~ (trigger.body.column ?? inputs.column_change) ~ ' (execution ' ~ execution.id ~ '). The change breaks an exposure or the analysis did not finish: check the execution logs.'} | toJson }}