expression
Diesel: apply embedded migrations
A migration records a schema change under a version. embed_migrations packages migration files into the compiled executable; run_pending_migrations applies versions not already recorded. This example applies a single migration to a new disposable database and confirms the table is usable. Uses a disposable in-memory SQLite database. Expected stdout (not executed): applied: 1, then 0 Common mistake: Editing an already applied migration or assuming the macro always rebuilds when SQL files change.
Formal Syntax & Structure
rust syntaxrust
conn.run_pending_migrations(MIGRATIONS)?Working Example
Example Snippetrust
use diesel::prelude::*;use diesel::sqlite::SqliteConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut conn = SqliteConnection::establish(":memory:")?; let first = conn.run_pending_migrations(MIGRATIONS).map_err(|e| e.to_string())?.len(); let second = conn.run_pending_migrations(MIGRATIONS).map_err(|e| e.to_string())?.len(); diesel::sql_query("INSERT INTO labels (id, name) VALUES (1, 'Pen')").execute(&mut conn)?; println!("applied: {first}, then {second}"); Ok(())}