We are going to design a toolkit for zero-downtime schema migrations.
The toolkit should support:
- Expand (adding new columns/tables without breaking old code)
- Migrate (moving data from old schema to new schema in a phased way)
- Contract (removing old columns/tables after all code has been updated to use new ones)
- Verifiers (to ensure the migration is correct and data is consistent)
- Rollbacks (ability to revert a migration if something goes wrong)
Steps for a typical zero-downtime migration (using expand/migrate/contract):
-
Expand:
- Add new columns/tables (nullable or with default) without removing old ones.
- Deploy code that writes to both old and new (if necessary) but reads from old (or new if possible) safely.
-
Migrate:
- Backfill data from old to new (if needed). This can be done in batches.
- Deploy code that reads from new and writes to both (if necessary) until all reads are from new.
-
Contract:
- Remove old columns/tables after all code has been updated to use new ones and old data is no longer needed.
However, we want a toolkit that helps manage these steps with verifiers and rollbacks.
Design:
We'll have a set of tools (CLI or library) that:
- Generate migration files (SQL or code) for each step (expand, migrate, contract) with metadata.
- Provide a way to run these migrations in order, with the ability to rollback (by having down migrations for each step?).
- Provide verifiers to check data consistency and schema state at each step.
However, note that for zero-downtime, the contract step is the one that removes old columns. So the rollback of contract might be tricky (if we drop a column, we can't get it back without a backup). So we must be cautious.
Alternatively, we might design the migrations to be reversible up to the expand step? But contract is the destructive step.
Let's think about the phases:
Phase 1: Expand (reversible by dropping the added columns/tables)
Phase 2: Migrate (reversible? maybe by moving data back? but if we have backfilled, then we might have overwritten old data? Actually, during migrate we might be writing to both, so the old data might still be there. But if we are reading from new and writing to both, then the old data might be out of sync? Actually, in a typical expand/migrate/contract:
- Expand: add new columns (say, new_name) and keep old (old_name). Code writes to both? Or writes to old and then backfill to new? Or writes to both?
There are two common patterns:
Pattern A (for adding a column):
- Expand: add new_column (nullable). Old code writes to old_column, new code writes to both old and new? Or only to new? It depends.
But to avoid breaking old code, we must keep old_column. So we might have:
Step 1: Add new_column (nullable, no default). Deploy code that writes to both old_column and new_column? Or only to old_column? Actually, if we want to backfill, we can have a separate backfill job.
Alternatively:
Step 1: Add new_column (nullable). Deploy code that writes to old_column (as before) and also writes to new_column? That would be dual write. Then we backfill existing data from old_column to new_column. Then we switch reads to new_column and then we can drop old_column.
Pattern B (for renaming a column):
- Expand: add new_column, deploy code that writes to both, then backfill, then switch reads, then drop old_column.
So the migrate step might involve:
- Backfilling existing data (from old to new) in batches.
- Deploying code that reads from new and writes to both (until all writes are to new?).
Actually, the typical pattern for renaming a column without downtime:
1. Add the new column (with the new name) as nullable.
2. Backfill the new column from the old column (in a background job).
3. Deploy code that writes to both columns (so that new writes are in both).
4. Deploy code that reads from the new column and writes to both (so that reads are from new, but writes still to both for safety).
5. Once we are sure all code is reading from new and we have backfilled, we can deploy code that writes only to new (and stop writing to old). But note: we must ensure that we don't lose data that were written by old code during the backfill? Actually, during the backfill we are only reading from old, but if there are new writes (by new code) to old? We are writing to both, so old is still being updated? Actually, step 3 and 4: we write to both. So old is being updated by new code as well? That might be acceptable until we drop the old column.
6. Then we can drop the old column (contract).
But note: if we drop the old column, then any code that hasn't been updated to use the new column will break. So we must ensure all code is updated.
So the phases:
Expand: add new column, no code change? Or code change to write to both? Actually, we can do:
Step 1 (Expand): Add new column (nullable). Deploy code that writes to both old and new. Then backfill old to new.
Step 2 (Migrate): Deploy code that reads from new (and writes to both). Then wait until all reads are from new.
Step 3 (Contract): Deploy code that writes only to new. Then drop old column.
But wait, step 2: we are reading from new and writing to both. That means we are still writing to old. So the old column is being updated by new code? Yes.
Then step 3: we stop writing to old. But then what about the data that were written to old by old code during step 2? Actually, step 2: we have deployed code that reads from new and writes to both. But old code (if any) might still be running and writing only to old? That's a problem because we are in a phased rollout. We must ensure that all instances of the old code are gone before we stop writing to old? Actually, we can't stop writing to old until we are sure no old code is writing to it. But in step 2, we are writing to both, so the old column is being updated by new code (and possibly old code if still present). Then in step 3, we stop writing to old. But if there is still old code, it will write only to old and we will lose those writes (because we are not reading from old anymore and we will drop it). So we must ensure that all old code is gone before step 3.
Alternatively, we can do:
Step 1 (Expand): Add new column. Deploy code that writes to old and new (dual write). Then backfill.
Step 2 (Migrate): Deploy code that reads from new (and still writes to both). Then wait until all reads are from new.
Step 3 (Contract): Deploy code that writes only to new. Then drop old column.
But in step 3, we are writing only to new. If there is still old code, it will write to old and we will lose that data? Actually, we are not reading from old, so we won't see the new writes from old code? And then when we drop old, we lose that data? That's a problem.
So we must ensure that all old code is gone before step 3. How? We can have a feature flag? Or we can have a cutover point where we stop the old code.
Typically, we do:
- Deploy new code that writes to both and reads from old (or new if backfilled) and then switch reads to new, then stop writing to old.
But to avoid data loss, we must make sure that we don't have any old code writing to old after we stop writing to old.
So the sequence:
Phase 1 (Expand):
- Add new column (nullable).
- Deploy code that writes to both old and new (so that new writes are in both). This code must be backward compatible (so old code that doesn't know about the new column still works? Actually, old code will write only to old, but that's okay because we are writing to both in the new code? Wait, we are deploying new code that writes to both, but old code (if any) will write only to old. So during phase 1, we have:
Old code: writes to old only.
New code: writes to old and new.
Then we backfill: we run a job that copies old to new for existing rows.
Phase 2 (Migrate):
- Deploy code that reads from new (and writes to both). Now, all reads are from new. But we still have old code that writes to old only? We must get rid of old code? Actually, if we have old code, it will write to old only and we are not reading from old, so we lose those writes? But we are still writing to old from new code, so old is being updated by new code? Actually, in phase 2, new code writes to both, so old is being updated by new code. But if there is old code, it writes to old only. Then when we switch reads to new, we are reading from new, but old code is writing to old only, so new code (which writes to both) will not see the updates from old code because it's writing only to old? And then when we stop writing to old (phase 3), we lose the updates from old code? That's a problem.
So we must ensure that during phase 2, we have no old code? Or we must have a way to capture writes from old code? Actually, the typical solution is to have a cutover where we stop the old code and only run new code. But that might not be zero-downtime? We can do a rolling upgrade? Actually, we can:
- First, deploy new code that writes to both and reads from old (or new if backfilled). Then we can switch reads to new without stopping old code? But then old code is still writing to old only, and we are reading from new? That means we are not reading the updates from old code? That's a consistency issue.
Actually, in phase 2, we want to read from new. But if old code is writing to old only, then the new column (new) is not updated by old code. So we have a consistency problem: reads from new will not see the latest writes from old code (if any). Therefore, we must ensure that during phase 2, there is no old code writing to old only. So we must have a cutover for the writers as well? But that might cause downtime?
Alternatively, we can have:
Phase 1: Add new column, deploy new code that writes to both (so old code writes to old only, new code writes to both). Then backfill.
Phase 2: Deploy new code that reads from new and writes to both. But we must also stop old code? Actually, we can't stop old code immediately because we might have a rolling upgrade. So we need to ensure that during the rolling upgrade, we don't have a mix of old and new code writing to different columns? That's tricky.
The common solution is to have a feature flag that controls which column to write to, and then:
Step 1: Deploy new code that writes to both (and reads from old). Set flag to write to both.
Step 2: Backfill.
Step 3: Set flag to read from new (and write to both). Then wait until all code is updated to read from new? Actually, we can change the read path in the new code, but old code still reads from old? That's okay because we are not dropping old yet.
Step 4: Set flag to write only to new. Then wait until we are sure no old code is running? Then drop old.
But step 4: we set flag to write only to new. Then any old code that hasn't been upgraded will write to old only? So we must have a way to know when all old code is gone? We can use a canary or a timeout? This is where verifiers come in.
Given the complexity, the toolkit should provide:
- A way to define the migration steps (expand, migrate, contract) with conditions.
- Verifiers to check:
* After expand: new column exists and is nullable (or has default) and old column still exists.
* After backfill: data in new column matches old column for all rows (or for a sample?).
* After migrate: all reads are from new? How to check? We might need to log or have a way to know which read path is being used? Or we can have a feature flag that we set and then check that all instances have the flag set? That's more of a deployment issue.
* After contract: old column is dropped, and we have verified that all code is using new.
- Rollbacks:
* For expand: drop the new column.
* For migrate: switch reads back to old? But if we have written to new and not to old (if we stopped writing to old in the migrate step? Actually, in the typical sequence, we don't stop writing to old until contract). So in migrate, we are still writing to both. So rollback of migrate would be to switch reads back to old? And then we can stop writing to new? But then we have to backfill again? Actually, if we rollback after migrate, we want to go back to the state where we were writing to both and reading from old? So we can:
Rollback of migrate: set the feature flag to read from old (and write to both). Then we are back to the state after expand.
* For contract: we cannot rollback by restoring the old column? We would have to restore from backup. So we must not drop the old column until we are absolutely sure. So the toolkit should warn that contract is irreversible without backup.
So the toolkit should:
- Have a migration plan that consists of steps (each step is either expand, migrate, or contract).
- Each step has:
* An up (or forward) action (SQL or code to run).
* A down (or backward) action (if reversible).
- Verifiers: for each step, we can run verifiers (which are also reversible? or just checks).
- The toolkit should manage the state of the migration (which steps have been run, and which are reversed).
- We can have a table in the database to track the migration state? Or we can rely on the migration files and a separate table? Like a schema_migrations table.
But note: we might have multiple databases? And we want to run migrations on multiple shards? The toolkit should be distributed? That's complex.
Let's simplify: assume a single database for now.
Proposed design:
We have a directory of migration files, each with:
- A version number (timestamp)
- A type (expand, migrate, contract)
- An up SQL (or code) and a down SQL (if reversible).
- A set of verifiers (SQL queries or code) that check the state.
We have a table `migration_history`:
id (primary key)
version (string, the migration version)
type (enum: expand, migrate, contract)
status (enum: pending, running, completed, rolled_back)
started_at, completed_at, rolled_back_at
checksum (of the migration file? to detect changes)
We also have a table `verification_results`:
migration_id (foreign key to migration_history)
verifier_name
passed (boolean)
message
ran_at
The toolkit CLI:
Commands:
migrate <version> [--dry-run] [--rollback]
- Runs the migration up to the given version (in order) and runs verifiers after each step.
- If any verifier fails, it can stop (or continue?).
--rollback: rollback to the previous version? Or rollback a specific step?
verify <version>
- Runs the verifiers for the given migration (if completed) or for a specific step?
rollback <version>
- Rollback the migration to the previous version (by running down steps in reverse order).
plan
- Show the plan of migrations.
How to handle the fact that expand and migrate are reversible but contract is not?
We can mark the migration as irreversible? Or we can have a flag in the migration file:
irreversible: true
Then when trying to rollback a contract, the toolkit will refuse unless forced (and then it will require a backup?).
How to handle the backfill during migrate?
The migrate step might be a long-running backfill. We can break it into multiple batches? The toolkit can support:
- A backfill script that runs in batches, and we can check the progress.
But the migration step might be represented by a single SQL (like UPDATE) that runs for a long time? Or we might have a separate backfill job.
We can have:
In the migration file for migrate:
up: |
-- This is a long running update, so we do it in batches?
-- We can provide a stored procedure or a script that runs in batches.
down: |
-- How to rollback? We might have to move data back from new to old? But if we have been writing to both, then old and new should be in sync? Actually, if we have been writing to both, then during the migrate phase we are reading from new and writing to both. So if we rollback, we want to read from old and write to both? Then we don't need to move data? But if we have done a backfill, then the data in new and old should be the same for existing rows? But for new rows written during the migrate phase, we wrote to both. So if we rollback, we are still safe because old has the data? Actually, if we rollback after migrate, we switch reads back to old. Then we are reading from old, which has all the data (because we wrote to both). So we don't need to move data? But what about the rows that were backfilled? They are in both. So we are safe.
So the down for migrate might be just a change in the application code? Actually, the migration might be just a change in the schema and a change in the application. So the toolkit might not be able to rollback the application code. We are only managing the database schema and data.
Therefore, the toolkit should assume that the application code is deployed along with the database migration? Or we separate the two?
In a typical deployment, we might:
Step 1: Deploy new code that writes to both (and reads from old) -> this is the expand step in code, but the database step is just adding the column.
Step 2: Run backfill (database).
Step 3: Deploy new code that reads from new (and writes to both) -> this is the migrate step in code, but the database step might be just a verifier? Actually, the database step for migrate might be empty? Or we might have to change some constraints?
So the database migration steps:
Expand: add new column (and maybe an index?).
Migrate: possibly create an index on the new column? Or change a constraint? Or nothing? And run the backfill.
Contract: drop old column.
So the toolkit should allow:
- For expand: up = "ALTER TABLE ... ADD COLUMN ...", down = "ALTER TABLE ... DROP COLUMN ..."
- For migrate: up = a backfill script (maybe a stored procedure that runs in batches) and then create an index on the new column? down = drop the index and maybe move data back? But if we are writing to both, then we don't need to move data back? Actually, if we rollback, we want to go back to reading from old, so we don't need the index on new? But if we drop the index, then when we switch back to old, we might have an index on old? That's okay.
But note: if we rollback after migrate, we are going back to the state after expand (where we have both columns and we are writing to both and reading from old). So we might want to drop the index on new? Because in the state after expand, we might not have an index on new? Actually, we might have created the index in the expand step? Or in the migrate step?
So we have to design the steps carefully.
Let's define:
Expand:
- Add new column (nullable, no default if it's a big table).
- Create an index on the new column? But if we are going to query by the new column, we might want the index. But we are not querying by it until we switch reads? So we can create the index in the expand step? But creating an index on a big table can be heavy and lock? We can create it concurrently? That's database specific.
Migrate:
- Backfill data (if needed).
- Then we might want to set the new column as NOT NULL? But we can't until we have backfilled and we are sure we are writing to it? Actually, we can set NOT NULL in the contract step? Or in migrate after backfill? But if we set NOT NULL in migrate, then we must have no nulls. And we must be writing to it in the new code. But we are writing to both, so if we set NOT NULL, then the old code might write null to the old column? That's okay because we are not using old for reading? But we are still writing to old? Actually, we are writing to both, so if the new code writes a value to new and old, then new is not null. But if the old code writes to old only, then new remains null? So we cannot set NOT NULL until we stop old code? So we set NOT NULL in contract.
Contract:
- Drop old column.
- Set new column as NOT NULL? Or we might have already set it? Actually, we might want to set NOT NULL in contract because by then we are sure that new is always written (by new code) and we have no old code.
So the steps:
Expand:
up:
ALTER TABLE ... ADD COLUMN new_column ...;
CREATE INDEX CONCURRENTLY ... ON ... (new_column); -- if needed
down:
DROP INDEX CONCURRENTLY ...;
ALTER TABLE ... DROP COLUMN new_column;
Migrate:
up:
-- Backfill in batches? We can have a stored procedure that does:
DO $$
DECLARE
batch_size INT := 1000;
rows_updated INT;
BEGIN
LOOP
UPDATE ... SET new_column = old_column WHERE new_column IS NULL LIMIT batch_size;
GET DIAGNOSTICS rows_updated = ROW_COUNT;
EXIT WHEN rows_updated = 0;
END LOOP;
END $$;
-- Then maybe create a NOT NULL constraint? But we can't because old code might write null? Actually, we are writing to both, so if old code writes, it writes only to old, so new might be null? So we cannot set NOT NULL until contract.
down:
-- We don't need to move data back? Because if we rollback, we are going to read from old and write to both? So we don't need to clear new? Actually, we might have backfilled, so new has data. But if we rollback, we are going to read from old, so it's okay? But then when we write, we write to both. So if we rollback, we are in the state after expand: we have both columns and we are writing to both. So we don't need to do anything? But what about the index on new? We might have created an index in expand? Then in down, we should drop the index? But we created the index in expand, so the down of expand already drops it? Actually, the down of migrate should not drop the index because the index was created in expand? So the down of migrate might be empty? Or we might have created the index in migrate? Then we drop it in down.
Contract:
up:
ALTER TABLE ... DROP COLUMN old_column;
ALTER TABLE ... ALTER COLUMN new_column SET NOT NULL; -- if we want
-- Maybe rename new_column to old_column? That would be a rename, but we are dropping old? Actually, we are dropping old, so we might want to rename new to old? That would break the code that uses the new name? So we don't rename.
down:
-- We cannot restore the old column without a backup. So we must not allow down on contract? Or we must have a backup.
So the down for contract is not possible without a backup. So we mark contract as irreversible.
But note: the migrate step might have created an index on the new column? Then in the down of migrate, we drop that index? But then in the down of expand, we also drop the index? That would be double drop? So we must be careful about the order.
Actually, the expand step might not create the index? We might create the index in migrate? Because during expand we are not using the new column for reads? So we can create the index in migrate, after backfill? Then in the down of migrate, we drop the index.
So:
Expand:
up: add column.
down: drop column.
Migrate:
up: backfill and create index (if needed).
down: drop index and maybe clear the new column? But if we rollback, we are going to read from old, so we don't care about the new column? But we are still writing to both? Actually, if we rollback, we are going to the state after expand, which has the new column (with data) and we are writing to both. So we don't need to clear the new column? But if we rollback, we are going to run the down of expand? No, we are rolling back migration by migration. So we rollback contract (if any) then migrate then expand? Actually, we rollback in reverse order.
So if we rollback from a contract, we first rollback contract (which is irreversible? so we can't) then rollback migrate (drop index) then rollback expand (drop column). But if we rolled back migrate, we drop the index on new. Then we rollback expand, we drop the new column. So that's consistent.
But if we rollback from migrate (without contract), then we rollback migrate: drop index on new, and then we are in the state after expand (with new column and index? wait, we dropped the index in the down of migrate, but we created the index in migrate? So in the state after expand, we don't have the index? That's okay because we are reading from old.
So the state after expand: new column exists (with data from backfill) but no index? And we are writing to both and reading from old.
Then in migrate, we create the index and switch reads to new. Then in contract, we drop old and set not null.
So if we rollback migrate, we drop the index and switch reads back to old? Actually, the migrate step might also include a change in the application to read from new. So the rollback of migrate would be to change the application back to read from old? That's outside the database.
So the database toolkit only handles the database schema and data. The application code deployment is separate.
Therefore, the migration file for migrate might not include the application code change. We might have:
- Database migration: backfill and create index.
- Application deployment: change read path.
But then the verifier for migrate might check that the read path has been switched? That's not a database check.
So maybe we separate the migration into:
- Database schema and data migrations.
- Application migrations (which might be feature flags, etc.)
And the toolkit only handles the database part? But then the zero-downtime migration involves both.
Alternatively, we can have the toolkit manage the entire process, including feature flags? That might be too broad.
Given the scope, let's assume the toolkit is for database schema and data only, and the application deployment is managed separately.
Then the steps:
Step 1 (Expand):
- Database: add column and index (if needed).
- Application: deploy code that writes to both (and reads from old).
Step 2 (Migrate):
- Database: backfill (if needed) and then create index? Actually, we might have created the index in step 1? But if we create the index in step 1, then during backfill we are updating the new column and the index is being updated? That might slow down the backfill? So we might want to create the index after backfill.
So:
Step 1: add column (without index). Deploy code that writes to both (and reads from old).
Step 2: backfill (without index). Then create index (concurrently). Then deploy code that reads from new (and writes to both).
Step 3: contract: drop old column and set new column as not null? Then deploy code that writes only to new.
But then the index creation in step 2 might be heavy and we might want to do it in a separate step? Or we can do:
Step 1: add column.
Step 2: backfill.
Step 3: create index.
Step 4: switch reads to new.
Step 5: stop writing to old (in code) and drop old column.
That's too many steps.
Let's stick to three steps (expand, migrate, contract) and let the migrate step include:
- Backfill
- Create index (if needed)
- Then we deploy code to read from new (but that's separate).
So the toolkit's migrate step only does the database part: backfill and then create index? And then we have a separate application deployment to switch reads.
But then the verifier for migrate would check that the backfill is done and the index exists? And then we have a separate verifier for the application? That's outside the toolkit.
So the toolkit is only for database. The application deployment is separate and might be coordinated by a separate system.
Therefore, the toolkit will:
- For expand: add column (and maybe index? we can make it configurable).
- For migrate: run a backfill (if provided) and then create index? Or we can have two separate migrations? Actually, the migrate step might be broken into:
migrate_data: backfill
migrate_index: create index
But then we have two migrate steps? That breaks the three steps pattern.
Alternatively, we can have:
expand: add column (and maybe index? but we don't want index during backfill? so we don't create index in expand)
migrate:
up: backfill data (in batches) and then create index? But we want to create index after backfill to avoid index maintenance during backfill? So we do:
up:
-- backfill without index
-- then create index concurrently
down:
-- drop index
-- and maybe clear the new column? But we don't want to break the backfill? Actually, if we rollback, we are going to read from old, so we don't need the new column? But we are still writing to both? So we don't clear.
contract: drop old column.
But then the index creation in migrate might take time and we might want to run it concurrently? That's database specific.
Given the complexity, we might design the toolkit to be flexible:
Each migration step has:
- up: a SQL script (or multiple) that can be run.
- down: a SQL script (if reversible).
And we can have:
expand.sql:
ALTER TABLE ... ADD COLUMN ...;
migrate.sql:
-- backfill in batches? We can provide a stored procedure that does batch updates.
-- then create index concurrently.
contract.sql:
ALTER TABLE ... DROP COLUMN ...;
ALTER TABLE ... ALTER COLUMN ... SET NOT NULL; -- if needed
And the verifiers:
After expand:
check that new column exists and is nullable.
After migrate:
check that backfill is complete (select count where new_column is null) and that index exists.
After contract:
check that old column does not exist and new column is not null.
But note: the contract step might set not null, so we check that.
Rollback:
expand: drop the new column (and index if we created one in expand? but we didn't create index in expand, so only drop column).
migrate: drop the index (and maybe clear the new column? but we don't have to because we are going to drop the column in the next rollback? Actually, if we rollback migrate, we are going back to expand state, which has the column (with data) but no index? So we drop the index and that's it.
contract: we cannot rollback without backup? So we mark it as irreversible.
How to handle the backfill batch updates? We can provide a template that does:
UPDATE ... SET new_column = old_column WHERE new_column IS NULL LIMIT {batch_size};
And then we run it in a loop until no rows are updated.
But the same update might run for a long time and lock rows? We can use a cursor? Or we can do:
UPDATE ... SET new_column = old_column
WHERE id IN (SELECT id FROM ... WHERE new_column IS NULL LIMIT batch_size FOR UPDATE SKIP LOCKED);
That's more advanced and database specific.
Given the variety of databases, we might make the backfill script custom per migration.
So the toolkit just runs the provided SQL scripts and runs the verifiers.
The verifiers can be:
- A SQL query that returns 0 rows if successful, or a message.
Example verifier for expand:
SELECT 1 FROM information_schema.columns
WHERE table_name = '...' and column_name = 'new_column'
AND is_nullable = 'YES';
If it returns 0 rows, then the column doesn't exist or is not nullable? That's a failure.
Example verifier for migrate (backfill complete):
SELECT 1 FROM ... WHERE new_column IS NULL LIMIT 1;
If it returns a row, then backfill not complete.
Example verifier for contract:
SELECT 1 FROM information_schema.columns
WHERE table_name = '...' and column_name = 'old_column';
If it returns a row, then old column still exists.
So the toolkit:
- Reads migration files from a directory (with version and type).
- For each migration, runs the up SQL (if not already run) and then runs the verifiers.
- If any verifier fails, it stops and marks the migration as failed? And then we can rollback?
- We have a state table to track which migrations have been run and their status.
- We can rollback a migration (if it's not contract and if down is provided) by running the down SQL and then the verifiers for the previous state? Actually, when we rollback, we run the down of the migration and then we are in the previous state. We might want to run the verifiers of the previous migration? Or we can run the verifiers of the current state (after rollback)?
Let's define:
We have a sequence of migrations: M1 (expand), M2 (migrate), M3 (contract).
We run M1, then M2, then M3.
If we want to rollback from M3, we cannot.
If we want to rollback from M2, we run M2 down, and then we are in the state after M1 (which is complete). We can then run the verifier of M1? But M1 verifier already passed? We might want to run the verifier of M1 again? Actually, after rolling back M2, we are in the state of M1 completed, so we don't need to run M1 verifier? But what if the down of M2 broke something? We should run the verifier of M1 to make sure we are still in a good state? But M1 verifier checks for the existence of the new column and that it's nullable. That should still be true. So we can run the verifier of the current state (which is M1) or we can run the verifier of M1? Actually, we have a state table, and we mark M2 as rolled_back, and then we are at M1 completed. So we can run the verifier of M1? But we already ran it when we completed M1. We might not need to run it again? But if the down of M2 did something that broke M1's state? For example, if the down of M2 dropped the index that was created in M2, but M1 doesn't require the index? So it's okay.
So after rollback, we don't run any verifier? Or we run the verifier of the current state? Actually, we should run the verifier of the migration that is now the latest completed? That is M1. But we don't have a verifier for the state after M1? We have a verifier for M1 (which is the state after M1). So we can run the verifier of M1? But note: the verifier of M1 was run when we completed M1. We might want to run it again to ensure that after rolling back M2, M1's state is still valid? But if M2's down doesn't touch M1's objects, then it's okay.
Alternatively, we can run the verifier of the migration that we are rolling back to? That is, after rolling back M2, we run the verifier of M1? But we are not rolling back to M1? We are rolling back M2, so we are reverting the changes of M2, and then we are at M1. So we should run the verifier of M1? Actually, we are at M1 completed, so we don't need to run M1's verifier again? But if we want to be safe, we can.
Let's decide: after any migration (up or down), we run the verifier of the current state? But the current state after a down is the state of the previous migration? So we run the verifier of the previous migration? That might be confusing.
Instead, we can associate verifiers with the state after the migration. So:
After running M1 up, we run M1's verifier (which checks the state after M1).
After running M2 up, we run M2's verifier (which checks the state after M2).
After running M2 down, we are in the state after M1, so we run M1's verifier.
That makes sense.
So the workflow:
To migrate up to M2:
Run M1 up -> run M1 verifier (must pass)
Run M2 up -> run M2 verifier (must pass)
To rollback from M2 to M1:
Run M2 down -> run M1 verifier (must pass)
To rollback from M1 (to before M1):
Run M1 down -> run no verifier? Because we are in the initial state? Or we can have a verifier for the initial state? That's not defined.
So we only have verifiers for migrations that have been applied.
Implementation:
We have a table `migration_history` with:
version (string, unique)
type (enum: expand, migrate, contract)
status (enum: pending, completed, rolled_back)
started_at, completed_at, rolled_back_at
up_checksum, down_checksum (to detect if the migration file changed)
And a table `verification_results`:
migration_version (foreign key to migration_history.version)
verifier_name
passed (boolean)
message
ran_at
Steps for running a migration up:
1. Check if the migration file has changed (by checksum) and if the migration is already completed? If completed and checksum changed, we might warn? Or we can allow re-run? But that might be dangerous.
2. Start a transaction? We might want to run the up SQL in a transaction? But for long backfills, we might not want to run in one transaction? So we can't.
3. Run the up SQL (which might be multiple statements). We assume the up SQL is idempotent? Not necessarily.
4. If the up SQL succeeds, then run the verifiers for this migration.
5. If all verifiers pass, mark the migration as completed.
6. If any verifier fails, mark the migration as failed? And then we can rollback? But we might not have a down? Or we can run the down? That's a choice.
Steps for rolling back:
1. Check that the migration is completed and that it is reversible (not contract? or have a down?).
2. Run the down SQL.
3. Run the verifier of the previous migration (the one that is now the latest completed). If there is no previous migration (i.e., we are rolling back the first migration), then we don't run a verifier? Or we run a general verifier that checks the initial state? That's not defined.
4. If the verifier passes, mark the current migration as rolled_back.
But note: when we rollback, we are reverting the changes of the current migration, so we are in the state of the previous migration. So we run the verifier of the previous migration to ensure that we are in a good state.
How to handle multiple databases (shards)? We might need to run the migration on each shard. The toolkit should support that?
We can have a configuration that lists the databases, and then we run the migrations on each database? But the migrations might be different per shard? Usually, we have the same schema.
We can have a command that runs on a single database, and then we orchestrate across shards with a script.
Given the complexity of sharding, we leave it out for now.
Implementation:
We'll write a CLI in Python (or any language) that:
- Reads a directory of migration files.
- Each migration file is a YAML (or JSON) with:
version: "20240101000000"
type: expand|migrate|contract
up: |
SQL statements...
down: |
SQL statements... (optional, if missing then not reversible)
verifiers:
- name: "check_new_column_exists"
sql: "SELECT ..."
expected: "empty" # or "non_empty", "count", etc.
But we can also have the verifiers as separate files? Or we can have the verifiers in the same file.
We'll have a command:
toolkit migrate [target_version]
It will:
- Read all migration files in order (by version).
- For each migration that is not completed, run the up SQL and then the verifiers.
- If any verifier fails, stop and report.
- We can have a flag to force continue? But that might be dangerous.
Rollback:
toolkit rollback [migration_version]
It will:
- Find the migration with the given version.
- Check that it is completed and has a down.
- Run the down SQL.
- Then find the previous migration (by version) that is completed (or the one that is now the latest completed) and run its verifiers.
- If the verifiers pass, mark the current migration as rolled_back.
We also need a way to mark a migration as completed without running? Or to force? For example, if we ran the migration manually, we can insert a record in the history table? That's possible.
How to handle the initial state? We might have no migrations run.
When we run the first migration, after up, we run its verifier. Then mark as completed.
When we rollback the first migration, we run its down, and then there is no previous migration? So we don't run any verifier? Or we can have a verifier for the initial state? That's tricky.
We can say: after rolling back the first migration, we are in the initial state, so we don't run any verifier.
Let's code the CLI structure:
We have:
class Migration:
version: str
type: str
up_sql: str
down_sql: Optional[str]
verifiers: List[Verifier]
class Verifier:
name: str
sql: str
expected: str # could be "empty", "non_empty", "count", etc. or we can have a function that checks the result.
But we can make the verifier just a SQL that should return 0 rows for success? Or we can have:
verifier:
- name: ...
sql: ...
expected:
type: "row_count"
value: 0
or
type: "value"
value: "something"
Actually, we can run the SQL and then check:
If expected is "empty": then the query should return 0 rows.
If expected is "non_empty": then at least 1 row.
If expected is "count": then the count of rows should be equal to a given number.
But the verifier might be more complex? We can have a Python function? But then we need to run it in the context of the database? We can have the verifier as a SQL that returns a single value? And then we compare?
Alternatively, we can have:
verifier:
- name: ...
sql: "SELECT COUNT(*) FROM ... WHERE ..."
min: 0
max: 0
But that's limited.
Let's keep it simple: the verifier is a SQL that should return 0 rows for success. We can also have:
- If the verifier returns any row, it fails and the row is the error message.
So:
Run the verifier SQL.
If it returns at least one row, then the first column of the first row is the error message? Or we can have the verifier return a message.
Actually, we can have:
verifier:
- name: ...
sql: "SELECT 'error message' FROM ... WHERE condition"
Then if the query returns a row, the first column is the error message.
Or we can have:
verifier:
- name: ...
check_sql: "SELECT 1 FROM ... WHERE condition"
message_sql: "SELECT 'error message' FROM ... WHERE condition"
That's more complex.
Let's do:
verifier:
- name: ...
sql: "SELECT 'some error' WHERE condition"
Then if the query returns a row, the first column is the error message.
But what if we want to check that a count is 0? We can do:
sql: "SELECT 'has rows' FROM table WHERE condition LIMIT 1"
Then if there are rows, it returns 'has rows', else 0 rows.
So the verifier passes if the query returns 0 rows.
Steps for running a verifier:
Execute the SQL.
If the result set has 0 rows -> pass.
Else, fail with the first row's first column as the message.
But what if we want to check that a column is NOT NULL? We can do:
sql: "SELECT column_name FROM information_schema.columns WHERE table_name = ... AND column_name = ... AND is_nullable = 'NO'"
That returns a row if it's not nullable? Actually, we want to check that it is nullable? Then we do:
sql: "SELECT 'column is not nullable' FROM information_schema.columns WHERE table_name = ... AND column_name = ... AND is_nullable = 'NO'"
Then if it's not nullable, it returns a row with the message.
So that works.
Now, the state table:
We'll create a table in the target database called `schema_migration_toolkit` (or something) to track:
migration_version (string, primary key)
migration_type (string)
up_checksum (string)
down_checksum (string, nullable)
status (string: pending, completed, rolled_back)
started_at (timestamp)
completed_at (timestamp, nullable)
rolled_back_at (timestamp, nullable)
And a table for verifier results:
migration_version (string, foreign key)
verifier_name (string)
passed (boolean)
message (text, nullable)
ran_at (timestamp)
We might run multiple verifiers per migration.
The CLI will connect to the database and:
- Check if the state table exists, if not, create it.
- Then for each migration file (sorted by version):
If the migration is already in the state table with status completed and the checksum matches, skip.
If the migration is in the state table with status completed but checksum changed, we might error? Or we can allow re-run? We can have a flag to force.
If the migration is not in the state table, or is pending or failed, then run it.
For rolling back:
We specify the version to rollback. We check that the migration is completed and has a down.
Then we run the down SQL.
Then we run the verifier of the previous migration (the one that is now the latest completed). How to find the previous? We look at the state table for the migration with the highest version that is less than the current and is completed? But note: we might have skipped some? Actually, we run migrations in order, so we should have a contiguous set? Not necessarily if we skip? We can have a gap? We might have run M1 and M3, but not M2? That would be weird.
We should enforce that we run in order? The toolkit should run migrations in version order and not skip? So we only consider migrations that are in the directory and we run them in order.
So when rolling back, we rollback the specified migration, and then we run the verifier of the migration that is now the latest completed (which might be the previous one in the directory, but if we skipped some, then it might be earlier). But we should not skip? So we assume we have run all previous migrations.
So we can find the previous migration by:
SELECT version FROM migration_history
WHERE status = 'completed'
AND version < current_version
ORDER BY version DESC
LIMIT 1;
Then run its verifiers.
If there is no previous migration (i.e., we are rolling back the first migration), then we don't run any verifier.
How to run the SQL?
We can use a database connection (we support one database? or multiple?).
We'll assume one database for now.
Verifiers run in the same transaction? We might want to run the verifiers in a separate transaction? Because the migration might have made changes that are not committed? Actually, the migration up SQL might be autocommit? For long backfills, we might not use a transaction.
So we run the up SQL (which might commit implicitly or we commit after?).
Then we run the verifiers in a new transaction? Or we don't use transaction for verifiers? We can run each verifier in its own transaction? That might be heavy.
We can run all verifiers in one transaction? But if one fails, we might want to rollback the verifiers? But the migration up has already been committed? So we don't need to rollback the verifiers.
Actually, the verifiers are just checks, so we can run them without transaction? But we want to see a consistent state? We might want to run the verifiers in a read-only transaction? That's database specific.
We can run the verifiers in a separate connection? Or we can use the same connection and set autocommit?
Given the complexity, we run the up SQL and then commit? But if the up SQL is a long backfill, we might want to run it in batches and commit each batch? That's up to the migration writer.
So the toolkit just runs the SQL as provided.
Then for verifiers, we run each verifier SQL in a separate transaction? Or we run all in one? We can run each verifier in its own transaction to avoid locking? But we are just reading.
Let's run each verifier in a separate transaction (autocommit mode) so that we get a consistent view? Actually, if the migration up committed, then the verifiers will see the committed state.
So we can run the verifiers in autocommit.
Now, the down SQL:
We run the down SQL and then commit? Similarly.
But note: if the down SQL is also long, we might want to run in batches? The migration writer should handle that.
So the toolkit just runs the SQL as is.
Now, the state table:
We need to record:
- migration version
- type
- up_checksum (of the up SQL)
- down_checksum (of the down SQL, if exists)
- status: pending, completed, rolled_back
- started_at, completed_at, rolled_back_at
We can also record the verifier results.
Steps for running up:
1. Read the migration file.
2. Compute checksum of up_sql and down_sql.
3. Check if there is an existing record for this version.
If not, insert a record with status pending, started_at=now, up_checksum, down_checksum.
If exists and status is completed and checksums match, skip.
If exists and status is completed but checksums differ, error (or force?).
If exists and status is pending or failed, then we retry? Or we error? We can have a flag to force.
4. Run the up_sql. If it fails, update the record to status=failed? And abort.
5. Run the verifiers. For each verifier:
Run the sql.
If it returns rows, then the verifier fails. Collect the messages.
Record the verifier result in the verification_results table.
6. If all verifiers pass, update the migration record to status=completed, completed_at=now.
7. If any verifier fails, we do not mark as completed. We leave it as pending? Or failed? And then we can rollback? But we ran the up_sql already? So we might want to run the down_sql? That's a choice.
We can have:
If any verifier fails, then we automatically run the down_sql (if exists) and then mark as rolled_back? But that might be dangerous because the down_sql might not be safe to run if the up_sql partially succeeded? Actually, the up_sql might have been run and committed? Then we run the down_sql to revert? But the down_sql might not be designed to run after a partial up? We assume the up_sql is atomic? But for long operations, it might not be.
Alternatively, we can leave it as failed and let the user decide to rollback.
Given the complexity, we can have:
If any verifier fails, we do not run the down automatically. We mark the migration as failed and let the user run rollback.
But then the database is in a state where the migration up has been applied but the verifier failed? That might be an inconsistent state.
So we might want to run the down_sql automatically on verifier failure? But only if the up_sql was successful? And we must be in a transaction? But we can't for long operations.
Let's not automate the rollback on verifier failure. We'll mark the migration as failed and then the user can run rollback.
So:
If up_sql succeeds but verifiers fail, we set status=failed and record the verifier failures.
Then the user can run:
toolkit rollback <version>
Which will run the down_sql and then run the verifier of the previous migration.
Steps for rollback:
1. Check that the migration exists and is completed and has a down_sql.
2. Run the down_sql.
3. Find the previous migration (the latest completed with version less than the current). If exists, run its verifiers.
4. If the verifiers pass, update the current migration status to rolled_back, set rolled_back_at.
5. If the verifiers fail, then we have a problem: the down_sql might have broken the previous state? We leave the migration as completed? Actually, the down_sql was run, but the previous state is not valid? We might mark the current migration as rolled_back? But the previous migration's verifier failed? That means the previous migration is not valid? But we are rolling back the current, so we are in the state of the previous migration? If the previous migration's verifier fails, then the state is not valid? But we didn't change the previous migration? We only ran the down of the current.
Actually, the previous migration's verifier might fail because the down of the current migration broke something? For example, if the current migration created an index and the down dropped it, but the previous migration's verifier expects the index? Then the previous migration's verifier will fail.
So we must design the verifiers carefully: the verifier for a migration should only check the changes made by that migration? Or the state after that migration?
Example:
M1 (expand): adds column A.
Verifier for M1: checks that column A exists and is nullable.
M2 (migrate): creates index on A, and backfills.
Verifier for M2: checks that index exists and backfill is complete (no nulls in A?).
If we rollback M2, we drop the index. Then we run the verifier for M1? The verifier for M1 only checks that column A exists and is nullable. That should still be true. So it passes.
But if the verifier for M1 also checked that the index exists? Then it would fail after rolling back M2.
So the verifier for a migration should only check the state that is expected after that migration, and that state should be a subset of the state after later migrations? That is, the state after M1 should be a valid state even after M2? Because M2 builds upon M1.
So the verifier for M1 should not check for the index (which is added in M2). It only checks for the column.
Therefore, when we rollback M2, we run the verifier of M1 and it should pass.
But what if the down of M2 does something that breaks M1? For example, if the down of M2 drops the column? That would be wrong because M1 added the column. So the down of M2 should only drop the index and maybe clear the column? But not drop the column.
So the down of a migration should not break the previous state.
Therefore, the verifier of the previous migration should pass.
So in rollback:
Run down of current migration.
Then run the verifier of the previous migration (if any).
If that verifier passes, then mark current as rolled_back.
If it fails, then we have a problem: the down of current broke the previous state. We don't mark as rolled_back? We leave it as completed? But we ran the down? Actually, we ran the down, so we are in a state that is not the previous state? We might need to fix manually.
We can have a force flag? Or we can leave it as completed and the user must fix.
But note: the down of the current migration might have been written incorrectly. So we should not mark it as rolled_back if the verifier of the previous state fails.
We can:
If the verifier of the previous state fails, then we do not mark the current migration as rolled_back. We leave it as completed? But we ran the down? Actually, we ran the down and it succeeded (no SQL error) but the state is not as expected? Then we mark it as rolled_back? But the verifier failed? We can mark it as rolled_back but with a warning? Or we can have a status "rollback_failed"?
Let's have:
status:
pending
completed
rolled_back
failed (up failed)
rollback_failed (down succeeded but verifier of previous state failed)
Then the user can investigate.
Summary:
We have a toolkit that:
- Tracks migrations in a state table.
- Runs up SQL and then verifiers for each migration in order.
- Can rollback a migration by running down SQL and then the verifier of the previous migration.
We assume:
- The up and down SQL are provided by the user and are idempotent? Not necessarily, but we run them only once (unless forced).
- The verifiers are provided and are specific to the state after that migration.
- The down SQL of a migration should not break the state of the previous migration.
- The verifier of a migration should only check the changes introduced by that migration, and should pass in the state after that migration and also after any subsequent migrations? Actually, after subsequent migrations, the state might have more changes, but the verifier for M1 should still pass because M1's changes are still there? Unless M2 or M3 dropped them? But then M2 and M3 are built on M1, so they should not drop M1's changes until contract (which is the last step). And contract is the one that drops the old column. So after contract, the verifier for M1 (which checks for the new column) should still pass? Actually, contract drops the old column, but the new column is still there. So M1's verifier (which checks for the new column) should pass. But M1 also might have checked that the old column exists? No, M1 is expand, which adds the new column. So M1's verifier checks for the new column. After contract, the new column is still there, so it passes.
But what about M2's verifier? M2 checks for the index on the new column. After contract, the index might still be there? Yes. So it passes.
So the verifiers should be designed to pass in the final state (after all migrations) as well? That's good.
However, note: the contract step might drop the old column and set the new column as NOT NULL. Then the verifier for M1 (which checked that the new column is nullable) would fail? Because after contract, the new column is NOT NULL.
So we have a problem: the verifier for M1 expects the new column to be nullable. But after contract, it's not nullable. So the verifier for M1 would fail in the final state.
Therefore, the verifier for a migration should only check the state immediately after that migration? But then when we rollback, we run the verifier of the previous migration (which is M1) and we are in the state after M1 (with the new column nullable). That's correct.
But if we run the verifier of M1 after M3 (contract), it would fail because the new column is not nullable? But we don't run the verifier of M1 after M3? We only run the verifier of M3 (contract) after M3. And M3's verifier might check that the old column is dropped and the new column is not nullable.
So the verifier for M1 is only run after M1 (and after rolling back M2, we run M1's verifier). It is not run after M3.
So we are safe.
Therefore, the verifier for a migration should check the state immediately after that migration, and that state might changed by later migrations? But the later migrations should not break the verifier of the earlier migrations? Actually, they might (like changing nullable to not nullable). So we must design the verifiers to be specific to the state after that migration and not depend on later changes.
Example: M1 (expand) adds column A as nullable. Verifier: column A exists and is nullable.
M3 (contract) sets column A as not nullable. Then after M3, the verifier for M1 would fail because column A is not nullable.
But we don't run the verifier for M1 after M3. We run the verifier for M3 after M3.
So it's okay.
But what if we rollback M3? Then we run the down of M3 (which sets column A as nullable again? Actually, the down of M3 would set it back to nullable? And drop the old column? Wait, M3 up: drop old column and set new column as not nullable. So down: set new column as nullable and restore old column? But we dropped the old column, so we can't restore without backup. So M3 is irreversible? Then we cannot rollback M3.
So we mark M3 as irreversible.
Therefore, we only run the verifier of M2 after rolling back M3? Actually, we cannot rollback M3 because it's irreversible.
So we don't have that issue.
Conclusion:
The toolkit will:
- Have a state table to track migrations.
- Run migrations in order (by version) and run verifiers after each.
- On rollback, run the down of the specified migration and then the verifier of the previous migration (if any).
We must design the migrations so that:
- The down of a migration does not break the state of the previous migration.
- The verifier of a migration checks the state after that migration, and that state should be a valid state even after later migrations? Not necessarily, because later migrations might change it (like setting not null). But we don't run the verifier of an earlier migration after a later one.
But when we rollback, we run the verifier of the previous migration, which should pass in the state after the down of the current migration? That state should be the same as the state after the previous migration (if the down of the current migration correctly reverts).
So the down of the current migration should bring us back to the state after the previous migration.
Therefore, the verifier of the previous migration should pass.
Example:
M1: add column A (nullable). Verifier: column A exists and is nullable.
M2: backfill and create index on A. Verifier: index exists and no nulls in A.
Down of M2: drop index. Then we run the verifier of M1: column A exists and is nullable. That should pass.
M3: drop column B (old) and set A as not null. Irreversible.
If we could rollback M3, we would set A as nullable and restore column B? But we can't without backup. So we mark M3 as irreversible.
Now, the backfill in M2: the down of M2 does not clear the data in A? That's okay because the verifier of M1 does not check the data, only the column's nullability.
But what if the verifier of M1 also checked that there are no nulls? Then after rolling back M2, we have nulls (because we didn't clear the data? Actually, we didn't clear the data, so if the backfill filled all nulls, then after rolling back M2, the column A still has no nulls? But what if during M2 we had new rows inserted that were not backfilled? Actually, during M2 we are writing to both A and B? So A should have data for all rows? But if we rollback M2, we are going back to the state after M1, where A might have nulls for old rows? Actually, in M1 we added A as nullable. Then in M2 we backfilled old rows. Then in M2 we are writing to both, so new rows have A filled? So after M2, A has no nulls? Then after rolling back M2, we are in the state after M1, which should have nulls for old rows? But we backfilled, so we filled the old rows. Then we are in a state where A has no nulls? But the verifier of M1 expects A to be nullable, but it might have no nulls? That's okay because nullable means it can have nulls, but it doesn't have to.
So the verifier of M1 only checks that the column is nullable, not that it has nulls.
So we are safe.
Implementation plan:
We'll write a Python script (or a small tool) that:
- Connects to the database (using env variables for connection string).
- Creates the state tables if not exists.
- Reads all migration files from a directory (with extension .yaml or .sql?).
- For each migration file, parse it.
- Then run the migrations in order.
The migration file format:
We can use YAML:
version: "20240101000000"
type: expand # or migrate, contract
up: |
ALTER TABLE ... ADD COLUMN ...;
down: |
ALTER TABLE ... DROP COLUMN ...;
verifiers:
- name: "check_column_exists"
sql: |
SELECT 'column does not exist'
FROM information_schema.columns
WHERE table_name = '...' AND column_name = '...'
# We can have multiple verifiers.
Or we can have separate files for up, down, and verifiers? But having one file per migration is simpler.
We'll use YAML.
Steps:
1. Load all migration files and sort by version.
2. For each migration:
Check if it's already in the state table and completed with same checksum -> skip.
If it's in the state table and completed but checksum changed -> error (unless --force).
If it's in the state table and status is pending or failed -> we can retry? Or error? We can have a flag to reset.
Otherwise, run:
- Insert a record with status=pending, started_at=now.
- Run the up SQL (using a cursor, commit after? We'll let the user decide by including commit in the SQL? Or we commit after each statement? We can set autocommit=True? That might be dangerous for long transactions? We can run without transaction? Actually, we can run each statement separately? We'll run the entire up SQL as one string? That might have multiple statements.
We can use `connection.execute(up_sql)` and then commit? But if the up_sql has multiple statements, we might need to split? Some databases support multiple statements in one execute? PostgreSQL does with `;`? But we might have a DO block? It's safer to run the entire string as one execute? And let the database handle it.
We'll use `connection.execute(up_sql)` and then commit? Actually, we might want to commit after the entire up_sql? But if the up_sql is long, we might not want to hold a transaction? We can set autocommit=True? Then each statement is committed? That might be what the user expects? For example, a backfill update in batches: the user might write:
DO $$
DECLARE
batch_size INT := 1000;
rows_updated INT;
BEGIN
LOOP
UPDATE ... WHERE ... LIMIT batch_size;
GET DIAGNOSTICS rows_updated = ROW_COUNT;
EXIT WHEN rows_updated = 0;
END LOOP;
END $$;
This runs in one transaction? Actually, the DO block runs in a transaction? In PostgreSQL, a DO block runs in a transaction? Yes, unless we use autonomous transactions? Not supported.
So if we run the entire up_sql in one transaction, it might be long and hold locks? That might be bad.
Alternatively, we can split the up_sql by semicolon and run each statement separately? But then we lose the transaction? And the user might expect the entire up_sql to be atomic? Not necessarily for long backfills.
Given the complexity, we let the user write the up_sql as they wish, and we run it as one string. If they want to break into batches, they can use a loop that commits? But in a DO block, it's one transaction. So they might need to use a different approach? Actually, for a backfill, we can do:
UPDATE ... SET ... WHERE ... AND ... LIMIT batch_size;
and then run it in a loop from a client? But we are running from the toolkit.
We can provide a way to run a script that does batch updates with commits? But that's beyond the scope.
So we assume the up_sql is a single transaction? Or we set autocommit=True and then the up_sql might have multiple statements and each is committed? That's dangerous because if one fails, the previous ones are committed.
We'll do:
connection.autocommit = False
try:
connection.execute(up_sql)
connection.commit()
except:
connection.rollback()
raise
So the entire up_sql is run in one transaction.
But if the up_sql is a long backfill, it might be a long transaction and cause issues.
We can have an option to run without transaction? But then if it fails, we might have partial updates.
We leave it to the user to write the up_sql in a way that is safe? For example, they can break it into batches and commit each batch? But then they would have to write a loop that commits? In a DO block, we can't commit in the middle. So they might need to use a client-side script? That's not ideal.
Alternatively, we can split the up_sql by semicolon and run each statement in its own transaction? But that might break if there are statements that depend on each other? For example, a CREATE TABLE and then INSERT? They must be in the same transaction? Not necessarily.
Given the trade-offs, we'll run the entire up_sql in one transaction. We warn the user that long operations should be broken into multiple migrations? Or we can have a special type of migration that runs in batches? That's getting complex.
We can have:
In the migration file, we can have:
up: |
-- This will be run in one transaction.
or
up_batch: 1000 # and then we split by semicolon and run in batches of 1000 statements? That doesn't make sense.
Actually, we can have:
up: a list of SQL statements? Then we can run each in its own transaction? But then we lose atomicity.
We'll stick to running the entire up_sql in one transaction.
For long backfills, the user can write a stored procedure that does batch updates and commits in the procedure? But in PostgreSQL, a stored procedure (DO block) runs in a transaction. So they cannot commit inside.
They can use a function that uses autonomous transactions? Not supported.
So the user must break the backfill into multiple migrations? Or use a tool that does batch updates from the client? That's outside the toolkit.
So we assume the up_sql is a single transaction and the user is aware of the implications.
3. After the up_sql, run the verifiers.
4. If all verifiers pass, mark as completed.
5. If any verifier fails, mark as failed and do not run down automatically.
Rollback:
1. Check the migration is completed and has down_sql.
2. Run the down_sql in a transaction.
3. Find the previous completed migration (by version). If exists, run its verifiers.
4. If the verifiers pass, mark the current migration as rolled_back.
5. If the verifiers fail, mark the current migration as rollback_failed.
We'll also have commands to show the status.
This is a basic design.
Let's code the structure:
File: toolkit.py
Classes:
Database:
- connection
- create_tables()
- get_migration_history()
- set_migration_status(version, status, ...)
Migration:
- version
- type
- up_sql
- down_sql
- verifiers (list of Verifier)
Verifier:
- name
- sql
Functions:
load_migrations(directory) -> list of Migration, sorted by version.
run_migration(migration, dry_run=False) -> None
run_verifier(verifier, connection) -> (passed, message)
rollback_migration(version, dry_run=False) -> None
CLI:
migrate [target_version] [--dry-run] [--force]
rollback <version> [--dry-run] [--force]
status
We'll use argparse.
This is a big task, so we'll outline the code.
Let's start by defining the state table schema:
CREATE TABLE IF NOT EXISTS schema_migration_history (
version VARCHAR(255) PRIMARY KEY,
type VARCHAR(50) NOT NULL,
up_checksum VARCHAR(64) NOT NULL,
down_checksum VARCHAR(64) NULL,
status VARCHAR(50) NOT NULL,
started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP NULL,
rolled_back_at TIMESTAMP NULL
);
CREATE TABLE IF NOT EXISTS schema_verification_results (
id SERIAL PRIMARY KEY,
migration_version VARCHAR(255) REFERENCES schema_migration_history(version),
verifier_name VARCHAR(255) NOT NULL,
passed BOOLEAN NOT NULL,
message TEXT NULL,
ran_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
We'll use SQLite for simplicity? Or we support multiple databases? We'll use SQLAlchemy to support multiple databases? But that adds dependency.
We'll use the database driver directly? We can use psycopg2 for PostgreSQL? But we want to be database agnostic?
Given the complexity, we'll assume PostgreSQL for now.
Steps:
1. Parse command line.
2. Load migrations from directory.
3. Connect to database.
4. Create state tables if not exists.
5. For migrate: for each migration until target version (or all if not specified), run the migration if needed.
We'll code accordingly.
Due to the complexity and length, we'll write a simplified version that demonstrates the concept.
Let's write the code structure.
Note: This is a big project, so we'll write a minimal version that can be extended.
We'll assume:
- Migration files are in a directory, named like "20240101000000_expand.yaml"
- The YAML file has:
version: "20240101000000"
type: expand
up: "SQL string"
down: "SQL string" (optional)
verifiers:
- name: "verifier1"
sql: "SELECT ..."
- We'll compute the checksum of up and down (SHA256 of the string?).
Let's code.</think>
I'll design a comprehensive zero-downtime schema migration toolkit with expand/migrate/contract phases, verification, and rollback capabilities. This follows industry best practices (GitHub, Shopify, Airbnb patterns).
System Architecture
schema-migration-toolkit/
├── cli/ # Command-line interface
├── core/
│ ├── migrator.py # Main migration orchestrator
│ ├── phases/ # Expand/Migrate/Contract phases
│ ├── verifiers/ # Data/schema verification
│ ├── rollback/ # Rollback strategies
│ └── state/ # Migration state tracking
├── database/
│ ├── adapters/ # Database-specific implementations
│ └── connectivity.py # Connection management
├── migrations/ # Migration definitions
│ ├── 001_add_new_column/
│ │ ├── expand.sql
│ │ ├── migrate.sql
│ │ ├── contract.sql
│ │ ├── verify.py
│ │ └── rollback.sql
├── config/
│ └── settings.yaml # Toolkit configuration
├── plugins/ # Extensions for specific patterns
└── utils/
├── diff.py # Schema diffing
├── checksum.py # Data checksums
└── locking.py # Distributed locking
Core Components
1. Migration Phase Implementation
# core/phases/phase_base.py
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
class MigrationPhase(ABC):
"""Base class for migration phases"""
def __init__(self, migration_id: str, config: Dict[str, Any]):
self.migration_id = migration_id
self.config = config
self.state_manager = StateManager()
@abstractmethod
def execute(self, dry_run: bool = False) -> bool:
"""Execute the phase"""
pass
@abstractmethod
def verify(self) -> Dict[str, Any]:
"""Verify phase completion"""
pass
@abstractmethod
def rollback(self) -> bool:
"""Rollback this phase"""
pass
Expand Phase (Additive Changes)
# core/phases/expand.py
class ExpandPhase(MigrationPhase):
"""
Phase 1: Expand - Add new columns/tables without breaking old code
- Add nullable columns with defaults
- Create new tables
- Add indexes concurrently
- Never remove or modify existing structures
"""
def execute(self, dry_run=False):
sql = self._load_sql('expand.sql')
# Execute with safety checks
with self.state_manager.transaction():
if dry_run:
self._log_sql(sql)
return True
# Run expand SQL (must be reversible)
self.database.execute(sql)
# Record phase completion
self.state_manager.record_phase(
self.migration_id,
'expand',
'completed'
)
return True
Migrate Phase (Data Transformation)
# core/phases/migrate.py
class MigratePhase(MigrationPhase):
"""
Phase 2: Migrate - Backfill and transition data
- Batch data migration
- Dual-write during transition
- Read from new structure gradually
"""
def execute(self, dry_run=False):
# 1. Backfill in batches
self._backfill_data(dry_run)
# 2. Enable dual-write in application
self._deploy_dual_write_flag()
# 3. Verify dual-write consistency
self._verify_dual_write()
# 4. Switch reads to new structure
self._switch_reads()
return True
def _backfill_data(self, dry_run):
"""Backfill in configurable batches with progress tracking"""
batch_size = self.config.get('batch_size', 10000)
while True:
# Get batch of records needing migration
records = self._get_migration_batch(batch_size)
if not records:
break
# Process batch
for record in records:
self._migrate_record(record, dry_run)
# Update progress
self.state_manager.update_progress(
self.migration_id,
records_processed=len(records)
)
# Optional pause between batches
if self.config.get('batch_delay'):
time.sleep(self.config['batch_delay'])
Contract Phase (Cleanup)
# core/phases/contract.py
class ContractPhase(MigrationPhase):
"""
Phase 3: Contract - Remove old structures
- Only after 100% of traffic uses new schema
- Requires verification that old data unnecessary
- Irreversible - must have backup
"""
def execute(self, dry_run=False):
# Pre-flight checks
self._pre_contract_checks()
# Verify no old code paths active
if not self._verify_no_old_writes():
raise MigrationError("Old write paths still active")
# Execute contract SQL
sql = self._load_sql('contract.sql')
if dry_run:
self._log_sql(sql)
return True
self.database.execute(sql)
# Record completion
self.state_manager.record_phase(
self.migration_id,
'contract',
'completed'
)
return True
2. Verification Framework
# core/verifiers/verifier.py
class Verifier:
"""Base verifier interface"""
@abstractmethod
def verify(self, context: Dict) -> VerificationResult:
"""Run verification and return result"""
pass
@abstractmethod
def get_checksum(self) -> str:
"""Get data checksum for comparison"""
pass
# core/verifiers/schema_verifier.py
class SchemaVerifier(Verifier):
"""Verify schema state matches expectations"""
def verify(self, context):
expected = self.config['expected_schema']
actual = self.database.get_schema(self.config['table'])
diff = SchemaDiff.compare(expected, actual)
return VerificationResult(
passed=diff.is_empty(),
diff=diff,
timestamp=datetime.utcnow()
)
# core/verifiers/data_verifier.py
class DataConsistencyVerifier(Verifier):
"""Verify data consistency between old/new schemas"""
def verify(self, context):
# Sample records comparison
sample_size = self.config.get('sample_size', 1000)
mismatches = 0
for record in self._get_sample_records(sample_size):
old_value = self._query_old(record['id'])
new_value = self._query_new(record['id'])
if not self._values_equal(old_value, new_value):
mismatches += 1
if mismatches > self.config.get('max_mismatches', 0):
return VerificationResult(
passed=False,
message=f"Too many mismatches: {mismatches}"
)
return VerificationResult(passed=True)
# core/verifiers/cross_table_verifier.py
class CrossTableVerifier(Verifier):
"""Verify foreign key/relationship integrity"""
def verify(self, context):
# Check for orphaned records
orphan_count = self.database.execute("""
SELECT COUNT(*) FROM new_table nt
LEFT JOIN old_table ot ON nt.old_id = ot.id
WHERE ot.id IS NOT NULL
""").scalar()
return VerificationResult(
passed=orphan_count == 0,
message=f"Found {orphan_count} orphaned records" if orphan_count > 0 else None
)
3. Rollback System
# core/rollback/rollback_manager.py
class RollbackManager:
"""Manages safe rollback procedures"""
ROLLBACK_STRATEGIES = {
'expand': 'drop_added_objects',
'migrate': 'reverse_data_migration',
'contract': 'restore_from_backup' # Irreversible without backup
}
def __init__(self, migration_id: str):
self.migration_id = migration_id
self.state = StateManager().get_migration_state(migration_id)
def can_rollback(self) -> Tuple[bool, str]:
"""Check if rollback is safe"""
if self.state['phase'] == 'contract':
return False, "Contract phase is irreversible without backup"
if self.state['completed_steps'] < 2:
return False, "Insufficient migration progress"
# Check for ongoing writes to old schema
if self._has_recent_writes_to_old():
return False, "Recent writes detected to old schema"
return True, "Safe to rollback"
def execute_rollback(self, strategy: str = None):
"""Execute rollback with specified strategy"""
can_rollback, reason = self.can_rollback()
if not can_rollback:
raise RollbackError(reason)
# 1. Stop application writes
self._disable_application_writes()
# 2. Choose rollback strategy
strategy = strategy or self.ROLLBACK_STRATEGIES[self.state['phase']]
# 3. Execute rollback
if strategy == 'reverse_data_migration':
self._reverse_data_migration()
elif strategy == 'drop_added_objects':
self._drop_added_objects()
elif strategy == 'restore_from_backup':
self._restore_from_backup()
# 4. Verify rollback
self._verify_rollback()
# 5. Re-enable old code paths
self._enable_old_code_paths()
# 6. Update state
self.state_manager.record_rollback(
self.migration_id,
strategy=strategy
)
4. State Tracking
# core/state/state_manager.py
class StateManager:
"""Track migration state across distributed systems"""
def __init__(self, database, lock_manager):
self.db = database
self.lock_manager = lock_manager
self._create_state_table()
def acquire_lock(self, migration_id: str) -> bool:
"""Acquire distributed lock for migration"""
lock_id = f"migration:{migration_id}"
return self.lock_manager.acquire(
lock_id,
ttl=3600, # 1 hour
timeout=300
)
def record_phase(self, migration_id: str, phase: str, status: str):
"""Record phase completion"""
self.db.execute("""
INSERT INTO migration_phases
(migration_id, phase, status, completed_at)
VALUES (?, ?, ?, ?)
ON CONFLICT (migration_id, phase)
DO UPDATE SET status = ?, completed_at = ?
""", [migration_id, phase, status, datetime.utcnow(),
status, datetime.utcnow()])
def get_migration_state(self, migration_id: str) -> Dict:
"""Get complete migration state"""
phases = self.db.execute("""
SELECT phase, status, completed_at
FROM migration_phases
WHERE migration_id = ?
ORDER BY completed_at
""", [migration_id]).fetchall()
progress = self.db.execute("""
SELECT records_processed, total_records
FROM migration_progress
WHERE migration_id = ?
""", [migration_id]).fetchone()
return {
'migration_id': migration_id,
'phases': phases,
'progress': progress,
'current_phase': phases[-1]['phase'] if phases else None
}
def verify_checkpoint(self, migration_id: str, checkpoint: str) -> bool:
"""Verify a specific checkpoint was reached"""
return self.db.execute("""
SELECT 1 FROM checkpoints
WHERE migration_id = ? AND checkpoint = ?
""", [migration_id, checkpoint]).scalar() is not None
5. CLI Interface
# CLI commands
# Start migration
$ schema-migrate start \
--migration=add_email_column \
--phase=expand \
--batch-size=5000 \
--dry-run
# Check status
$ schema-migrate status --migration=add_email_column
# Verify
$ schema-migrate verify --migration=add_email_column --checksum
# Continue to next phase
$ schema-migrate continue --migration=add_email_column --phase=migrate
# Rollback (with confirmation)
$ schema-migrate rollback --migration=add_email_column \
--strategy=reverse_data_migration \
--force
# Emergency pause
$ schema-migrate pause --migration=add_email_column
6. Migration Definition Example
# migrations/001_add_user_email/migration.yaml
id: "001_add_user_email"
description: "Add email column to users table"
dependencies: []
phases:
expand:
sql: |
-- Add nullable column with default
ALTER TABLE users
ADD COLUMN email VARCHAR(255) NULL,
ADD CONSTRAINT users_email_unique UNIQUE (email);
-- Concurrent index creation
CREATE INDEX CONCURRENTLY idx_users_email
ON users(email) WHERE email IS NOT NULL;
rollback: |
DROP INDEX CONCURRENTLY idx_users_email;
ALTER TABLE users DROP COLUMN email;
ALTER TABLE users DROP CONSTRAINT users_email_unique;
verifiers:
- type: schema
check: "column_exists('users', 'email')"
- type: nullability
check: "is_nullable('users', 'email')"
migrate:
batch_size: 10000
sql: |
-- Backfill email from legacy_email column
UPDATE users
SET email = legacy_email
WHERE email IS NULL AND legacy_email IS NOT NULL;
dual_write: true
read_from_new: false
verifiers:
- type: data_consistency
sample_size: 1000
compare_columns: [email, legacy_email]
- type: checksum
table: users
column: email
where: "email IS NOT NULL"
contract:
sql: |
-- Verify no legacy writes
SELECT 1 FROM migration_log
WHERE wrote_to_legacy = true
AND timestamp > now() - interval '1 hour';
-- Drop legacy column
ALTER TABLE users DROP COLUMN legacy_email;
requires_verification: true
irreversible: true
verifiers:
- type: no_legacy_writes
window_hours: 24
- type: column_absent
check: "column_not_exists('users', 'legacy_email')"
# config/settings.yaml
database:
adapter: postgresql
connection:
host: ${DB_HOST}
port: 5432
database: ${DB_NAME}
pool_size: 10
migration:
batch_size: 10000
batch_delay_seconds: 0.5
verification_sample_size: 10000
max_verification_mismatches: 0.01 # 1%
monitoring:
metrics_enabled: true
alert_on_mismatch: true
alert_channels: [slack, email]
safety:
max_downtime_seconds: 300
require_backup_before_contract: true
auto_rollback_on_verification_failure: true
7. Database Adapter Pattern
# database/adapters/postgresql.py
class PostgreSQLAdapter(DatabaseAdapter):
"""PostgreSQL-specific implementations"""
def add_column_concurrently(self, table: str, column: str, dtype: str):
"""Add column without locking table"""
return f"""
ALTER TABLE {table}
ADD COLUMN {column} {dtype};
CREATE INDEX CONCURRENTLY idx_{table}_{column}
ON {table}({column});
"""
def checksum_table(self, table: str, column: str = None) -> str:
"""Calculate consistent table checksum"""
if column:
return f"""
SELECT MD5(STRING_AGG(
CAST({column} AS TEXT), ',' ORDER BY id
)) FROM {table} WHERE {column} IS NOT NULL
"""
return f"""
SELECT MD5(STRING_AGG(
t::TEXT, ',' ORDER BY id
)) FROM (SELECT * FROM {table} ORDER BY id) t
"""
Safety Mechanisms
1. Circuit Breaker Pattern
class CircuitBreaker:
"""Stop migration if error rate exceeds threshold"""
def __init__(self, failure_threshold=5, recovery_timeout=60):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.last_failure_time = None
self.state = 'CLOSED' # CLOSED, OPEN, HALF_OPEN
def before_execution(self):
if self.state == 'OPEN':
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = 'HALF_OPEN'
else:
raise CircuitBreakerOpenError()
def after_execution(self, success: bool):
if success:
self.failure_count = 0
self.state = 'CLOSED'
else:
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = 'OPEN'
2. Progressive Cutover
class ProgressiveCutover:
"""Gradually shift traffic to new schema"""
def __init__(self):
self.percentages = [1, 5, 10, 25, 50, 100]
self.current_index = 0
def next_cutover(self):
"""Move to next percentage of traffic"""
if self.current_index < len(self.percentages) - 1:
self.current_index += 1
return self.percentages[self.current_index]
return 100
def should_read_from_new(self) -> bool:
"""Determine if request should use new schema"""
# Based on feature flag, user ID hash, or request header
return random.random() * 100 < self.percentages[self.current_index]
Deployment Integration
# kubernetes/migration-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: schema-migration-001
spec:
template:
spec:
containers:
- name: migrator
image: schema-migration-toolkit:latest
command: ["migrate", "start", "--migration=001_add_email"]
env:
- name: DB_CONNECTION_STRING
valueFrom:
secretKeyRef:
name: db-secret
key: connection-string
- name: MIGRATION_LOCK_KEY
value: "migration:001_add_email"
resources:
requests:
memory: "512Mi"
cpu: "500m"
restartPolicy: Never
backoffLimit: 3
Monitoring & Alerting
# utils/metrics.py
class MigrationMetrics:
"""Prometheus metrics for migrations"""
def __init__(self):
self.migration_duration = Histogram(
'migration_duration_seconds',
'Time spent in each migration phase',
['migration_id', 'phase']
)
self.verification_mismatches = Counter(
'verification_mismatches_total',
'Number of data mismatches found',
['migration_id', 'verifier']
)
self.batches_processed = Counter(
'migration_batches_total',
'Number of batches processed',
['migration_id']
)
Best Practices Enforced
- Never Drop Columns in Expand/Migrate: Only add/modify in additive ways
- Always Backward Compatible: Old code must work with new schema
- Batch Size Safety: Configurable with progress tracking
- Verification Before Each Phase: Fail fast on inconsistencies
- Rollback Safety Checks: Verify rollback won't break dependencies
- Monitoring Integration: Track progress, errors, durations
- Distributed Locking: Prevent concurrent migrations on same table
- Idempotent Operations: All phases safe to retry
Emergency Procedures
# Emergency stop (kills all migration activities)
$ schema-migrate emergency-stop --reason="high error rate"
# Checkpoint rollback (to last known good state)
$ schema-migrate rollback --to-checkpoint=expand_complete
# Data repair mode (skip verifications for urgent fixes)
$ schema-migrate repair --skip-verification --force
This toolkit provides:
- Zero-downtime: Through expand/migrate/contract phases
- Safety: Multiple verification layers and rollback capabilities
- Observability: Full audit trail, metrics, and progress tracking
- Flexibility: Database-agnostic with pluggable adapters
- Production-ready: Circuit breakers, progressive cutover, locking
The key insight is making migrations reversible until the contract phase, with automated verification at each step, and progressive traffic shifting for read/write operations.