id: atlas-database-schema-migration-safety-gate
namespace: company.database
description: |
Pre-deployment database migration safety gate powered by Ariga Atlas. Clones SQL migration
repositories, performs dry-run AST simulation against an ephemeral dev engine, and halts
deployment upon detecting dropped columns, missing default values, or locking hazards.
inputs:
- id: git_repository_url
type: STRING
displayName: Migration Git Repository URL
description: Remote Git repository containing the versioned SQL migration files
to audit.
required: true
- id: git_branch
type: STRING
displayName: Git Branch
defaults: "main"
description: Branch or reference to check out when cloning the migration repository.
required: true
- id: migrations_dir
type: STRING
displayName: Migrations Directory Path
defaults: "migrations"
description: Relative path within the repository where versioned SQL migration
scripts reside.
required: true
- id: dev_database_url
type: STRING
displayName: Dev Database URL
defaults: "sqlite://ci?mode=memory&cache=shared"
description: Connection URL of the ephemeral dev database used by Atlas to
dry-run migrations and extract schema AST diffs (e.g. SQLite in-memory or
a Dockerized staging instance).
required: true
- id: latest_migrations_count
type: INT
displayName: Latest Migrations to Lint
defaults: 5
description: Number of recent migration files to lint against the schema baseline.
- id: allow_destructive_changes
type: BOOL
displayName: Allow Destructive Changes
defaults: false
description: When false, any destructive change (dropped tables, dropped
columns, incompatible type conversions, or non-null additions without
defaults) fails the gate. When true, destructive mutations proceed with
explicit Slack audit warnings.
- id: slack_channel
type: STRING
displayName: Slack Notification Channel
defaults: "#database-deployments"
description: Destination Slack channel for migration review notifications and
incident alerts.
triggers:
- id: pull_request_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Webhook endpoint called by GitHub Actions or GitLab CI on pull
request creation or update to evaluate pending database migrations.
key: "{{ secret('ATLAS_GATE_WEBHOOK_KEY') }}"
disabled: true
inputs:
git_repository_url: replace-with-your-git-repository-url
tasks:
- id: clone_and_lint_migrations
type: io.kestra.plugin.core.flow.WorkingDirectory
description: Clones the versioned migration repository into an isolated
workspace and runs Atlas migration linting against the dev database.
tasks:
- id: clone_migration_repository
type: io.kestra.plugin.git.Clone
description: Checks out the target migration repository branch.
url: "{{ inputs.git_repository_url }}"
branch: "{{ inputs.git_branch }}"
- id: run_atlas_lint
type: io.kestra.plugin.scripts.shell.Commands
description: Executes Atlas migrate lint to detect destructive DDL, lock
hazards, and data-dependent migration risks.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: arigaio/atlas:latest-alpine
outputFiles:
- atlas-lint-report.json
commands:
- |
atlas migrate lint \
--dir "file://{{ inputs.migrations_dir }}" \
--dev-url "{{ inputs.dev_database_url }}" \
--latest {{ inputs.latest_migrations_count }} \
--format {% raw %}'{{ json . }}'{% endraw %} > atlas-lint-report.json || true
if [ ! -s atlas-lint-report.json ]; then
echo '[]' > atlas-lint-report.json
fi
- id: evaluate_migration_safety
type: io.kestra.plugin.scripts.python.Script
description: Parses Atlas linting diagnostics, categorizes destructive mutations
versus concurrency lock hazards, and computes the deployment gate verdict.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.11-slim
beforeCommands:
- pip install --no-cache-dir kestra
env:
ALLOW_DESTRUCTIVE: "{{ inputs.allow_destructive_changes }}"
script: |
import json
import os
from kestra import Kestra
allow_destructive = os.environ.get("ALLOW_DESTRUCTIVE", "false").lower() == "true"
report_path = "atlas-lint-report.json"
raw_reports = []
if os.path.exists(report_path):
with open(report_path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
if isinstance(data, list):
raw_reports = data
elif isinstance(data, dict):
raw_reports = data.get("Files", data.get("Reports", [data]))
except Exception as exc:
print(f"Error parsing Atlas JSON output: {exc}")
DESTRUCTIVE_CODES = {
"DS101", # Schema was dropped
"DS102", # Table was dropped
"DS103", # Non-virtual column was dropped
"MF103", # Adding a non-nullable column without a default (dialect-agnostic)
"MY101", # Adding a non-nullable column without a DEFAULT (MySQL)
"MY130", # Column type change requires a table copy (MySQL)
"PG301", # Column type/collation change requires a table or index rewrite (Postgres)
}
CONCURRENCY_CODES = {
"PG101", # Missing CONCURRENTLY in index creation
"PG102", # Missing CONCURRENTLY in index deletion
"PG104", # PRIMARY KEY constraint acquires an ACCESS EXCLUSIVE lock
"PG105", # UNIQUE constraint acquires an ACCESS EXCLUSIVE lock
"PG312", # Redefining a primary key holds an ACCESS EXCLUSIVE lock
"MY132", # Adding a primary key requires a table rebuild (MySQL)
"MY137", # Modifying the primary key rebuilds the table and secondary indexes (MySQL)
"MY147", # Changing column nullability requires a table rebuild (MySQL)
}
destructive_findings = []
concurrency_findings = []
all_diagnostics = []
for item in raw_reports:
file_name = item.get("Name", item.get("File", "migration.sql"))
reports = item.get("Reports", [])
for rep in reports:
diagnostics = rep.get("Diagnostics", [])
for diag in diagnostics:
code = diag.get("Code", "UNKNOWN")
text = diag.get("Text", "Diagnostic message")
finding = {
"file": file_name,
"code": code,
"message": text,
"pos": diag.get("Pos", 0),
}
all_diagnostics.append(finding)
if code in DESTRUCTIVE_CODES or "drop" in text.lower():
destructive_findings.append(finding)
elif code in CONCURRENCY_CODES or "lock" in text.lower() or "concurrent" in text.lower():
concurrency_findings.append(finding)
destructive_count = len(destructive_findings)
concurrency_count = len(concurrency_findings)
total_count = len(all_diagnostics)
if destructive_count > 0 and not allow_destructive:
verdict = "DESTRUCTIVE_SCHEMA_MUTATION"
summary = f"Database Gate Blocked: {destructive_count} destructive schema change(s) detected (dropped tables/columns or unbackfilled non-null columns)."
elif concurrency_count > 0:
verdict = "CONCURRENCY_LOCK_HAZARD"
summary = f"Database Gate Warning: {concurrency_count} locking or non-concurrent index operation(s) detected."
else:
verdict = "MIGRATION_APPROVED"
summary = f"Migration Gate Passed: {len(raw_reports)} file(s) evaluated against baseline schema with 0 blocking hazards."
print(f"Verdict: {verdict}")
print(f"Summary: {summary}")
print(f"Destructive Findings: {destructive_count}")
print(f"Concurrency Hazards: {concurrency_count}")
Kestra.outputs({
"verdict": verdict,
"summary": summary,
"evaluated_files_count": len(raw_reports),
"total_diagnostics_count": total_count,
"destructive_count": destructive_count,
"concurrency_count": concurrency_count,
"destructive_findings": destructive_findings,
"concurrency_findings": concurrency_findings,
})
- id: route_migration_verdict
type: io.kestra.plugin.core.flow.Switch
description: Evaluates the migration safety verdict and routes the deployment
pipeline accordingly.
value: "{{ outputs.evaluate_migration_safety.vars.verdict }}"
cases:
DESTRUCTIVE_SCHEMA_MUTATION:
- id: alert_destructive_mutation
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches high-priority alert to database operations channel
detailing destructive schema risks.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "CRITICAL: Database Migration Blocked by Destructive Change Gate",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Atlas Migration Safety Gate Failure"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Verdict:* `DESTRUCTIVE_SCHEMA_MUTATION`\n*Destructive Violations:* `{{ outputs.evaluate_migration_safety.vars.destructive_count }}`\n*Execution ID:* `{{ execution.id }}`\n*Summary:* {{ outputs.evaluate_migration_safety.vars.summary }}"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Action Required:* Review migration script. Ensure non-null columns include default values and table/column drops follow a two-phase deprecation window. Set `allow_destructive_changes: true` only if approved by DBA lead."
}
}
]
}
- id: fail_destructive_gate
type: io.kestra.plugin.core.execution.Fail
description: Halts workflow and fails execution to prevent unsafe GitOps
database rollout.
errorMessage: "Deployment blocked: {{
outputs.evaluate_migration_safety.vars.destructive_count }}
destructive database schema changes detected by Atlas."
CONCURRENCY_LOCK_HAZARD:
- id: alert_concurrency_hazard
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Sends warning notification regarding non-concurrent indexing or
exclusive lock hazards.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "WARNING: Database Migration Concurrency Lock Hazard",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Database Migration Concurrency Lock Hazard"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Verdict:* `CONCURRENCY_LOCK_HAZARD`\n*Lock Hazards:* `{{ outputs.evaluate_migration_safety.vars.concurrency_count }}`\n*Execution ID:* `{{ execution.id }}`\n*Summary:* {{ outputs.evaluate_migration_safety.vars.summary }}"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Recommendation:* For Postgres, add `CONCURRENTLY` to `CREATE INDEX`/`DROP INDEX` and avoid constraint builds that take an ACCESS EXCLUSIVE lock. For MySQL, expect a table rebuild for primary key or nullability changes. Execute during off-peak maintenance hours to avoid table write starvation."
}
}
]
}
- id: fail_concurrency_gate
type: io.kestra.plugin.core.execution.Fail
description: Halts workflow to prevent table locks on high-throughput production
databases.
errorMessage: "Deployment blocked: {{
outputs.evaluate_migration_safety.vars.concurrency_count }}
concurrency lock hazards detected by Atlas."
MIGRATION_APPROVED:
- id: log_migration_approval
type: io.kestra.plugin.core.log.Log
description: Records verified migration approval audit log.
message: |
================================================================================
ATLAS MIGRATION SAFETY GATE: APPROVED
================================================================================
Execution ID: {{ execution.id }}
Files Evaluated: {{ outputs.evaluate_migration_safety.vars.evaluated_files_count }}
Total Diagnostics: {{ outputs.evaluate_migration_safety.vars.total_diagnostics_count }}
Destructive Findings: {{ outputs.evaluate_migration_safety.vars.destructive_count }}
Concurrency Hazards: {{ outputs.evaluate_migration_safety.vars.concurrency_count }}
Verdict: {{ outputs.evaluate_migration_safety.vars.verdict }}
Status: Approved for staging / production deployment.
================================================================================