|
| 1 | +use sea_orm_migration::prelude::*; |
| 2 | +use sea_orm_migration::sea_orm::ConnectionTrait; |
| 3 | + |
| 4 | +/// Convert the moderation timestamp columns from `timestamp without time zone` |
| 5 | +/// (naive) to `timestamptz`, so stored instants are unambiguous UTC and can't |
| 6 | +/// be reinterpreted in a reader's local timezone (issue #102). |
| 7 | +/// |
| 8 | +/// Each conversion is guarded on the column's current type so it is a no-op on |
| 9 | +/// a fresh database (where the entity-derived `created_*` tables are already |
| 10 | +/// `timestamptz`) and only rewrites legacy naive columns on existing |
| 11 | +/// deployments. Existing naive values are stamped as UTC via `AT TIME ZONE |
| 12 | +/// 'UTC'` rather than relying on the session timezone. |
| 13 | +#[derive(DeriveMigrationName)] |
| 14 | +pub struct Migration; |
| 15 | + |
| 16 | +const COLUMNS: &[(&str, &str)] = &[ |
| 17 | + ("processed_content", "created_at"), |
| 18 | + ("processed_content", "updated_at"), |
| 19 | + ("created_content", "created_at"), |
| 20 | + ("created_event", "created_at"), |
| 21 | +]; |
| 22 | + |
| 23 | +#[async_trait::async_trait] |
| 24 | +impl MigrationTrait for Migration { |
| 25 | + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { |
| 26 | + let conn = manager.get_connection(); |
| 27 | + for (table, column) in COLUMNS { |
| 28 | + conn.execute_unprepared(&format!( |
| 29 | + r#"DO $$ |
| 30 | +BEGIN |
| 31 | + IF EXISTS ( |
| 32 | + SELECT 1 FROM information_schema.columns |
| 33 | + WHERE table_name = '{table}' AND column_name = '{column}' |
| 34 | + AND table_schema = current_schema() |
| 35 | + AND data_type = 'timestamp without time zone' |
| 36 | + ) THEN |
| 37 | + ALTER TABLE "{table}" |
| 38 | + ALTER COLUMN "{column}" TYPE timestamptz USING "{column}" AT TIME ZONE 'UTC'; |
| 39 | + END IF; |
| 40 | +END $$;"# |
| 41 | + )) |
| 42 | + .await?; |
| 43 | + } |
| 44 | + Ok(()) |
| 45 | + } |
| 46 | + |
| 47 | + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { |
| 48 | + let conn = manager.get_connection(); |
| 49 | + for (table, column) in COLUMNS { |
| 50 | + conn.execute_unprepared(&format!( |
| 51 | + r#"DO $$ |
| 52 | +BEGIN |
| 53 | + IF EXISTS ( |
| 54 | + SELECT 1 FROM information_schema.columns |
| 55 | + WHERE table_name = '{table}' AND column_name = '{column}' |
| 56 | + AND table_schema = current_schema() |
| 57 | + AND data_type = 'timestamp with time zone' |
| 58 | + ) THEN |
| 59 | + ALTER TABLE "{table}" |
| 60 | + ALTER COLUMN "{column}" TYPE timestamp USING "{column}" AT TIME ZONE 'UTC'; |
| 61 | + END IF; |
| 62 | +END $$;"# |
| 63 | + )) |
| 64 | + .await?; |
| 65 | + } |
| 66 | + Ok(()) |
| 67 | + } |
| 68 | +} |
0 commit comments