Migrations
When you change a model, the database must change with it. In Django,
makemigrations writes a migration file, migrate applies it, and
showmigrations tells you where a database stands. rind works the same
way, with the same three steps:
| Django | rind |
|---|---|
python manage.py makemigrations | rind make |
python manage.py makemigrations --check | rind check |
python manage.py migrate | rind migrate |
python manage.py showmigrations | rind status |
python manage.py migrate --fake | rind migrate --fake |
python manage.py migrate <app> --fake | rind migrate --fake --only <domain> |
python manage.py sqlmigrate | not needed: the migration is SQL |
the django_migrations table | the rind_migrations table |
rind makes four choices of its own:
- the migration files are plain SQL, not code;
- a rename is a question that
makeasks you, as Django does; - there is no going back: to undo a change, you write a new migration;
- the migrations are compiled into the binary, so a deployed server needs no source tree to migrate its database.
A first migration
Say you add a field to the Station model of the sample:
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub struct Station {
// …
/// A photo of the station: its key in the storage.
#[column(max_length = 500)]
pub photo: Option<rind::db::types::File>,
}
}
You ask rind to write the migration:
rind make
network 0003_station_photo
add network_station.photo
make has written a new file in the folder of the domain’s migrations.
It is plain SQL, and you can read it before anything runs:
-- rind migration: network 0003_station_photo
-- add network_station.photo
ALTER TABLE "network_station" ADD COLUMN "photo" character varying(500);
rind status lists every migration, in the order they are applied, with
[x] for the ones the database has and [ ] for the others:
[x] network 0001_initial
[x] accounts 0001_initial
[x] network 0002_keys
[ ] network 0003_station_photo
Then you apply what is missing:
rind migrate
applied network 0003_station_photo
rind … runs the application’s own binary (cargo run -p app -- …),
with the project’s .env as its environment. The database is
DATABASE_URL, or the one you give with --database URL. See
The command line.
Why the migrations are plain SQL
A Django migration is Python code: a list of operations
(AddField, AlterField, RunPython…) that Django turns into SQL when it
runs. rind writes the SQL itself, once, into the file. There are three
reasons for this:
- What you review is what runs. There is no translation step left. A reviewer, or a database administrator who does not know Rust, reads the exact statements the database will receive.
- The file is yours to edit.
makewrites the first draft. You may then add a statement, a data step or a backfill: where Django needs aRunPythonor aRunSQLoperation, you write the SQL in the file. - Old migrations never break. A Django migration imports historical models, and old migrations can stop working when the code around them changes. A SQL file depends on nothing in your code, so it runs the same way in five years.
To know what changed since the last migration without code, rind keeps a second file beside each migration: the schema of the domain once that migration is applied (see the files of a domain). This is what Django rebuilds by replaying its migrations in memory.
A domain’s migrations
A domain is one crate of models, like a Django app (see the glossary). Each domain has its own folder of migrations, inside its models crate:
network-models/migrations/
0001_initial.sql
0001_initial.state.json
0002_keys.sql
0002_keys.state.json
embedded.rs
- The
.sqlfile is the migration. Its first lines say what it is and which migrations of other domains it depends on.makewrites it, and then it belongs to you. - The
.state.jsonfile is the schema of the domain once the migration is applied: its tables, columns, keys, indexes. The nextmakecompares the models with it. This is why making a migration needs no database, and whymakecan see that a column was perhaps renamed. embedded.rslists the files for the compiler.makekeeps it up to date; do not edit it by hand.
The crate gives its domain to the application with a function, usually
called migrations():
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("network", schema()).extension("postgis")
}
}
The domain! macro takes the domain’s name and its tables (the
schema() function of the crate), and compiles in the files of the
crate’s migrations folder. The application lists every domain in its
app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
.models(network_models::migrations())
.models(accounts_models::migrations())
// …
}
rind add domain creates a new models crate with an empty index,
migrations/embedded.rs, so that the crate builds before its first
migration exists.
Extensions, types and functions the tables need
Some tables need something that is not a table: a PostgreSQL extension
(postgis, vector), or a type, a function or a text search
configuration. You declare it on the domain, and the domain’s migrations
create it before the tables:
#![allow(unused)]
fn main() {
rind::migrations::domain!("classify", schema())
.extension("vector")
.object("TYPE", "classify_embedding_kind", include_str!("../sql/classify_embedding_kind.sql"))
}
.extension(name)is created withCREATE EXTENSION IF NOT EXISTS..object(kind, name, sql)is created by the SQL you give.kindis the word that followsDROPto remove it (TYPE,FUNCTION…).
Writing migrations: make and check
rind make compares each domain’s models with the state its last
migration recorded, and writes a migration for each domain that changed.
It reads no database. The first migration of a domain is named
initial; a later one is named after what it does when it does one thing
(0003_station_photo), and changes otherwise. --name gives your own
name: rind make --name add_photos.
Most changes of a model become one SQL statement each:
| You change the model | The migration has |
|---|---|
| a new model, a new link table | CREATE TABLE, then its keys |
| a model removed | DROP TABLE |
| a field added or removed | ADD COLUMN, DROP COLUMN |
| a type, a length | ALTER COLUMN … TYPE … USING |
Option added or removed | DROP NOT NULL / SET NOT NULL |
| a default | SET DEFAULT / DROP DEFAULT |
a foreign key, its target, its on_delete | the constraint and its index |
| an index, a uniqueness, a condition | CREATE INDEX, ADD CONSTRAINT, or their drop |
| the name of a constraint or of an index | a rename |
rind check writes nothing. It fails when a model changed and has no
migration yet, as Django’s makemigrations --check does. It also fails
when the models do not hold together across domains (a key to a table
that does not exist, two constraints with the same name), or when a
folder’s embedded.rs is not what the folder has. Run it in CI.
The sample also runs the same check with its tests
(sample/tests/schema.rs, through rind::testing::check), so
cargo test fails when a model changed without its migration.
When a column was renamed
When a column (or a table) disappeared and another one of the same shape
appeared, make cannot know whether you renamed it or replaced it. So it
asks you, as Django does:
Was network_station.code renamed to network_station.reference? [y/N]
If you answer yes, the migration has a RENAME, and the data stays. If you
answer no, the old column is dropped, with its data, and the new one is
added empty.
When nobody can answer (in a script, in CI), give the renames beforehand.
A column is table.old=new, and a table is old=new:
rind make --rename network_station.code=reference
rind make --rename network_stop=network_station
Without a terminal and without --rename, the answer is no.
A new required field: what only you can write
A new field that is not an Option and has no default is a problem for
the rows that already exist: they have no value for it. Django asks you
for a one-off default when you run makemigrations. rind writes the
migration in three steps and leaves the middle one to you:
ALTER TABLE "network_station" ADD COLUMN "rank" integer;
-- TO COMPLETE: the rows that exist need a value. Write it here, then remove this line:
-- UPDATE "network_station" SET "rank" = …;
ALTER TABLE "network_station" ALTER COLUMN "rank" SET NOT NULL;
The column is added empty, you fill it, and then it becomes required.
make tells you which file is waiting:
network 0007_station_rank
add network_station.rank
TO COMPLETE before it can be applied: "…/0007_station_rank.sql"
A migration that still has a -- TO COMPLETE line is not applied:
migrate stops there and applies nothing after it. Write the UPDATE,
remove the line, and migrate again.
Applying migrations: migrate and status
rind migrate applies, in order, every migration the database does not
have yet.
- Each migration runs in its own transaction. A migration that fails
leaves nothing of itself behind, and nothing after it is tried. You fix
the file and run
migrateagain. - What is applied is recorded in a table,
rind_migrations, with a fingerprint of the file’s text. The table is created by the firstmigrate;statusonly reads it, and changes nothing in the database. rind statusshows an edited migration. A migration whose file changed after it was applied is marked[!] edited since it was applied. Editing it does not apply the change: write a new migration instead.migratewarns about forgotten migrations. If the binary’s models have changes that no migration has, it says so before it applies the others.
Migrating when the server starts
Several processes can migrate the same database at once, for example the instances of a deployment that start together. One of them applies each migration; the others wait, then find it done. So an application can safely migrate when it starts:
#![allow(unused)]
fn main() {
rind::migrations::migrate(&db, sample::app().migrations(), false).await?;
}
The last argument is fake (see below). A
deployed binary needs no source tree: it applies the migrations that were
compiled into it.
Coming from Django: there is no
migrate <app> 0002to go back to an older migration, and no reverse operation in a migration. To undo a change, change the model back and runmake: the new migration does the opposite of the old one.
Migrations across domains
A migration comes after the one before it in its domain. When its foreign
keys point to tables of another domain, it also comes after the migration
of that domain that creates those tables. make writes these
dependencies as -- depends: lines at the top of the file, and migrate
finds an order that respects them all:
-- rind migration: network 0002_keys
-- depends: accounts 0001_initial
Two domains can point to each other. In the sample, a station has a
manager (a user of accounts), and a user has a home station (in
network). Neither domain’s first migration can come after the other’s.
make then does what Django’s makemigrations does in that case: it
creates the tables first, without the keys between them, and adds those
keys in a second migration of each domain:
network 0001_initial the stations, without their key to the users
accounts 0001_initial the users, without their key to the stations
network 0002_keys
accounts 0002_keys
Naming constraints and indexes
rind gives a name to every constraint and index it creates:
<table>_<columns>_idx for an index, _key for a unique column, _fkey
for a foreign key. You can give any of them another name. This is how a
model describes a database that already exists, created by Django for
example, whose names are not rind’s:
| On | The name is given with |
|---|---|
| a foreign key | #[fk(Target, constraint = "…", index = "…")] |
| a unique column | #[column(unique = "…")] |
| an indexed column | #[column(index = "…")] |
#[index(on(..))], #[unique(on(..))] | name = "…" |
| a condition | #[check(name = "…", sql = "…")] |
If you change a name on the model, the next migration renames the constraint or the index in the database.
Taking over a database
Sometimes the tables already exist: a Django application, or another
program, created them, and rind now takes over. You write the models that
describe these tables (rind can write them for you: see
Starting from a database), and make writes their first
migrations as usual. But these migrations must not run, since the tables
are already there. You record them as applied instead, as Django’s
migrate --fake does:
rind migrate --fake
--fake records every migration the database does not have, and runs
none. A -- TO COMPLETE line does not stop it.
Often only some domains already exist in the database, and the others are
new: the application’s own tables, which rind must create. --only
chooses the domains, as migrate <app> --fake does in Django:
rind migrate --fake --only locations,structures,users # recorded, not run
rind migrate # the others, run
--only puts the migrations of every domain in order, so it knows the
dependencies between domains, and then applies only those of the domains
you named. A migration that depends on another domain (because one of its
keys points to that domain’s table) is refused until that other domain is
applied or recorded. For example, rind migrate --only documents is
refused while the users migrations that documents points to are not
in the database.
Checking the models against the database first
Before you record anything, check that the models describe the database faithfully. Two commands compare them:
rind dbcheckcompares tables, columns and types (db.check_schema(&tables)in code).rind constraintscompares constraints and indexes, by name and by what they are. With--sql, it prints theRENAMEstatements that would give the database the models’ names.
rind dbcheck
rind constraints # what differs, by name and by what it is
rind constraints --sql # the renames that give the database the models' names
rind verify goes further: it applies every migration to an empty schema
and compares the result with the models. With --against URL, it also
compares it with the database the models were written from (see
Starting from a database).
Reference
The commands
rind make [--name NAME] [--rename OLD=NEW]... # write what changed in the models
rind check # fail if a change has no migration
rind status # on DATABASE_URL, or --database URL
rind migrate [--fake] [--only a,b]
rind constraints [--sql] # the constraints and indexes that differ
rind verify # every migration on an empty schema, compared with the models
rind verify --against URL [--schema S] # … and with that database
make and check read no database, and refuse --database. status,
migrate and constraints read DATABASE_URL or --database URL.
| Command | What it does |
|---|---|
make | writes a migration for each domain whose models changed; asks about renames |
make --name NAME | names the new migrations NNNN_<name> |
make --rename old=new | a table renamed, answered beforehand |
make --rename table.old=new | a column renamed, answered beforehand (table is the new table name) |
check | fails if the models do not hold together, if a change has no migration, or if an embedded.rs is stale |
status | every migration in order: [x] applied, [ ] not, [!] edited since it was applied |
migrate | applies what the database does not have, each migration in a transaction |
migrate --fake | records the migrations without running them |
migrate --only a,b | only the migrations of these domains (with --fake or without) |
constraints | the constraints and indexes the models and the database do not have alike |
constraints --sql | the statements that rename them to the models’ names |
verify | applies every migration to a temporary schema, compares it with the models, drops the schema |
In code
An application that does not use rind::cli can call the same commands
itself, with the arguments of the command line (without the program’s
name; status and migrate then take the database’s address as their
first argument):
#![allow(unused)]
fn main() {
rind::migrations::run(app.migrations(), &args).await?;
}
The functions behind the commands are in rind::migrations:
| Function | Does |
|---|---|
migrate(&db, domains, fake) | rind migrate, rind migrate --fake |
migrate_only(&db, domains, Some(&["a", "b"][..]), fake) | rind migrate --only a,b |
status(&db, domains) | rind status: a Status per migration (domain, name, applied, changed) |
make(domains, &mut ask, name) | rind make; ask answers the renames (NoRename, Renames(..)) |
pending_changes(domains, &mut ask) | what check reports: the changes without a migration |
The files
| File | Written by | Holds |
|---|---|---|
NNNN_name.sql | make, then you | the SQL; a -- rind migration: line, then -- depends: <domain> <name> lines |
NNNN_name.state.json | make | the schema of the domain after this migration |
embedded.rs | make (and rind add domain, empty) | the list of files compiled into the binary |
rind_migrations (a table) | migrate | domain, name, applied_at, fingerprint |