python
# schema-change-approval-bot.py
#
# A GitHub webhook-based bot for approving schema changes.
# Features:
# - Impact analysis: Parses PR diffs for SQL schema changes (ALTER, CREATE, DROP).
# - Reviewers: Auto-assigns reviewers based on change severity (low/medium/high).
# - Rollout windows: Enforces deployment only during specified windows via a status check.
#
# Setup:
# 1. Create a GitHub repo for your schemas (e.g., repo-name: "team/schema").
# 2. Propose changes via PRs with SQL files (e.g., schema.sql diffs).
# 3. Set up GitHub webhook: Payload URL = https://your-server/webhook, Events: Pull requests.
# 4. Set env vars: GITHUB_TOKEN (repo scoped), REVIEWERS_LOW/MED/HIGH (comma-separated GitHub usernames),
# ROLLOUT_WINDOWS (JSON: '[{"days":["mon","tue"],"start":"02:00","end":"04:00"}]').
# 5. Run: python schema-change-approval-bot.py
# 6. For rollout: Call /rollout-check?owner=team&repo=schema&sha=<commit-sha>&pr=<pr-number>
# (e.g., from CI/CD pipeline).
#
# Limitations: Basic SQL parsing (regex-based). Extend for your SQL dialect (MySQL/Postgres/etc.).
# Assumes schema changes in files like *.sql.
import os
import re
import json
from datetime import datetime
from flask import Flask, request, jsonify, abort
from github import Github, GithubException
from github.CheckRun import CheckRun
from github.PullRequest import PullRequest
app = Flask(__name__)
# Config (override with env vars)
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
if not GITHUB_TOKEN:
raise ValueError("Set GITHUB_TOKEN env var")
gh = Github(GITHUB_TOKEN)
REVIEWERS_LOW = os.getenv('REVIEWERS_LOW', 'dev1,dev2').split(',')
REVIEWERS_MED = os.getenv('REVIEWERS_MED', 'dev-lead,dba-junior').split(',')
REVIEWERS_HIGH = os.getenv('REVIEWERS_HIGH', 'db-lead,eng-manager,security').split(',')
REVIEWERS = {
'low': REVIEWERS_LOW,
'medium': REVIEWERS_MED,
'high': REVIEWERS_HIGH
}
ROLLOUT_WINDOWS_JSON = os.getenv(
'ROLLOUT_WINDOWS',
'[{"days":["mon","tue","wed","thu","fri"],"start":"02:00","end":"04:00"}]'
)
ROLLOUT_WINDOWS = json.loads(ROLLOUT_WINDOWS_JSON)
# SQL impact patterns (extend as needed)
IMPACT_PATTERNS = {
'breaking': [
r'ALTER TABLE\s+\w+\s+DROP\s+COLUMN', # Drop column
r'ALTER TABLE\s+\w+\s+DROP\s+TABLE', # Drop table (rare in ALTER)
r'ALTER TABLE\s+\w+\s+CHANGE\s+\w+\s+\w+\s+(\w+(?:\s+\w+)*)\s', # Type narrowing (simplistic)
r'DROP\s+INDEX', r'DROP\s+CONSTRAINT' # Drops
],
'potentially_breaking': [
r'ALTER TABLE\s+\w+\s+MODIFY\s+COLUMN', # Type changes
r'RENAME\s+COLUMN', r'RENAME\s+TABLE',
r'ADD\s+CONSTRAINT' # New constraints may fail data
],
'safe': [
r'CREATE\s+INDEX', r'ADD\s+COLUMN', r'CREATE\s+TABLE' # Additions
]
}
def parse_impact(diff):
"""Parse GitHub PR diff for schema changes."""
impacts = {'breaking': [], 'potentially_breaking': [], 'safe': []}
diff_lower = diff.lower()
for category, patterns in IMPACT_PATTERNS.items():
for pattern in patterns:
matches = re.findall(pattern, diff_lower, re.IGNORECASE | re.MULTILINE)
impacts[category].extend(matches)
return impacts
def get_severity(impacts):
"""Determine severity from impacts."""
if impacts['breaking']:
return 'high'
elif impacts['potentially_breaking']:
return 'medium'
elif impacts['safe']:
return 'low'
return 'none'
def get_day_name():
"""Get current UTC day (mon-sun)."""
return datetime.utcnow().strftime('%a').lower()
def is_rollout_window():
"""Check if current UTC time is in a rollout window."""
now = datetime.utcnow()
day = get_day_name()
hour_min = now.strftime('%H:%M')
for window in ROLLOUT_WINDOWS:
if day in window['days'] and window['start'] <= hour_min <= window['end']:
return True
return False
def post_comment(repo_full_name, pr_number, message):
"""Post comment on PR."""
try:
repo = gh.get_repo(repo_full_name)
pr = repo.get_pull(pr_number)
pr.create_issue_comment(message)
except GithubException as e:
app.logger.error(f"Failed to post comment: {e}")
def request_reviews(repo_full_name, pr_number, reviewers):
"""Request reviews from users."""
try:
repo = gh.get_repo(repo_full_name)
pr = repo.get_pull(pr_number)
users = [gh.get_user(r.strip()) for r in reviewers if r.strip()]
pr.create_review_request(reviewers=users)
except GithubException as e:
app.logger.error(f"Failed to request reviews: {e}")
def create_check(repo_full_name, sha, name, conclusion, output):
"""Create/update GitHub check run."""
try:
repo = gh.get_repo(repo_full_name)
check_runs = repo.get_check_runs(head_sha=sha)
# Update last run or create new
for run in check_runs:
if run.name == name:
run.edit(output={'title': name, 'summary': output['summary'], 'text': output['text']},
conclusion=conclusion)
return
repo.create_check_run(name=name, head_sha=sha, status='completed',
conclusion=conclusion, output=output)
except GithubException as e:
app.logger.error(f"Failed to create check: {e}")
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
event = request.headers.get('X-GitHub-Event')
if event == 'pull_request' and data['action'] in ['opened', 'synchronize', 'reopened']:
pr = data['pull_request']
repo_full_name = pr['base']['repo']['full_name']
pr_number = pr['number']
head_sha = pr['head']['sha']
# Fetch full diff
repo = gh.get_repo(repo_full_name)
pull = repo.get_pull(pr_number)
diff = pull.get_files() # Get changed files
diff_content = '\n'.join([f.file_to_patch() for f in pull.get_files() if f.filename.endswith('.sql')])
if not diff_content:
post_comment(repo_full_name, pr_number, "No SQL schema changes detected. Skipping analysis.")
return jsonify({'status': 'ok'})
impacts = parse_impact(diff_content)
severity = get_severity(impacts)
summary = f"### Schema Impact Analysis\n**Severity:** {severity}\n\n"
summary += "**Breaking:** " + ', '.join(impacts['breaking']) + '\n'
summary += "**Potentially Breaking:** " + ', '.join(impacts['potentially_breaking']) + '\n'
summary += "**Safe:** " + ', '.join(impacts['safe']) + '\n'
summary += f"**Reviewers Assigned:** {', '.join(REVIEWERS[severity])}\n"
summary += "**Rollout:** Only during windows (check /rollout-check in CI)."
post_comment(repo_full_name, pr_number, summary)
# Auto-request reviewers
request_reviews(repo_full_name, pr_number, REVIEWERS[severity])
# Impact check
conclusion = 'success' if severity != 'high' else 'failure' if impacts['breaking'] else 'neutral'
create_check(repo_full_name, head_sha, 'schema-impact', conclusion,
{'title': 'Schema Impact', 'summary': severity, 'text': summary})
elif event == 'pull_request_review' and data['action'] == 'submitted':
# Optional: Auto-merge on approvals (add logic if needed)
pass
return jsonify({'status': 'ok'})
@app.route('/rollout-check')
def rollout_check():
owner = request.args.get('owner')
repo_name = request.args.get('repo')
sha = request.args.get('sha')
pr_number = request.args.get('pr', type=int)
repo_full_name = f"{owner}/{repo_name}"
in_window = is_rollout_window()
now_str = datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC (%a)')
summary = f"Rollout Window Check: {'✅ APPROVED' if in_window else '❌ DENIED'}\n"
summary += f"Current time: {now_str}\n"
if not in_window:
summary += "Deploy only during configured windows.\n"
summary += f"Windows: {json.dumps(ROLLOUT_WINDOWS, indent=2)}"
conclusion = 'success' if in_window else 'failure'
create_check(repo_full_name, sha, 'rollout-window', conclusion,
{'title': 'Rollout Window', 'summary': 'Approved' if in_window else 'Outside Window',
'text': summary})
if pr_number:
post_comment(repo_full_name, pr_number, summary)
return jsonify({'approved': in_window, 'summary': summary})
@app.route('/health')
def health():
return jsonify({'status': 'healthy'})
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=False)
This bot enforces safe schema changes end-to-end. Test with sample PRs! 🚀