diff --git a/models b/models index 8d67f95cd..14f3ac424 100644 --- a/models +++ b/models @@ -52,7 +52,7 @@ School json name (CI Text) shorthand (CI Text) UniqueSchool name - UniqueSchoolShorthand shorthand + UniqueSchoolShorthand shorthand -- required for Normalisation of CI Text Primary shorthand -- newtype Key School = School { unSchoolKey :: SchoolShorthand } deriving Eq DegreeCourse json diff --git a/src/Model/Migration.hs b/src/Model/Migration.hs index 368b4b2cf..d5f10dfcb 100644 --- a/src/Model/Migration.hs +++ b/src/Model/Migration.hs @@ -23,6 +23,7 @@ import qualified Data.Set as Set import Database.Persist.Sql import Database.Persist.Postgresql +import Data.CaseInsensitive (CI) -- Database versions must follow https://pvp.haskell.org: -- - Breaking changes are instances where manual migration is necessary (via customMigrations; i.e. changing a columns format) @@ -92,6 +93,7 @@ customMigrations = Map.fromListWith (>>) ) , ( AppliedMigrationKey [migrationVersion|0.0.0|] [version|1.0.0|] , do -- Better JSON encoding + haveSheetTable <- [sqlQQ| SELECT to_regclass('sheet'); |] case haveSheetTable :: [Maybe (Single Text)] of @@ -102,4 +104,32 @@ customMigrations = Map.fromListWith (>>) |] _other -> return () ) + , ( AppliedMigrationKey [migrationVersion|1.0.0|] [version|2.0.0|] + , do -- SchoolId is the Shorthand CI Text now + {- + Confusion about quotes, from the SQL Manual: + Single quotes for string constants, double quotes for table/column names. + + QuasiQuoter: ^{TableName} @{ColumnName} (includes Escaping); + #{anything} (no escaping); + -} + -- Read old table into memory + -- schoolTable :: [(Single Int64, Single Text)] + schoolTable <- [sqlQQ| SELECT "id", "shorthand" FROM "school"; |] + let _sT = schoolTable :: [(Single Int64, Single (CI Text))] + -- Convert columns containing SchoolId + [executeQQ| + ALTER TABLE "user_admin" ALTER COLUMN "school" TYPE citext; + ALTER TABLE "user_lecturer" ALTER COLUMN "school" TYPE citext; + ALTER TABLE "course" ALTER COLUMN "school" TYPE citext; + |] + -- Convert Number-Strings to Shorthands + forM_ schoolTable (\(Single idnr, Single ssh) -> + [executeQQ| + UPDATE "user_admin" SET "school" = '#{ssh}' WHERE "school" = '#{idnr}'; + UPDATE "user_lecturer" SET "school" = '#{ssh}' WHERE "school" = '#{idnr}'; + UPDATE "user_course" SET "school" = '#{ssh}' WHERE "school" = '#{idnr}'; + |] + ) + ) ]