Migration là các script có đánh số phiên bản để thay đổi schema một cách có kiểm soát — giống "git cho cấu trúc DB". Mỗi migration có phần up (áp dụng) và down (rollback), được ghi lại trong bảng _migrations để biết cái nào đã chạy.
Công cụ thường gặp: Prisma Migrate (prisma migrate dev sinh migration từ diff schema, prisma migrate deploy áp lên production), Knex, Flyway, Liquibase.
Trong CI/CD: migration chạy trước khi deploy code mới, để schema sẵn sàng cho code.
Migration không downtime trên bảng lớn cần nhiều bước nhỏ, mỗi bước một lần deploy:
thêm cột nullable → deploy code đọc cột mới → backfill dữ liệu → mới thêm NOT NULL → bỏ cột cũ.
Nguy hiểm cần nhớ:
- ALTER TABLE ... NOT NULL không có default trên bảng lớn sẽ khóa cả bảng (PostgreSQL); dùng NOT VALID rồi validate riêng.
- DROP COLUMN không rollback được nếu đã có dữ liệu.
Nguyên tắc: không bao giờ sửa migration đã deploy, test cả down trước khi merge, và review migration kỹ như review code — thay đổi schema gần như không thể đảo ngược.
A migration is a version-numbered script that changes the schema in a controlled way — like "git for the DB structure". Each migration has an up (apply) and down (rollback) part, recorded in a _migrations table so you know which ones have run.
Common tools: Prisma Migrate (prisma migrate dev generates a migration from the schema diff, prisma migrate deploy applies it in production), Knex, Flyway, Liquibase.
In CI/CD: migrations run before deploying new code, so the schema is ready for it.
Zero-downtime migrations on large tables need several small steps, one deploy each:
add a nullable column → deploy code that reads it → backfill data → only then add NOT NULL → drop the old column.
Dangers to remember:
- ALTER TABLE ... NOT NULL with no default on a large table locks the whole table (PostgreSQL); use NOT VALID then validate separately.
- DROP COLUMN can't be rolled back once data exists.
Rules: never edit a deployed migration, test the down before merging, and review migrations as carefully as code — schema changes are nearly irreversible.