Skip to main content

Crate migratrom

Crate migratrom 

Source
Expand description

Declarative, self-verifying migrations for PostgreSQL and SQLite.

Most applications should use an adapter crate rather than implement Db: migratrom-sqlite for a sqlx::SqlitePool or migratrom-postgres for a sqlx::PgPool. Each adapter exposes an apply_migrations convenience function that acquires and pins one connection for the complete migration run.

§The migration model

A Migration is a node in a parent/child DAG containing ordered Operations. Construct operations with operations’ builders, then pass the complete migration list to an adapter. The runner:

  1. creates and reads its history table;
  2. verifies checksums for migrations already in that table;
  3. orders pending migrations by their parent relationship; and
  4. executes each operation as postcheck → precheck → DDL → postcheck.

A passing postcheck skips an operation, so operations are idempotent. Editing the operation body of an applied migration causes a checksum failure rather than silently changing recorded history.

§Define migrations

Build migrations with a dialect matching the database that will apply them. This example only constructs the migration; see the adapter crates for pool setup and execution.

use migratrom::operations::{add_column, create_table};
use migratrom::{ColumnDef, Migration, PrimaryKey, SqliteDialect};

let dialect = SqliteDialect;
let users = Migration::new(
    1,
    None,
    vec![create_table(
        "main",
        "users",
        &[ColumnDef::new("id", "INTEGER"), ColumnDef::new("email", "TEXT")],
        Some(&PrimaryKey { columns: vec!["id".into()] }),
        &dialect,
    )?],
);
let add_name = Migration::new(
    2,
    Some(users.id),
    vec![add_column(
        "main",
        "users",
        &ColumnDef::new("name", "TEXT").nullable(true),
        &dialect,
    )?],
);
let _: Vec<Migration> = vec![users, add_name];

§Applying safely

ApplyOptions controls the history-table name, dry runs, advisory locking, and progress logging. A dry run executes read-only checks but performs no DDL or history writes. PostgreSQL migrations acquire an advisory lock by default; SQLite does not support advisory locks. A migration normally runs in one transaction. An Operation::outside_transaction operation, such as a concurrent PostgreSQL index, divides it into transactional segments.

§Advanced integrations

Implement Db only when an application cannot use the provided sqlx adapters. Implement SqlDialect to support another database engine. Use MigrationLogger to integrate migration progress with an application’s logging system.

For supported schema changes, start with the operations cookbook. For manually authored DDL, use operations::raw_sql and supply explicit checks.

Modules§

checksum
Migration checksum API: canonical encoding, digesting, parsing, and verification.
operations
Schema-change cookbook.

Structs§

AppliedRecord
A stored history row, used to checksum-verify already-applied migrations.
ApplyOptions
Options controlling an apply run.
ApplyResult
The result of applying migrations.
Check
A boolean-returning SQL probe. Must yield one row / one column / boolean.
ColumnDef
A column definition used by create_table and add_column.
ConsoleLogger
Default logger writing info/warn to stdout and errors to stderr.
CreateIndexOptions
Options for create_index.
DialectCapabilities
What an SQL dialect can express. Builders gate on these flags.
ExecuteStep
A side-effecting DDL/DML statement.
ForeignKeyReference
The relation referenced by a foreign key.
ForeignKeySpec
A named foreign-key constraint specification.
Migration
A migration: a node in the dependency DAG carrying ordered operations.
Operation
A single, named, self-verifying unit of change.
PostgresDialect
PostgreSQL dialect: full feature set, catalog-backed existence probes, advisory locking.
PrimaryKey
A composite primary key over existing column names.
SqliteDialect
SQLite dialect: pragma/sqlite_master-backed probes, no advanced features, no advisory locks.

Enums§

MigratromError
Everything that can go wrong while planning or applying migrations.
OpOutcome
Whether an operation ran or was skipped because it was already applied.
ReferentialAction
Referential action for foreign keys.

Constants§

DEFAULT_HISTORY_TABLE
Default history table name, shared with the Swift and TypeScript siblings.

Traits§

Db
The only contract the engine has with a database.
MigrationLogger
Receives progress messages from the runner.
Row
Positional row decode for the fixed-order SELECTs used by history reads.
SqlDialect
Database-specific SQL generator used by migration builders and the runner.

Functions§

advisory_lock_key
First eight SHA-256 bytes of the history-table name as a signed, big-endian 64-bit advisory-lock key.
apply_migrations
Apply pending migrations in dependency order and record them in history.
ensure_history_table
Create the history table if it does not already exist.
plan_order
Validate the migration graph and return the unapplied migrations in order.
read_applied_ids
Read the set of already-applied migration ids.
read_applied_records
Read the full applied records keyed by id (id, checksum, operations).
record_migration
Insert a history row recording an applied migration.
run_operation
Run a single operation.
with_transaction
Run body inside a transaction, committing on success and rolling back on error.

Type Aliases§

Result
Convenient result alias used throughout the crate.