{-# LANGUAGE GHC2021 #-}{-# LANGUAGE OverloadedStrings #-}-- | The migrations of the example project, and the functions that run them.-- The monad of the migrations is in-- "Database.DagMigrations.PostgreSQL.Example.Migration". The guides-- @writing-haskell-migrations.md@ and @converting-from-dbmigrations.md@-- quote both modules verbatim, so a change to a quoted definition changes-- the guides too.module Database.DagMigrations.PostgreSQL.Example ( -- * The registry registry, -- * Running ProjectError (..), migrateProject, inspectProject, )whereimport Control.Monad (unless)import Data.Bifunctor (first)import Data.Foldable (traverse_)import Data.List (sort)import Data.List.NonEmpty (NonEmpty)import Data.Map.Strict qualified as Mapimport Data.Set qualified as Setimport Data.Text (Text)import Data.Text qualified as Textimport Database.DagMigrations ( Direction, Fingerprint (..), Inspection, Migration (..), MigrationGraph, Migrator (..), RunError, Target, ValidationError, defaultRunSettings, inspect, migrate, silentProgress, textIdentifiers, validate, )import Database.DagMigrations.PostgreSQL.Example.Migration (ProjectMigration, executeRow, failMigration, projectInterpreter, queryRows, runSql)import Database.DagMigrations.PostgreSQL.Simple (PgError, Transaction, defaultAdapterSettings, postgresAdapter)import Database.PostgreSQL.Simple (Connection, Only (..))-- | Every migration of the project.registry :: [Migration Text ProjectMigration]registry = [createViews, addViewFilters, splitViewFilters, normalizeViewNames]-- | A migration converted from a @dbmigrations@ YAML file: its identifier-- is the file's name without the extension, and its actions run the text-- of @Apply@ and @Revert@. Its fingerprint is @1@, which the first run-- records in the tracking table, so that a later change to the migration-- and its fingerprint shows up as a mismatch.createViews :: Migration Text ProjectMigrationcreateViews = Migration { migrationId = "2022-11-27_22-28-18_create-views", migrationDependencies = Set.empty, migrationDescription = "Create saved views", migrationFingerprint = Just (Fingerprint "1"), migrationUp = runSql "CREATE TABLE saved_views (name text PRIMARY KEY, definition text NOT NULL);", migrationDown = Just (runSql "DROP TABLE saved_views;") }-- | A migration that only changes the schema.addViewFilters :: Migration Text ProjectMigrationaddViewFilters = Migration { migrationId = "2026-03-08_00-00-00_add-view-filters", migrationDependencies = Set.fromList ["2022-11-27_22-28-18_create-views"], migrationDescription = "Add a filter column to saved views", migrationFingerprint = Just (Fingerprint "1"), migrationUp = runSql "ALTER TABLE saved_views ADD COLUMN filter text;", migrationDown = Just (runSql "ALTER TABLE saved_views DROP COLUMN filter;") }-- | A data migration with a frozen type: it reads each saved view's-- definition as 'SavedViewV1', and writes the filter part to the new-- column. Every definition must be of version 1; when one is not, the-- migration fails, names every such view, and changes nothing. Its-- 'migrationDown' is 'Nothing', so no run can revert it.splitViewFilters :: Migration Text ProjectMigrationsplitViewFilters = Migration { migrationId = "2026-03-09_00-00-00_split-view-filters", migrationDependencies = Set.fromList ["2026-03-08_00-00-00_add-view-filters"], migrationDescription = "Move each view's filter to its own column", migrationFingerprint = Just (Fingerprint "1"), migrationUp = do rows <- queryRows "SELECT name, definition FROM saved_views ORDER BY name" () let decoded = [(name, decodeSavedViewV1 definition) | (name, definition) <- rows] invalid = sort [name | (name, Nothing) <- decoded] unless (null invalid) $ failMigration ("saved views whose definition is not of version 1: " <> Text.intercalate ", " (map quoted invalid)) traverse_ ( \(name, view) -> executeRow "UPDATE saved_views SET definition = ?, filter = ? WHERE name = ?" (savedViewColumns view, savedViewFilter view, name) ) [(name, view) | (name, Just view) <- decoded], migrationDown = Nothing }-- | A saved view's definition as @2026-03-09_00-00-00_split-view-filters@-- reads it: the columns, a @|@, and the filter, which may be empty. The-- migration keeps this copy of the type and its decoder. So when someone-- changes the application's own type, the migration still does the same-- thing.data SavedViewV1 = SavedViewV1 { savedViewColumns :: Text, savedViewFilter :: Text }-- | Reads a definition of version 1, or returns 'Nothing' when the text-- holds no @|@.decodeSavedViewV1 :: Text -> Maybe SavedViewV1decodeSavedViewV1 definition = case Text.breakOn "|" definition of (columns, rest) | not (Text.null rest) -> Just (SavedViewV1 columns (Text.drop 1 rest)) _ -> Nothing-- | A data migration that uses the application's current code,-- 'normalizeViewName'. On a new database, @saved_views@ is empty when this-- migration runs, so the migration changes nothing there, whatever-- 'normalizeViewName' does by then. A later migration that fills-- @saved_views@ must depend on this one. When two names normalize to the-- same name, the migration fails, names them, and changes nothing. The-- renames assume that a normalized name normalizes to itself.normalizeViewNames :: Migration Text ProjectMigrationnormalizeViewNames = Migration { migrationId = "2026-03-10_00-00-00_normalize-view-names", migrationDependencies = Set.fromList ["2022-11-27_22-28-18_create-views"], migrationDescription = "Normalize the names of saved views", migrationFingerprint = Just (Fingerprint "1"), migrationUp = do names <- map fromOnly <$> queryRows "SELECT name FROM saved_views ORDER BY name" () let groups = Map.fromListWith (flip (<>)) [(normalizeViewName name, [name]) | name <- names] clashes = [sort group | group <- Map.elems groups, length group > 1] unless (null clashes) $ failMigration ("saved views whose names normalize to the same name: " <> Text.intercalate "; " (map (Text.intercalate ", " . map quoted) clashes)) traverse_ (\name -> executeRow "UPDATE saved_views SET name = ? WHERE name = ?" (normalizeViewName name, name)) [name | name <- names, normalizeViewName name /= name], migrationDown = Nothing }-- | Puts the name of a saved view in double quotes, for a message.quoted :: Text -> Textquoted name = "\"" <> name <> "\""-- | The application's current rule for the name of a saved view. The-- example defines it here; a project imports it from its application code.normalizeViewName :: Text -> TextnormalizeViewName = Text.toLower . Text.strip-- | Why a run or an inspection of the project's migrations failed.data ProjectError = -- | The registry is not valid, for these reasons. InvalidRegistry (NonEmpty (ValidationError Text)) | -- | The run or the inspection failed with this error. RunFailed (RunError Text Text PgError) deriving (Eq, Show)-- | Validates the registry, and moves the database to the target, with-- 'defaultAdapterSettings' and 'defaultRunSettings'. The connection must be-- open and idle, and no other code may use it during the run. Returns-- 'Left' when the registry is not valid or the run fails; the steps before-- a failed step stay committed. After an asynchronous exception, the-- caller closes the connection.migrateProject :: Connection -> Direction -> Target Text -> IO (Either ProjectError ())migrateProject connection direction target = case validate registry of Left errors -> pure (Left (InvalidRegistry errors)) Right graph -> first RunFailed <$> migrate (projectMigrator connection graph) direction target-- | Validates the registry, and reads the state of the database without the-- run lock. Writes nothing. The connection must be open and idle. Returns-- 'Left' when the registry is not valid or the adapter cannot read the-- tracking table.inspectProject :: Connection -> IO (Either ProjectError (Inspection Text))inspectProject connection = case validate registry of Left errors -> pure (Left (InvalidRegistry errors)) Right graph -> first RunFailed <$> inspect (projectMigrator connection graph)-- | The project's migrator over the connection, with-- 'defaultAdapterSettings' and 'defaultRunSettings'.projectMigrator :: Connection -> MigrationGraph Text ProjectMigration -> Migrator Text ProjectMigration Transaction Text PgErrorprojectMigrator connection graph = Migrator { migratorAdapter = postgresAdapter defaultAdapterSettings connection, migratorCodec = textIdentifiers, migratorInterpreter = projectInterpreter, migratorProgress = silentProgress, migratorSettings = defaultRunSettings, migratorGraph = graph }