|
| 1 | +use sea_orm_migration::{prelude::*, MigrationName}; |
| 2 | + |
| 3 | +use entity::file::Entity; |
| 4 | + |
| 5 | +use crate::utils::macros::{create_table_from_entity, exec_stmt}; |
| 6 | + |
| 7 | +pub struct Migration; |
| 8 | + |
| 9 | +impl MigrationName for Migration { |
| 10 | + fn name(&self) -> &str { |
| 11 | + "m20221103_000015_create_files_table" |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +#[async_trait::async_trait] |
| 16 | +impl MigrationTrait for Migration { |
| 17 | + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { |
| 18 | + exec_stmt!(manager, r#"drop table if exists files"#)?; |
| 19 | + create_table_from_entity!(manager, Entity)?; |
| 20 | + |
| 21 | + // Set default value for created_at / updated_at columns and adds constraint |
| 22 | + exec_stmt!( |
| 23 | + manager, |
| 24 | + r#"alter table files |
| 25 | + alter column created_at set default now(), |
| 26 | + alter column updated_at set default now(), |
| 27 | + add constraint files_storage_key_unique unique (storage_key), |
| 28 | + alter column tags type text[], |
| 29 | + alter column tags set default '{{}}'::text[], |
| 30 | + alter column metadata type jsonb, |
| 31 | + alter column metadata set default '{{}}'::jsonb, |
| 32 | + drop constraint if exists "fk-files-namespace", |
| 33 | + add constraint "fk-files-namespace" |
| 34 | + foreign key (namespace) |
| 35 | + references namespaces (name) |
| 36 | + on update cascade |
| 37 | + on delete cascade |
| 38 | + "# |
| 39 | + )?; |
| 40 | + exec_stmt!(manager, r#"create index tags_idx on files (tags)"#)?; |
| 41 | + exec_stmt!(manager, r#"create index metadata_idx on files (metadata)"#)?; |
| 42 | + |
| 43 | + // Trigger for timestamps |
| 44 | + exec_stmt!( |
| 45 | + manager, |
| 46 | + r#"create trigger _100_timestamps |
| 47 | + before insert or update on files |
| 48 | + for each row execute procedure tg__timestamps(); |
| 49 | + "# |
| 50 | + )?; |
| 51 | + exec_stmt!( |
| 52 | + manager, |
| 53 | + r#"create trigger _500_create_missing_namespace |
| 54 | + before insert or update on files |
| 55 | + for each row execute procedure public.tg__create_missing_namespace(); |
| 56 | + "# |
| 57 | + )?; |
| 58 | + |
| 59 | + Ok(()) |
| 60 | + } |
| 61 | + |
| 62 | + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { |
| 63 | + manager |
| 64 | + .drop_table(Table::drop().table(Entity).to_owned()) |
| 65 | + .await?; |
| 66 | + Ok(()) |
| 67 | + } |
| 68 | +} |
0 commit comments