2.2 KiB · text History 1ce9641
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(ApiTokens::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(ApiTokens::Id).big_integer().not_null().auto_increment().primary_key())
                    .col(ColumnDef::new(ApiTokens::UserId).big_integer().not_null())
                    .col(ColumnDef::new(ApiTokens::Token).string_len(128).not_null().unique_key())
                    .col(ColumnDef::new(ApiTokens::Label).string_len(255).null())
                    .col(ColumnDef::new(ApiTokens::LastUsedAt).timestamp_with_time_zone().null())
                    .col(ColumnDef::new(ApiTokens::ExpiresAt).timestamp_with_time_zone().null())
                    .col(ColumnDef::new(ApiTokens::CreatedAt).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_api_tokens_user_id")
                            .from(ApiTokens::Table, ApiTokens::UserId)
                            .to(Alias::new("users"), Alias::new("id"))
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await?;
        manager
            .create_index(
                Index::create()
                    .name("idx_api_tokens_user_id")
                    .table(ApiTokens::Table)
                    .col(ApiTokens::UserId)
                    .to_owned(),
            )
            .await?;
        Ok(())
    }

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

#[derive(DeriveIden)]
enum ApiTokens {
    Table,
    Id,
    UserId,
    Token,
    Label,
    LastUsedAt,
    ExpiresAt,
    CreatedAt,
}