Migrations

model! macro, makemigrations, migration up.

● ● ●
use runique::prelude::*;

model! {
    Article,
    table: "article",
    pk: id => Pk,
    {
        title:      text     [max_length: 255, required],
        content:    text     [required],
        author_id:  Pk       [required],
        published:  bool     [default: false],
    },
    relations: {
        belongs_to: eihwaz_users via author_id [cascade],
    }
}

// A column is NOT NULL unless declared `nullable`;
// `required` only makes the form field mandatory.
# Generate migration files from the entities
runique makemigrations

# Destructive changes (dropped column, shorter length...) need --force
runique makemigrations --force

# Apply all pending migrations
runique migration up

# Roll back the last migration / view the state (SeaORM)
sea-orm-cli migrate down -n 1
sea-orm-cli migrate status
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(Alias::new("article"))
                    .if_not_exists()
                    .col(ColumnDef::new(Alias::new("id")).integer().not_null()
                        .auto_increment().primary_key())
                    .col(ColumnDef::new(Alias::new("title")).string_len(255).not_null())
                    .col(ColumnDef::new(Alias::new("content")).string().not_null())
                    .col(ColumnDef::new(Alias::new("author_id")).integer().not_null())
                    .col(ColumnDef::new(Alias::new("published")).boolean().not_null()
                        .default(false))
                    .foreign_key(
                        ForeignKey::create()
                            .name("article_author_id_eihwaz_users_fkey")
                            .from(Alias::new("article"), Alias::new("author_id"))
                            .to(Alias::new("eihwaz_users"), Alias::new("id"))
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::NoAction),
                    )
                    .to_owned(),
            )
            .await?;
        // every belongs_to column gets its index
        manager
            .create_index(
                Index::create()
                    .name("idx_article_author_id")
                    .table(Alias::new("article"))
                    .col(Alias::new("author_id"))
                    .to_owned(),
            )
            .await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(Alias::new("article")).to_owned()).await
    }
}