id: database-migration-safety-gate
namespace: company.team
description: |
Review and safely apply database migrations by detecting destructive operations,
compatibility risks, and missing rollback plans. Low- and medium-risk migrations
are applied automatically, while high-risk migrations require explicit human
approval before any database changes are made.
inputs:
- id: migration_name
type: STRING
displayName: Migration name
defaults: add_customer_phone
description: Identifier, ticket name, or change name for the database migration.
- id: migration_sql
type: STRING
displayName: Migration SQL
defaults: |
ALTER TABLE customers ADD COLUMN phone VARCHAR;
description: SQL migration statement to inspect and apply.
- id: rollback_sql
type: STRING
displayName: Rollback SQL
defaults: |
ALTER TABLE customers DROP COLUMN phone;
description: |
SQL statement that can reverse the migration. Leave empty to add a
missing-rollback risk to the migration score.
- id: min_high_risk_score
type: INT
displayName: High-risk score threshold
defaults: 4
description: |
Risk score at or above this value requires human approval before
the migration can be applied.
tasks:
- id: prepare_demo_database
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
Initializes an embedded DuckDB database with a demo customer schema
that can be modified by the migration.
url: jdbc:duckdb:/tmp/kestra-migration-safety-gate.duckdb
fetchType: NONE
sql: |
CREATE OR REPLACE TABLE customers (
id INTEGER,
name VARCHAR,
email VARCHAR,
created_at TIMESTAMP
);
DELETE FROM customers;
INSERT INTO customers VALUES
(1, 'Alice', 'alice@example.com', CURRENT_TIMESTAMP),
(2, 'Bob', 'bob@example.com', CURRENT_TIMESTAMP);
CREATE OR REPLACE TABLE orders (
id INTEGER,
customer_id INTEGER,
amount DECIMAL(10, 2)
);
- id: migration_checks
type: io.kestra.plugin.core.flow.Parallel
description: |
Runs independent migration safety checks in parallel for destructive
operations, compatibility risks, and rollback availability.
tasks:
- id: destructive_change_check
type: io.kestra.plugin.scripts.python.Script
description: |
Detects SQL operations that can permanently remove database
structures or data.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
migration.sql: "{{ inputs.migration_sql }}"
script: |
import json
import re
with open("migration.sql", "r") as f:
sql = f.read().upper()
patterns = {
"DROP TABLE": r"\bDROP\s+TABLE\b",
"DROP COLUMN": r"\bDROP\s+COLUMN\b",
"TRUNCATE": r"\bTRUNCATE\b",
"DELETE": r"\bDELETE\s+FROM\b",
}
findings = [
name
for name, pattern in patterns.items()
if re.search(pattern, sql)
]
is_destructive = len(findings) > 0
if findings:
finding_summary = ", ".join(findings)
else:
finding_summary = "No destructive operations detected"
print("Destructive change check:")
print(f"Destructive: {is_destructive}")
print(f"Findings: {finding_summary}")
print("::" + json.dumps({
"outputs": {
"is_destructive": is_destructive,
"finding_summary": finding_summary
}
}) + "::")
- id: compatibility_check
type: io.kestra.plugin.scripts.python.Script
description: |
Detects schema modifications that may introduce compatibility
or migration-time risks.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
migration.sql: "{{ inputs.migration_sql }}"
script: |
import json
import re
with open("migration.sql", "r") as f:
sql = f.read().upper()
findings = []
if re.search(
r"\bALTER\s+TABLE\b.*\bALTER\s+COLUMN\b.*\bTYPE\b",
sql,
re.DOTALL
):
findings.append("column type change")
if re.search(
r"\bALTER\s+TABLE\b.*\bSET\s+NOT\s+NULL\b",
sql,
re.DOTALL
):
findings.append("NOT NULL constraint addition")
if re.search(
r"\bALTER\s+TABLE\b.*\bADD\s+CONSTRAINT\b",
sql,
re.DOTALL
):
findings.append("new table constraint")
if re.search(
r"\bCREATE\s+INDEX\b",
sql,
re.DOTALL
):
findings.append("index creation")
has_compat_risk = len(findings) > 0
if findings:
finding_summary = ", ".join(findings)
else:
finding_summary = "No compatibility risks detected"
print("Compatibility check:")
print(f"Compatibility risk: {has_compat_risk}")
print(f"Findings: {finding_summary}")
print("::" + json.dumps({
"outputs": {
"has_compat_risk": has_compat_risk,
"finding_summary": finding_summary
}
}) + "::")
- id: rollback_check
type: io.kestra.plugin.scripts.python.Script
description: |
Checks whether a rollback migration has been supplied.
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
rollback.sql: "{{ inputs.rollback_sql }}"
script: |
import json
with open("rollback.sql", "r") as f:
rollback = f.read().strip()
has_rollback = len(rollback) > 0
if has_rollback:
message = "Rollback SQL provided"
else:
message = "Missing rollback SQL"
print(f"Rollback check: {message}")
print("::" + json.dumps({
"outputs": {
"has_rollback": has_rollback,
"message": message
}
}) + "::")
- id: risk_assessment
type: io.kestra.plugin.scripts.python.Script
description: |
Aggregates the parallel safety checks into a transparent weighted
risk score and classifies the migration as LOW, MEDIUM, or HIGH.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
IS_DESTRUCTIVE: "{{ outputs.destructive_change_check.vars.is_destructive }}"
DESTRUCTIVE_FINDINGS: "{{ outputs.destructive_change_check.vars.finding_summary }}"
HAS_COMPAT_RISK: "{{ outputs.compatibility_check.vars.has_compat_risk }}"
COMPAT_FINDINGS: "{{ outputs.compatibility_check.vars.finding_summary }}"
HAS_ROLLBACK: "{{ outputs.rollback_check.vars.has_rollback }}"
ROLLBACK_MESSAGE: "{{ outputs.rollback_check.vars.message }}"
MIN_HIGH_RISK_SCORE: "{{ inputs.min_high_risk_score }}"
MIGRATION_NAME: "{{ inputs.migration_name }}"
script: |
import json
import os
is_destructive = (
os.environ.get("IS_DESTRUCTIVE", "false").lower() == "true"
)
destructive_findings = os.environ.get(
"DESTRUCTIVE_FINDINGS",
"No destructive operations detected"
)
has_compat_risk = (
os.environ.get("HAS_COMPAT_RISK", "false").lower() == "true"
)
compat_findings = os.environ.get(
"COMPAT_FINDINGS",
"No compatibility risks detected"
)
has_rollback = (
os.environ.get("HAS_ROLLBACK", "false").lower() == "true"
)
rollback_message = os.environ.get(
"ROLLBACK_MESSAGE",
"Rollback status unavailable"
)
high_threshold = int(
os.environ.get("MIN_HIGH_RISK_SCORE", "4")
)
migration_name = os.environ.get(
"MIGRATION_NAME",
""
)
score = 0
findings = []
if is_destructive:
score += 4
findings.append(
f"Destructive operation: {destructive_findings}"
)
if has_compat_risk:
score += 2
findings.append(
f"Compatibility risk: {compat_findings}"
)
if not has_rollback:
score += 1
findings.append(
"No rollback migration supplied"
)
if score >= high_threshold:
risk_level = "HIGH"
elif score >= 2:
risk_level = "MEDIUM"
else:
risk_level = "LOW"
if not findings:
findings.append("No significant migration risks detected")
finding_summary = "\n".join(
f"- {finding}"
for finding in findings
)
print(f"Migration: {migration_name}")
print(f"Calculated Score: {score}")
print(f"Risk Level: {risk_level}")
print("Findings:")
print(finding_summary)
print("::" + json.dumps({
"outputs": {
"risk_score": score,
"risk_level": risk_level,
"finding_summary": finding_summary
}
}) + "::")
- id: route_migration
type: io.kestra.plugin.core.flow.If
description: |
Automatically applies low- and medium-risk migrations while routing
high-risk migrations through an interactive approval gate.
condition: "{{ outputs.risk_assessment.vars.risk_level == 'HIGH' }}"
then:
- id: log_high_risk_warning
type: io.kestra.plugin.core.log.Log
description: |
Logs the migration risk and explains why human approval is required.
message: |
HIGH-RISK MIGRATION DETECTED
Migration:
{{ inputs.migration_name }}
Risk Level:
{{ outputs.risk_assessment.vars.risk_level }}
Risk Score:
{{ outputs.risk_assessment.vars.risk_score }}
Findings:
{{ outputs.risk_assessment.vars.finding_summary }}
Pausing execution for reviewer sign-off...
- id: human_review
type: io.kestra.plugin.core.flow.Pause
description: |
Pauses the workflow until a reviewer explicitly approves or
rejects the high-risk migration.
onResume:
- id: approved
type: BOOL
displayName: Approve Migration?
description: |
Check this option to authorize execution of the migration.
defaults: false
- id: reviewer_comment
type: STRING
displayName: Reviewer Comment
description: |
Provide the reason, justification, or conditions for the decision.
defaults: ""
- id: check_approval_decision
type: io.kestra.plugin.core.flow.If
description: |
Continues with the migration only when the reviewer explicitly
approved it.
condition: "{{ outputs.human_review.onResume.approved }}"
then:
- id: apply_approved_migration
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
Executes the migration after explicit human approval.
url: jdbc:duckdb:/tmp/kestra-migration-safety-gate.duckdb
fetchType: NONE
sql: |
{{ inputs.migration_sql }}
- id: verify_schema_post_approval
type: io.kestra.plugin.jdbc.duckdb.Query
description: |
Inspects the customer schema after the approved migration.
url: jdbc:duckdb:/tmp/kestra-migration-safety-gate.duckdb
fetchType: FETCH
sql: |
DESCRIBE customers;
- id: log_approval_success
type: io.kestra.plugin.core.log.Log
description: |
Records the successful application of an approved migration.
message: |
Migration '{{ inputs.migration_name }}' APPROVED and APPLIED.
Risk Level:
{{ outputs.risk_assessment.vars.risk_level }}
Risk Score:
{{ outputs.risk_assessment.vars.risk_score }}
Reviewer Notes:
{{ outputs.human_review.onResume.reviewer_comment }}
Schema verification completed successfully.
else:
- id: log_rejection
type: io.kestra.plugin.core.log.Log
description: |
Records the rejection of a high-risk migration without
modifying the database.
message: |
Migration '{{ inputs.migration_name }}' REJECTED by reviewer.
Risk Level:
{{ outputs.risk_assessment.vars.risk_level }}
Risk Score:
{{ outputs.risk_assessment.vars.risk_score }}
Reviewer Notes:
{{ outputs.human_review.onResume.reviewer_comment }}
No database changes were applied.
else:
- id: apply_low_risk_migration
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
Automatically applies a migration that remains below the
high-risk approval threshold.
url: jdbc:duckdb:/tmp/kestra-migration-safety-gate.duckdb
fetchType: NONE
sql: |
{{ inputs.migration_sql }}
- id: verify_schema_after_auto_apply
type: io.kestra.plugin.jdbc.duckdb.Query
description: |
Inspects the customer schema after automatic migration.
url: jdbc:duckdb:/tmp/kestra-migration-safety-gate.duckdb
fetchType: FETCH
sql: |
DESCRIBE customers;
- id: log_auto_applied
type: io.kestra.plugin.core.log.Log
description: |
Records successful automatic application of a low- or
medium-risk migration.
message: |
Migration '{{ inputs.migration_name }}' passed the safety gate.
Risk Level:
{{ outputs.risk_assessment.vars.risk_level }}
Risk Score:
{{ outputs.risk_assessment.vars.risk_score }}
Changes were applied and schema verification completed successfully.
triggers:
- id: daily_migration_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: |
Optional daily migration safety sweep. Disabled by default until
connected to a real migration source.
cron: "0 7 * * *"
disabled: true