database-migration — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited database-migration (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
Database migrations are high-risk operations that can cause data loss, service outages, and inconsistencies. Rushed migrations fail; systematic migrations succeed.
Core principle: ALWAYS have a tested rollback plan before executing any migration. No migration is too small for planning.
Violating the letter of this process is violating the spirit of database migration safety.
Use this when urgent schema change needed. Don't think, follow the list.
| Minute | Action | Output |
|---|---|---|
| 0-1 | Identify what needs to change and why | change_classified |
| 1-2 | Check if change is reversible | rollback_possible or requires_planning |
| 2-3 | Estimate rows affected and lock impact | impact_assessed |
| 3-4 | Create backup of affected tables | backup_verified |
| 4-5 | If >1M rows or DDL lock: STOP, use full process | proceed or escalate |
After 5 minutes: Proceed to Phase 2 (Plan) if safe, otherwise follow full process.
NO MIGRATION WITHOUT A TESTED ROLLBACK PLAN FIRSTIf you haven't verified you can undo the change, you cannot execute the migration.
Use for ANY database change:
Use this ESPECIALLY when:
Don't skip when:
This skill is for systematic database migrations. Don't use it for:
Key distinction: This skill manages schema and data changes in systems with existing data. For new projects without data, standard migration tools suffice.
You MUST complete each phase before proceeding to the next.
digraph database_migration {
rankdir=TB;
node [shape=box];
"1. Assess" -> "2. Plan";
"2. Plan" -> "3. Prepare";
"3. Prepare" -> "4. Execute";
"4. Execute" -> "5. Verify";
"5. Verify" -> "6. Document";
"Skip Phase?" [shape=diamond];
"2. Plan" -> "Skip Phase?" [style=dashed, label="tempted?"];
"Skip Phase?" -> "STOP" [label="NO"];
"STOP" [shape=doublecircle, color=red];
}Classify the migration:
SELECT COUNT(*) FROM table| Risk | Criteria | Approach |
|---|---|---|
| Low | <100K rows, additive only, nullable | Direct migration |
| Medium | 100K-10M rows, non-destructive | Batched migration |
| High | >10M rows, schema + data | Expand-Contract |
| Critical | Destructive, FK changes | Blue-Green or Shadow |
Completion criteria:
migration_type_identified - DDL/DML/Combined/Destructiverisk_level_classified - Low/Medium/High/Criticalimpact_measured - Row count, lock estimateDesign the migration strategy:
See expand-contract-patterns.md for zero-downtime techniques.
| Pattern | Use When | Downtime |
|---|---|---|
| Direct | Low risk, off-peak | Brief |
| Batched | Medium risk, large tables | None |
| Expand-Contract | High risk, zero-downtime required | None |
| Blue-Green | Critical, full schema redesign | Switchover only |
| Shadow Table | Type changes, column renames | Cutover only |
See rollback-strategies.md for detailed procedures.
| Change Type | Rollback Approach |
|---|---|
| ADD COLUMN (nullable) | DROP COLUMN |
| ADD COLUMN (not null) | Restore from backup or dual-write |
| DROP COLUMN | Restore from backup (data loss!) |
| ADD INDEX | DROP INDEX |
| MODIFY TYPE (widening) | No action needed |
| MODIFY TYPE (narrowing) | Restore from backup |
| ADD FK | DROP FK |
| DROP FK | Re-add FK (verify data integrity) |
Completion criteria:
pattern_selected - Migration pattern chosenrollback_designed - Rollback procedure documentedscript_created - Migration script with UP/DOWNSet up for safe execution:
See validation-procedures.md for integrity checks.
-- Example validation queries
-- Verify row count
SELECT COUNT(*) as pre_count FROM target_table;
-- Verify data integrity
SELECT COUNT(*) as orphans
FROM child_table c
LEFT JOIN parent_table p ON c.parent_id = p.id
WHERE p.id IS NULL;
-- Verify constraints
SELECT constraint_name, constraint_type
FROM information_schema.table_constraints
WHERE table_name = 'target_table';Completion criteria:
backup_created - Backup verified restorablemonitoring_active - Dashboards and alerts readypre_validation_passed - All integrity checks greenrollback_tested - Rollback verified in stagingRun the migration:
See large-scale-migration.md for batch processing.
For batched migrations:
-- Example batch processing
DO $$
DECLARE
batch_size INT := 10000;
total_rows INT;
processed INT := 0;
BEGIN
SELECT COUNT(*) INTO total_rows FROM target_table WHERE condition;
WHILE processed < total_rows LOOP
UPDATE target_table
SET new_column = transform(old_column)
WHERE id IN (
SELECT id FROM target_table
WHERE condition AND new_column IS NULL
LIMIT batch_size
);
processed := processed + batch_size;
RAISE NOTICE 'Processed % of % rows', processed, total_rows;
-- Brief pause to reduce lock contention
PERFORM pg_sleep(0.1);
END LOOP;
END $$;Completion criteria:
migration_executed - All changes appliedno_abort_triggered - Execution completed without abortstakeholders_notified - Team informed of completionConfirm migration success:
-- Verify row count matches expectation
SELECT COUNT(*) as post_count FROM target_table;
-- Verify data transformation
SELECT COUNT(*) as failed_transforms
FROM target_table
WHERE new_column IS NULL AND old_column IS NOT NULL;
-- Verify referential integrity
SELECT COUNT(*) as broken_refs
FROM child_table c
LEFT JOIN parent_table p ON c.parent_id = p.id
WHERE p.id IS NULL;Completion criteria:
post_validation_passed - All integrity checks greenapplication_healthy - Critical paths workingmetrics_verified - Pre/post comparison acceptableThe migration is NOT complete until documented:
Completion criteria:
changelog_updated - Migration documentedschema_docs_updated - Documentation currentticket_closed - Migration ticket resolvedcleanup_scheduled - Follow-up tasks createdIf you catch yourself thinking:
ALL of these mean: STOP. Return to Phase 2.
| Excuse | Reality |
|---|---|
| "It's just a nullable column" | Nullable columns become NOT NULL. Plan for it. |
| "Table has only 100K rows" | Tables grow. Build habits for when it's 100M. |
| "Staging worked fine" | Production has different data, scale, and traffic patterns. |
| "We can restore from backup" | Backup restore = downtime. Test it, measure it. |
| "It's off-peak hours" | Off-peak is when batch jobs run. Verify traffic patterns. |
| "Migration tool handles rollback" | Tools generate rollback, not verify it. Test manually. |
| "We've done this before" | Past success doesn't guarantee future success. Follow process. |
| "Business is pressuring us" | Outages cost more than delays. Process protects everyone. |
| Phase | Key Activities | Verification Key |
|---|---|---|
| 1. Assess | Type, impact, risk level | risk_level_classified |
| 2. Plan | Pattern, rollback, script | rollback_designed |
| 3. Prepare | Backup, monitoring, test rollback | rollback_tested |
| 4. Execute | Announce, batch, monitor | migration_executed |
| 5. Verify | Validation, health, metrics | post_validation_passed |
| 6. Document | Changelog, schema docs, cleanup | ticket_closed |
| Risk Level | Max Duration | Rollback Window | Required Approvals |
|---|---|---|---|
| Low | 1 hour | 24 hours | 1 reviewer |
| Medium | 4 hours | 72 hours | 2 reviewers |
| High | 1 day | 1 week | Tech lead + DBA |
| Critical | 1 week | 2 weeks | Architecture review |
Database migrations require careful coordination with deployment pipelines.
Always progress: Dev → Staging → Production
| Environment | Purpose | Migration Timing | Approval |
|---|---|---|---|
| Dev | Experiment freely | On commit | None |
| Staging | Verify with prod-like data | Pre-deploy | Auto |
| Production | Real execution | During deploy window | Manual |
Key principle: Migrations that pass staging with production-like data volume succeed in production.
1. Pre-Deploy Migration (Recommended)
# CI/CD pipeline example
stages:
- test
- migrate-staging
- validate-staging
- approve-production
- migrate-production
- deploy-application
- validate-production
migrate-production:
script:
- ./run-migration.sh --env production
- ./validate-migration.sh --env production
when: manual # Require explicit approval
allow_failure: false2. Application-Driven Migration (ORM Tools)
# For ORM-managed migrations (Prisma, TypeORM, Django, Rails)
deploy-production:
script:
# Backup before ORM migration
- ./backup-database.sh
# Run ORM migration with timeout
- timeout 30m npx prisma migrate deploy
# Validate after migration
- ./validate-schema.sh
on_failure:
- ./alert-oncall.sh "Migration failed"| Tool | Migration Command | Rollback Command | Notes |
|---|---|---|---|
| Prisma | prisma migrate deploy | Manual or prisma migrate reset | No auto-rollback in prod |
| TypeORM | typeorm migration:run | typeorm migration:revert | Revert runs DOWN method |
| Django | python manage.py migrate | python manage.py migrate app 00XX | Specify target migration |
| Rails | rails db:migrate | rails db:rollback STEP=1 | STEP controls rollback depth |
| Flyway | flyway migrate | flyway undo (Teams only) | Undo requires paid version |
| Liquibase | liquibase update | liquibase rollback | Requires rollback tags |
ORM Best Practices:
--dry-run or --preview)digraph deployment_window {
rankdir=LR;
node [shape=box];
"Announce Window" -> "Run Pre-checks";
"Run Pre-checks" -> "Execute Migration";
"Execute Migration" -> "Verify Success";
"Verify Success" -> "Deploy App" [label="pass"];
"Verify Success" -> "Rollback" [label="fail"];
"Deploy App" -> "Close Window";
"Rollback" -> "Close Window";
}Checklist for deployment windows:
# Example: environment-specific migration config
migration:
dev:
batch_size: 50000 # Faster iteration
pause_between: 10ms
timeout: 10m
require_rollback_test: false
staging:
batch_size: 10000 # Match production settings
pause_between: 100ms
timeout: 30m
require_rollback_test: true
production:
batch_size: 5000 # Conservative
pause_between: 200ms
timeout: 60m
require_rollback_test: true
require_manual_approval: trueThese files provide detailed guidance for specific phases:
From database migration data:
~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.