Skip to content

fboulnois/migrio

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

migrio

An asynchronous database migration library for PostgreSQL.

  • sqlx is a 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.
  • tokio-postgres is an extremely fast PostgreSQL client for Rust built on tokio but it does not provide any migration functionality.

migrio combines the best of both of these crates. 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.0"
  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

About

A drop-in database migration library in Rust for PostgreSQL

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages