Skip to main content

Crate migrio

Crate migrio 

Source
Expand description

§migrio

An asynchronous database migration library for PostgreSQL.

migrio combines the best of the sqlx and tokio-postgres crates. sqlx is a fully featured library for working with databases in Rust and provides a fantastic migration feature which is simple and easy to use. However, it also depends on a lot of crates and is not specifically focused on performance. On the other hand, tokio-postgres is an extremely fast PostgreSQL client for Rust built on tokio but it does not provide any migration functionality.

By only focusing on migrations, migrio is able to provide a simple way to apply and roll back migrations in your database. It provides a nearly drop-in replacement for the migration functionality of sqlx, but is built on top of tokio-postgres to minimize dependencies.

§Usage

  1. Create a migration directory with SQL files. Each file should be named with a version number and a description, for example:
migrations/
  ├── 0001_initial.sql
  ├── 0002_add_column.sql
  ├── 0003_add_table.up.sql
  └── 0003_add_table.down.sql
  1. Add migrio to your Cargo.toml:
[dependencies]
migrio = "1.1"
  1. Run the migration from your code:
use migrio::Migration;

// let (mut client, connection) = tokio_postgres::connect(...).await?;
// ...

let migration = Migration::new("migrations")?;
migration.run(&mut client).await?;

§API

The API and functionality of migrio is nearly identical to sqlx:

// type alias of migrio::Migration
use migrio::Migrator;

// create a new migration from the `migration_dir` directory
let migration = Migrator::new(migration_dir)?;

// run all migrations
migration.run(&mut client).await?;

// roll back migrations up to a specific version
migration.undo(&mut client, version).await?;

migrio sorts the migrations by version number and applies them in order. If a migration fails, the entire migration is rolled back. Migrations use the following naming scheme for files:

{VERSION}_{DESCRIPTION}.sql
{VERSION}_{DESCRIPTION}.up.sql
{VERSION}_{DESCRIPTION}.down.sql

{VERSION} is a number that represents the order in which the migrations should be applied. {DESCRIPTION} is a human-readable description of the migration. migrio also supports optional reversible up and down migrations. When using reversible migrations, each up migration should be paired with a corresponding down migration. The down migrations are applied in reverse order when undoing a migration.

§Development

§Building

To build the library:

cargo build

§Testing

To run unit tests:

cargo test

To also run integration tests against a PostgreSQL database:

docker compose -f tests/docker-compose.test.yml up -d
cargo test -- --include-ignored

Structs§

Migration
Migration object to handle the migration process

Enums§

MigrationError
Error handling for migrations

Type Aliases§

Migrator
Alias for compatibility with sqlx