Database Migration Validation Golang CI: Schema vs Spec Automatically
Validate database migrations in CI/CD for Go. AI-powered migration SQL review, schema-vs-spec check, breaking-change detection, and a safety gate before deploy.
Database Migration Validation Golang CI: Schema vs Spec
Database migration validation in CI/CD is a mandatory safety net for every Go service that touches a production database. Migration is the riskiest operation in software deployment: a single wrong migration can cause data loss, downtime, or corruption that’s hard to recover from. Even more dangerous, migrations often “run perfectly” in development and staging (an empty database) but hang for hours in production because of a table lock.
In this article we build a layered safety net for Go database migrations: from instant static analysis, to AI-powered lock review, to a dry run in staging — all as gates before deploy.
12.1 Why Migration Validation Matters
The value of validation is clearest from a real incident. The case study below shows how a single, seemingly trivial ALTER TABLE line can freeze production for 45 minutes.
1Sprint 7: Developer A adds a new column to the orders table:
2 ALTER TABLE orders ADD COLUMN metadata JSONB NOT NULL DEFAULT '{}';
3
4 In development: runs perfectly
5 In staging: runs perfectly (empty database)
6 In production: HANGS for 45 minutes
7
8 Why? PostgreSQL cannot add a NOT NULL column
9 to a table with millions of rows without a full table rewrite:
10 → Full table lock during the rewrite
11 → No concurrency during the rewrite
12
13 The correct fix (multi-step):
14 Step 1: ALTER TABLE orders ADD COLUMN metadata JSONB DEFAULT '{}';
15 Step 2: UPDATE orders SET metadata = '{}' WHERE metadata IS NULL; (batched)
16 Step 3: ALTER TABLE orders ALTER COLUMN metadata SET NOT NULL;
17
18 With migration validation in CI:
19 AI flagging: "BLOCKING: NOT NULL without default on large table"
20 → Developer fixes before deploy. Incident avoided.The main lesson: a test on an empty database never measures the actual lock duration. That’s exactly why we need layered validation that deliberately takes production table size into account.
12.2 Three Layers of Migration Review
Instead of a single check, we assemble a layered defense with different cost-vs-depth trade-offs. The summary below maps the three layers along with their costs.
1LAYER 1: Static Pattern Check (instant, zero cost)
2 grep for known dangerous patterns:
3 - NOT NULL without DEFAULT on a possibly-large table
4 - DROP TABLE / DROP COLUMN / TRUNCATE
5 - CREATE INDEX without CONCURRENTLY
6 Cost: Zero
7
8LAYER 2: AI Migration Review (2 seconds, ~$0.002)
9 Claude reviews the migration for:
10 - Lock-heavy operations in production
11 - Missing rollback / data loss potential
12 - Naming convention violations
13 Cost: ~$0.002 per review
14
15LAYER 3: Dry Run (optional, needs a staging DB)
16 Run the migration against a staging database
17 Verify there's no error, measure duration
18 Cost: staging DB computeThe combination of all three closes each other’s gaps: the static check catches known patterns, the AI catches semantic context, and the dry run catches runtime errors. Let’s build from the cheapest layer.
12.3 Layer 1: Static Pattern Check
The first layer must be instant and free. The bash script below greps the migration for known dangerous patterns, separates BLOCKING issues from WARNINGs, and fails CI if any are blocking.
1#!/bin/bash
2# scripts/check-migration-safety.sh
3set -euo pipefail
4
5MIGRATION_FILE="${1}"
6SQL=$(cat "$MIGRATION_FILE")
7ISSUES=()
8WARNINGS=()
9
10# NOT NULL without DEFAULT (lock-heavy)
11if echo "$SQL" | grep -qiE "ADD COLUMN.*NOT NULL" && \
12 ! echo "$SQL" | grep -qiE "ADD COLUMN.*DEFAULT.*NOT NULL|ADD COLUMN.*NOT NULL.*DEFAULT"; then
13 ISSUES+=("BLOCKING: NOT NULL column without DEFAULT — full table rewrite on large tables")
14fi
15
16# DROP TABLE / TRUNCATE (data loss)
17echo "$SQL" | grep -qiE "DROP TABLE(?! IF EXISTS.*CASCADE)" && \
18 ISSUES+=("BLOCKING: DROP TABLE detected — data will be permanently lost")
19echo "$SQL" | grep -qiE "TRUNCATE" && \
20 ISSUES+=("BLOCKING: TRUNCATE will delete ALL data from table")
21
22# DROP COLUMN (verify Go refs)
23echo "$SQL" | grep -qiE "DROP COLUMN" && \
24 WARNINGS+=("WARNING: DROP COLUMN — verify no Go code still references this column")
25
26# CREATE INDEX without CONCURRENTLY (lock)
27echo "$SQL" | grep -qiE "CREATE INDEX(?! CONCURRENTLY)" && \
28 WARNINGS+=("WARNING: CREATE INDEX without CONCURRENTLY — locks table during creation")
29
30# Missing down migration
31DOWN="${MIGRATION_FILE/.up.sql/.down.sql}"
32[ ! -f "$DOWN" ] && WARNINGS+=("WARNING: No down migration found")
33
34PASS=true
35if [ "${#ISSUES[@]}" -gt 0 ]; then
36 echo "❌ BLOCKING ISSUES:"; printf ' - %s\n' "${ISSUES[@]}"; PASS=false
37fi
38[ "${#WARNINGS[@]}" -gt 0 ] && { echo "⚠️ WARNINGS:"; printf ' - %s\n' "${WARNINGS[@]}"; }
39
40[ "$PASS" == "false" ] && { echo "Migration rejected. Fix blocking issues."; exit 1; }
41echo "✅ Static migration check passed"The strength of this layer is speed and zero cost — it catches the most common patterns before a single AI token is spent. But grep doesn’t understand context: it doesn’t know whether orders has millions of rows. That’s where the second layer comes in.
12.4 Layer 2: AI Migration Review
The second layer provides the context grep lacks: table size estimation and semantic understanding. The script below flags known large tables, then asks the AI to analyze locks, data safety, and zero-downtime feasibility.
1#!/bin/bash
2# scripts/ai-migration-review.sh
3set -euo pipefail
4
5MIGRATION_FILE="${1}"
6SQL=$(cat "$MIGRATION_FILE")
7
8# Estimate table size by name (production needs actual stats)
9LARGE_TABLES=("orders" "order_items" "products" "users" "payments")
10AFFECTED=$(echo "$SQL" | grep -ioP '(?:ALTER TABLE|TABLE|UPDATE)\s+\K\w+' | sort -u)
11
12TABLE_SIZE_CONTEXT=""
13for table in $AFFECTED; do
14 if echo "${LARGE_TABLES[@]}" | grep -qw "$table"; then
15 TABLE_SIZE_CONTEXT="$TABLE_SIZE_CONTEXT\n$table: LARGE (millions of rows, production)"
16 else
17 TABLE_SIZE_CONTEXT="$TABLE_SIZE_CONTEXT\n$table: SMALL (new or reference table)"
18 fi
19done
20
21PROMPT="Review this database migration for a production PostgreSQL 15.
22
23ESTIMATED TABLE SIZES:$TABLE_SIZE_CONTEXT
24
25MIGRATION SQL:
26$SQL
27
28Review for:
291. LOCK ANALYSIS — how long is the table lock? blocking vs non-blocking?
302. DATA SAFETY — risk of data loss? NOT NULL without a migration path?
313. ROLLBACK SAFETY — can it be rolled back? implications of the down migration?
324. PRODUCTION SAFETY — safe for zero downtime? need a maintenance window?
33
34Output format:
35VERDICT: SAFE | NEEDS_REVIEW | BLOCKING
36LOCK_RISK: LOW | MEDIUM | HIGH
37DETAILS: [issue]: [explanation + recommendation]
38SAFE_EXECUTION_ORDER (if needed, multi-step): [numbered steps]"
39
40RESULT=$(./scripts/claude-call.sh "$PROMPT" 800)
41echo "$RESULT"
42
43VERDICT=$(echo "$RESULT" | grep "^VERDICT:" | grep -oP '(SAFE|NEEDS_REVIEW|BLOCKING)')
44[ "$VERDICT" == "BLOCKING" ] && { echo "::error::Migration blocked by AI review"; exit 1; }
45[ "$VERDICT" == "NEEDS_REVIEW" ] && echo "::warning::Migration needs manual review"This table-size context is what lets the AI give a different verdict for identical SQL on a small table vs a millions-of-rows table. The AI knows that “large table” means CONCURRENT is mandatory and an implicit cast is expensive — something a simple grep cannot. We then wire both layers together into a single PR gate.
12.5 GitHub Actions: Migration Validation Workflow
Both layers need to run automatically on every PR that touches a migration. The workflow below detects the changed migration files, runs the static check then the AI review, and posts the result as a PR comment while also enforcing the verdict.
1# .github/workflows/migration-validation.yml
2name: Database Migration Validation
3
4on:
5 pull_request:
6 paths: ['migrations/**', 'db/migrations/**', '**/*.sql']
7
8jobs:
9 validate-migrations:
10 runs-on: ubuntu-latest
11 permissions:
12 pull-requests: write
13 contents: read
14 env:
15 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
16 steps:
17 - uses: actions/checkout@v4
18 with: { fetch-depth: 0 }
19
20 - name: Find changed migrations
21 id: migrations
22 run: |
23 CHANGED=$(git diff origin/${{ github.base_ref }}...HEAD --name-only \
24 -- 'migrations/**' '**/*.sql' | grep -v '.down.sql' || true)
25 echo "changed=$CHANGED" >> $GITHUB_OUTPUT
26 echo "count=$(echo "$CHANGED" | grep -c '.' || echo 0)" >> $GITHUB_OUTPUT
27
28 - name: Static safety check (Layer 1)
29 id: static
30 if: steps.migrations.outputs.count != '0'
31 run: |
32 PASS=true
33 for m in ${{ steps.migrations.outputs.changed }}; do
34 ./scripts/check-migration-safety.sh "$m" || PASS=false
35 done
36 echo "pass=$PASS" >> $GITHUB_OUTPUT
37
38 - name: AI migration review (Layer 2)
39 id: ai_review
40 if: |
41 steps.migrations.outputs.count != '0' &&
42 steps.static.outputs.pass == 'true'
43 continue-on-error: true
44 run: |
45 OVERALL="SAFE"
46 for m in ${{ steps.migrations.outputs.changed }}; do
47 REVIEW=$(./scripts/ai-migration-review.sh "$m" 2>&1) || true
48 V=$(echo "$REVIEW" | grep "^VERDICT:" | grep -oP '(SAFE|NEEDS_REVIEW|BLOCKING)' || echo "SAFE")
49 [ "$V" == "BLOCKING" ] && OVERALL="BLOCKING"
50 done
51 echo "verdict=$OVERALL" >> $GITHUB_OUTPUT
52
53 - name: Enforce migration safety
54 if: steps.migrations.outputs.count != '0'
55 run: |
56 [ "${{ steps.static.outputs.pass }}" != "true" ] && \
57 { echo "::error::Blocked by static safety check"; exit 1; }
58 [ "${{ steps.ai_review.outputs.verdict }}" == "BLOCKING" ] && \
59 { echo "::error::Blocked by AI review"; exit 1; }
60 echo "✅ Migration validation passed"Note the continue-on-error: true on the AI step: if the API is down, the AI review is skipped but the static check still guards the gate — the same graceful degradation as the previous article. For complex migrations, we can add a third layer.
12.6 Layer 3: Dry Run on a Staging Database
Static and semantic analysis still don’t run the actual SQL. The third layer runs the migration against a staging schema in a Postgres container, measures the duration, and warns if it’s too slow.
1dry-run:
2 runs-on: ubuntu-latest
3 services:
4 postgres:
5 image: postgres:15
6 env: { POSTGRES_DB: dry_run, POSTGRES_USER: test, POSTGRES_PASSWORD: test }
7 ports: ['5432:5432']
8 options: --health-cmd pg_isready --health-interval 10s
9 steps:
10 - uses: actions/checkout@v4
11 - uses: actions/setup-go@v5
12 with: { go-version: '1.22' }
13
14 - name: Restore staging schema (no data)
15 run: |
16 [ -f testdata/staging-schema.sql ] && \
17 psql -h localhost -U test -d dry_run < testdata/staging-schema.sql || \
18 echo "No staging schema dump, using empty DB"
19
20 - name: Run and time migration
21 env:
22 DATABASE_URL: postgres://test:test@localhost:5432/dry_run
23 run: |
24 START=$(date +%s%N)
25 go run ./cmd/migrate/main.go up
26 DURATION=$(( ($(date +%s%N) - START) / 1000000 ))
27 echo "Migration completed in ${DURATION}ms"
28 [ "$DURATION" -gt 5000 ] && \
29 echo "::warning::Migration > 5s — may cause a lock on a large production table"The key to realism here is testdata/staging-schema.sql, which replicates the production structure (without data) — a dry run against an empty DB is useless. The 5-second threshold is an early warning: if it’s slow in staging, it’ll be far slower in production. Now, the safe SQL pattern for the most dangerous case.
12.7 Safe Multi-Step NOT NULL Migration
The NOT NULL-on-a-large-table case from the case study at the start has a standard solution: break it into steps that each lock only for a fraction of a second. The SQL below adds a NOT NULL column safely across four steps.
1-- SAFE pattern for adding a NOT NULL column to a large table
2
3-- Step 1: Add a nullable column with a default (instant, no lock)
4ALTER TABLE orders ADD COLUMN cancel_window_minutes INT DEFAULT 30;
5
6-- Step 2: Populate existing rows in batches (no long lock)
7DO $$
8DECLARE rows_updated INT;
9BEGIN
10 LOOP
11 UPDATE orders SET cancel_window_minutes = 30
12 WHERE order_id IN (
13 SELECT order_id FROM orders
14 WHERE cancel_window_minutes IS NULL LIMIT 10000
15 );
16 GET DIAGNOSTICS rows_updated = ROW_COUNT;
17 EXIT WHEN rows_updated = 0;
18 PERFORM pg_sleep(0.1); -- brief pause between batches
19 END LOOP;
20END $$;
21
22-- Step 3: Add the NOT NULL constraint (fast, column already populated)
23ALTER TABLE orders ALTER COLUMN cancel_window_minutes SET NOT NULL;Each step is safe to run in production: total lock time becomes milliseconds per step, not minutes. The batching in Step 2 with pg_sleep gives room to other queries so they don’t starve. Migrations like this are usually run through a Go runner.
12.8 Integration with golang-migrate
The runner that executes those SQL files also needs to be tidy and rollback-capable. The Go program below wraps golang-migrate with three subcommands — up, down, and status — used both in the CI dry run and in production deployment.
1// cmd/migrate/main.go
2package main
3
4import (
5 "errors"
6 "fmt"
7 "log"
8 "os"
9
10 "github.com/golang-migrate/migrate/v4"
11 _ "github.com/golang-migrate/migrate/v4/database/postgres"
12 _ "github.com/golang-migrate/migrate/v4/source/file"
13)
14
15func main() {
16 m, err := migrate.New("file://migrations", os.Getenv("DATABASE_URL"))
17 if err != nil {
18 log.Fatal(err)
19 }
20 defer m.Close()
21
22 switch os.Args[1] {
23 case "up":
24 if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
25 log.Fatalf("migrate up: %v", err)
26 }
27 version, _, _ := m.Version()
28 fmt.Printf("Current version: %d\n", version)
29
30 case "down":
31 if err := m.Steps(-1); err != nil {
32 log.Fatalf("migrate down: %v", err)
33 }
34
35 case "status":
36 version, dirty, _ := m.Version()
37 fmt.Printf("Version: %d, Dirty: %v\n", version, dirty)
38 }
39}Note the handling of migrate.ErrNoChange, which is skipped — without it, a re-run in CI would fail even though nothing is wrong. The dirty field on status is also crucial: it indicates a migration that stopped halfway and needs manual intervention. To keep all of this orderly, migration files need a naming convention.
12.9 Migration Naming Convention
The migration execution order depends on the file name, so the naming convention isn’t about aesthetics but about correctness. The guide below defines the timestamp format and examples of valid vs invalid names.
1Format: {14-digit-timestamp}_{description}.{up|down}.sql
2
3✅ Valid:
4 20260715142030_add_cancel_window_to_orders.up.sql
5 20260715142030_add_cancel_window_to_orders.down.sql
6 20260720000000_create_flash_sales_table.up.sql
7
8❌ Invalid:
9 migration1.sql (no timestamp, no type)
10 fix_orders.sql (no timestamp, no type)
11 1234.sql (too short)Timestamp-based naming ensures migrations always apply in the correct order across all environments. This convention can be enforced automatically in CI with a small script.
1# scripts/check-migration-naming.sh
2for file in migrations/*.sql; do
3 BASENAME=$(basename "$file")
4 if ! echo "$BASENAME" | grep -qP '^\d{14}_[a-z_]+\.(up|down)\.sql$'; then
5 echo "❌ Invalid migration name: $BASENAME"
6 echo " Expected: 20260715142030_description_here.up.sql"
7 exit 1
8 fi
9 # Every .up.sql must have a .down.sql
10 if echo "$file" | grep -q "\.up\.sql$"; then
11 DOWN="${file/.up.sql/.down.sql}"
12 [ -f "$DOWN" ] || echo "⚠️ Missing down migration for: $BASENAME"
13 fi
14done
15echo "✅ All migration names valid"The up/down pairing check in this script enforces an important rule: a down migration that’s never written is a down migration that will fail when it’s needed most. For a real deployment, all of this is captured in a playbook.
12.10 Migration Playbook for Production
Automation in CI closes many risks, but deployment to production still needs a clear human procedure. The playbook below summarizes the pre-migration checklist, the execution steps, and the rollback procedure.
1# Migration Playbook — Production Deployment
2
3## Pre-Migration Checklist
4□ Migration reviewed via CI pipeline (static + AI)
5□ Dry run completed on staging database (< 5 seconds)
6□ Down migration exists and tested
7□ Database backup before deploy (if critical table)
8□ Rollback plan documented
9
10## Migration Execution Steps
111. Check state: `go run cmd/migrate/main.go status`
122. Run: `go run cmd/migrate/main.go up`
133. Verify: `go run cmd/migrate/main.go status` + check application logs
144. Monitor for 5-10 minutes after the migration
15
16## Rollback Procedure
171. Immediate: notify the team via Slack
182. Rollback: `go run cmd/migrate/main.go down 1`
193. Verify: check application health
204. Document: write an incident reportThis playbook translates the automated gates into human actions that can be executed under incident pressure — when people tend to panic and forget steps. A few specific traps still need watching.
12.11 Tips & Gotchas
Migrations have sharp corners that are distinctly PostgreSQL. The points below are the ones that most often bite in production.
💡 Tip 1: CONCURRENT for index creation. CREATE INDEX CONCURRENTLY doesn’t lock the table (though it’s slower). For a large production table, always use CONCURRENTLY.
💡 Tip 2: Multi-step for NOT NULL. Don’t do ADD COLUMN NOT NULL directly. The safe pattern: add column → populate batched → add constraint.
💡 Tip 3: Test the down migration. A down migration that’s never tested will fail when it’s needed most. Test in CI: up → down 1 → up.
⚠️ Gotcha 1: Non-idempotent migrations. CI can re-run on retry. Use IF NOT EXISTS and IF EXISTS for safety.
⚠️ Gotcha 2: Enum type changes. A PostgreSQL enum can’t remove an existing value. Plan enum changes very carefully.
⚠️ Gotcha 3: Long migration = long lock. Even ALTER TABLE ... SET DEFAULT on a large table can lock for several seconds. Always measure the duration in the dry run.
Gotcha 2 is the most unrecoverable: an enum mistake can often only be fixed by creating a new type and migrating the whole column. All these warnings converge on one layered approach.
12.12 Summary
Database migration validation is an investment worth making for every Go service that touches a production database. The three-layer approach works because each layer covers the others’ gaps:
Layer 1 (static check): Instant, zero cost. Catches known dangerous patterns.
Layer 2 (AI review): ~2 seconds, ~$0.002. Semantic understanding for lock analysis and safety assessment with table-size context.
Layer 3 (dry run): Staging compute cost. Real execution to catch runtime errors and measure the actual duration.
Combined effect: production migration incidents drop dramatically because all dangerous patterns are caught before deploy. Total cost under $0.005 per migration — far cheaper than a single 45-minute outage.
In the next article, we move up to the orchestration level: how to deploy across many environments with AI checkpoints that hold promotion until conditions are safe.