# Writing Haskell migrationsIn `dag-migrations`, a migration is a Haskell value. This guide is for theauthors of a project's migrations: how to define them, how to run them, andhow to keep them correct while the rest of the project's code changes.The code in this guide comes from two modules of an example project, in the`dag-migrations` repository:- `Database.DagMigrations.PostgreSQL.Example.Migration`, in [`dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example/Migration.hs`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example/Migration.hs), holds the monad of the migrations and its operations;- `Database.DagMigrations.PostgreSQL.Example`, in [`dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example.hs`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example.hs), holds the migrations and the functions that run them.The test suite of `dag-migrations-postgresql-simple` compiles both modules,and runs the migrations against PostgreSQL. Both modules enable thelanguage extensions `GHC2021` and `OverloadedStrings` with `LANGUAGE`pragmas, so a project that copies them needs no extensions of its own. Thefirst module imports:```haskellimport Control.Monad (void)import Control.Monad.Trans.Class (lift)import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)import Control.Monad.Trans.Reader (ReaderT (..), runReaderT)import Data.Text (Text)import Database.DagMigrations (Interpreter (..))import Database.DagMigrations.PostgreSQL.Simple (Transaction, executeSqlIn, transactionConnection)import Database.PostgreSQL.Simple (FromRow, Query, ToRow, execute, query)```The second module imports:```haskellimport 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 (..))```## Terms- The **registry** is the list of every migration of a project.- The **tracking table** is the table in which the adapter records the identifier of each migration that the runner has applied to the database.- An **adapter** gives the library access to one kind of database. The PostgreSQL adapter is `postgresAdapter`, from `dag-migrations-postgresql-simple`.- The **runner** is the code behind `migrate`, which applies and reverts migrations through an adapter.- The **run lock** is a lock that the adapter holds while a run lasts, so that two runs against the same database never happen at the same time. The PostgreSQL adapter uses an advisory lock.## A migrationA value of type `Migration i m` describes one migration. Its identifierhas type `i`, and its actions run in the monad `m`:```haskell-- | 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;") }```- `migrationId :: i` names the migration. No two migrations of the registry have the same identifier.- `migrationDependencies :: Set i` holds the identifiers of the migrations that the runner must apply before this one. The migrations and their dependencies form a directed acyclic graph.- `migrationDescription :: Text` is text for people to read.- `migrationFingerprint :: Maybe Fingerprint` is a value that the migration's author changes whenever the migration's effect changes. See [Fingerprints](#fingerprints).- `migrationUp :: m ()` is the action that applies the migration.- `migrationDown :: Maybe (m ())` is the action that reverts the migration, or `Nothing` when the migration cannot be reverted.For SQL that spans several lines, `dag-migrations-postgresql-simple` hasthe quasiquoter `sqlText`, in the module`Database.DagMigrations.PostgreSQL.SqlText`. A quotation`[sqlText| ... |]` holds the SQL one line to a line of the source file,without escapes, and stands for the SQL's text. The documentation of themodule describes the layout of a quotation.The example project's registry is:```haskell-- | Every migration of the project.registry :: [Migration Text ProjectMigration]registry = [createViews, addViewFilters, splitViewFilters, normalizeViewNames]````validate` takes the registry. It returns a `MigrationGraph` when theregistry is valid. Otherwise it returns every problem that it found:repeated identifiers, dependencies on identifiers that no migration has,and cycles.## The monad of the migrationsThe library does not constrain the monad in which migrations run. A projectchooses a monad that gives its migrations exactly the operations that theyneed. The example project defines the monad `ProjectMigration`, with threeoperations, `runSql`, `queryRows` and `executeRow`, and one way to fail,`failMigration`. The monad, the operation `runSql`, and `failMigration` are:```haskell-- | The monad in which the project's migrations run.newtype ProjectMigration a = ProjectMigration (ReaderT Transaction (ExceptT Text IO) a) deriving (Functor, Applicative, Monad)``````haskell-- | Runs SQL text in the migration's transaction. The text may hold several-- statements, and its last statement may be a query, whose rows 'runSql'-- discards. The text must not hold @COMMIT@, @ROLLBACK@,-- @COPY ... FROM STDIN@ or @COPY ... TO STDOUT@. When PostgreSQL rejects a-- statement, the migration fails with the adapter's error, and the adapter-- rolls back its transaction.runSql :: Text -> ProjectMigration ()runSql sql = ProjectMigration (ReaderT (lift . (`executeSqlIn` sql)))``````haskell-- | Ends the migration with this message. The adapter rolls back the-- migration's transaction, and the run reports the message in-- 'Database.DagMigrations.MigrationFailed'.failMigration :: Text -> ProjectMigration afailMigration = ProjectMigration . lift . throwE````ProjectMigration` has no `MonadIO` instance, and its module does not exportits constructor. So a migration in another module reaches the database onlythrough the three operations. The type does not stop every escape:- code that imports `Database.PostgreSQL.Simple.Internal` or `System.IO.Unsafe` can run other `IO`;- a `FromRow` instance of a row type that a migration reads can run `IO`, and so can an application function that the migration calls;- the database runs the migration's SQL with the privileges of the database role, which may include reading files on the server.A reviewer of a migration therefore checks its imports, the instances ofthe row types that it reads and writes, the application functions that itcalls, and its SQL.An author must not run `COMMIT` or `ROLLBACK` through any of the threeoperations. After such a statement, the adapter can no longer roll back themigration's changes, and some of them may stay committed without a row inthe tracking table. The PostgreSQL adapter detects this in most cases, andreports `TransactionEnded`.To give migrations another operation, a project adds a function of type`... -> ProjectMigration a` to the monad's module. A project never changeswhat an existing operation does, because every old migration uses theoperations, and a new database runs the old migrations with the operationsof the day.An `Interpreter tx m e` runs an action of the monad `m` in a transaction oftype `tx`. It returns `Left` with an error of type `e` when the actionfails, and the adapter then rolls the transaction back. The exampleproject's interpreter is:```haskell-- | Runs a 'ProjectMigration' in a transaction of the PostgreSQL adapter.projectInterpreter :: Interpreter Transaction ProjectMigration TextprojectInterpreter = Interpreter (\tx (ProjectMigration action) -> runExceptT (runReaderT action tx))```## Running migrations`migrate` takes a `Migrator`, a direction, and a target. A `Migrator` holds:- the adapter;- the identifier codec, which converts identifiers to the text values in the tracking table and back. `textIdentifiers` is the codec for `Text` identifiers;- the interpreter;- a `Progress` value, which receives an event for each thing that the runner does. `silentProgress` ignores the events;- the `RunSettings`;- the graph that `validate` returned.The example project builds its `Migrator`, and runs its migrations, withthese definitions:```haskell-- | 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 }``````haskell-- | 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)``````haskell-- | 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```The runner takes the run lock, and holds it while it takes these steps:1. It reads the applied migrations from the tracking table, through the adapter. When the table does not exist, the adapter reads no migrations. The PostgreSQL adapter also reads the table that `dbmigrations` created, without its row `root`, and with no fingerprints.2. It compares the recorded fingerprints with the registered ones, and plans the run. When the comparison or the plan fails, the run writes nothing.3. It creates the tracking table, or upgrades it to the current version.4. In one transaction, it records the registered fingerprints of applied migrations that have none recorded (see [Fingerprints](#fingerprints)).5. It runs each step of the plan in its own transaction. A step applies or reverts one migration, and records the change in the tracking table in the same transaction.The first failed step ends the run. What the run did before it stayscommitted: the table's creation or upgrade, the recorded fingerprints, andthe steps before the failed one.The runner builds the plan from the direction and the target:- `Up` with `AllMigrations` applies every registered migration that the database has not applied.- `Up` with `TargetMigration t` applies `t` and the migrations that `t` depends on, directly or indirectly. It skips each of them that the database has applied.- `Down` with `TargetMigration t` reverts every applied migration that depends on `t`, directly or indirectly. It keeps `t` applied.- `Down` with `AllMigrations` reverts every applied migration.An `Up` plan applies migrations in one fixed order: the lexicographicallyleast order, by the identifiers' `Ord` instance, in which every migrationcomes after its dependencies. A `Down` plan reverts migrations in thereverse of that order. When a `Down` plan would revert a migrationwhose `migrationDown` is `Nothing`, the runner reverts nothing. It thenreports every such migration.`inspect` reads the state of the database without the run lock, and writesnothing. Its result, an `Inspection`, has these fields:- `inspectedStatus`: each registered migration, in the order of the `Up` plans, with whether the database has applied it;- `inspectedUnregistered`: the applied identifiers that no registered migration has;- `inspectedMismatches`: the fingerprint mismatches;- `inspectedToRecord`: the fingerprints that a run would record on first use.The example project calls it in `inspectProject`:```haskell-- | 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)```## FingerprintsThe runner uses fingerprints to detect that someone changed a migrationafter the runner applied it to a database.- When the runner applies a migration, the runner records the migration's fingerprint in the tracking table.- When the tracking table holds no fingerprint for an applied migration, and the migration's registered fingerprint is `Just f`, the runner records `f`. The same rule covers a migration that the runner applied before the migration had a fingerprint.- When the tracking table holds a fingerprint for an applied migration, and the migration's registered fingerprint differs or is `Nothing`, the run fails and writes nothing. Failing is the default policy, `MismatchIsError`. Under `MismatchIsWarning`, the runner reports the mismatch through the `Progress` value, and continues; with `silentProgress`, nobody sees the report. The field `runFingerprintPolicy` of `RunSettings` holds the policy.- When neither the tracking table nor the registry holds a fingerprint for a migration, the runner compares nothing.- After a person checks that a changed migration is still correct for the databases that applied it, `acceptFingerprints` records the registered fingerprints of the migrations that the person names.When an author changes what a migration does, the author changes itsfingerprint too. A migration converted from `dbmigrations` has thefingerprint `1`, which the first run records in each database. A projectmust not edit those migrations, because `dbmigrations` applied them to theproject's databases in their current form. If someone edits one and changesits fingerprint, each run fails with `FingerprintsMismatched` on everydatabase that has recorded `1`. A database on which no run has recorded `1` yet records thenew fingerprint without a report; the guide[Converting from `dbmigrations`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/docs/converting-from-dbmigrations.md)has the procedure that records `1` everywhere.## Migrations and code that changesA migration must give an acceptable result whatever later changes theproject makes to the code that it calls.When someone creates a new database, the runner applies every migration toit. The actions of each migration then call the application's code as thatcode exists at that time, not as it was when someone wrote the migration.So a migration whose actions call application code meets the rule in oneof two ways.The same holds for code outside the application. A project never changeswhat an existing operation of its migration monad does. A frozen type hasan encoder and a decoder that its migration writes by hand, not instancesthat a library derives, because a new release of the library can change aderived instance.### Frozen typesThe migration keeps its own copy of every application type and functionthat it uses. This migration reads each saved view's definition with itsown type, `SavedViewV1`:```haskell-- | 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 }``````haskell-- | 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 }``````haskell-- | 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```When the application's own type for a saved view changes, this migrationstill reads definitions of version 1, because the migration does not referto the application's type.### Current code on an empty tableThe migration changes existing rows with the application's current code.On a new database, the table is empty when the migration runs, as long asevery other migration that fills the table depends on this one, directly orindirectly. The migration then changes nothing there. Here,`normalizeViewName` stands for application code, and `quoted` only shapesthe error message. Before it renames any view, the migration checks that notwo names normalize to the same name, so that it fails with a message thatnames the views, not with the primary key's error. The renames assume thata normalized name normalizes to itself:```haskell-- | 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 }```When someone changes the type of `normalizeViewName`, this migration stopscompiling. Its author then copies the code that the migration uses, as inthe first pattern, or updates the migration. The compiler reports a changeof type, but cannot report a change of behavior. A database that has rowsin the table, and has not yet applied the migration, gets the currentbehavior of `normalizeViewName`. Use this pattern only when the currentbehavior is acceptable for such a database.A migration that uses application code to create or fill rows, even on anempty database, needs the first pattern.