NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RUST CLIENT / MIGRATIONS

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:

AutoMigrateconnect does
Apply (default)applies what is pending (steps, then model sync) before returning; a failure is connect's error
Verifychanges nothing, and fails if anything is pending, edited, unknown or drifted
Offnothing; 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

calldoesreturns
migrator.apply(&client), client.migrate(&migrator)applies pending steps, then syncs the modelsMigrationReport
migrator.verify(&client)changes nothing; Err unless up to dateMigrationPlan
migrator.plan(&client)what apply would do, changing nothingMigrationPlan
migrator.status(&client)where every step standsVec<StepStatus>
migrator.rollback_to(&client, Some("0002_defaults"))undoes the steps applied after the named one, newest first; None undoes allthe 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(())
}
StepStatemeaning
Appliedrecorded, with the checksum it has now
Pendingnot recorded yet
Changedapplied with other statements than it has now
Unknownrecorded in the database, absent from this code

StepStatus has name, state and applied_at: Option<Timestamp>.

MigrationPlan fieldlists
pendingsteps not yet applied
repeatablerepeatable steps to run (new or changed)
changedsteps edited after they ran
unknownrecorded steps this code does not have
out_of_orderpending steps that come before an applied one
baselinesteps a baseline would record without running
schema_changeschanges the model sync would make
ensuredunique keys and indexes it would (re)create with IF NOT EXISTS
driftdifferences 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 fieldlists
appliedsteps run by this call
reappliedrepeatable steps run again
baselinedsteps recorded by a baseline without running
acceptededited steps whose new checksum was recorded (accept_changed)
schema_changeswhat the model sync changed
ensuredkeys and indexes made sure of
warningsdrift and other things that did not stop the run

Steps

kindadded withruns
SQLstep(name, &[statements])once, in the order steps were added
Rustcode_step(name, version, closure)once, in order; version is its checksum: change it when the code's effect changes
repeatablerepeatable(name, &[statements])after the other steps; first when added, then again whenever its statements change
a model's tablecreate_table::<M>(name)?once, creating the table as the struct is when the step is added
undodown(&[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

situationdefaultto allow it
a fresh databaseevery step, then every model's table is created
several instances starting at onceone migrates under a lock row (in <table>_lock); the others wait, then find nothing to dolock_timeout(Duration): how long to wait (default 60 s)
a process died holding the lockthe lock is taken over once older than 15 minuteslock_stale_after(Duration)
an existing database adopting migrationsbaseline("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 ranerroraccept_changed(true): records the new checksum
an older build against a newer database (recorded steps this code lacks)errorignore_unknown(true)
a step merged from another branch, added before steps already appliederrorallow_out_of_order(true)
several applications in one databasetable("app2_migrations"): their own record table
going backrollback_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:

differencedefaultpolicy field
no tablecreated, with keys and indexescreate_tables (on)
a field with no columnADD COLUMN, with its DEFAULT and REFERENCESadd_columns (on)
#[rdb(renamed_from = "old")] on a field or the structRENAME COLUMN / RENAME TO, keeping the datarenames (on)
a unique or index field without onecreatedkeys (on)
nullability that differsreportednullability (off): SET / DROP NOT NULL
a type that differsreportedretype (off): ALTER COLUMN … TYPE
a column the struct does not havereported, keptdrop_columns (off): DROP COLUMN
a partitioned model over a plain tablereportedconvert_partitioning (off): ALTER TABLE … PARTITION BY HASH
a partitioned table the model does not partition, or partitioned by another keyalways reportednone: the server only converts plain tables to partitioned

fail_on_drift: true makes reported differences an error instead of a warning.

presetmeans
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.
✓ page rendered in 119 µs axum + tera + htmx · no other javascript