ποΈ Stateful Continuous Delivery: Automating Schema-as-Code with Zero Drift
Stateless microservices can be deployed, scaled, and destroyed ephemerally within seconds. Relational databases, however, represent stateful single points of failure. In enterprise continuous delivery, manual SQL execution by database administrators (DBAs) introduces operational bottlenecks, environmental drift, audit non-compliance, and schema corruption. Database Migration Pipeline Integration treats DDL and DML scripts as version-controlled software assets (Schema-as-Code). Using engines such as Flyway and Liquibase orchestrated directly through Jenkins Declarative Pipelines, teams execute automated schema migrations prior to application rollouts. By integrating pre-flight validation dry-runs (updateSQL and info), schema locking recovery handlers (DATABASECHANGELOGLOCK), ephemeral Testcontainers sandbox verification, and the three-phase Expand-Contract migration pattern, CI/CD systems maintain full backward compatibility across distributed production deployments.
SCHEMA-AS-CODE MIGRATION STATE MACHINE:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SOURCE CONTROL REPOSITORY (Git SCM) β
β Migration Directory: db/migration/ β
β βββ V1_0__init_schema.sql (CRC32/SHA-256 Checksum: 7f8a9b0c) β
β βββ V1_1__add_customer_email.sql (CRC32/SHA-256 Checksum: 1d2e3f4a) β
β βββ V1_2__create_orders_table.sql (CRC32/SHA-256 Checksum: 5b6c7d8e) β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Step 1: Pipeline Checkout & Discovery)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JENKINS MIGRATION RUNNER (Flyway / Liquibase CLI) β
β β
β Pre-Flight State Evaluation: β
β 1. Connects to Target Database over JDBC via Credentials Binding β
β 2. Acquires Distributed Exclusive Migration Lock: β
β β’ Liquibase: SELECT * FROM DATABASECHANGELOGLOCK (Sets LOCKED = TRUE) β
β β’ Flyway: SELECT ... FOR UPDATE (Table-level lock on flyway_schema_history) β
β 3. Compares Local Git Migrations against Database History Ledger: β
β β’ Verifies checksums of already-applied scripts (Detects illegal script tampering!) β
β β’ Identifies pending migrations: [V1_2__create_orders_table.sql] β
ββββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Step 2: Transactional Execution)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TARGET RELATIONAL DATABASE (PostgreSQL / MySQL) β
β β
β Execute within Database Transaction: β
β BEGIN TRANSACTION; β
β β’ Executes: CREATE TABLE orders (id BIGINT PRIMARY KEY, total NUMERIC(12,2)...); β
β β’ Inserts Audit Record into Schema History Ledger: β
β INSERT INTO flyway_schema_history (installed_rank, version, description, checksum)β
β VALUES (3, '1.2', 'create orders table', '5b6c7d8e'); β
β COMMIT; β
β β
β 4. Releases Distributed Migration Lock (LOCKED = FALSE) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
pipeline {
agent { label 'docker-capable-host' }
options {
timeout(time: 30, unit: 'MINUTES')
timestamps()
ansiColor('xterm')
}
environment {
DB_CREDENTIALS_ID = 'production-aurora-postgres-creds'
DB_URL = 'jdbc:postgresql://postgres-prod.internal.company.com:5432/ledger'
FLYWAY_IMAGE = 'flyway/flyway:10.8-alpine'
}
stages {
stage('Pre-Flight Database Audit (Flyway Info)') {
steps {
echo "[*] Connecting to database and auditing pending migrations..."
withCredentials([usernamePassword(credentialsId: env.DB_CREDENTIALS_ID,
usernameVariable: 'DB_USER',
passwordVariable: 'DB_PASSWORD')]) {
// Execute Flyway Info: Prints migration ledger state without executing DDL
sh """
docker run --rm \
-v \${WORKSPACE}/db/migration:/flyway/sql:ro \
${FLYWAY_IMAGE} \
-url="${DB_URL}" \
-user="${DB_USER}" \
-password="${DB_PASSWORD}" \
-connectRetries=5 \
info
"""
}
}
}
stage('Execute Database Schema Migration') {
steps {
echo "[*] Applying pending schema migrations to production database..."
withCredentials([usernamePassword(credentialsId: env.DB_CREDENTIALS_ID,
usernameVariable: 'DB_USER',
passwordVariable: 'DB_PASSWORD')]) {
// Execute Flyway Migrate: Applies pending scripts sequentially inside transactions
sh """
docker run --rm \
-v \${WORKSPACE}/db/migration:/flyway/sql:ro \
${FLYWAY_IMAGE} \
-url="${DB_URL}" \
-user="${DB_USER}" \
-password="${DB_PASSWORD}" \
-outOfOrder=false \
-validateOnMigrate=true \
migrate
"""
}
}
}
}
post {
failure {
echo "[β] FATAL: Database migration failed! Inspect database locking tables."
}
}
}
-- File: db/migration/V1_0__create_payment_ledger.sql
-- PREFIX: 'V' = Versioned Migration (Executed exactly once in numerical order)
-- SEPARATOR: '__' (Double underscore separates version from description)
CREATE TABLE IF NOT EXISTS payment_transactions (
transaction_id VARCHAR(64) PRIMARY KEY,
customer_id VARCHAR(64) NOT NULL,
amount NUMERIC(15, 2) NOT NULL,
currency VARCHAR(3) NOT NULL DEFAULT 'INR',
status VARCHAR(32) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_payment_customer ON payment_transactions(customer_id);
-- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- File: db/migration/R__create_audit_views.sql
-- PREFIX: 'R' = Repeatable Migration (Re-executed whenever its checksum changes)
CREATE OR REPLACE VIEW v_daily_settlement_totals AS
SELECT
DATE_TRUNC('day', created_at) AS settlement_date,
currency,
SUM(amount) AS total_settled_amount,
COUNT(transaction_id) AS total_count
FROM payment_transactions
WHERE status = 'SETTLED'
GROUP BY DATE_TRUNC('day', created_at), currency;
databaseChangeLog:
- changeSet:
id: 20261107-01-add-wallet-table
author: devops_team
changes:
- createTable:
tableName: user_wallets
columns:
- column:
name: wallet_id
type: VARCHAR(64)
constraints:
primaryKey: true
nullable: false
- column:
name: user_id
type: VARCHAR(64)
constraints:
nullable: false
- column:
name: balance
type: NUMERIC(15, 2)
defaultValueNumeric: 0.00
rollback:
- dropTable:
tableName: user_wallets
- changeSet:
id: 20261107-02-add-wallet-index
author: devops_team
changes:
- createIndex:
indexName: idx_wallet_user
tableName: user_wallets
columns:
- column:
name: user_id
rollback:
- dropIndex:
indexName: idx_wallet_user
tableName: user_wallets
pipeline {
agent { label 'docker-capable-host' }
environment {
LIQUIBASE_IMAGE = 'liquibase/liquibase:4.26-alpine'
DB_URL = 'jdbc:postgresql://postgres-prod.internal.company.com:5432/ledger'
DB_CREDS = credentials('production-aurora-postgres-creds')
}
stages {
stage('Generate SQL Audit Preview (updateSQL)') {
steps {
echo "[*] Generating dry-run updateSQL execution plan for DBA audit..."
sh """
docker run --rm \
-v \${WORKSPACE}/db/changelog:/liquibase/changelog:ro \
\${LIQUIBASE_IMAGE} \
--changelog-file=changelog/db.changelog-master.yaml \
--url="\${DB_URL}" \
--username="\${DB_CREDS_USR}" \
--password="\${DB_CREDS_PSW}" \
update-sql > target/migration_preview.sql
"""
// Archive raw SQL for regulatory audit compliance
archiveArtifacts artifacts: 'target/migration_preview.sql'
}
}
stage('Execute Liquibase Update') {
steps {
echo "[*] Tagging database and applying Liquibase changesets..."
sh """
# 1. Tag current state to enable exact point-in-time rollback if downstream steps fail
docker run --rm \
-v \${WORKSPACE}/db/changelog:/liquibase/changelog:ro \
\${LIQUIBASE_IMAGE} \
--changelog-file=changelog/db.changelog-master.yaml \
--url="\${DB_URL}" \
--username="\${DB_CREDS_USR}" \
--password="\${DB_CREDS_PSW}" \
tag --tag="pre-release-build-\${BUILD_NUMBER}"
# 2. Execute migration
docker run --rm \
-v \${WORKSPACE}/db/changelog:/liquibase/changelog:ro \
\${LIQUIBASE_IMAGE} \
--changelog-file=changelog/db.changelog-master.yaml \
--url="\${DB_URL}" \
--username="\${DB_CREDS_USR}" \
--password="\${DB_CREDS_PSW}" \
update
"""
}
}
}
}
stage('Pre-Flight Migration Sandbox Test') {
steps {
echo "[*] Provisioning isolated ephemeral PostgreSQL container to test migrations..."
script {
// 1. Launch ephemeral database container on local agent Docker daemon
def pgContainerId = sh(
script: 'docker run -d -e POSTGRES_DB=sandbox -e POSTGRES_PASSWORD=testpass -p 5433:5432 postgres:15-alpine',
returnStdout: true
).trim()
try {
// Wait for database readiness
sh 'while ! docker exec ' + pgContainerId + ' pg_isready -U postgres; do sleep 1; done'
echo "[+] Ephemeral sandbox running. Executing Flyway migrations against test instance..."
// 2. Execute Flyway migration against ephemeral sandbox
sh """
docker run --rm --network=host \
-v \${WORKSPACE}/db/migration:/flyway/sql:ro \
flyway/flyway:10.8-alpine \
-url="jdbc:postgresql://localhost:5433/sandbox" \
-user="postgres" \
-password="testpass" \
migrate
"""
echo "[+] Testing schema rollback (Clean / Undo)..."
// 3. Verify that the schema is functional and queries compile cleanly
sh """
docker exec ${pgContainerId} psql -U postgres -d sandbox -c "
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
"
"""
echo "[β] Pre-flight sandbox migration verification PASSED."
} finally {
// 4. Destroy ephemeral database sandbox completely
echo "[*] Tearing down ephemeral database sandbox..."
sh "docker rm -f ${pgContainerId} || true"
}
}
}
}
THE THREE-PHASE EXPAND-CONTRACT (PARALLEL RUN) MIGRATION PATTERN:
OBJECTIVE: Rename column 'phone' to 'phone_number' without dropping customer traffic.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PHASE 1: EXPAND (BACKWARD-COMPATIBLE RELEASE - PIPELINE BUILD N)
1. Migration V1_1__expand_phone_number.sql:
β’ ALTER TABLE users ADD COLUMN phone_number VARCHAR(32);
2. Deploy Application Version 1.1:
β’ Reads from: 'phone' (fallback to phone_number)
β’ Writes to: BOTH 'phone' AND 'phone_number' (Dual-Write)
3. Database Backfill Script:
β’ UPDATE users SET phone_number = phone WHERE phone_number IS NULL;
β
Result: Both old App v1.0 and new App v1.1 function concurrently with zero downtime!
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PHASE 2: TRANSITION & VERIFY (PIPELINE BUILD N+1)
1. Deploy Application Version 1.2:
β’ Reads from: 'phone_number' exclusively
β’ Writes to: 'phone_number' exclusively
2. Verification:
β’ Verify zero queries touch the legacy 'phone' column in telemetry.
β
Result: The legacy column is now completely unreferenced by active production workloads.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PHASE 3: CONTRACT (DESTRUCTIVE CLEANUP - PIPELINE BUILD N+2)
1. Migration V1_2__contract_drop_legacy_phone.sql:
β’ ALTER TABLE users DROP COLUMN phone;
β
Result: Technical debt purged; schema is fully modernized with zero production interruptions!
-- db/migration/V2_0__expand_dual_write_trigger.sql
-- Step A: Add new column
ALTER TABLE users ADD COLUMN phone_number VARCHAR(32);
-- Step B: Backfill existing data
UPDATE users SET phone_number = phone WHERE phone_number IS NULL;
-- Step C: Create synchronous synchronization trigger for legacy clients during cutover
CREATE OR REPLACE FUNCTION sync_user_phone()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.phone_number IS NOT NULL AND NEW.phone IS NULL THEN
NEW.phone := NEW.phone_number;
ELSIF NEW.phone IS NOT NULL AND NEW.phone_number IS NULL THEN
NEW.phone_number := NEW.phone;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_sync_user_phone
BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION sync_user_phone();
#!/usr/bin/env bash
# ==============================================================================
# Script: release_migration_locks.sh
# Purpose: Detects and safely releases stale migration locks left by aborted CI jobs
# Usage: ./release_migration_locks.sh <db_host> <db_name> <db_user>
# ==============================================================================
set -euo pipefail
DB_HOST="${1:-postgres-prod.internal.company.com}"
DB_NAME="${2:-ledger}"
DB_USER="${3:-postgres}"
echo "[!] Checking for stale migration locks on: ${DB_HOST}/${DB_NAME}..."
# 1. LIQUIBASE LOCK RECOVERY
# Inspect if DATABASECHANGELOGLOCK is stuck in LOCKED=TRUE state
LOCKED_STATUS=$(PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -d "${DB_NAME}" -t -A \
-c "SELECT locked FROM databasechangeloglock WHERE id=1;" 2>/dev/null || echo "NOT_FOUND")
if [ "${LOCKED_STATUS}" == "t" ] || [ "${LOCKED_STATUS}" == "TRUE" ]; then
echo "[!] STALE LOCK DETECTED: Liquibase is locked!"
# Query who locked it and when
PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -d "${DB_NAME}" \
-c "SELECT id, locked, lockgranted, lockedby FROM databasechangeloglock;"
echo "[*] Forcing lock release via Liquibase releaseLocks command..."
docker run --rm \
liquibase/liquibase:4.26-alpine \
--url="jdbc:postgresql://${DB_HOST}:5432/${DB_NAME}" \
--username="${DB_USER}" \
--password="${DB_PASSWORD}" \
release-locks
echo "[β] Liquibase lock successfully cleared."
fi
# 2. FLYWAY REPAIR & LOCK RECOVERY
# If a Flyway migration fails midway, it marks the last migration as 'FAILED'
FAILED_COUNT=$(PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -d "${DB_NAME}" -t -A \
-c "SELECT count(*) FROM flyway_schema_history WHERE success = false;" 2>/dev/null || echo "0")
if [ "${FAILED_COUNT}" -gt 0 ]; then
echo "[!] FAILED MIGRATION DETECTED: ${FAILED_COUNT} uncommitted/failed scripts found in flyway_schema_history!"
echo "[*] Running Flyway repair to reset schema history metadata..."
docker run --rm \
-v ${WORKSPACE}/db/migration:/flyway/sql:ro \
flyway/flyway:10.8-alpine \
-url="jdbc:postgresql://${DB_HOST}:5432/${DB_NAME}" \
-user="${DB_USER}" \
-password="${DB_PASSWORD}" \
repair
echo "[β] Flyway repair complete. Failed state cleaned."
fi
CONTINUOUS DEPLOYMENT SEQUENCING DECISION MATRIX:
[Incoming Production Release]
β
βΌ
Does this release contain database DDL/DML?
β
βββββββββββββββββ΄ββββββββββββββββ
β YES β NO
βΌ βΌ
Does the DDL add NEW nullable/default fields? Standard Stateless Deploy
(Additive / Non-Breaking) (Rolling update application pods)
β
βββββββββββββββββ΄ββββββββββββββββ
β YES β NO (Destructive: Drop, Alter Type, Rename)
βΌ βΌ
βββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββ
β EXECUTE MIGRATION FIRST β β VIOLATION OF ZERO-DOWNTIME ARCHITECTURE! β
β (Pre-Deployment Phase) β β Refactor into Expand-Contract Pattern! β
β β β 1. Pipeline N: Expand (Additive DDL) β
β 1. Run Flyway / Liquibase β β 2. Pipeline N+1: Application update β
β 2. Schema evolves safely β β 3. Pipeline N+2: Contract (Cleanup DDL) β
β 3. Rolling update app pods β βββββββββββββββββββββββββββββββββββββββββββββββββ
β 4. New pods consume new schemaβ
βββββββββββββββββββββββββββββββββ
WHY RUNNING MIGRATIONS INSIDE APP CONTAINER STARTUP IS AN ANTI-PATTERN:
β’ Defect: Putting 'flyway.migrate()' inside Spring Boot or Node.js main() startup.
β’ Problem: When Kubernetes scales out 10 new pods simultaneously, 10 PODS ATTEMPT TO MIGRATE
THE DATABASE CONCURRENTLY!
β’ Result: Deadlocks on schema history tables, race conditions, and connection pool exhaustion.
β’ Solution: Separate database migration into an isolated Jenkins Pipeline stage or dedicated
Kubernetes Job (helm.sh/hook: pre-install, pre-upgrade) before application pods boot!
COMMON DATABASE MIGRATION DEFECTS & REMEDIATIONS:
1. ERROR: "FlywayException: Validate failed: Migration Checksum Mismatch for migration version 1.2"
β’ Symptom: Jenkins fails immediately during the pre-flight Flyway validation stage.
β’ Cause: A developer modified the text or whitespace of 'V1_2__add_status.sql' in Git AFTER
it had already run against staging or production.
β’ Remediation:
- DO NOT edit applied migration files! Revert the file in Git to its exact historical state.
- Author a brand-new incremental migration file: 'V1_3__fix_status_column.sql'.
- In non-production environments only, run: flyway repair to sync the checksum.
2. PIPELINE HANGS INDEFINITELY ON DDL: "Lock wait timeout exceeded; try restarting transaction"
β’ Cause: The migration executed an 'ALTER TABLE' on a high-throughput table that holds active
long-running SELECT or UPDATE transactions. The DDL requests an ACCESS EXCLUSIVE lock and hangs.
β’ Remediation: Set strict statement and lock timeouts in migration scripts:
SET lock_timeout = '5s';
SET statement_timeout = '30s';
ALTER TABLE payments ADD COLUMN provider VARCHAR(64);
3. OUT-OF-ORDER MIGRATION FAILURE IN MULTI-BRANCH WORKFLOWS:
β’ Scenario: Developer A merges 'V1.3'. Developer B concurrently merges 'V1.2'.
β’ Symptom: Flyway throws: "Found non-empty schema(s) without schema history table! Out of order."
β’ Remediation: In multi-developer teams, use timestamp-based versioning rather than sequential:
V20261107140230__add_orders.sql instead of V1_2__add_orders.sql, and enable outOfOrder=true:
flyway.outOfOrder=true
4. NON-TRANSACTIONAL DDL STATE CORRUPTION (MYSQL / ORACLE):
β’ Cause: In MySQL, DDL statements trigger implicit commits. If a script creates Table 1 and fails
on Table 2, Table 1 remains created, but the history table does not record the migration!
β’ Remediation: Maintain exactly ONE DDL statement per migration file in databases that lack
transactional DDL support.
DATABASE MIGRATION PIPELINE SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β ARCHITECTURAL COMPONENT β FLYWAY MECHANISM β LIQUIBASE β PRIMARY OPERATIONAL ROLE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Schema Ledger Table β flyway_schema_history β DATABASECHANGELOGβ Tracks applied versions & sumsβ
β Locking Table β Table-level lock β DATABASECHANGELOGβ Prevents concurrent migrationsβ
β Dry-Run Command β flyway info β update-sql β Pre-flight audit & DBA review β
β Execution Command β flyway migrate β update β Applies pending changesets β
β Recovery Command β flyway repair β release-locks β Fixes broken state/locks β
β Schema-as-Code Format β Raw SQL (V*.sql, R*.sql) β YAML, XML, SQL β Version-controlled DDL/DML β
β Zero-Downtime Pattern β Expand-Contract (3 phases) β Expand-Contract β Prevents app version crashes β
β Sandbox Verification β Ephemeral Testcontainers β Ephemeral Docker β Catches syntax errors in CI β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 DATABASE MIGRATION AXIOMS FOR DEVOPS SREs: β
β 1. Immutable History: Never edit or rename a migration script once applied to an environment. β
β 2. Pre-Flight Sandbox: Always validate migrations against an ephemeral testcontainer before production. β
β 3. Decouple from Pod Boot: Never let application containers migrate the database during pod startup. β
β 4. Expand-Contract Mandate: Deconstruct schema changes into additive, transitional, and cleanup releases. β
β 5. Set Lock Timeouts: Always configure explicit lock_timeout values on DDL to prevent table deadlocks. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ