Migrations
A Migrator keeps a database's schema in step with your code. It holds two things: ordered steps (SQL or Rust), each applied once and recorded in a table, and models whose tables it keeps matching their structs, adding columns as fields are added. It can run when the client connects, or when you call it.
A first migrator
rust
use rasterizeddb_client::orm::{AutoMigrate, Migrator, SyncPolicy};
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "accounts")]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(unique)]
email: String,
}
fn migrations() -> Migrator {
Migrator::new()
// SQL, run once, in the order added. `down` undoes it for rollback_to.
.step("0001_settings", &[
"CREATE TABLE IF NOT EXISTS settings (k TEXT NOT NULL, v TEXT, PRIMARY KEY (k))",
])
.down(&["DROP TABLE IF EXISTS settings"])
// Rust, for data changes. The version string stands for the code in the checksum.
.code_step("0002_defaults", "v1", |c| {
Box::pin(async move {
c.exec(
"INSERT INTO settings (k, v) VALUES ($1, $2) ON CONFLICT (k) DO NOTHING",
params!["theme", "dark"],
)
.await?;
Ok(())
})
})
// Run again whenever its text changes.
.repeatable("r_vacuum", &["SET CONFIG vacuum.enabled = on"])
// Keep this table matching its struct on every run.
.model::<Account>()
.sync_policy(SyncPolicy::default())
}
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect(
"unix:/run/rdb/rdb.sock",
Options { migrations: Some(migrations()), auto_migrate: AutoMigrate::Apply, ..Options::default() },
)
.await?;
let _ = client;
Ok(())
}
Migrating on connect
Options::migrations holds the migrator, and Options::auto_migrate says what Client::connect does with it:
AutoMigrate | connect does |
Apply (default) | applies what is pending (steps, then model sync) before returning; a failure is connect's error |
Verify | changes nothing, and fails if anything is pending, edited, unknown or drifted |
Off | nothing; call client.migrate(&migrator) yourself |
A common setup: services start with Verify, so a service never runs against a database that is behind; a deploy job runs Apply once before the services roll out.
rust
use rasterizeddb_client::orm::{AutoMigrate, Migrator};
use rasterizeddb_client::prelude::*;
async fn start_service(migrations: Migrator) -> Result<Client> {
Client::connect(
"unix:/run/rdb/rdb.sock",
Options { migrations: Some(migrations), auto_migrate: AutoMigrate::Verify, ..Options::default() },
)
.await
}
async fn deploy_job(migrations: &Migrator) -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let report = client.migrate(migrations).await?;
println!("applied {:?}, schema changes {:?}", report.applied, report.schema_changes);
for warning in &report.warnings {
eprintln!("warning: {warning}");
}
Ok(())
}
Running by hand
| call | does | returns |
migrator.apply(&client), client.migrate(&migrator) | applies pending steps, then syncs the models | MigrationReport |
migrator.verify(&client) | changes nothing; Err unless up to date | MigrationPlan |
migrator.plan(&client) | what apply would do, changing nothing | MigrationPlan |
migrator.status(&client) | where every step stands | Vec<StepStatus> |
migrator.rollback_to(&client, Some("0002_defaults")) | undoes the steps applied after the named one, newest first; None undoes all | the names undone |
rust
use rasterizeddb_client::orm::{Migrator, StepState};
use rasterizeddb_client::prelude::*;
async fn show(client: &Client, migrator: &Migrator) -> Result<()> {
for step in migrator.status(client).await? {
let when = step.applied_at.map(|t| t.to_string()).unwrap_or_default();
println!("{:<20} {:?} {when}", step.name, step.state);
if step.state == StepState::Changed {
eprintln!("{} was edited after it ran", step.name);
}
}
let plan = migrator.plan(client).await?;
if !plan.is_up_to_date() {
println!("pending: {:?}, drift: {:?}", plan.pending, plan.drift);
}
Ok(())
}
StepState | meaning |
Applied | recorded, with the checksum it has now |
Pending | not recorded yet |
Changed | applied with other statements than it has now |
Unknown | recorded in the database, absent from this code |
StepStatus has name, state and applied_at: Option<Timestamp>.
MigrationPlan field | lists |
pending | steps not yet applied |
repeatable | repeatable steps to run (new or changed) |
changed | steps edited after they ran |
unknown | recorded steps this code does not have |
out_of_order | pending steps that come before an applied one |
baseline | steps a baseline would record without running |
schema_changes | changes the model sync would make |
ensured | unique keys and indexes it would (re)create with IF NOT EXISTS |
drift | differences the sync policy does not allow it to fix |
plan.is_up_to_date() is true when there is nothing to run and nothing edited, unknown, out of order or drifted (ensured does not count).
MigrationReport field | lists |
applied | steps run by this call |
reapplied | repeatable steps run again |
baselined | steps recorded by a baseline without running |
accepted | edited steps whose new checksum was recorded (accept_changed) |
schema_changes | what the model sync changed |
ensured | keys and indexes made sure of |
warnings | drift and other things that did not stop the run |
Steps
| kind | added with | runs |
| SQL | step(name, &[statements]) | once, in the order steps were added |
| Rust | code_step(name, version, closure) | once, in order; version is its checksum: change it when the code's effect changes |
| repeatable | repeatable(name, &[statements]) | after the other steps; first when added, then again whenever its statements change |
| a model's table | create_table::<M>(name)? | once, creating the table as the struct is when the step is added |
| undo | down(&[statements]), down_code(closure) | by rollback_to, for the step added just before |
- Names identify steps. A name must be non-empty and used once per migrator. Each step is recorded by name, with a checksum of its statements, the kind and the time. Never rename or edit a step that has run; add a new one. The default record table is
rdb_client_migrations.
- One statement per string. The server runs one statement per request, so list statements separately. Before anything runs,
apply, plan, verify and rollback_to check every statement of every step and down step: a string holding a second statement, or BEGIN/COMMIT/ROLLBACK, is refused with the step's name and the statement's position.
- Steps are not transactional. Each statement commits on its own, and a step is recorded only after all its statements have run. A step that fails part-way runs again from its first statement next time. Write statements that are safe to repeat (
IF NOT EXISTS, ON CONFLICT DO NOTHING), or give each its own step.
- A code step's closure gets a
&Client and returns Box::pin(async move { … }). Use the client for every statement; it may open a transaction with c.begin() for its own work.
Scenarios
| situation | default | to allow it |
| a fresh database | every step, then every model's table is created | |
| several instances starting at once | one migrates under a lock row (in <table>_lock); the others wait, then find nothing to do | lock_timeout(Duration): how long to wait (default 60 s) |
| a process died holding the lock | the lock is taken over once older than 15 minutes | lock_stale_after(Duration) |
| an existing database adopting migrations | | baseline("0003_…"): when nothing is recorded yet, records the steps up to and including that one as applied without running them |
| a step edited after it ran | error | accept_changed(true): records the new checksum |
| an older build against a newer database (recorded steps this code lacks) | error | ignore_unknown(true) |
| a step merged from another branch, added before steps already applied | error | allow_out_of_order(true) |
| several applications in one database | | table("app2_migrations"): their own record table |
| going back | | rollback_to(&client, Some("0002_…")); every step to undo needs a down, or nothing is undone |
rust
use rasterizeddb_client::orm::Migrator;
use std::time::Duration;
fn adopt_existing() -> Migrator {
Migrator::new()
.step("0001_accounts", &["CREATE TABLE IF NOT EXISTS accounts (id BIGSERIAL, email TEXT NOT NULL, PRIMARY KEY (id))"])
.step("0002_orders", &["CREATE TABLE IF NOT EXISTS orders (id BIGSERIAL, account_id BIGINT NOT NULL, PRIMARY KEY (id))"])
.step("0003_order_index", &["CREATE INDEX IF NOT EXISTS orders_account_idx ON orders (account_id)"])
.down(&["DROP INDEX IF EXISTS orders_account_idx"])
// The live database already has 0001 and 0002.
.baseline("0002_orders")
.table("shop_migrations")
.lock_timeout(Duration::from_secs(120))
}
rollback_to also refuses, before undoing anything, when the database records steps this code does not have (they may depend on what would be undone), unless ignore_unknown(true).
Keeping tables matching their structs
For each model::<M>(), every run compares the table with the struct and acts under the SyncPolicy:
| difference | default | policy field |
| no table | created, with keys and indexes | create_tables (on) |
| a field with no column | ADD COLUMN, with its DEFAULT and REFERENCES | add_columns (on) |
#[rdb(renamed_from = "old")] on a field or the struct | RENAME COLUMN / RENAME TO, keeping the data | renames (on) |
a unique or index field without one | created | keys (on) |
| nullability that differs | reported | nullability (off): SET / DROP NOT NULL |
| a type that differs | reported | retype (off): ALTER COLUMN … TYPE |
| a column the struct does not have | reported, kept | drop_columns (off): DROP COLUMN |
| a partitioned model over a plain table | reported | convert_partitioning (off): ALTER TABLE … PARTITION BY HASH |
| a partitioned table the model does not partition, or partitioned by another key | always reported | none: the server only converts plain tables to partitioned |
fail_on_drift: true makes reported differences an error instead of a warning.
| preset | means |
SyncPolicy::default() | create, add, rename, keys |
SyncPolicy::additive() | create, add and keys; never rename, alter or drop |
SyncPolicy::exact() | everything, dropping columns included: the table becomes exactly the model. For development databases |
SyncPolicy::report_only() | no changes at all; differences are still reported |
rust
use rasterizeddb_client::orm::{Migrator, SyncPolicy};
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "accounts")]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
email: String,
// Added in this release. NOT NULL on a table with rows needs a default.
#[rdb(default = "'free'")]
plan: String,
// Was `full_name` before; renamed in place.
#[rdb(renamed_from = "full_name")]
name: Option<String>,
}
fn migrations(strict: bool) -> Migrator {
let policy = SyncPolicy { fail_on_drift: strict, ..SyncPolicy::default() };
Migrator::new().model::<Account>().sync_policy(policy)
}
- A
NOT NULL field added to a table that holds rows needs a #[rdb(default = "…")]; without one the server refuses the column and says so. Make the field an Option or give it a default.
- Partitioning. Converting a plain table is offline: the statement holds the table exclusively, so readers and writers wait while every row is copied into its partition. No preset turns it on,
exact() included; set convert_partitioning: true for the one run that should do it, at a quiet time. The number of partitions is compared at creation only.
- Foreign keys on columns that already exist are not compared. Change one with SQL in a step.
Grants, compression and shards in a sync
grants(name, &[Grant]) adds a repeatable step of GRANTs (its undo revokes them), built with the administration API's Grant.
sync_compression(bool) decides whether the sync applies a model's compression and row_compression attributes to an existing table. Unset, it follows the policy: on under default() and exact(), off (reported as drift) under additive() and report_only(). It changes how values written from then on are stored; existing rows are not rewritten.
apply_sharded runs apply on every shard of a client-side router; see Client-side sharding.
Limits
- Steps are not transactional: a step that fails part-way runs again from its start. Write repeatable statements.
- The migrator runs on a
Client, not inside a transaction.
- Steps run in the order they were added to the migrator, not sorted by name.
- Foreign keys of existing columns are not compared by the model sync.
rollback_to needs a down on every step it undoes; repeatable steps are not undone.