Macro migrations_macros::embed_migrations

source ·
embed_migrations!() { /* proc-macro */ }
Expand description

This macro will read your migrations at compile time, and create a constant value containing an embedded list of all your migrations as available at compile time. This is useful if you would like to use Diesel’s migration infrastructure, but want to ship a single executable file (such as for embedded applications). It can also be used to apply migrations to an in memory database (Diesel does this for its own test suite).

You can optionally pass the path to the migrations directory to this macro. When left unspecified, Diesel will search for the migrations directory in the same way that Diesel CLI does. If specified, the path should be relative to the directory where Cargo.toml resides.

§Examples

use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../../migrations/postgresql");


fn run_migrations(connection: &mut impl MigrationHarness<DB>) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {

    // This will run the necessary migrations.
    //
    // See the documentation for `MigrationHarness` for
    // all available methods.
    connection.run_pending_migrations(MIGRATIONS)?;

    Ok(())
}

§Automatic rebuilds

Due to limitations in rusts proc-macro API there is currently no way to signal that a specific proc macro should be rerun if some external file changes/is added. This implies that embed_migrations! cannot regenerate the list of embedded migrations if only the migrations are changed. This limitation can be solved by adding a custom build.rs file to your crate, such that the crate is rebuild if the migration directory changes.

Add the following build.rs file to your project to fix the problem

fn main() {
   println!("cargo:rerun-if-changed=path/to/your/migration/dir/relative/to/your/Cargo.toml");
}