引言
数据库迁移的风险来自两个系统无法共享事务:schema 变化与应用代码发布不同步。滚动发布期间,新旧代码必须同时能读写数据库。
核心问题
先改表再发代码,旧代码可能因列不存在而失败;先发代码再改表,新代码可能引用尚不存在的结构。迁移必须按兼容顺序分阶段进行。
Expand-Contract
先扩展:增加新列、新表或新索引,保持旧结构可用;再双写或回填;然后切换读取;最后收缩:删除旧列和旧代码。每个阶段都可独立部署和回滚。
兼容与锁
新增可选列通常安全;改类型、重命名和删除需要过渡。大表上的 ALTER 可能长时间持锁,应使用并发建索引、分批回填和 lock timeout。删除前列要经过两个发布周期并确认无读取。
验证
在预发用真实数据量和旧代码测试迁移;监控复制延迟、锁等待和错误率。迁移脚本与代码一起版本化,确保任何一个已部署版本都能在对应 schema 上工作。
代码示例
-- Migration 1 (expand): add the new column, keep it in sync.
ALTER TABLE users ADD COLUMN handle VARCHAR(40);
CREATE OR REPLACE FUNCTION sync_handle() RETURNS TRIGGER AS $$
BEGIN NEW.handle := COALESCE(NEW.handle, NEW.username); RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER users_sync_handle BEFORE INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION sync_handle();
UPDATE users SET handle = username WHERE handle IS NULL; -- batched in practice
// New code: read handle, fall back to username. Tolerates both schemas.
function displayName(user: { handle?: string | null; username: string }): string {
return user.handle ?? user.username;
}
// New code: write to both during the transition.
async function updateUser(id: string, handle: string) {
await db.users.update({ where: { id }, data: { handle, username: handle } }); // write both
}
async function backfillHandle(batchSize = 5000) {
let migrated = 0;
while (true) {
const rows = await db.users.findMany({ where: { handle: null }, take: batchSize, orderBy: { id: "asc" } });
if (rows.length === 0) break;
await db.users.updateMany({ where: { id: { in: rows.map(r => r.id) } }, data: { handle: sql`username` } });
migrated += rows.length;
await sleep(100); // yield to reduce lock pressure
console.log(`backfilled ${migrated} rows`);
}
}
// Instrument the fallback so you can verify it is unused before dropping.
function displayName(user: { handle?: string | null; username: string }): string {
if (user.handle) return user.handle;
logger.warn({ msg: "username column still read", userId: user.id }); // remove after migration 2
return user.username;
}
-- Locks the table for the duration — fine for small tables, dangerous for large ones.
CREATE INDEX orders_status_created ON orders (status, created_at);
-- Non-blocking: takes longer but allows concurrent reads and writes.
CREATE INDEX CONCURRENTLY orders_status_created ON orders (status, created_at);
async function dataMigration(controlKey: string) {
const state = await control.get(controlKey) ?? { lastId: "0", done: false };
if (state.done) return;
while (true) {
const batch = await db.users.findMany({ where: { id: { gt: state.lastId } }, take: 5000, orderBy: { id: "asc" } });
if (batch.length === 0) { await control.set(controlKey, { ...state, done: true }); break; }
await db.users.updateMany({ where: { id: { in: batch.map(b => b.id) } }, data: { searchVector: computeVector(batch) } });
state.lastId = batch[batch.length - 1].id;
await control.set(controlKey, state); // checkpoint progress
await sleep(100); // yield to reduce load
}
}