We are designing a system to track schema evolution in a database. The system should align:
- Prisma migrations (which are versioned and applied to the database)
- Drift detection (to detect when the actual database schema differs from the expected schema defined by Prisma)
- Rollback scripts (to undo migrations if needed)
The goal is to have a robust way to manage schema changes, detect unsanctioned changes, and be able to rollback.
We assume we are using Prisma as the ORM and migration tool. Prisma generates migration files (in SQL or as a Prisma Migration step) and maintains a migration history table.
However, note: Prisma does not natively support rollback in the same way as some other tools (like Flyway). Prisma migrations are typically forward-only, but we can generate down migrations if we use SQL migrations and write the down SQL.
Steps:
-
Prisma Migrations:
- We use
prisma migrate dev for development and prisma migrate deploy for production.
- Prisma creates a
_prisma_migrations table to track which migrations have been applied.
- Each migration has a
name (timestamp-based) and checksum (hash of the migration files).
-
Drift Detection:
- We need to periodically check if the actual database schema matches the expected schema from the Prisma schema file (or the last applied migration?).
- We can use
prisma migrate diff to compare the database with the Prisma schema or with a specific migration.
-
Rollback Scripts:
- For each migration, we should have a corresponding rollback script (if possible). This might be a down migration in SQL.
- Since Prisma doesn't generate down migrations by default, we have to write them ourselves.
Proposed Schema Evolution Tracker:
We will create a new table to track our own history, in addition to Prisma's _prisma_migrations table.
Let's call the table schema_evolution_tracker:
Columns:
id: primary key (auto-increment)
migration_name: the name of the Prisma migration (the timestamp and name) that we are tracking. This should be unique.
applied_at: timestamp when the migration was applied (we can record this when we apply a migration, but note Prisma already has a started_at and finished_at in _prisma_migrations). We might want to record our own timestamp for consistency? Or we can rely on Prisma's table.
rollback_script_path: the path to the rollback script for this migration (if exists). We might store a relative path from a known directory.
is_rolled_back: boolean to indicate if this migration has been rolled back.
rolled_back_at: timestamp when it was rolled back.
However, note: when we rollback a migration, we are effectively undoing the changes. But in Prisma, once you apply a migration, the _prisma_migrations table records it. If we rollback using our own script, we must also remove the entry from _prisma_migrations? That might break Prisma's state.
So, we have two options:
Option 1: Use Prisma's built-in mechanism for rollback by generating down migrations and then using prisma migrate resolve to mark migrations as rolled back? But note: prisma migrate resolve is for marking migrations as applied or rolled back without actually running SQL. We want to run the rollback SQL.
Option 2: We manage rollback ourselves and then update our own tracker and also update the _prisma_migrations table accordingly? But that's risky because Prisma might not be aware of the rollback and then try to reapply.
Let's reconsider:
Prisma does not have a built-in rollback command. The recommended way to rollback is to:
a) Restore the database from a backup (for production).
b) For development, you can reset the database and reapply migrations.
But we want a more controlled rollback for production? That's tricky.
Alternatively, we can design our system to:
- Only allow forward migrations in production, and have a backup and restore strategy for rollback.
But the requirement says "rollback scripts", so maybe we are expected to have down migrations.
Since Prisma doesn't generate down migrations, we have two choices:
-
Write the down migration SQL ourselves and store it. Then, when we want to rollback, we run the down migration SQL and then remove the migration record from _prisma_migrations? But note: Prisma's _prisma_migrations table has a checksum of the migration. If we remove the record, Prisma will think the migration was never applied.
-
Alternatively, we can use Prisma's migrate resolve to mark the migration as rolled back (without running SQL) and then run our down SQL? But then the database schema and Prisma's state would be out of sync.
This is a complex problem because Prisma is designed for forward-only migrations.
Let's change the requirement a bit: We are allowed to have down migrations only if we use raw SQL migrations and we manage the entire migration process ourselves (without relying on Prisma's migrate command for rollback). But then we are not using Prisma's migration engine for rollback.
Alternatively, we can use a different tool for migrations that supports down migrations, but the requirement says "Prisma migrations".
After research:
Prisma does not support down migrations. The team recommends using backups for rollback.
So, perhaps we design the tracker to only track forward migrations and then have a separate process for rollback that involves:
- Restoring from backup (which we also track in our table) and then reapplying the desired set of migrations.
But the requirement says "rollback scripts", so maybe we are expected to write the down SQL and run it manually? And then adjust the _prisma_migrations table?
Given the complexity and the fact that Prisma doesn't support down migrations, I propose:
We will track:
- All Prisma migrations that have been applied (by reading the
_prisma_migrations table).
- Periodically run
prisma migrate diff to detect drift (unsanctioned changes) by comparing the database schema with the Prisma schema file (or the last migration in the migrations directory).
For rollback, we do not generate automatic rollback scripts. Instead, we:
- Have a backup strategy (full backup before each migration) and then restore the backup to rollback.
But the requirement says "rollback scripts", so maybe we are expected to write the down SQL for each migration and store it, and then have a manual process to run the down SQL and then remove the migration from _prisma_migrations? That is error-prone.
Alternatively, we can use a tool like pg_dump for PostgreSQL to generate the down SQL? But that's not straightforward.
Given the constraints, I think we should:
-
Track migrations in our own table for auditing, but not interfere with Prisma's _prisma_migrations.
-
For rollback, we rely on backups and then reapply the migrations we want.
But then what is the purpose of the rollback_script_path? Maybe we can generate the down SQL by:
1. Having a copy of the database schema before the migration (from the previous migration) and then generating the diff? That's what `prisma migrate diff` does.
Actually, prisma migrate diff can generate the SQL to go from one schema to another. So we can:
- For each migration, we record the previous migration (or the state before the migration) and then we can generate the down SQL by reversing the diff.
However, note: Prisma migrations are not necessarily reversible because of data loss (like dropping a column). So we have to be cautious.
Proposed flow:
When we apply a migration (via Prisma):
1. We record the migration in our `schema_evolution_tracker` table with:
- `migration_name`
- `applied_at` (current timestamp)
- `rollback_script_path` (we generate the rollback script by using `prisma migrate diff` between the current state (after migration) and the state before the migration? But we don't have the before state unless we take a backup or have the previous migration's schema.)
How about:
We store the entire schema (as a SQL dump or Prisma schema) at each migration step? That's heavy.
Alternatively, we can:
- Before applying a migration, we generate the down script by comparing the target schema (the migration's up) with the current schema (which is the state before the migration). Then we store that down script.
Steps for applying a migration:
1. Read the current database schema (using `prisma migrate diff` with `--from` as the current database and `--to` as the target migration? Actually, Prisma's `migrate diff` can compare two schemas.
2. But we don't have the target schema until we apply? We have the migration files.
Actually, Prisma migration files are incremental. So:
Let's say we have migration A (already applied) and we want to apply migration B.
The current database state is after A. The target state is after B.
The up SQL for B is: from A to B.
The down SQL for B would be: from B to A.
We can generate the down SQL by:
`prisma migrate diff --from <schema after B> --to <schema after A>`
But we don't have the schema after B until we apply? Actually, we have the migration file for B which contains the up SQL. We can also generate the schema after B by applying the migration to a temporary database? That's heavy.
Alternatively, we can generate the down SQL by:
1. Having the Prisma schema file for the state after B (which is the Prisma schema after the change that B represents). But note: Prisma schema is the source of truth for the next state.
2. And the current state (before applying B) is the database after A (or we can get the Prisma schema for state A?).
This is getting too complicated.
Given the complexity and the fact that Prisma doesn't support down migrations, I think we should:
-
Not generate down migrations automatically.
-
Instead, we require the developer to write the down migration SQL when creating the up migration, and store it in the same directory as the up migration (with a naming convention, e.g., same name but with .down.sql).
Then, when we want to rollback:
1. We check the `schema_evolution_tracker` to see if we have a down script for the migration we want to rollback.
2. We run the down script.
3. We remove the migration record from `_prisma_migrations` (using `prisma migrate resolve` with `--rolled-back` and the migration name) so that Prisma knows it's rolled back.
4. Update our `schema_evolution_tracker` to mark the migration as rolled back.
But note: prisma migrate resolve can mark a migration as rolled back without running the SQL. We are running the SQL ourselves and then marking it as rolled back in Prisma's table.
Steps for rollback:
- For the migration we want to rollback (let's say `migration_name`):
a. Run the down SQL script (from the path stored in `rollback_script_path`).
b. Run `prisma migrate resolve --rolled-back <migration_name>` to update the `_prisma_migrations` table.
But caution: what if the down script fails? Then we have a half-rolled back state.
We must do this in a transaction? But the down script might contain multiple statements and we are running it outside of Prisma.
Alternatively, we can use Prisma's migration engine to apply the down migration? But Prisma doesn't have a command for that.
So, we have to manage the transaction ourselves? That's database-specific.
Given these challenges, perhaps we should not support automatic rollback via down scripts and instead rely on backups.
But the requirement says to align rollback scripts.
Let's stick to the plan:
We will:
- For each migration, we expect a down script (provided by the developer) and store its path in our tracker.
- When rolling back, we run the down script and then use `prisma migrate resolve` to mark it as rolled back.
However, note that prisma migrate resolve is a command that updates the _prisma_migrations table. We must run it after the down script successfully completes.
We can write a script that:
1. Reads the last applied migration (or a specific one) from `schema_evolution_tracker` that is not rolled back.
2. Runs the down script (using the database client, e.g., `psql` for PostgreSQL).
3. If the down script succeeds, then run `prisma migrate resolve --rolled-back <migration_name>`.
4. Update our tracker.
But what about multiple rollbacks? We might want to rollback multiple steps.
We can do:
- Rollback one by one, starting from the last applied migration.
However, note that the order of rollback is the reverse of application.
So, we can:
- List the migrations that are applied and not rolled back, ordered by applied_at (or by migration_name, which is timestamp?).
- Then rollback from the most recent to the oldest.
But the developer must ensure that the down scripts are safe to run in that order and that they are independent? Actually, they are dependent because each down script undoes a specific migration and the next down script undoes the previous migration, etc.
So we rollback in reverse order.
Now, for drift detection:
We can have a scheduled job that:
1. Uses `prisma migrate diff` to compare the current database schema with the Prisma schema file (or the last migration's schema) to see if there are any differences.
2. If there are differences, we log them and alert.
But note: the Prisma schema file might not reflect the last migration if we have multiple migrations and the Prisma schema is updated incrementally.
Actually, the Prisma schema should be the source of truth for the desired state. The migrations are incremental steps to get there.
So we can compare the database with the Prisma schema file.
Steps for drift detection:
`prisma migrate diff --from-url <database_url> --to-schema-datamodel ./prisma/schema.prisma`
This will show the diff between the current database and the Prisma schema.
If there are any differences, then there is drift.
But note: if we have unapplied migrations, then the database might be behind the Prisma schema. So we should only compare after applying all migrations? Or we compare with the last applied migration?
Actually, the Prisma schema represents the desired state. The migrations are the steps to get there. So if we have unapplied migrations, then the database is not at the desired state, but that's expected until we apply.
So we want to detect unsanctioned changes, meaning changes that are not part of the migrations.
How?
We can:
1. Apply all pending migrations (in a controlled manner) and then compare? But that would be the same as having no drift.
2. Or, we can compare the current database with the state that we would have if we applied all migrations? That is the Prisma schema.
But what if we have unapplied migrations? Then the database is behind, but that's not drift, that's just not up to date.
We want to detect changes that are not in the migration history.
So, we can:
- Get the set of changes that are in the migration history (by reading the `_prisma_migrations` table and the migration files) and then compare the current database with the state after the last applied migration? But then if we have unapplied migrations, we would see drift (because the database is behind).
Actually, drift means the database has changed in a way that is not recorded in the migration history. So:
- We should compare the current database with the state that the last applied migration would have produced.
How to get the state of the last applied migration?
We can generate a schema from the last applied migration? Prisma doesn't store the schema for each migration. We only have the migration steps.
Alternatively, we can:
- Have a baseline: the initial schema (from the first migration) and then apply all migrations in order to generate the expected schema? But that's heavy.
Given the complexity, maybe we do:
- Compare the current database with the Prisma schema (the desired state). If they match, then no drift.
- But if they don't match, it could be because:
a) We have unapplied migrations (so the database is behind) -> not drift, just not up to date.
b) There are unsanctioned changes (drift).
How to distinguish?
We can check the `_prisma_migrations` table: if the last applied migration is the same as the last migration file (by name) then we are up to date. If not, then there are unapplied migrations.
But what if we have multiple migration directories? (Prisma supports multiple migration directories? Not typically.)
So:
Let `last_migration_in_filesystem` be the last file in the migrations directory (by timestamp?).
And `last_applied_migration` from `_prisma_migrations` (by order of applied? actually, the table has `finished_at`).
If `last_applied_migration` is the same as `last_migration_in_filesystem`, then we are up to date. Then if there is a diff, it's drift.
If they are different, then we have unapplied migrations and we should apply them first? But we are only detecting drift.
So, in our drift detection, we only alert if:
- The database is at the state of the last applied migration (i.e., no unapplied migrations) and there is a diff between the database and the Prisma schema? But wait, the Prisma schema might be ahead of the last applied migration.
Actually, the Prisma schema is the desired state. The last applied migration is the current state. So if we have unapplied migrations, the current state (last applied) is behind the desired state (Prisma schema). That's not drift, that's just not up to date.
So we want to detect when the current state (last applied) does not match the Prisma schema and there are no unapplied migrations? But then if we have unapplied migrations, we don't consider it drift.
Alternatively, we can compute the expected state by applying all migrations (from the baseline to the last migration) to the initial schema? That's complex.
Given the time, let's simplify:
We will have two states:
1. The state of the database after the last applied migration (we can get this by taking the initial schema and applying all migrations up to the last applied? But we don't store the initial schema?).
2. The desired state (Prisma schema).
We want to detect if the database (current state) is different from the desired state and that the difference is not because of unapplied migrations.
How?
We can generate the expected state by:
a) Take the initial schema (from the first migration? Actually, the first migration is from the initial schema to the first change. So we need the initial schema? Prisma doesn't store the initial schema separately.)
Alternatively, we can:
- Generate the schema from the Prisma schema file (using `prisma generate`? That generates the client, not the schema SQL).
- Or, we can use `prisma migrate diff` to generate the SQL that would be run to get from the current database to the Prisma schema. If that SQL is empty, then no drift (and no unapplied migrations?).
But note: `prisma migrate diff` compares two schemas. We can compare the current database with the Prisma schema. If it returns an empty diff, then the database matches the Prisma schema.
If it returns a diff, then either:
- There are unapplied migrations (so the Prisma schema is ahead) and the diff is the unapplied migrations.
- There is drift (unsanctioned changes).
How to tell?
We can check if the diff matches the unapplied migrations.
Steps:
1. Get the list of applied migrations (from `_prisma_migrations`).
2. Get the list of all migration files (from the migrations directory).
3. Compute the unapplied migrations (the ones in the filesystem that are not in the applied list).
4. For each unapplied migration, we can read the up SQL and see if the diff we got from `prisma migrate diff` is exactly the concatenation of the unapplied migrations? That's complex because the diff might be in a different order.
Alternatively, we can:
- Apply the unapplied migrations to a temporary database and then compare? That's heavy.
Given the complexity, perhaps we accept that:
- We run drift detection only when we are at the latest migration (i.e., no unapplied migrations). Then, if there is a diff, it's drift.
- How do we know we are at the latest migration? We compare the last applied migration name with the last migration file name.
So, our drift detection job:
Step 1: Check if we are at the latest migration.
Step 2: If yes, then run `prisma migrate diff` between the database and the Prisma schema. If there is any diff, then we have drift.
Step 3: If we are not at the latest, then we don't run drift detection? Or we note that there are unapplied migrations and we don't consider it drift.
But what if there are unapplied migrations and also drift? Then we might miss drift.
Alternatively, we can:
- Generate the expected state by applying all migrations (applied and unapplied) to a baseline? That's too heavy.
Given the trade-offs, I think we do:
- Only check for drift when there are no unapplied migrations.
- And we have a separate alert for unapplied migrations.
So, the plan:
Schema Evolution Tracker Table:
We create a table schema_evolution_tracker:
CREATE TABLE schema_evolution_tracker (
id SERIAL PRIMARY KEY,
migration_name VARCHAR(255) NOT NULL UNIQUE,
applied_at TIMESTAMP NOT NULL,
rollback_script_path VARCHAR(1024),
is_rolled_back BOOLEAN DEFAULT FALSE,
rolled_back_at TIMESTAMP
);
We will populate this table when we apply a migration via Prisma? We can have a post-migration hook? Prisma doesn't have hooks for migrations.
Alternatively, we can have a script that:
1. Runs `prisma migrate deploy` (or `prisma migrate dev` for development) to apply migrations.
2. Then, reads the `_prisma_migrations` table to get the last applied migration (or all applied) and then inserts/updates our tracker.
But we also want to track rollbacks.
For rollback:
We have a script that:
1. Queries the `schema_evolution_tracker` for the most recent migration that is not rolled back.
2. Runs the down script (from `rollback_script_path`) for that migration.
3. If successful, runs `prisma migrate resolve --rolled-back <migration_name>`.
4. Updates the tracker to set `is_rolled_back` to true and `rolled_back_at` to current timestamp.
But note: what if we want to rollback multiple steps? We can do:
while there are unrolled_back migrations, rollback the most recent one.
But we might want to rollback to a specific point? Then we need to rollback until we reach the desired migration.
We can design the rollback script to take an optional target migration name? Then we rollback until we reach that migration (exclusive?).
Example:
rollback-to <target_migration_name>
This will rollback all migrations that are after the target_migration_name.
But then we need to know the order of migrations. We can order by applied_at or by migration_name (which is timestamp-based).
Since migration_name is a timestamp, we can use that to order.
Steps for rollback-to:
Get the list of applied and not rolled back migrations, ordered by `migration_name` (ascending for application, so descending for rollback).
Rollback from the most recent until we rollback to the one just after the target? Or until we rollback the target?
Actually, we want to rollback to a state that includes the target migration. So we rollback all migrations that are after the target.
Example:
Applied: A, B, C (C is most recent)
Target: B
Rollback: C (so we are left with A, B)
So we rollback all migrations with `migration_name` > target_migration_name (if migration_name is a timestamp string, we can compare lexicographically because they are in the format `YYYYMMDDHHMMSS`).
But note: what if we have multiple migration directories? We assume one.
Now, for drift detection:
We have a script that:
1. Get the last applied migration (that is not rolled back) from `schema_evolution_tracker` (or from `_prisma_migrations`? We can use our tracker to get the last applied that is not rolled back).
2. Get the last migration file in the migrations directory.
3. If the last applied migration (not rolled back) is not the same as the last migration file, then there are unapplied migrations. Alert and exit (or don't run drift detection).
4. If they are the same, then run:
`prisma migrate diff --from-url <database_url> --to-schema-datamodel ./prisma/schema.prisma`
5. If the diff is non-empty, then we have drift. Alert.
But note: the Prisma schema might have changed since the last migration? Actually, the last migration should reflect the Prisma schema at the time of the migration. But if we change the Prisma schema and then generate a new migration, then the last migration file will correspond to the new Prisma schema.
So, when we apply migrations, we are aligning the database with the Prisma schema.
Therefore, if we are at the latest migration and the Prisma schema is the same as the one used to generate the last migration, then the database should match the Prisma schema.
But what if we change the Prisma schema and then generate a new migration? Then the last migration file will be new, and we will have unapplied migrations until we apply it.
So our drift detection only runs when we are at the latest migration.
Implementation:
We will have:
- A script to apply migrations and update the tracker.
- A script to rollback (one or to a target) and update the tracker and the Prisma migrations table.
- A script for drift detection.
But note: when we apply a migration via Prisma, it updates the _prisma_migrations table. We want to update our tracker accordingly.
How to capture the migration event?
We can:
1. Before applying migrations, get the list of currently applied migrations (from `_prisma_migrations`).
2. Apply the migrations (using `prisma migrate deploy`).
3. After applying, get the new list of applied migrations.
4. The difference are the new migrations. For each new migration, we insert into our tracker.
But what about the rollback script path? We need to know where to find the down script for that migration.
We can assume that for each migration, we have a down script in the same directory as the up migration, with the same name but with `.down.sql`? Or we can have a convention:
The migration directory for a migration `20210101000000_init` contains:
- `migration.sql` (the up script) or `steps` directory? Actually, Prisma can generate SQL migrations or use the built-in migration engine.
If we use SQL migrations (`prisma migrate dev --create-only` and then write SQL), then we have a `migration.sql` and we can also create a `migration.down.sql`.
But Prisma also supports a `--create-only` that creates a migration with an empty `migration.sql` and then we write our own?
Actually, Prisma's default is to generate a `migration.sql` with the up changes. We can then write a `migration.down.sql` ourselves.
We can store the relative path to the down script in our tracker.
How to get the path?
The migration name is the directory name (e.g., `20210101000000_init`). The down script would be in that directory: `./migrations/20210101000000_init/migration.down.sql`
But note: Prisma might use a different structure? Actually, by default, Prisma creates:
`./migrations/20210101000000_init/migration.sql`
So we can store: `./migrations/20210101000000_init/migration.down.sql`
And if the file doesn't exist, then we cannot rollback.
So, when we apply a migration, we:
1. Get the list of new migrations (by comparing the `_prisma_migrations` table before and after).
2. For each new migration, check if the down script exists at the expected path. If yes, store the path. If not, store NULL and we cannot rollback that migration.
Now, what about drift detection? We compare the database with the Prisma schema. But note:
The Prisma schema might have changed since the last migration? Actually, the last migration should have been generated from the Prisma schema at that time. But if we change the Prisma schema and then generate a new migration, then the last migration file corresponds to the new Prisma schema.
So when we are at the latest migration, the Prisma schema should be the same as the last migration's intended state? Not necessarily: we might have changed the Prisma schema after generating the migration? But then we would have uncommitted changes? We assume that the Prisma schema file is committed and the migrations are generated from it.
So, the workflow:
- We change the Prisma schema.
- We generate a migration (which creates a new migration directory with `migration.sql` and possibly `migration.down.sql` if we write it).
- We apply the migration.
Then the database should match the Prisma schema.
So, if we are at the latest migration, then the database should match the Prisma schema.
Therefore, drift detection is:
`prisma migrate diff --from-url <database_url> --to-schema-datamodel ./prisma/schema.prisma`
And if there is any diff, then we have drift (unsanctioned changes).
But wait: what if we have multiple databases (like multiple environments)? We assume we are checking one database at a time.
Now, let's design the scripts:
Script 1: apply_migrations.sh
Steps:
1. Backup the database (optional but recommended). We can have a separate backup script.
2. Get the current list of applied migrations from `_prisma_migrations` (by querying the table and storing the `migration_name`).
3. Run `prisma migrate deploy` (or `prisma migrate dev` for development? We assume production uses `deploy`).
4. Get the new list of applied migrations.
5. For each new migration (in the new list but not in the old list):
a. Determine the path to the down script: `./migrations/<migration_name>/migration.down.sql` (if using SQL migrations) or maybe `./migrations/<migration_name>/down.sql`? We need to decide.
b. Check if the down script exists.
c. Insert into `schema_evolution_tracker`:
- `migration_name`
- `applied_at` (current timestamp)
- `rollback_script_path` (if the down script exists, else NULL)
6. Also, we might want to record the user who applied? Not in the current design.
Script 2: rollback.sh
This script can rollback one step or to a target.
Usage:
rollback.sh [--target <migration_name>]
If no target, rollback one step (the most recent).
Steps:
1. Get the list of applied and not rolled back migrations from `schema_evolution_tracker` (where `is_rolled_back` is false), ordered by `migration_name` (ascending for application, so we want the last one for one-step rollback, or all after the target for rollback-to).
2. Determine which migrations to rollback:
- If target is provided: rollback all migrations with `migration_name` > target (lexicographically, because they are timestamps).
- If no target: rollback the most recent (max `migration_name`).
3. For each migration to rollback (in reverse order of application, i.e., from most recent to oldest):
a. Check if `rollback_script_path` is not NULL. If NULL, error and exit (cannot rollback this migration).
b. Run the down script using the database client (we need the database URL). We assume we have a way to run SQL (like `psql` for PostgreSQL).
c. If the down script fails, exit with error.
d. After successful down script, run `prisma migrate resolve --rolled-back <migration_name>`.
e. Update `schema_evolution_tracker` for this migration: set `is_rolled_back` to true and `rolled_back_at` to current timestamp.
Script 3: detect_drift.sh
Steps:
1. Get the last applied migration (not rolled back) from `schema_evolution_tracker` (order by `migration_name` desc, limit 1).
2. Get the last migration file in the migrations directory (by name, which is timestamp).
3. If the last applied migration (from step 1) is not the same as the last migration file, then:
- Print "There are unapplied migrations. Please apply them first."
- Exit 1.
4. If they are the same, then:
Run `prisma migrate diff --from-url <database_url> --to-schema-datamodel ./prisma/schema.prisma`
- If the output is empty, then no drift.
- If the output is non-empty, then we have drift.
But note: the prisma migrate diff command returns a non-zero exit code if there is a diff? Actually, it returns 0 even if there is a diff? We have to check the output.
Alternatively, we can use --script to output the SQL and then check if it's empty.
Example:
`prisma migrate diff --from-url <db_url> --to-schema-datamodel ./prisma/schema.prisma --script`
This outputs the SQL that would be run to migrate from the current database to the Prisma schema. If empty, then no diff.
So we can:
diff_sql=$(prisma migrate diff --from-url $DATABASE_URL --to-schema-datamodel ./prisma/schema.prisma --script)
if [ -n "$diff_sql" ]; then
echo "Drift detected:"
echo "$diff_sql"
exit 1
else
echo "No drift detected."
exit 0
fi
But note: if there are unapplied migrations, then the diff_sql would be the unapplied migrations. We are only running this when there are no unapplied migrations (step 3), so if there is a diff, it must be drift.
However, what if the Prisma schema has changed since the last migration? Then the last migration file would not match the Prisma schema? But we just checked that the last applied migration is the same as the last migration file. And the last migration file was generated from the Prisma schema at that time. But if we change the Prisma schema and then generate a new migration, then the last migration file would be new and we would have unapplied migrations (so step 3 would catch that).
So, the condition in step 3 ensures that the Prisma schema and the last migration file are in sync? Not exactly: we are comparing the last applied migration with the last migration file. But the last migration file might have been generated from an older Prisma schema? Actually, the migration file is generated from the Prisma schema at the time of generation.
So, if we change the Prisma schema and then generate a new migration, then the last migration file will be new and the last applied migration will be the previous one, so step 3 will detect unapplied migrations.
Therefore, when we pass step 3, we know that:
- The last applied migration is the same as the last migration file.
- And the last migration file was generated from the Prisma schema at that time.
- But the Prisma schema might have changed since then? If it changed, then we would have generated a new migration and the last migration file would be different? Actually, if we change the Prisma schema and don't generate a migration, then the last migration file would be the same as before, but the Prisma schema would be different.
Then, when we run `prisma migrate diff`, we would get a diff (because the Prisma schema is different from the last migration's state). But we are at the latest migration (by file) and the Prisma schema is different? That means we have uncommitted changes in the Prisma schema? But we assume the Prisma schema is committed and the migrations are generated from it.
So, the intended workflow is:
Change Prisma schema -> generate migration -> apply migration.
Therefore, the Prisma schema and the last migration file should be in sync.
If they are not, then we have a problem: we changed the Prisma schema without generating a migration? Then we have drift? Actually, that's exactly what we want to detect: the database is at the state of the last migration, but the Prisma schema is different (unsanctioned change? or just ungenerated migration?).
But note: we are comparing the database (which is at the state of the last applied migration) with the Prisma schema (which might be ahead). That would show a diff that is exactly the next migration? But we don't have that migration file? Then it's not in the migration history.
So that would be drift? Or just an ungenerated migration?
Actually, if we change the Prisma schema and don't generate a migration, then the database is not at the desired state (the Prisma schema). But that's not a change to the database, that's a change to the desired state.
Drift is when the database changes without going through the migration process.
So, if we change the Prisma schema and don't generate a migration, then the database is not at the desired state, but that's not drift because we haven't changed the database? Actually, the database is behind.
But wait: the database is at the state of the last migration. The Prisma schema is ahead. That's not drift, that's just the database not being up to date with the desired state.
However, we already checked that there are no unapplied migrations (by comparing the last applied migration with the last migration file). So if the Prisma schema is ahead and there is no migration file for that change, then we have a problem: the Prisma schema has changed but we haven't generated a migration. That is a kind of drift? Actually, it's a configuration drift: the source of truth (Prisma schema) has changed but the migration history hasn't been updated.
But the requirement is to detect drift in the database, not in the Prisma schema.
So, we are only concerned with the database schema differing from the expected schema.
The expected schema is the Prisma schema? Or the last applied migration?
We want the database to match the Prisma schema. So if the Prisma schema is ahead, then the database is behind, but that's not a change to the database.
Therefore, we should only run drift detection when the Prisma schema and the last migration file are in sync? Actually, we want to know if the database matches the Prisma schema. So we can run the diff regardless, but then if there is a diff, it could be because:
- The database is behind (unapplied migrations) -> we already check for unapplied migrations and skip.
- The database is ahead (drift) -> we catch this.
- The Prisma schema is ahead and we have unapplied migrations -> we skip because we have unapplied migrations.
- The Prisma schema is ahead and we don't have a migration for it? Then we have a problem: the Prisma schema has changed but we haven't generated a migration. But that's not a database drift, it's a source code drift.
So, we are only concerned with the database schema being different from the Prisma schema when there are no unapplied migrations.
Therefore, our current drift detection is correct.
However, what if the Prisma schema is behind the last migration? That shouldn't happen because we generate migrations from the Prisma schema. But if we rollback a migration and then change the Prisma schema to an older state? Then the last migration file (which is the one we rolled back) might be ahead of the Prisma schema? But we rolled back the migration, so the database is at the state of the previous migration, and the Prisma schema might be at an even older state? Then we have a diff? But that's expected because we rolled back and then changed the Prisma schema to an older state? Actually, after rollback, the database is at the state of the previous migration, and the Prisma schema should be at the state of the previous migration? Not necessarily: we might have changed the Prisma schema after rollback.
Again, we are only concerned with the database vs Prisma schema when there are no unapplied migrations.
So, if we rollback and then change the Prisma schema to match the rolled back state, then there should be no diff.
If we rollback and then change the Prisma schema to something else, then we will have a diff and that's drift? Actually, that's a change to the desired state, not a change to the database.
So, we are only checking the database against the current Prisma schema. If they don't match and there are no unapplied migrations, then the database has been changed without going through the migration process.
Summary:
We have:
- A table to track our own migration history (including rollback status and down script path).
- Scripts to:
a) Apply migrations and update our tracker.
b) Rollback one or to a target, and update our tracker and Prisma's `_prisma_migrations` table.
c) Detect drift by comparing the database with the Prisma schema only when there are no unapplied migrations.
This is a complex system and we must be cautious.
Let's write the SQL for the table:
CREATE TABLE schema_evolution_tracker (
id SERIAL PRIMARY KEY,
migration_name VARCHAR(255) NOT NULL UNIQUE,
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
rollback_script_path VARCHAR(1024),
is_rolled_back BOOLEAN NOT NULL DEFAULT FALSE,
rolled_back_at TIMESTAMP
);
We assume the migration_name is the same as the directory name in the migrations folder and the name in _prisma_migrations.
Now, the scripts:
We assume the following:
- Database URL is in an environment variable `DATABASE_URL`.
- Prisma is installed and the `prisma` CLI is available.
- The migrations directory is `./migrations`.
- The Prisma schema file is `./prisma/schema.prisma`.
We also assume that we are using SQL migrations (so each migration has a migration.sql and we write migration.down.sql). If we use the built-in migration engine (which doesn't generate SQL), then we cannot have a down script? So we only support SQL migrations.
We must enforce that we use SQL migrations.
Steps for apply_migrations.sh:
#!/bin/bash
set -e
# Step 1: Get current applied migrations from _prisma_migrations
current_migrations=$(psql $DATABASE_URL -t -c "SELECT migration_name FROM _prisma_migrations ORDER BY started_at;")
# Step 2: Apply migrations
prisma migrate deploy
# Step 3: Get new applied migrations
new_migrations=$(psql $DATABASE_URL -t -c "SELECT migration_name FROM _prisma_migrations ORDER BY started_at;")
# Step 4: Compute the difference (new_migrations - current_migrations)
# We assume that the order is the same and that the new_migrations list includes the old ones and then the new ones.
# We can use comm or awk to get the new ones.
# Let's store the current_migrations in a file
echo "$current_migrations" > /tmp/current_migrations.txt
echo "$new_migrations" > /tmp/new_migrations.txt
# Get the new ones (lines in new_migrations.txt that are not in current_migrations.txt)
new_only=$(comm -13 <(sort /tmp/current_migrations.txt) <(sort /tmp/new_migrations.txt))
# Step 5: For each new migration, insert into our tracker
for migration in $new_only; do
# Trim whitespace
migration=$(echo $migration | xargs)
# Path to down script
down_script="./migrations/$migration/migration.down.sql"
if [ -f "$down_script" ]; then
rollback_path="$down_script"
else
rollback_path=NULL
fi
# Insert into tracker
if [ "$rollback_path" = "NULL" ]; then
psql $DATABASE_URL -c "INSERT INTO schema_evolution_tracker (migration_name, applied_at, rollback_script_path) VALUES ('$migration', NOW(), NULL);"
else
psql $DATABASE_URL -c "INSERT INTO schema_evolution_tracker (migration_name, applied_at, rollback_script_path) VALUES ('$migration', NOW(), '$rollback_path');"
fi
done
echo "Applied $($new_only | wc -l) migrations and updated tracker."
Note: This script uses psql and assumes PostgreSQL. For other databases, we need to adjust.
For rollback.sh:
#!/bin/bash
set -e
target_migration=$1
# Step 1: Get the list of applied and not rolled back migrations
if [ -z "$target_migration" ]; then
# Get the most recent migration that is not rolled back
migration_to_rollback=$(psql $DATABASE_URL -t -c "SELECT migration_name FROM schema_evolution_tracker WHERE is_rolled_back = false ORDER BY migration_name DESC LIMIT 1;")
else
# Get all migrations that are after the target (and not rolled back)
migration_to_rollback=$(psql $DATABASE_URL -t -c "SELECT migration_name FROM schema_evolution_tracker WHERE is_rolled_back = false AND migration_name > '$target_migration' ORDER BY migration_name DESC;")
fi
if [ -z "$migration_to_rollback" ]; then
echo "No migrations to rollback."
exit 0
fi
# Step 2: Rollback each migration in reverse order (from most recent to oldest)
# The variable migration_to_rollback might have multiple lines. We process from top (most recent) to bottom.
echo "$migration_to_rollback" | while read migration; do
migration=$(echo $migration | xargs)
echo "Rolling back migration: $migration"
# Get the rollback script path from the tracker
rollback_script=$(psql $DATABASE_URL -t -c "SELECT rollback_script_path FROM schema_evolution_tracker WHERE migration_name = '$migration';")
if [ -z "$rollback_script" ] || [ "$rollback_script" = "NULL" ]; then
echo "Error: No rollback script found for migration $migration. Cannot rollback."
exit 1
fi
# Run the down script
echo "Running down script: $rollback_script"
# We assume the down script is a SQL file that can be run with psql
psql $DATABASE_URL -f "$rollback_script"
# Mark as rolled back in Prisma
prisma migrate resolve --rolled-back "$migration"
# Update our tracker
psql $DATABASE_URL -c "UPDATE schema_evolution_tracker SET is_rolled_back = true, rolled_back_at = NOW() WHERE migration_name = '$migration';"
done
echo "Rollback complete."
For detect_drift.sh:
#!/bin/bash
set -e
# Step 1: Get the last applied migration (not rolled back)
last_applied_migration=$(psql $DATABASE_URL -t -c "SELECT migration_name FROM schema_evolution_tracker WHERE is_rolled_back = false ORDER BY migration_name DESC LIMIT 1;")
# Step 2: Get the last migration file in the migrations directory
# We assume the migration directories are named as timestamps and we can sort by name.
last_migration_file=$(ls -1 ./migrations | sort -n | tail -1)
# Step 3: Compare
if [ "$last_applied_migration" != "$last_migration_file" ]; then
echo "There are unapplied migrations. Last applied: $last_applied_migration, last migration file: $last_migration_file."
exit 1
fi
# Step 4: Run drift detection
diff_sql=$(prisma migrate diff --from-url $DATABASE_URL --to-schema-datamodel ./prisma/schema.prisma --script)
if [ -n "$diff_sql" ]; then
echo "Drift detected:"
echo "$diff_sql"
exit 1
else
echo "No drift detected."
exit 0
fi
Note: The detect_drift.sh script only works if there are no rolled back migrations? Actually, we are only looking at the last applied migration that is not rolled back. But what if we rolled back the last migration? Then the last applied (not rolled back) might be an older one, and the last migration file might be newer (unapplied). So we would get "unapplied migrations" and not run the diff.
That's correct: if we rolled back, then we are not at the latest migration, so we don't run drift detection.
But what if we rolled back and then the Prisma schema changed? Then the last migration file might be the same as before (if we didn't generate a new migration) and the last applied (not rolled back) is older. Then we have unapplied migrations? Actually, the last migration file is the same as the one we rolled back? Then we have unapplied migrations? We rolled back, so the migration we rolled back is marked as rolled back, and the last applied (not rolled back) is the one before that. The last migration file is the one we rolled back? Then they are different? Actually, the last migration file is the one we rolled back (because it's the latest in the filesystem) and the last applied (not rolled back) is older. So we have unapplied migrations? But we rolled back, so we don't want to apply that migration again? Actually, the migration we rolled back is still in the filesystem, but we don't want to apply it because we rolled back? We might want to apply it again? That's a separate issue.
This is getting complex.
Perhaps we should only run drift detection when:
- There are no unapplied migrations (i.e., the last migration file is the same as the last applied migration, regardless of rollback?).
But if we rolled back, then the last applied migration (not rolled back) might be older than the last migration file. So we have unapplied migrations? Actually, the last migration file is the one we rolled back? Then it's unapplied? But we rolled it back, so it's not applied.
So we have unapplied migrations? Then we skip drift detection.
That seems safe.
However, what if we rolled back and then changed the Prisma schema and generated a new migration? Then the last migration file is new, and the last applied (not rolled back) is older, so we have unapplied migrations (the new one) and we skip drift detection. Then we apply the new migration and then run drift detection? That's correct.
So the logic holds.
But note: what if we rolled back and then changed the Prisma schema to match the rolled back state? Then the last migration file (the one we rolled back) is still the latest, and the last applied (not rolled back) is older, so we have unapplied migrations? Actually, the migration we rolled back is still in the filesystem and is the latest, but we rolled it back so it's not applied. So we have an unapplied migration (the one we rolled back) and we skip drift detection. But then the database is at the state of the migration before the rolled back one, and the Prisma schema is at the state of the rolled back migration? Because we changed the Prisma schema to match the rolled back state? Then we have a diff? But we are skipping drift detection because of unapplied migrations.
We want to detect that the database is not at the state of the Prisma schema? But we have an unapplied migration (the one we rolled back) that would bring the database to the Prisma schema? Then it's not drift, it's just not applied.
So again, we skip.
Therefore, we only run drift detection when we are at the latest migration (by file) and that migration is applied (not rolled back). But note: we might have rolled back the latest migration? Then the latest migration is rolled back and not applied? Then the last applied (not rolled back) is older, so we have unapplied migrations (the latest one) and we skip.
So, the condition is:
last_applied_migration (not rolled back) must be the same as the last_migration_file.
That means:
- There are no unapplied migrations (the last migration file is applied).
- And the last migration file is not rolled back? Actually, if it's applied and not rolled back, then it's the current state.
But what if we rolled back the last migration? Then the last migration file is not applied? Actually, we rolled it back, so it's not applied. Then the last applied (not rolled back) is older, so they are different -> unapplied migrations.
So, the condition is correct.
However, we are only checking the last migration. What if we have multiple unapplied migrations? Then the last applied (not rolled back) is older than the last migration file, so we skip.
So, we are safe.
This is a design. We must test it.
Note: This design assumes we are using PostgreSQL and the psql command. For other databases, we need to adjust the SQL queries and the way we run SQL scripts.
Also, we assume that the migration names in the _prisma_migrations table are the same as the directory names.
And we assume that the down script is in the migration directory and named migration.down.sql.
We also assume that the prisma CLI is available and configured.
This is a complex system and should be tested thoroughly.
Let me know if there are any questions.
I'll design a comprehensive Schema Evolution Tracker that integrates Prisma migrations, drift detection, and rollback capabilities. This system provides visibility, safety, and control over database schema changes.
Architecture Overview
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────────┐
│ Developer │───▶│ Schema Change │───▶│ Migration Generator│
│ makes change │ │ Detection (Drift) │ │ (Prisma) │
└─────────────────┘ └────────────────────┘ └─────────────────────┘
│
▼
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────────┐
│ Rollback │◀───│ Migration Tracker │◀───│ Migration Applier │
│ Management │ │ (Audit & State) │ │ (Prisma + Custom) │
└─────────────────┘ └────────────────────┘ └─────────────────────┘
│ │ │
└────────────────────────┼─────────────────────────┘
▼
┌─────────────────────┐
│ Central Registry │
│ & Alerting │
└─────────────────────┘
1. Core Schema & Tracking Tables
schema_evolution_metadata (Main tracker)
CREATE TABLE schema_evolution_metadata (
id BIGSERIAL PRIMARY KEY,
migration_name VARCHAR(255) UNIQUE NOT NULL,
prisma_migration_id VARCHAR(255) REFERENCES _prisma_migrations(id),
checksum VARCHAR(64) NOT NULL, -- SHA256 of migration files
applied_at TIMESTAMPTZ,
rolled_back_at TIMESTAMPTZ,
is_currently_applied BOOLEAN DEFAULT true,
migration_type VARCHAR(50) CHECK (migration_type IN ('sql', 'python', 'json', 'custom')),
source_file_path TEXT NOT NULL,
down_migration_file_path TEXT,
generated_by VARCHAR(100) DEFAULT 'prisma',
created_by VARCHAR(100),
created_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT valid_migration_state CHECK (
(is_currently_applied = true AND rolled_back_at IS NULL) OR
(is_currently_applied = false AND rolled_back_at IS NOT NULL)
)
);
schema_snapshots (Baseline comparisons)
CREATE TABLE schema_snapshots (
id BIGSERIAL PRIMARY KEY,
snapshot_name VARCHAR(255) NOT NULL,
migration_id BIGINT REFERENCES schema_evolution_metadata(id),
schema_hash VARCHAR(64) NOT NULL, -- Hash of entire schema
schema_dump TEXT NOT NULL, -- Full DDL snapshot
drift_detection_enabled BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(snapshot_name, migration_id)
);
drift_events (Detection log)
CREATE TABLE drift_events (
id BIGSERIAL PRIMARY KEY,
snapshot_id BIGINT REFERENCES schema_snapshots(id),
drift_type VARCHAR(50) NOT NULL, -- 'unsanctioned_change', 'missing_migration', 'orphaned_object'
object_type VARCHAR(50), -- 'table', 'column', 'index', 'constraint'
object_name VARCHAR(255),
expected_state JSONB,
actual_state JSONB,
severity VARCHAR(20) CHECK (severity IN ('info', 'warning', 'critical')),
detected_at TIMESTAMPTZ DEFAULT NOW(),
resolved_at TIMESTAMPTZ,
resolution_method VARCHAR(100)
);
rollback_scripts (Versioned rollbacks)
CREATE TABLE rollback_scripts (
id BIGSERIAL PRIMARY KEY,
migration_id BIGINT REFERENCES schema_evolution_metadata(id) ON DELETE CASCADE,
script_hash VARCHAR(64) NOT NULL,
script_content TEXT NOT NULL,
rollback_type VARCHAR(50) CHECK (rollback_type IN ('full', 'partial', 'data_only')),
safety_checks JSONB, -- Pre-rollback validation rules
created_at TIMESTAMPTZ DEFAULT NOW(),
verified_at TIMESTAMPTZ,
UNIQUE(migration_id, script_hash)
);
2. Migration Workflow Integration
A. Migration Generation Hook
// prisma/migrate/hooks/post-generate.js
const { execSync } = require('child_process');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
module.exports = async (migration) => {
// 1. Generate rollback script automatically (if possible)
await generateRollbackScript(migration);
// 2. Calculate checksum of migration files
const checksum = calculateMigrationChecksum(migration);
// 3. Register in evolution tracker
await registerMigration(migration, checksum);
// 4. Create baseline snapshot if first migration
if (isFirstMigration(migration)) {
await createInitialSnapshot(migration);
}
// 5. Trigger drift check after migration
await triggerDriftDetection(migration);
};
async function generateRollbackScript(migration) {
// Use Prisma's introspection to generate reverse SQL
// or use database-specific tools (pg_dump, mysqldump etc.)
const downScript = await generateDownMigration(migration);
const downPath = path.join(migration.dir, `${migration.name}.down.sql`);
fs.writeFileSync(downPath, downScript);
}
B. Migration Application with Tracking
// scripts/apply-tracked-migration.ts
import { PrismaClient } from '@prisma/client';
import { execSync } from 'child_process';
const prisma = new PrismaClient();
async function applyMigrationWithTracking(migrationName: string) {
// Start transaction
await prisma.$transaction(async (tx) => {
// 1. Apply Prisma migration
execSync(`npx prisma migrate deploy --name=${migrationName}`, {
stdio: 'inherit'
});
// 2. Get migration details from Prisma's _prisma_migrations
const prismaMigration = await tx.migration.findUnique({
where: { migration_name: migrationName }
});
// 3. Update our tracker
await tx.schemaEvolutionMetadata.update({
where: { migration_name: migrationName },
data: {
prisma_migration_id: prismaMigration.id,
applied_at: new Date(),
is_currently_applied: true
}
});
// 4. Create new snapshot
await createSnapshotAfterMigration(migrationName, tx);
});
}
3. Drift Detection System
Automated Drift Detection Service
# services/drift_detector.py
import asyncio
from datetime import datetime
from prismadb import get_db
from schema_utils import dump_schema, compare_schemas
class DriftDetector:
def __init__(self):
self.db = get_db()
self.detection_interval = 3600 # 1 hour
async def detect_all_drifts(self):
"""Run drift detection on all tracked databases"""
databases = await self.db.get_tracked_databases()
for db in databases:
try:
await self.detect_drift_for_database(db)
except Exception as e:
await self.log_error(db, str(e))
async def detect_drift_for_database(self, database_config):
"""Compare current schema with last approved snapshot"""
# 1. Get current schema
current_schema = await dump_schema(database_config)
current_hash = self._hash_schema(current_schema)
# 2. Get last approved snapshot
last_snapshot = await self.db.get_last_snapshot(
database_config.id,
approved_only=True
)
if not last_snapshot:
await self.create_initial_snapshot(database_config, current_schema)
return
# 3. Compare schemas
differences = compare_schemas(
last_snapshot.schema_dump,
current_schema
)
if differences:
await self.record_drift_event(
database_config.id,
last_snapshot.id,
differences
)
# 4. Alert on critical drifts
if any(d['severity'] == 'critical' for d in differences):
await self.send_alert(database_config, differences)
def _hash_schema(self, schema_dump: str) -> str:
return hashlib.sha256(schema_dump.encode()).hexdigest()
Pre-commit/Pull Request Hook
#!/bin/bash
# .git/hooks/pre-commit
# Check for schema changes
if git diff --cached --name-only | grep -q 'prisma/schema.prisma'; then
echo "Schema change detected. Running drift check..."
# Generate temporary migration
npx prisma migrate dev --create-only --name temp-check
# Compare with last applied migration
npx prisma migrate diff \
--from-url=$DATABASE_URL \
--to-schema-datamodel=./prisma/schema.prisma \
--script > /tmp/diff.sql
if [ -s /tmp/diff.sql ]; then
echo "ERROR: Uncommitted schema changes detected:"
cat /tmp/diff.sql
echo ""
echo "Please create a proper migration with:"
echo " npx prisma migrate dev --name descriptive-name"
exit 1
fi
fi
4. Rollback Management
Safe Rollback Process
// scripts/safe-rollback.ts
import { execSync } from 'child_process';
importquirer from 'inquirer';
interface RollbackPlan {
migration: string;
downScript: string;
impactAssessment: {
tablesAffected: string[];
dataLossRisk: 'none' | 'low' | 'medium' | 'high';
breakingChanges: boolean;
};
}
class RollbackManager {
async planRollback(targetMigration?: string): Promise<RollbackPlan[]> {
// 1. Get rollback chain
const chain = await this.getRollbackChain(targetMigration);
// 2. Validate each step
const validated = [];
for (const step of chain) {
const assessment = await this.assessRollbackImpact(step);
if (assessment.dataLossRisk === 'high' && !await this.confirmHighRisk()) {
throw new Error('High-risk rollback cancelled by user');
}
validated.push({ ...step, impactAssessment: assessment });
}
return validated;
}
async executeRollback(plan: RollbackPlan[]) {
for (const step of plan) {
console.log(`Rolling back: ${step.migration}`);
// Run safety checks
await this.runPreRollbackChecks(step);
// Execute down script
execSync(`psql $DATABASE_URL -f ${step.downScript}`, {
stdio: 'inherit'
});
// Mark as rolled back in Prisma
execSync(`npx prisma migrate resolve --rolled-back ${step.migration}`);
// Update our tracker
await this.updateTracker(step.migration);
// Create post-rollback snapshot
await this.createRollbackSnapshot(step.migration);
}
}
}
Rollback Verification
-- Verify rollback integrity
WITH rollback_check AS (
SELECT
m.migration_name,
m.applied_at,
m.rolled_back_at,
COUNT(*) as object_count_diff
FROM schema_evolution_metadata m
JOIN schema_snapshots s ON s.migration_id = m.id
WHERE m.is_currently_applied = false
AND m.rolled_back_at IS NOT NULL
GROUP BY m.id
)
SELECT * FROM rollback_check
WHERE object_count_diff != 0 -- Schema objects count changed unexpectedly
OR rolled_back_at < applied_at; -- Temporal anomaly
5. Schema Baseline & Health Dashboard
Health Query
-- Monthly schema health report
SELECT
DATE_TRUNC('month', applied_at) as month,
COUNT(*) as migrations_applied,
COUNT(*) FILTER (WHERE is_currently_applied = false) as migrations_rolled_back,
COUNT(DISTINCT created_by) as developers_involved,
AVG(EXTRACT(EPOCH FROM (rolled_back_at - applied_at))/3600) as avg_rollback_time_hours,
COUNT(d.id) as drift_events
FROM schema_evolution_metadata m
LEFT JOIN drift_events d ON d.migration_id = m.id
GROUP BY DATE_TRUNC('month', applied_at)
ORDER BY month DESC;
Unapplied Migration Alert
-- Find migrations in filesystem but not in database
WITH filesystem_migrations AS (
SELECT unnest(string_to_array(
regexp_replace(
regexp_replace(
directory,
'^.*/(\d{14}_.*)$',
'\1'
),
'/$',
''
),
','
)) as migration_name
FROM (
SELECT array_agg(filename) as directory
FROM (
SELECT filename
FROM pg_ls_dir('./migrations')
WHERE filename ~ '^\d{14}_'
) files
) dirs
)
SELECT
f.migration_name,
'Missing in database' as issue,
'high' as severity
FROM filesystem_migrations f
LEFT JOIN _prisma_migrations p ON p.migration_name = f.migration_name
WHERE p.id IS NULL;
6. CI/CD Integration
GitHub Actions Workflow
# .github/workflows/schema-evolution.yml
name: Schema Evolution Guard
on:
pull_request:
paths:
- 'prisma/schema.prisma'
- 'migrations/**'
jobs:
drift-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Database
run: |
docker-compose up -d postgres
npx prisma migrate deploy
- name: Check for Uncommitted Schema Changes
run: |
npx prisma migrate diff \
--from-url=${{ secrets.DATABASE_URL }} \
--to-schema-datamodel=./prisma/schema.prisma \
--script > diff.sql
if [ -s diff.sql ]; then
echo "❌ Uncommitted schema changes detected:"
cat diff.sql
exit 1
fi
- name: Verify Rollback Scripts
run: |
for migration in migrations/*; do
if [ -f "$migration/migration.sql" ] && [ ! -f "$migration/migration.down.sql" ]; then
echo "⚠️ Missing rollback script for: $(basename $migration)"
fi
done
- name: Update Schema Tracker
run: |
node scripts/update-tracker.js
git add schema_evolution_metadata.json
7. Monitoring & Alerting
Prometheus Metrics Exporter
// metrics/schema-evolution-metrics.js
const client = require('prom-client');
const migrationCounter = new client.Counter({
name: 'schema_migrations_total',
help: 'Total schema migrations by status',
labelNames: ['status', 'developer']
});
const driftCounter = new client.Counter({
name: 'schema_drift_events_total',
help: 'Total drift detection events',
labelNames: ['severity', 'type', 'database']
});
const rollbackDuration = new client.Histogram({
name: 'schema_rollback_duration_seconds',
help: 'Rollback operation duration',
labelNames: ['migration', 'success']
});
// Export metrics
app.get('/metrics', async (req, res) => {
res.set('Content-Type', client.register.contentType);
res.end(await client.register.metrics());
});
8. Best Practices & Safeguards
A. Required Safeguards for Production
-
Drift Prevention
-- Disable direct DDL in production (PostgreSQL example)
CREATE OR REPLACE FUNCTION prevent_direct_ddl()
RETURNS event_trigger AS $$
BEGIN
RAISE EXCEPTION 'Direct DDL forbidden. Use Prisma migrations only.';
END;
$$ LANGUAGE plpgsql;
CREATE EVENT TRIGGER prevent_ddl ON ddl_command_end
EXECUTE FUNCTION prevent_direct_ddl();
-
Migration Validation Rules
// validation/schema-rules.js
const forbiddenPatterns = [
/DROP\s+TABLE/i,
/ALTER\s+TABLE.*DROP\s+COLUMN/i,
/TRUNCATE/i
];
function validateMigration(sql: string): { valid: boolean; issues: string[] } {
const issues = [];
for (const pattern of forbiddenPatterns) {
if (pattern.test(sql)) {
issues.push(`Forbidden pattern: ${pattern}`);
}
}
return {
valid: issues.length === 0,
issues
};
}
B. Rollback Safety Checklist
## Before Rollback Verification
1. [ ] Backup database (full dump)
2. [ ] Review down migration SQL for data loss
3. [ ] Check foreign key constraints will remain valid
4. [ ] Verify application compatibility (API contracts)
5. [ ] Test in staging environment with production clone
6. [ ] Notify stakeholders (maintenance window if needed)
7. [ ] Prepare rollback of rollback (double revert plan)
8. [ ] Monitor application logs during rollback
9. Implementation Roadmap
Phase 1: Foundation (Week 1-2)
- Set up
schema_evolution_metadata table
- Implement basic migration tracking hooks
- Create initial schema snapshot
Phase 2: Detection (Week 3-4)
- Implement drift detection service
- Set up automated scheduling
- Create alerting rules
Phase 3: Safety (Week 5-6)
- Add rollback script generation
- Implement rollback verification
- Add production safeguards (event triggers)
Phase 4: Observability (Week 7-8)
- Integrate metrics/dashboards
- Create health reports
- Set up anomaly detection
Phase 5: Automation (Week 9-10)
- CI/CD integration
- Auto-remediation for simple drifts
- Documentation auto-generation
10. Example Commands
# Check schema health
npx ts-node scripts/check-schema-health.ts
# Generate rollback plan
npx ts-node scripts/rollback-plan.ts --to 20240101_initial
# Execute safe rollback
npx ts-node scripts/execute-rollback.ts --plan rollback-plan.json
# Force drift resolution (emergency)
npx ts-node scripts/resolve-drift.ts \
--drift-id 123 \
--method restore_snapshot \
--snapshot-id 456
Key Design Decisions
- Immutable Migration Records: Never delete migration records, only mark as rolled back
- Snapshot-based Comparison: Regular schema snapshots enable accurate drift detection
- Prisma-First Integration: All changes must go through Prisma migration system
- Surgical Rollbacks: Each migration gets its own verified down script
- Defense in Depth: Multiple layers of safeguards (hooks, triggers, validation)
- Audit Trail: Complete history of who changed what and when
Monitoring Alerts
alerts:
- name: SchemaDriftDetected
expr: schema_drift_events_total{severity="critical"} > 0
for: 5m
- name: UnappliedMigrations
expr: schema_migrations_total{status="generated"} - schema_migrations_total{status="applied"} > 0
- name: DirectDDLAttempt
expr: increase(schema_direct_ddl_attempts_total[1h]) > 0
- name: MissingRollbackScript
expr: schema_migrations_total - schema_rollback_scripts_total > 0
This system provides:
- Visibility: Complete audit trail of all schema changes
- Safety: Multiple safeguards against accidental drift
- Recovery: Verified, versioned rollback capabilities
- Compliance: Meets regulatory requirements for change tracking
- Automation: Reduces manual oversight needs
The tracker acts as a "source of truth" overlay on Prisma's own migration system, adding the missing pieces for enterprise-grade schema management.