# Preview a migration

> Run a migration on a fresh copy of your database and see what it would do to production before you run it.

Source: https://rowsafe.sh/docs/guides/preview-migrations

A migration that's instant on your laptop can lock a busy production table for minutes. **Preview a migration** runs it on a fresh copy of your database, on its own server, and shows you the locks, rewrites, rows and time first. Production is never touched.

It works for PostgreSQL, MySQL, MariaDB, MongoDB, ClickHouse and SQLite (not yet Redis and Valkey). What it can tell differs a little per engine: see [Other engines](#other-engines).

## What you get

- **A verdict:** *Safe*, *Careful*, *Dangerous*, or *Fails* (the migration errors on production's data).
- **What to change**, in plain words: use `CREATE INDEX CONCURRENTLY`, add a constraint `NOT VALID` then `VALIDATE` it, add a column instead of changing its type, set `lock_timeout`, batch a large `UPDATE`.
- **Each statement:** time, rows changed, locks and what they block, tables rewritten, indexes built, tables dropped.
- **Row-level security** (PostgreSQL, [below](#row-level-security)): a new table your API can reach without it, row-level security turned off, a policy dropped, a policy that lets every row through.

## Row-level security

If your app talks to PostgreSQL through an API such as Supabase or PostgREST, AI-written migrations often create a table without row-level security, or turn it off to get past a permission error. The preview compares the copy's row-level security before and after the migration, and flags:

| Finding                                                                                                                            | Verdict                                                                                      |
| ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| A new table your API's roles (`anon`, `authenticated`, ...) can use without row-level security, in a database that already uses it | Careful                                                                                      |
| `DISABLE ROW LEVEL SECURITY` on a table                                                                                            | Careful; **Dangerous** when `anon` can read it (anyone with your public key reads every row) |
| A policy dropped (not recreated under the same name)                                                                               | Careful                                                                                      |
| A policy whose rule is always true (`USING (true)`) for your API's roles                                                           | Careful                                                                                      |

Each comes with what to do, such as "Turn on row-level security and add a policy" in the same migration. Rowsafe reads only the catalog: table and policy names and flags, never rows or a policy's rule. These are the same rules as [Pulse's row-level security check](https://rowsafe.sh/docs/guides/security#row-level-security-supabase-postgrest). When the migration can't run (it's only read), the preview still catches `DISABLE ROW LEVEL SECURITY`, `DROP POLICY` and `USING (true)` from the SQL itself.

## Preview from the dashboard

1. Open the database, then **Guard → Migration previews**.
2. Click **Preview a migration**, and paste the SQL (for MongoDB, its mongosh calls) or upload the file.
3. Watch it run, then read the report.

The first preview restores a copy, which takes about as long as a restore test (Proof). For PostgreSQL, Rowsafe keeps that copy for an hour, so the next previews start in seconds, each on its own clone (one preview never sees another's changes). Other engines restore a new copy every time.

## Preview from a terminal or CI

```sh
rowsafe preview app migrations/0042_add_reference.sql
```

The report prints when the preview ends.

| Option                               | What it does                                                                                                                                                                                            |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--db NAME`                          | The database to run it in, when the server has several and it isn't the one named like `app`                                                                                                            |
| `--json`                             | One object with `verdict`, `summary`, `error` (empty when the preview ran), `markdown` (a ready-made pull request comment) and `result` (every statement)                                               |
| `--format markdown`                  | Prints the pull request comment                                                                                                                                                                         |
| `--fail-on dangerous` (or `careful`) | Exits `3` at or above that verdict, and `2` when the migration fails: use it to stop a CI job. Without it, the command exits `0` once the preview ran, whatever the verdict, and `1` if it couldn't run |
| `-` (instead of a file)              | Reads the SQL from standard input                                                                                                                                                                       |

In GitHub Actions, use the action's `preview-sql` ([Save a Mark before every deploy](https://rowsafe.sh/docs/guides/deploys#preview-the-migration-first)).

AI agents use the `preview_migration` tool of the [MCP server](https://rowsafe.sh/docs/reference/mcp). It needs no write access: an API key and a local `rowsafe mcp` always have it; apps signed in with Rowsafe get it with **Act for you**. The [Guard skill](https://rowsafe.sh/docs/guides/ai-agents) tells agents to preview every migration.

## Without the agent

`rowsafe preview postgres://user@host:5432/db FILE.sql` (or a [saved name](https://rowsafe.sh/docs/guides/no-account#save-a-database-once)) checks a PostgreSQL migration without the agent: on an empty copy of the schema in a temporary database on the same server when the connection's user may create databases, else by reading the SQL. Table sizes come from your database's statistics, so times are estimates, and errors that depend on your rows can't show. Same verdicts, options and exit codes; nothing on your database changes, and there is no restore point. See [Check a migration first](https://rowsafe.sh/docs/guides/no-account#check-a-migration-first). On a server Rowsafe protects on its own, `sudo rowsafe preview NAME FILE` runs on a full copy restored from its backups, as here: see [Rowsafe on your server](https://rowsafe.sh/docs/guides/no-account-server#preview-a-migration).

## Get your migration's SQL

Preview the SQL your tool would run, not its source file.

**Prisma**

Create the migration without applying it, then preview its file:

```sh
npx prisma migrate dev --create-only --name add_reference
rowsafe preview app prisma/migrations/*_add_reference/migration.sql
```

**Django**

```sh
python manage.py sqlmigrate shop 0042 > /tmp/0042.sql
rowsafe preview app /tmp/0042.sql
```

**Alembic**

Offline mode prints the SQL between two revisions:

```sh
alembic upgrade 3f2a1b:head --sql > /tmp/upgrade.sql
rowsafe preview app /tmp/upgrade.sql
```

Alembic wraps it in `BEGIN` and `COMMIT`; Rowsafe runs it as written.

**Rails**

Rails can't print a migration's SQL without running it. Run it once on your development database and copy the statements it logged (between `BEGIN` and `COMMIT` in `log/development.log`), or write the migration with `execute` and preview that SQL.

**Drizzle**

`drizzle-kit generate` writes the SQL file; preview it before `drizzle-kit migrate`:

```sh
npx drizzle-kit generate
rowsafe preview app drizzle/0007_add_reference.sql
```

**Flyway, Liquibase, goose**

- **Flyway:** preview the `V42__add_reference.sql` file itself.
- **Liquibase:** `liquibase update-sql > /tmp/update.sql`, then preview that file.
- **goose:** preview only the `-- +goose Up` part (Rowsafe would run the `Down` part too).

## Other engines

**MySQL and MariaDB**

- **The copy:** latest backup plus every binary log since, on a private server with no network port.
- **Statements run one by one**, as MySQL and MariaDB run them. Schema changes commit one at a time, so a migration that fails halfway leaves earlier changes on production: the preview shows that as **Dangerous**.
- **Locks are inferred** (Rowsafe can't watch them on the copy): a statement that copies the table (a column type change, `ALGORITHM=COPY`, `OPTIMIZE TABLE`) blocks writes for its whole run, `LOCK=EXCLUSIVE` blocks reads too, and `ALGORITHM=INSTANT` or `INPLACE` take only a brief lock.
- **Not run** (marked in the report): `GRANT`, `CREATE USER`, `SET GLOBAL`, `LOAD DATA`, `INTO OUTFILE`.

**MongoDB**

Write the migration as plain mongosh calls with literal values:

```js
db.orders.updateMany({ status: "old" }, { $set: { archived: true } })
db.orders.createIndex({ archived: 1, created: -1 })
db.getCollection("audit-log").drop()
```

- **The copy:** latest backup plus the oplog since.
- **Rowsafe runs each call itself**, never the file as JavaScript: no variables, loops, functions or `require()`.
- **Supported:** inserts, updates, deletes, `createIndex`, `dropIndex`, `createCollection`, `drop`, `renameCollection`, `aggregate` and schema `runCommand`s (`collMod`, `create`, `createIndexes`, ...). Reads are skipped.
- **Findings** for `drop()`, `deleteMany({})`, `updateMany({}, ...)`, `$unset` and new validators.

**ClickHouse**

- **The copy:** your newest backup (one every hour).
- **Mutations** (`ALTER TABLE ... UPDATE/DELETE`, `MODIFY COLUMN`) run to the end on the copy so their time shows. On production, they keep rewriting parts in the background after the migration returns.
- **Not run** (marked in the report): table functions such as `url()` or `s3()`, external dictionaries and table engines, files, `SYSTEM`, `GRANT`, users and roles.

**SQLite**

- **The copy:** the file from your latest backup and every change since, in a private folder on the same server. Kept an hour; each migration runs on a fresh copy of it.
- **One transaction**, unless your SQL has its own `BEGIN`/`COMMIT` or statements that can't run in one (`VACUUM`, `PRAGMA journal_mode`, `PRAGMA foreign_keys`).
- **Locks:** SQLite has one write lock for the whole file, so your app's writes wait for the whole migration (or each statement). In WAL mode reads go on; in rollback-journal mode they wait while it commits. A `VACUUM` needs about the file's size free; the preview says if there's room.
- **Table rebuilds** (as Rails and Django do for most `ALTER TABLE`s) and `DROP COLUMN` show as rewrites.
- **Findings:** index builds and `VACUUM` with how long writes would wait, a `NOT NULL` column without a default, `PRAGMA foreign_keys` inside a transaction (it does nothing there), orphaned rows (`foreign_key_check`), and a failure that leaves earlier statements applied.
- **Foreign keys are off**, the SQLite default.
- **Not run** (marked in the report): `ATTACH`, `VACUUM INTO`, `load_extension`, `.read`, `.import`. Functions or collations your app registers in code don't exist on the copy, so statements using them fail there.

## How it works, and its limits

- **Where:** on the database's server, at low CPU and IO priority, on no network port, with no background jobs (pg_cron doesn't run). Needs the agent running, at least one backup, and free disk: about 1.3 times the cluster's size plus 1 GB, plus room for a clone when a copy is reused.
- **Freshness:** at most about a minute behind production (ClickHouse: its newest backup). A copy is reused for up to an hour (`fresh_minutes` in the API, `--fresh` in the CLI).
- **Transactions:** without its own `BEGIN`/`COMMIT`, a migration runs in one transaction, so locks last until the end. Otherwise, or with `CREATE INDEX CONCURRENTLY` or `VACUUM`, statement by statement. psql commands (`\set`, `\c`) are skipped.
- **Never as a superuser (PostgreSQL):** the migration runs as a regular role that owns your tables. Rowsafe runs `CREATE EXTENSION` first, as a superuser. `ALTER SYSTEM`, untrusted languages and `COPY` to a file fail, and say why.
- **Times are estimates:** the copy is usually slower, but on busy production a lock waits behind running queries, and every query behind it waits too. That's why Rowsafe suggests `lock_timeout`.
- **What reaches Rowsafe:** your SQL passes through and is deleted when the preview ends (only its size and a hash stay). The report holds table names, counts, sizes and timings. Values from your data in error messages show as `(a value from your data)`; the full message stays in the agent's log on your server.
- **Size:** up to 960 kB of SQL, 5,000 statements and 30 minutes per preview, and five previews waiting per database.
