Every migration ships with its undo.

shift runs safe, reversible migrations for Postgres and MySQL from one CLI.

$ brew install shift-cli
See the map
~ $ shift plan
  0043_add_order_status.up.sql     ALTER TABLE orders ADD COLUMN status text
  0043_add_order_status.down.sql   found   ALTER TABLE orders DROP COLUMN status
  nothing applied: this was a plan
~ $ shift up
  0043_add_order_status   applied    in one transaction, lock_timeout 3s
~ $ shift down
  0043_add_order_status   reverted   schema matches 0042 again

shift won’t apply a migration until its down file has run cleanly on a scratch copy.

How the check works

One migration, start to undo

Each box is a command; the dashed line is the way back.

Diagram of one migration: write the up and down files, shift plan, shift check, shift up to production at 0043; the way back runs from production through shift down to the schema at 0042. the way back 0043.up.sql 0043.down.sql written together shift plan prints the SQL, applies nothing shift check up, then down, on a scratch copy shift up applies, records its checksum production at 0043 shift down runs 0043.down.sql schema at 0042 again
  1. Write 0043.up.sql and 0043.down.sql together.
  2. shift plan prints the SQL and applies nothing.
  3. shift check runs up, then down, on a scratch copy.
  4. shift up applies it and records its checksum: production is at 0043.
  5. shift down runs 0043.down.sql: the schema is at 0042 again.
Rows of server racks with their status lights on
One binary on your laptop or in CI; nothing runs on the server.

Postgres and MySQL, handled differently

Two engines, two ways to fail.

WhenOn PostgresOn MySQL
A migration failsRolls back with the transactionRuns the down file
A lock is heldSET lock_timeout before each statementSET SESSION lock_wait_timeout
An index is addedCREATE INDEX CONCURRENTLYALGORITHM=INPLACE, LOCK=NONE
History is keptshift_migrations, one row a file

Read the plan before it runs

Every statement and the lock it takes.

~/shop $ shift plan --to 0045

  file                               statement                                      lock        down
  ─────────────────────────────────  ─────────────────────────────────────────────  ──────────  ─────
  0044_index_orders_customer.up.sql  CREATE INDEX CONCURRENTLY orders_customer_idx  none        found
  0045_add_refunds_table.up.sql      CREATE TABLE refunds (id bigserial, …)         new table   found

  2 to apply, 0 changes made

From shift new to shift down

Plain SQL files, five commands.

  1. shift new <name>

    Writes 0046_<name>.up.sql and its .down.sql

  2. shift plan

    Takes --db and --to, like every command

  3. shift check

    Needs a throwaway database in --scratch

  4. shift up --to <n>

    Stops at file <n>, checksums each one

  5. shift down --to <n>

    Reverts newest first, back to <n>

Run shift plan on staging first

Install it, then read what it would do.

$ brew install shift-cli
$ shift plan --db $STAGING_URL