expression

SeaORM: migration up and down

A migration describes an ordered change to schema. The migrator tracks applied changes. This fixture creates an empty tags table, runs up again to check the applied ledger, then reverts one migration. Down drops the table and would destroy its contents; use only the disposable database here. Production changes need a separately reviewed rollout and recovery plan. Uses a disposable in-memory SQLite database. Expected stdout (not executed): up: table exists down: table absent Common mistake: Running destructive down migrations on a live database merely to test them.

Formal Syntax & Structure

rust syntaxrust
Migrator::up(&db, None).await?; Migrator::down(&db, Some(1)).await?;

Working Example

Example Snippetrust
use sea_orm::{ActiveModelTrait, ConnectOptions, ConnectionTrait, Database,    DatabaseConnection, DbBackend, DbErr, EntityTrait, LoaderTrait, ModelTrait,    PaginatorTrait, QueryOrder, Set, Statement, TransactionTrait};
mod shelf {    use sea_orm::entity::prelude::*;    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]    #[sea_orm(table_name = "shelves")]    pub struct Model {        #[sea_orm(primary_key)]        pub id: i32,        pub label: String,    }    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]    pub enum Relation {        #[sea_orm(has_many = "super::book::Entity")]        Book,    }    impl Related<super::book::Entity> for Entity {        fn to() -> RelationDef { Relation::Book.def() }    }    impl ActiveModelBehavior for ActiveModel {}}mod book {    use sea_orm::entity::prelude::*;    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]    #[sea_orm(table_name = "books")]    pub struct Model {        #[sea_orm(primary_key)]        pub id: i32,        pub shelf_id: i32,        pub title: String,    }    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]    pub enum Relation {        #[sea_orm(belongs_to = "super::shelf::Entity", from = "Column::ShelfId",                  to = "super::shelf::Column::Id")]        Shelf,    }    impl Related<super::shelf::Entity> for Entity {        fn to() -> RelationDef { Relation::Shelf.def() }    }    impl ActiveModelBehavior for ActiveModel {}}async fn empty_db() -> Result<DatabaseConnection, DbErr> {    let mut opt = ConnectOptions::new("sqlite::memory:");    opt.max_connections(1).min_connections(1).sqlx_logging(false);    Database::connect(opt).await}async fn sample_db() -> Result<DatabaseConnection, DbErr> {    let db = empty_db().await?;    for sql in [        "PRAGMA foreign_keys = ON",        "CREATE TABLE shelves (id INTEGER PRIMARY KEY, label TEXT NOT NULL)",        "CREATE TABLE books (id INTEGER PRIMARY KEY, shelf_id INTEGER NOT NULL REFERENCES shelves(id), title TEXT NOT NULL)",        "INSERT INTO shelves VALUES (1, 'Science'), (2, 'Art')",        "INSERT INTO books VALUES (1, 1, 'Stars'), (2, 1, 'Plants')",    ] {        db.execute(Statement::from_string(DbBackend::Sqlite, sql.to_owned())).await?;    }    Ok(db)}#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), DbErr> {    mod migrations {        use sea_orm_migration::prelude::*;        mod m20261127_000001_tags {            use super::*;            #[derive(DeriveMigrationName)]            pub struct Migration;            #[async_trait]            impl MigrationTrait for Migration {                async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {                    manager.create_table(Table::create().table(Alias::new("tags"))                        .col(ColumnDef::new(Alias::new("id")).integer().not_null().primary_key())                        .to_owned()).await                }                async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {                    manager.drop_table(Table::drop().table(Alias::new("tags")).to_owned()).await                }            }        }        pub struct Migrator;        #[async_trait]        impl MigratorTrait for Migrator {            fn migrations() -> Vec<Box<dyn MigrationTrait>> {                vec![Box::new(m20261127_000001_tags::Migration)]            }        }    }    use migrations::Migrator;    use sea_orm_migration::{MigratorTrait, SchemaManager};    let db = empty_db().await?;    Migrator::up(&db, None).await?;    Migrator::up(&db, None).await?;    let manager = SchemaManager::new(&db);    assert!(manager.has_table("tags").await?);    println!("up: table exists");    Migrator::down(&db, Some(1)).await?;    assert!(!manager.has_table("tags").await?);    println!("down: table absent");    Ok(())}
Rust Reference