# Usage

> Reylo Migrate's workflows, the schema file, schemaless mode, the order migrations run in, and running migrations from code.

Workflows, the schema file and the order your migrations run in

Each workflow below is a few commands of the [CLI](https://reylo.dev/migrate/cli).

## Workflows

### Trying a change

Push changes to your development database, then write the migration:

```terminal
# force migrate your database to schema.sql (dev only, possibly destructive)
# use --watch to push on every save
$ reylo db push

# write the migration; dev records it without running it again
$ reylo migrate new add_bio
$ reylo migrate dev
```

### Dropping and renaming

A drop, or a rename Reylo Migrate can't be sure of, is refused until you [name it](https://reylo.dev/migrate-usage#disambiguation):

```terminal
# drop a column, and its data
$ reylo migrate new drop_bio --drop users.bio

# rename a column whose type changes too, keeping its rows
$ reylo migrate new rename_bio --rename users.bio=about
```

### Switching branches

After a switch, pull or merge, run `reylo migrate dev`:

```terminal
# rewind what feature-a ran, and run what's new on feature-b
$ git switch feature-b
$ reylo migrate dev
Applying to postgres://localhost:5432/app
  ↺ 20261104120000_add_tags.sql   rewound: it isn't in the migrations
    ! Dropped tags
  ✓ 20261104130000_add_posts.sql  applied · 3 ms
✓ Wrote reylo/reylo.lock

# after a conflict on reylo/reylo.lock, keep main's lines, then add yours back after them
$ reylo migrate dev
```

### Deploying

Try the deploy, run it, then confirm it:

```terminal
# in CI, before you deploy: on shadow databases, running nothing
$ reylo migrate deploy --dry-run

# when you deploy
$ reylo migrate deploy

# after: exits 1 unless the database has run every migration
$ reylo migrate status
```

Run the deploy before your new code goes live. On Postgres and MySQL, two deploys at once take turns. So each instance of your app can instead run [`migrate()`](https://reylo.dev/migrate-usage#api) as it starts. An older release then won't start on a database a newer one migrated.

Your old code keeps serving while the deploy runs, and after one that fails. So drop a column only once no running code reads it.

### Starting over

Rebuild your development database from your migrations, or empty it:

```terminal
# drop everything and run every migration
$ reylo db reset

# keep the schema, delete every row, and load your seed
$ reylo db wipe && reylo run --file seed.sql
```

### Adopting a hotfix

Keep a change made on production by hand:

```terminal
# print what the database has, and copy the change into reylo/schema.sql
$ reylo db introspect --url $PROD_URL

# write its migration, run it in development, and record it on production
$ reylo migrate new users_email
$ reylo migrate dev
$ reylo migrate history push --url $PROD_URL
```

Where production hasn't run every migration ahead of yours, `reylo migrate history push` moves yours ahead of them in the lock. Record the new order in development too, then deploy the rest:

```terminal
# record the lock's new order on your development database, running nothing
$ reylo migrate history push

# run the migrations production hasn't run
$ reylo migrate deploy --url $PROD_URL
```

It moves yours past no migration that changes data. Past one, it refuses and says to undo your change on production, then deploy. It prints the undo where it can run it safely. A server that ran them before yours, such as staging, takes your change too. Its deploy refusal gives the commands.

## Schema `schema.sql`

Declare your schema in plain SQL, as you would on the database. Reylo Migrate compares and migrates:

- Tables, columns, constraints and indexes
- Generated columns, and identity columns (Postgres)
- Enums (Postgres and MySQL), domains, composite and range types (Postgres)
- Views, and materialized views (Postgres)
- Triggers, functions (Postgres and MySQL), and procedures and events (MySQL)
- Partitions (Postgres and MySQL)
- Row level security policies, sequences, extensions and schemas (Postgres)
- Grants and comments (Postgres and MySQL)
- `STRICT` and `WITHOUT ROWID` tables (SQLite)

#### Enums and domains

```sql
create type mood as enum ('sad', 'ok', 'happy');
create domain email as text check (value like '%@%');
```

#### Generated columns

```sql
create table line_items (
  price numeric not null,
  qty integer not null,
  total numeric generated always as (price * qty) stored
);
```

#### Exclusion constraints

```sql
create extension btree_gist;

create table bookings (
  room integer not null,
  during tstzrange not null,
  exclude using gist (room with =, during with &&)
);
```

#### Partial indexes

```sql
create index users_unverified on users (created_at) where verified_at is null;
```

#### Materialized views

```sql
create materialized view room_totals as
  select room, sum(total) as total from bookings group by room;
create unique index room_totals_room on room_totals (room);
```

#### Functions and triggers

```sql
create function touch() returns trigger language plpgsql as $$
begin new.updated_at := now(); return new; end $$;

create trigger users_touch before update on users
  for each row execute function touch();
```

#### Row level security

```sql
alter table documents enable row level security;
create policy documents_own on documents
  using (owner_id = current_setting('app.user_id')::integer);
```

#### Grants and comments

```sql
grant select on room_totals to reporting;
comment on column users.verified_at is 'When they confirmed their email';
```

On MySQL, an account sees only its own grants unless it may read the privilege tables. An account that isn't an administrator needs them granted:

```sql
grant select on mysql.tables_priv to 'app'@'%';
grant select on mysql.columns_priv to 'app'@'%';
grant select on mysql.procs_priv to 'app'@'%';
```

A change to any of them is a migration:

`schema.sql`:

```sql
create policy docs_read on docs for select to reader using (owner_name = current_user); -- [!code --]
create policy docs_read on docs for select to reader, writer using (owner_name = current_user or body is null); -- [!code ++]
```

It writes this migration:

`20261106120000_writers_read.sql`:

```sql
drop policy docs_read on docs;
create policy docs_read on docs for select to reader, writer using (owner_name = current_user or body is null);
```

Text search configurations, security labels and a few other kinds are compared by name only, or not at all. Write their changes by hand. On MySQL, so is a routine, trigger or event made under another `sql_mode` than the server's.

## Disambiguation

Some changes to `schema.sql` read two ways, such as a drop or a rename. Reylo Migrate asks which you mean, and you answer with a flag.

### Drops

A table or column that goes is refused until you name it:

`schema.sql`:

```sql
create table users (
  id integer primary key,
  email text not null, -- [!code --]
  email text not null -- [!code ++]
  bio text -- [!code --]
);
```

Name it with `--drop`:

```terminal
$ reylo migrate new drop_bio
✗ This migration drops the column users.bio and its data

  To drop it:
    reylo migrate new drop_bio --drop users.bio

Nothing was changed.

$ reylo migrate new drop_bio --drop users.bio
✓ Wrote reylo/migrations/20261104150000_drop_bio.sql
  - column users.bio text

  ! Drops the column users.bio and its data
```

A table is named alone:

```terminal
$ reylo migrate new drop_tags --drop tags
✓ Wrote reylo/migrations/20261104150000_drop_tags.sql
  - table tags
      id integer not null
      name text not null
      primary key (id)

  ! Drops the table tags and its rows
```

### Column renames

A column replaced by one just like it is a rename, which keeps its rows:

`schema.sql`:

```sql
create table users (
  id integer primary key,
  email text not null,
  bio text -- [!code --]
  about text -- [!code ++]
);
```

It's written as a rename, and says so:

```terminal
$ reylo migrate new rename_bio
✓ Wrote reylo/migrations/20261104150000_rename_bio.sql
  ~ column users.[-bio-]{+about+} text

  ! Written as a rename, keeping its rows
    If they're different columns, delete the file, then:
      reylo migrate new rename_bio --drop users.bio
```

The migration carries the other reading:

`20261104150000_rename_bio.sql`:

```sql
-- users.bio is renamed about, keeping its rows. If they are two columns, write instead:
--   alter table users drop column bio;
--   alter table users add column about text;
alter table users rename column bio to about;
```

"Just like it" means the same type, nullability, default and collation. A column that differs in any of them could be either, so you say which:

`schema.sql`:

```sql
create table posts (
  id integer primary key,
  title varchar(100) -- [!code --]
  heading varchar(200) -- [!code ++]
);
```

Rename it with `--rename`, or drop it with `--drop`:

```terminal
$ reylo migrate new rename_title
✗ This migration can't tell a rename from a new column

    - column posts.title character varying(100)
    + column posts.heading character varying(200)

  To rename the column, keeping its rows:
    reylo migrate new rename_title --rename posts.title=heading
  To drop the column and its data, and add a new one:
    reylo migrate new rename_title --drop posts.title

Nothing was changed.

$ reylo migrate new rename_title --rename posts.title=heading
✓ Wrote reylo/migrations/20261104150000_rename_title.sql
  ~ column posts.[-title-]{+heading+} character varying([-100-]{+200+})
```

Several at once are asked together:

`schema.sql`:

```sql
create table posts (
  id integer primary key,
  title varchar(100) -- [!code --]
  heading varchar(200) -- [!code ++]
);

create table users (
  id integer primary key,
  bio varchar(200) -- [!code --]
  about text -- [!code ++]
);
```

Pick a flag for each:

```terminal
$ reylo migrate new tidy_columns
✗ This migration can't tell renames from new columns

    - column posts.title character varying(100)
    + column posts.heading character varying(200)
    - column users.bio character varying(200)
    + column users.about text

  For each, rename it to keep its rows, or drop it and add the new one:
    --rename posts.title=heading   or   --drop posts.title
    --rename users.bio=about       or   --drop users.bio
  Add the flags you picked to:
    reylo migrate new tidy_columns

Nothing was changed.

$ reylo migrate new tidy_columns --rename posts.title=heading --drop users.bio
✓ Wrote reylo/migrations/20261104150000_tidy_columns.sql
  ~ column posts.[-title-]{+heading+} character varying([-100-]{+200+})
  + column users.about text
  - column users.bio character varying(200)

  ! Drops the column users.bio and its data
```

### Table renames

A table replaced by one with the same columns is a rename:

`schema.sql`:

```sql
create table users ( -- [!code --]
create table accounts ( -- [!code ++]
  id integer primary key,
  email text not null
);

create table posts (
  id integer primary key,
  user_id integer references users (id) -- [!code --]
  user_id integer references accounts (id) -- [!code ++]
);
```

It's written as a rename, with what's named after the table:

```terminal
$ reylo migrate new rename_users
✓ Wrote reylo/migrations/20261104150000_rename_users.sql
  ~ table [-users-]{+accounts+}

  ! Written as a rename, keeping its rows
    If they're different tables, delete the file, then:
      reylo migrate new rename_users --drop users
```

A table that shares most of its columns could be either:

`schema.sql`:

```sql
create table orders ( -- [!code --]
create table invoices ( -- [!code ++]
  id integer primary key,
  customer text not null,
  total numeric(10, 2) not null,
  note text -- [!code --]
  paid_at timestamptz -- [!code ++]
);
```

Each answer is a command:

```terminal
$ reylo migrate new invoices
✗ This migration can't tell a rename from a new table

    - table orders
    + table invoices
    - column orders.note text
    + column invoices.paid_at timestamp with time zone

  To rename the table, keeping its rows:
    reylo migrate new invoices \
      --drop invoices.note \
      --rename orders=invoices
  To drop the table and its data, and create a new one:
    reylo migrate new invoices --drop orders

Nothing was changed.

$ reylo migrate new invoices --drop invoices.note --rename orders=invoices
✓ Wrote reylo/migrations/20261104150000_invoices.sql
  ~ table [-orders-]{+invoices+}
  + column invoices.paid_at timestamp with time zone
  - column orders.note text

  ! Drops the column invoices.note and its data
```

### Table rewrites

On Postgres, a change that copies a table while it blocks writes is refused until you accept it with `--blocking`:

`schema.sql`:

```sql
create table payments (
  id integer primary key,
  amount integer not null -- [!code --]
  amount bigint not null -- [!code ++]
);
```

Accept it where the table is small:

```terminal
$ reylo migrate new widen_amount
✗ This migration rewrites payments, copying every row while it blocks reads and writes to it
  On a table with many rows, the app's writes wait for as long as that takes.
  To change a column without copying its table, add a column, fill it in batches, then swap the two, each step a migration of its own.

  Where the table is small enough to wait for:
    reylo migrate new widen_amount --blocking

Nothing was changed.

$ reylo migrate new widen_amount --blocking
✓ Wrote reylo/migrations/20261104150000_widen_amount.sql
  + column payments.amount bigint not null
  - column payments.amount integer not null

  ! It rewrites payments, copying every row while it blocks reads and writes to it
```

New constraints and indexes are never asked about. They're written as several migrations, so that none blocks writes.

### Type changes

A type change that loses values is refused until you name the column with `--drop`:

`schema.sql`:

```sql
create table events (
  id integer primary key,
  starts_at timestamptz not null, -- [!code --]
  price numeric(10, 2) -- [!code --]
  starts_at date not null, -- [!code ++]
  price numeric(10, 0) -- [!code ++]
);
```

Each loss is named:

```terminal
$ reylo migrate new dates_only
✗ Column events.price changes from numeric(10,2) to numeric(10,0), which rounds to whole numbers

  To accept that:
    reylo migrate new dates_only --drop events.price

✗ Column events.starts_at changes from timestamp with time zone to date, which keeps only the date

  To accept that:
    reylo migrate new dates_only --drop events.starts_at

Nothing was changed.
```

Name both, with `--blocking` for the rewrite:

```terminal
$ reylo migrate new dates_only --drop events.starts_at,events.price --blocking
✓ Wrote reylo/migrations/20261104150000_dates_only.sql
  + column events.price numeric(10,0)
  + column events.starts_at date not null
  - column events.price numeric(10,2)
  - column events.starts_at timestamp with time zone not null

  ! It rewrites events, copying every row while it blocks reads and writes to it
  ! Column events.price changes from numeric(10,2) to numeric(10,0), which rounds to whole numbers
  ! Column events.starts_at changes from timestamp with time zone to date, which keeps only the date
```

A change that fails on a value it can't hold, such as a shorter `varchar`, isn't asked about: the migration fails on that row instead. On SQLite, only a change from text to a number loses values.

### Pushes

A push asks the same questions, and takes `--force` for every one at once:

```terminal
$ reylo db push
✗ This push drops the column users.nick and its data

  To drop it:
    reylo db push --drop users.nick
  To accept every destructive change:
    reylo db push --force

Nothing was changed.
```

With `--force`, a column that could be a rename is renamed where both types are of one kind, such as two numbers, and dropped otherwise. A push never asks for `--blocking`.

## Schemaless mode

Delete `schema.sql`, and your migrations are your schema.

Write migrations by hand, or change your development database and let `reylo migrate new` write the migration:

```terminal
$ reylo run 'alter table users add column bio text'
✓ alter table users add column bio text

$ reylo migrate new add_bio
✓ Wrote reylo/migrations/20261104140347_add_bio.sql
  + column users.bio text

$ reylo migrate dev
Applying to postgres://localhost:5432/app
  + 20261104140347_add_bio.sql  recorded: already in place
✓ Wrote reylo/reylo.lock
```

What changes:

- Checks against `schema.sql` are skipped.
- Your development database stands in for `schema.sql`, so `reylo migrate new` refuses until it has run every migration.
- There's nothing to push, so `reylo db push` refuses.

You lose the one file that shows your whole schema.

## Ordering `reylo.lock`

Your migrations run in one order: the lockfile's, or their names'.

### Lockfile

The lockfile lists your migrations in order, each with a checksum chained to the one before. A migration it doesn't list yet is a draft, free to edit:

`reylo.lock`:

```yaml
version: 1
schema: c7bf681b
migrations:
  - name: 20261104120000_users.sql
    checksum: c86e9de4
  - name: 20261104140347_add_bio.sql
    checksum: 78ad08c0
```

Two branches that each add a migration conflict on the lock in git. Keep main's lines, then run `reylo migrate dev` to add yours after them.

### Lock-free mode

Delete `reylo.lock`, and your migrations run in name order.

Status says so:

```terminal
$ reylo migrate status
Migrations on postgres://localhost:5432/app
  ✓ init.sql                 applied 2026-11-04 12:00 UTC
  ✓ 20261105090000_tags.sql  applied 2026-11-05 09:00 UTC
✓ Unchanged since its last migration
» With no lock, migrations run in name order
  To write one:
    reylo migrate lock
» With no lock to hold its checksum, reylo/schema.sql is checked against the migrations by a dry run
  To check it:
    reylo migrate deploy --dry-run
```

Without a lock, a merged migration can sort before one a database already ran. Then `reylo migrate dev` and `reylo migrate deploy` replay both orders on a shadow database, and refuse it where they end differently:

```terminal
$ reylo migrate deploy
✗ Migration 20261105080000_no_nick.sql sorts before 20261105090000_nick.sql, which this database already ran
  Run in name order, as on a fresh database, the migrations end differently:

    --- this database
    +++ a fresh database
    + column users.nick text

  Give it a later name, so that every database runs it after 20261105090000_nick.sql:
    mv reylo/migrations/20261105080000_no_nick.sql reylo/migrations/20261105090001_no_nick.sql

Nothing was changed.
```

You give up:

- **The same data everywhere.** No check can show that data written in two orders matches.
- **Checksums.** A migration edited before any database ran it goes unseen.

Only a missing lock turns it on. A `reylo.lock` that is there and can't be read is refused by every command.

To turn the lock back on, run `reylo migrate lock`.

## API

Run your migrations from code:

`server.ts`:

```ts
import { migrate } from "reylo";

// reylo migrate deploy, in this directory, on direct_url's database
const ran = await migrate();
```

It resolves to the names of the migrations it ran, and rejects with the deploy's problems. Pass `url` for another database:

```ts
await migrate({ url: process.env.PRODUCTION_URL });
```

A [Cloudflare Durable Object](https://reylo.dev/durable-objects#migrations) runs its migrations on itself, from its constructor.
