2542369203329244998d44d82a21038b435a547b / migration / src / m20261030_000016_create_invites_table.rs
Raw
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> {
// Create the invites table
manager
.create_table(
Table::create()
.table(Invites::Table)
.if_not_exists()
.col(
ColumnDef::new(Invites::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(Invites::Uuid)
.string_len(36)
.not_null()
.unique_key(),
)
.col(ColumnDef::new(Invites::CreatedBy).integer().not_null())
.col(
ColumnDef::new(Invites::CreatedAt)
.timestamp_with_time_zone()
.default(Expr::current_timestamp())
.not_null(),
)
.col(
ColumnDef::new(Invites::ExpiresAt)
.timestamp_with_time_zone()
.not_null(),
)
.col(ColumnDef::new(Invites::UsedBy).integer().null())
.col(
ColumnDef::new(Invites::UsedAt)
.timestamp_with_time_zone()
.null(),
)
.foreign_key(
ForeignKey::create()
.name("fk_invites_created_by")
.from(Invites::Table, Invites::CreatedBy)
.to(Users::Table, Users::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_invites_used_by")
.from(Invites::Table, Invites::UsedBy)
.to(Users::Table, Users::Id)
.on_delete(ForeignKeyAction::SetNull),
)
.to_owned(),
)
.await?;
// Add invited_by column to users table (without FK constraint - SQLite limitation)
manager
.alter_table(
Table::alter()
.table(Users::Table)
.add_column(ColumnDef::new(Users::InvitedBy).integer().null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
// Drop the column from users
manager
.alter_table(
Table::alter()
.table(Users::Table)
.drop_column(Users::InvitedBy)
.to_owned(),
)
.await?;
// Drop the invites table
manager
.drop_table(Table::drop().table(Invites::Table).to_owned())
.await
}
}
/// The invites table, as this migration knows it.
#[derive(Iden)]
pub enum Invites {
Table,
Id,
Uuid,
CreatedBy,
CreatedAt,
ExpiresAt,
UsedBy,
UsedAt,
}
/// The users table, for the foreign key.
#[derive(Iden)]
pub enum Users {
Table,
Id,
InvitedBy,
}