SeaQL/sea-orm

Less verbose migration

tyt2y3 opened this issue · 3 comments

https://cprimozic.net/notes/posts/trying-out-sea-orm/

I am aware that some people think that migration syntax is too verbose. Luckily the clever folks at Loco designed something better!

https://github.com/loco-rs/loco/blob/master/examples/demo/migration/src/m20220101_000001_users.rs#L11

use loco_rs::schema::*; // the magic

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let table = table_auto(Users::Table)
            .col(pk_auto(Users::Id).borrow_mut())
            .col(uuid(Users::Pid).borrow_mut())
            .col(string_uniq(Users::Email).borrow_mut())
            .col(string(Users::Password).borrow_mut())
            .col(string(Users::ApiKey).borrow_mut().unique_key())
            .col(string(Users::Name).borrow_mut())
            .col(string_null(Users::ResetToken).borrow_mut())
            .col(timestamp_null(Users::ResetSentAt).borrow_mut())
            .col(string_null(Users::EmailVerificationToken).borrow_mut())
            .col(timestamp_null(Users::EmailVerificationSentAt).borrow_mut())
            .col(timestamp_null(Users::EmailVerifiedAt).borrow_mut())
            .to_owned();
        manager.create_table(table).await?;
        Ok(())
    }
...

Reference: https://github.com/loco-rs/loco/blob/master/src/schema.rs

Umm... is it actually possible to remove the borrow_mut too? I've got an idea:

pub fn col(&mut self, column: &mut ColumnDef) -> &mut Self;

If we change column's type to IntoColumnDef which accepts both &mut and owned, we can eliminate the borrow_mut!

Done the change already. See the linked commit.

This is now on master and 1.0.0-rc.1

https://github.com/SeaQL/sea-orm/blob/master/examples/axum_example/migration/src/m20220120_000001_create_post_table.rs

use sea_orm_migration::schema::*; // where the good stuff are

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(Posts::Table)
                    .if_not_exists()
                    .col(pk_auto(Posts::Id))
                    .col(string(Posts::Title))
                    .col(string(Posts::Text))
                    .to_owned(),
            )
            .await
    }
    ..
}