tfiala-mongodb-migrator

Crates.iotfiala-mongodb-migrator
lib.rstfiala-mongodb-migrator
version0.2.6
sourcesrc
created_at2025-05-06 02:02:59.612911+00
updated_at2025-05-08 13:18:14.491678+00
descriptionMongoDB migrations management tool (fork of kakoc/mongodb_migrator with all deps updated)
homepage
repositoryhttps://github.com/tfiala/tfiala-mongodb-migrator
max_upload_size
id1661803
size155,338
Todd Fiala (tfiala)

documentation

README

github crates.io docs.rs build status codecov.io

Mongodb migrations management tool.

NOTE: this is a fork of mongodb_migrator

This is a (hopefully temporary) fork of the excellent work done by the Konstantin Matsiushonak (k.matushonok@gmail.com) at kakoc/mongodb_migrator.

The primary changes:

  • updated all dependencies to latest, notably the mongodb driver (2.x -> 3.x)
  • updated Rust version 2024

Expect this fork to go away once the dependency updates are integrated into the authoritative repo.

Setup

[dependencies]
tfiala-mongodb-migrator = "0.2.6"

Functionality

How to use

use anyhow::Result;
use async_trait::async_trait;
use mongodb::Database;
use serde_derive::{Deserialize, Serialize};
use testcontainers_modules::{
    mongo::Mongo,
    testcontainers::{runners::AsyncRunner, ContainerAsync},
};

use tfiala_mongodb_migrator::{
    migration::Migration,
    migrator::{
        default::DefaultMigrator,
        env::Env,
    },
};

#[tokio::main]
async fn main() -> Result<()> {
    let node = Mongo::default().start().await.unwrap();
    let host_port = node.get_host_port_ipv4(27017).await.unwrap();
    let url = format!("mongodb://localhost:{}/", host_port);
    let client = mongodb::Client::with_uri_str(url).await.unwrap();
    let db = client.database("test");

    let migrations: Vec<Box<dyn Migration>> = vec![Box::new(M0 {}), Box::new(M1 {})];
    DefaultMigrator::new()
        .with_conn(db.clone())
        .with_migrations_vec(migrations)
        .up()
        .await?;

    Ok(())
}

struct M0 {}
struct M1 {}

#[async_trait]
impl Migration for M0 {
    async fn up(&self, env: Env) -> Result<()> {
        let db = env.db().await?;
        db.collection("users")
            .insert_one(bson::doc! { "name": "Batman" })
            .await?;

        Ok(())
    }
}

#[async_trait]
impl Migration for M1 {
    async fn up(&self, env: Env) -> Result<()> {
        let db = env.db().await?;
        db.collection::<Users>("users")
            .update_one(
                bson::doc! { "name": "Batman" },
                bson::doc! { "$set": { "name": "Superman" } },
            )
            .await?;

        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
struct Users {
    name: String,
}

Roadmap

  • Rust based migrations
  • JavaScript based migrations
  • Logging
  • Rollbacks
  • Cli tool
  • UI dashboard
  • RESTful service
  • As npm package
  • Stragegies
    • Fail first
    • Try all
    • Retries
Commit count: 0

cargo fmt