packages feed

dag-migrations-postgresql-simple-0.1.0.0 / docs / converting-from-dbmigrations.md

# Converting from `dbmigrations`[`dbmigrations`](https://hackage.haskell.org/package/dbmigrations) keeps aproject's migrations as YAML files. It records the migrations that it hasapplied to a database in the table `installed_migrations`, the trackingtable. This guide converts the YAML files into `dag-migrations` values, andreplaces `dbmigrations` with the PostgreSQL adapter of`dag-migrations-postgresql-simple`. Each database keeps its tracking table,which the adapter upgrades, so every migration that `dbmigrations` appliedstays applied.An AI coding agent follows the steps in order; a person can follow themtoo. When a step says to stop and ask, the agent asks the project's owner,and goes on only after the owner answers. When a command of this guidefails, the agent stops and asks. The agent does not change a productiondatabase; the owner does, in step 7.The guide uses terms that are defined in the guide[Writing Haskell migrations](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations/docs/writing-haskell-migrations.md):the registry, the runner, the run lock, and the project's migration monad.That guide's example project, in the modules[`Database.DagMigrations.PostgreSQL.Example.Migration`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example/Migration.hs)and[`Database.DagMigrations.PostgreSQL.Example`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example.hs),is the model for the code that the agent adds in steps 1 and 3.## Before you startStop and ask when one of these conditions does not hold:- The project's databases are PostgreSQL databases, of version 9.6 or  later. The adapter's tests run on PostgreSQL 13 and later; on an older  server, tell the owner that the adapter is untested there.- The project keeps all its migrations in one directory, the directory that  it gives `dbmigrations` in `DBM_MIGRATION_STORE`, either in the  environment or in a `dbm.cfg` file. `dbmigrations` reads every file in  that directory whose name ends in `.yml` or `.txt` as a migration, and  ignores every other file.- The tracking table of each database is `installed_migrations`, and the  role that will run the migrations owns it. The upgrade alters the table,  which PostgreSQL allows only to its owner. Ask the owner for the result  of `SELECT tableowner FROM pg_tables WHERE tablename = 'installed_migrations'`  on each production database.- It is clear which package of the project holds the migrations, and where  the project runs `dbm-postgresql` or `moo-postgresql`: at the start of the  application, in a deployment script, or by hand.Do the work on a new branch, and ask the owner not to merge it beforestep 7.The agent needs these programs: `cabal`, with a package index (run`cabal update` when it has none), `pg_dump`, `psql`, and `dbm-postgresql`(`dbmigrations` 3.0) or `moo-postgresql` (earlier releases). It also needs aPostgreSQL server on which it may create databases. Below, `HOST` standsfor that server's connection string in libpq's `key=value` form, without`dbname`, such as `host=localhost user=postgres`.## Step 1: give the project a migration monadAdd `dag-migrations`, `dag-migrations-postgresql-simple`,`postgresql-simple`, `transformers`, `containers` and `text` to the`build-depends` of the package that holds the migrations.The project needs a monad for its migrations, with an operation`runSql :: Text -> M ()` that runs SQL text in the migration's transaction,where `M` is the monad. Copy the module`Database.DagMigrations.PostgreSQL.Example.Migration` whole. Rename themodule and the monad to fit the project, and replace the module's headercomment, which describes the example. Its `runSql` calls `executeSqlIn`from `Database.DagMigrations.PostgreSQL.Simple`. `executeSqlIn` runs textthat holds several statements, and text that ends in a query. It discardsthe query's rows. When the project already has a migration monad, stop andask instead.## Step 2: generate the migration modulesDo not write the converted migrations by hand. Save this program as`ConvertMigrations.hs` in a new, empty directory outside the project:```haskell{- cabal:build-depends: aeson >= 2.0, base, containers, directory, filepath, text, yaml-}{-# LANGUAGE OverloadedStrings #-}-- | Writes Haskell modules that hold the migrations of a directory of-- dbmigrations YAML files, as dag-migrations values: one module for each-- migration, and one module that lists them.---- Usage: cabal run -v0 ConvertMigrations.hs -- DIRECTORY OUTPUT PREFIX MONAD_MODULE MONAD---- DIRECTORY holds the YAML files. OUTPUT is a directory that does not exist-- yet. The program creates it, and writes each module into it, at the path-- that GHC expects under a source directory. PREFIX is the start of the name-- of each module. The module of the migration with the identifier ID is-- PREFIX.M followed by ID, with each '-' replaced by '_'. The module-- PREFIX.Registry exports registry, the list of every migration.-- MONAD_MODULE is the module that exports the project's migration monad,-- named MONAD, and its operation runSql :: Text -> MONAD ().---- The program writes the modules in UTF-8, and prints the name of each-- module that it wrote, one to a line. When a file cannot be converted, the-- directory holds no migration file, or OUTPUT exists, the program writes-- every problem to standard error, writes no module, and exits with status-- 1.module Main (main) whereimport Control.Monad (filterM, unless, when)import Data.Aeson ((.:), (.:?))import qualified Data.Aeson as Aesonimport qualified Data.Aeson.Key as Keyimport qualified Data.Aeson.KeyMap as KeyMapimport qualified Data.Aeson.Types as Aesonimport Data.Char (isAlphaNum, isAscii, toLower)import Data.Either (partitionEithers)import Data.List (intercalate, sort, sortOn)import qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe, maybeToList)import Data.Text (Text)import qualified Data.Text as Textimport qualified Data.Yaml as Yamlimport System.Directory (createDirectoryIfMissing, doesFileExist, doesPathExist, listDirectory)import System.Environment (getArgs)import System.Exit (exitFailure)import System.FilePath (joinPath, splitExtension, takeDirectory, takeExtension, (<.>), (</>))import System.IO (IOMode (WriteMode), hPutStr, hPutStrLn, hSetEncoding, stderr, utf8, withFile)-- | One migration, as its YAML file gives it.data Converted = Converted  { convertedId :: Text,    convertedDepends :: [Text],    convertedDescription :: Text,    convertedApply :: Text,    convertedRevert :: Maybe Text  }main :: IO ()main = do  arguments <- getArgs  case arguments of    [directory, output, prefix, monadModule, monad] -> do      entries <- sort <$> listDirectory directory      names <- filterM (doesFileExist . (directory </>)) entries      outputExists <- doesPathExist output      let files =            [ (stem, directory </> name)            | name <- names,              let (stem, extension) = splitExtension name,              extension `elem` [".yml", ".txt"]            ]          repeated =            Map.keys (Map.filter (> (1 :: Int)) (Map.fromListWith (+) [(stem, 1) | (stem, _) <- files]))          dotted = [path | (stem, path) <- files, not (null (takeExtension stem))]      results <- traverse (uncurry convert) files      let (problems, migrations) = partitionEithers results          named = sortOn (convertedId . snd) [(component, m) | m <- migrations, Just component <- [moduleComponent (convertedId m)]]          unnamed = [convertedId m | m <- migrations, Nothing <- [moduleComponent (convertedId m)]]          sameModule =            filter ((> 1) . length) . Map.elems $              Map.fromListWith (flip (<>)) [(map toLower component, [convertedId m]) | (component, m) <- named]          allProblems =            [output <> " exists; name a directory that does not exist yet" | outputExists]              <> ["the directory holds no migration file" | null files]              <> ["more than one file for the migration " <> stem | stem <- repeated]              <> [path <> ": the name holds a dot, so dbmigrations gives the migration another identifier" | path <- dotted]              <> problems              <> ["the identifier " <> Text.unpack identifier <> " holds a character other than an ASCII letter, a digit, '-' or '_', so it gives no module name" | identifier <- unnamed]              <> ["the identifiers " <> intercalate ", " (map Text.unpack identifiers) <> " give the same module name, when the case of letters is ignored" | identifiers <- sameModule]      if null allProblems        then do          let modules =                (prefix <> ".Registry", renderRegistry prefix monadModule monad named)                  : [(prefix <> "." <> component, renderMigration prefix monadModule monad component m) | (component, m) <- named]          mapM_ (writeModule output) modules          mapM_ (putStrLn . fst) modules        else mapM_ (hPutStrLn stderr) allProblems >> exitFailure    _ -> do      hPutStrLn stderr "usage: ConvertMigrations DIRECTORY OUTPUT PREFIX MONAD_MODULE MONAD"      exitFailure-- | Reads the YAML file of the migration with this identifier, or describes-- why it cannot.convert :: String -> FilePath -> IO (Either String Converted)convert identifier path = do  decoded <- Yaml.decodeFileEither path  pure $ case decoded of    Left err -> Left (path <> ": " <> Yaml.prettyPrintParseException err)    Right value -> either (Left . ((path <> ": ") <>)) Right (Aeson.parseEither (migration (Text.pack identifier)) value)-- | Parses the fields of one migration. Rejects, as dbmigrations does, a-- field that it does not know, a missing Apply or Depends, and a Depends-- that is neither null nor text. Unlike dbmigrations, ignores the value of-- Created. Also rejects the identifier root, which dbmigrations keeps for-- its own setup.migration :: Text -> Aeson.Value -> Aeson.Parser Convertedmigration identifier = Aeson.withObject "migration" $ \fields -> do  let unknown = [Key.toString key | key <- KeyMap.keys fields, Key.toText key `notElem` known]  unless (null unknown) (fail ("unknown fields: " <> intercalate ", " unknown))  when (identifier == "root") (fail "the identifier root belongs to dbmigrations")  depends <- fields .: "Depends"  dependencies <- case depends of    Aeson.Null -> pure []    Aeson.String text -> pure (Text.words text)    _ -> fail "Depends is not text"  when ("root" `elem` dependencies) (fail "Depends names root, which belongs to dbmigrations")  description <- fromMaybe "" <$> fields .:? "Description"  apply <- fields .: "Apply"  revert <- fields .:? "Revert"  pure (Converted identifier dependencies description apply revert)  where    known = ["Description", "Created", "Depends", "Apply", "Revert"]-- | The last part of the name of a migration's module: M, then the-- identifier with each '-' replaced by '_'. Nothing when the identifier-- holds a character other than an ASCII letter, a digit, '-' or '_'.moduleComponent :: Text -> Maybe StringmoduleComponent identifier  | Text.all allowed identifier = Just ('M' : map (\c -> if c == '-' then '_' else c) (Text.unpack identifier))  | otherwise = Nothing  where    allowed c = isAscii c && (isAlphaNum c || c == '-' || c == '_')-- | Writes the text of the module with this name under the output-- directory, in UTF-8.writeModule :: FilePath -> (String, String) -> IO ()writeModule output (name, text) = do  let path = output </> joinPath (words (map (\c -> if c == '.' then ' ' else c) name)) <.> "hs"  createDirectoryIfMissing True (takeDirectory path)  withFile path WriteMode (\handle -> hSetEncoding handle utf8 >> hPutStr handle text)-- | The text of the module that lists every migration.renderRegistry :: String -> String -> String -> [(String, Converted)] -> StringrenderRegistry prefix monadModule monad named =  unlines $    [ "-- | The registry: every migration of the project, each in a module of its",      "-- own. The conversion program wrote the first version of this module. A",      "-- later migration goes at the end of the list.",      "module " <> prefix <> ".Registry (registry) where",      "",      "import Data.Text (Text)",      "import Database.DagMigrations (Migration)",      "import " <> monadModule <> " (" <> monad <> ")"    ]      <> ["import qualified " <> prefix <> "." <> component <> " as " <> component | (component, _) <- named]      <> [ "",           "-- | Every migration of the project.",           "registry :: [Migration Text " <> monad <> "]",           "registry ="         ]      <> case [component <> ".migration" | (component, _) <- named] of        [] -> ["  []"]        items -> zipWith3 (\start item end -> start <> item <> end) ("  [ " : repeat "    ") items (replicate (length items - 1) "," <> [""]) <> ["  ]"]-- | The text of the module of one migration, whose name ends in this-- component. The module holds the SQL of Apply in the binding apply, and-- the SQL of Revert in the binding revert. Each line of SQL starts at the-- column where it starts in the YAML file, so a diff from the YAML file to-- the module shows the SQL unchanged.renderMigration :: String -> String -> String -> String -> Converted -> StringrenderMigration prefix monadModule monad component m =  unlines $    ["{-# LANGUAGE OverloadedStrings #-}"]      <> ["{-# LANGUAGE QuasiQuotes #-}" | anyQuotation]      <> [ "",           "-- | The migration " <> Text.unpack (convertedId m) <> ", converted from",           "-- dbmigrations. dbmigrations applied it to the project's databases in",           "-- this form, so nobody edits this module. Its fingerprint is 1, which",           "-- the first run records in the tracking table.",           "module " <> prefix <> "." <> component <> " (migration) where",           "",           "import qualified Data.Set as Set",           "import Data.Text (Text)",           "import Database.DagMigrations (Fingerprint (..), Migration (..))"         ]      <> ["import Database.DagMigrations.PostgreSQL.SqlText (sqlText)" | anyQuotation]      <> [ "import " <> monadModule <> " (" <> monad <> ", runSql)",           "import Prelude (Maybe (..))",           "",           "-- | The migration that this module holds.",           "migration :: Migration Text " <> monad,           "migration =",           "  Migration",           "    { migrationId = " <> literal (convertedId m) <> ",",           "      migrationDependencies = Set.fromList [" <> intercalate ", " (map literal (convertedDepends m)) <> "],",           "      migrationDescription = " <> literal (convertedDescription m) <> ",",           "      migrationFingerprint = Just (Fingerprint \"1\"),",           "      migrationUp = runSql apply,",           "      migrationDown = " <> maybe "Nothing" (const "Just (runSql revert)") (convertedRevert m),           "    }",           "",           "-- | The SQL that applies the migration.",           "apply :: Text"         ]      <> sqlBinding "apply" (convertedApply m)      <> case convertedRevert m of        Nothing -> []        Just revert -> ["", "-- | The SQL that reverts the migration.", "revert :: Text"] <> sqlBinding "revert" revert  where    anyQuotation = any quotable (convertedApply m : maybeToList (convertedRevert m))    -- ormolu leaves this layout as it is. The YAML files of dbmigrations    -- usually indent their SQL by two spaces.    sqlBinding name sql      | quotable sql = [name <> " =", "  [sqlText|"] <> quotedLines 2 sql <> ["  |]"]      | otherwise = [name <> " = " <> literal sql]    literal = show . Text.unpack-- | Whether the quasiquoter sqlText gives back this SQL text exactly from-- the lines that quotedLines writes. It does when the text ends in a line-- feed, holds neither |] nor a carriage return, and has a line that starts-- with a character other than a space.quotable :: Text -> Boolquotable sql =  "\n" `Text.isSuffixOf` sql    && not ("|]" `Text.isInfixOf` sql)    && not ("\r" `Text.isInfixOf` sql)    && any (\line -> maybe False ((/= ' ') . fst) (Text.uncons line)) (Text.lines sql)-- | The lines of SQL text inside a quotation [sqlText| ... |], each indented-- by this number of spaces. An empty line of the text stays empty.quotedLines :: Int -> Text -> [String]quotedLines indentation sql =  [if Text.null line then "" else replicate indentation ' ' <> Text.unpack line | line <- Text.lines sql]```From that directory, run the program with five arguments: the path of thedirectory of YAML files, a directory for the output that does not existyet, the start of the name of each module, and the module and the name ofthe project's migration monad. Copy the modules into the project's sourcetree only when the program succeeds. For example:```shcabal run -v0 ConvertMigrations.hs -- /path/to/project/migrations converted App.Migrations App.Migrations.Monad AppMigration \  && cp -r converted/. /path/to/project/src/```The option `-v0` keeps `cabal`'s messages out of the output. The programprints the name of each module that it wrote. Add the names to thepackage's `other-modules` or `exposed-modules`.The program reads each file whose name ends in `.yml` or `.txt` with a YAMLparser, and writes a module for it. The module's name is the start thatthe command gives, then `.M`, then the migration's identifier with each `-`replaced by `_`. In the example, the identifier`2026-03-08_00-00-00_add-view-filters` gives the module`App.Migrations.M2026_03_08_00_00_00_add_view_filters`. The module exports`migration`, of type `Migration Text M`, where `M` is the monad of step 1:- its identifier is the file's name without the extension, which is the  identifier that `installed_migrations` holds;- its dependencies are the words of `Depends`;- its description is `Description`, or empty text;- its `migrationUp` runs the text of `Apply`;- its `migrationDown` runs the text of `Revert`, or is `Nothing` when the  file has no `Revert`;- its fingerprint is `Just (Fingerprint "1")`. The first run records it in  each database, so a later change to the migration and its fingerprint  shows up as a mismatch.The module holds the SQL of `Apply` in the binding `apply`, and the SQLof `Revert` in the binding `revert`. Each line of SQL starts at column 3,where it starts in a YAML file that indents its SQL by two spaces. In aproject whose files do, each line of SQL in a module equals its line inthe YAML file, so `git blame -C -C` gives each line of SQL the commit thatwrote it in the YAML file. GitHub's blame view and its diffs do not lookfor copied lines, and show the modules as new files.The program also writes the module `Registry` under the same start, whichexports `registry`: the list of every migration, in the order of theiridentifiers.The program leaves out `Created`. It writes each SQL text in a quotation`[sqlText| ... |]`, one line of SQL to a line of the module. Thequasiquoter `sqlText`, from the module`Database.DagMigrations.PostgreSQL.SqlText`, gives back each such textexactly, with its quotes, backslashes and line breaks. The program writesa SQL text as a Haskell string literal instead when `sqlText` could notgive it back exactly. That is the case for a text that does not end in aline break, a text that holds `|]` or a carriage return, and a text inwhich no line starts with a character other than a space.The program rejects the fields and files that `dbmigrations` rejects,except a malformed `Created`, which it ignores; step 4 runs `dbmigrations`itself, which reports one. It also rejects these files:- a file whose name holds a dot before the extension, because  `dbmigrations` gives such a file another identifier;- a file whose identifier holds a character other than an ASCII letter, a  digit, `-` or `_`, because the identifier gives no module name;- two files whose identifiers give the same module name when the case of  letters is ignored, because their modules would be one file on a file  system that ignores case.When the program cannot convert a file, it names the file and the problem,and writes no module. Stop and ask when it reports a problem.When the project has a formatter for Haskell, format the modules with it.Do not edit the module of a converted migration by hand: `dbmigrations`applied the migration in this form. A migration that the project writeslater gets a module of its own, of the same form, and goes at the end of`registry`.## Step 3: write the project's runnerAdd a type and three functions to the package, modelled on thesedefinitions of the module `Database.DagMigrations.PostgreSQL.Example`. Inthe project's version, `ProjectMigration` is the monad of step 1, and theproject imports `registry` from the module `Registry` of step 2. Theexample module's import list, which the guide *Writing Haskellmigrations* shows, names the module of each function and type.```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``````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)``````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    }```When the project runs `dbm-postgresql` or `moo-postgresql` anywhere butinside the application, such as from a deployment script, from CI, or byhand as its documentation says, also add an executable to the package. Theexecutable reads a connection string from an environment variable, whichthe owner names, opens a connection, and calls the project's version of`migrateProject` with `Up` and `AllMigrations`. When the function returns`Left`, the executable writes the error with `show`, and exits with status1. Do not change the deployment script, or the start of the application,yet: step 6 does that.## Step 4: check the conversionWrite the files of items 2 and 3 outside the project's repository.1. Add a test that runs `validate` on the registry and expects `Right`.   When the package has no test suite, add one. Keep this test.2. Check once that the set of identifiers in `registry` equals   the set of names of the migration files, without their extensions, for   example from `cabal repl`. Do not commit this check, because it reads   the directory that step 6 deletes.3. Compare what the two tools build:   1. On the PostgreSQL server, create two empty databases, `from_yaml` and      `from_registry`.   2. Migrate `from_yaml` with `dbmigrations`:      ```sh      DBM_DATABASE="HOST dbname=from_yaml" DBM_MIGRATION_STORE=/path/to/project/migrations dbm-postgresql upgrade      ```      With a release of `dbmigrations` earlier than 3.0, run      `moo-postgresql upgrade` instead.   3. Migrate `from_registry` with the project's version of      `migrateProject`: through the executable of step 3, or from      `cabal repl`.   4. Dump both databases without the table `installed_migrations`, because      `dbmigrations` and `dag-migrations` give that table different      columns:      ```sh      for database in from_yaml from_registry; do        pg_dump --schema-only --exclude-table=installed_migrations --restrict-key=compare "HOST dbname=$database" > "$database.schema.sql"        pg_dump --data-only --exclude-table=installed_migrations --restrict-key=compare "HOST dbname=$database" > "$database.data.sql"      done      diff from_yaml.schema.sql from_registry.schema.sql      diff from_yaml.data.sql from_registry.data.sql      ```      If `pg_dump --help` does not list `--restrict-key`, leave that option      out. A `pg_dump` that knows the option writes a random key into each      dump, unless the command passes the key with this option.   5. Both `diff` commands must print nothing. When either prints a      difference, stop and ask. Some differences are harmless, and the      owner decides:      - two migrations that do not depend on each other can run in a        different order under the two tools, which can change the order of        columns or rows;      - a migration that writes values such as `now()`, `random()` or        `gen_random_uuid()` writes different values in the two databases.   6. Drop both databases.When the three checks pass, commit the work of steps 1 to 4, without theone-off check of item 2.## Step 5: check the upgrade on a copyAsk the owner for a copy of each production database, restored from abackup onto a server that the agent may use. For each copy:1. Record the identifiers that `dbmigrations` applied, each once:   ```sh   psql "HOST dbname=COPY" -Atc "SELECT DISTINCT migration_id FROM installed_migrations WHERE migration_id <> 'root' ORDER BY 1" > before.txt   ```2. List the identifiers that the tracking table holds in several rows:   ```sh   psql "HOST dbname=COPY" -Atc "SELECT migration_id, count(*) FROM installed_migrations GROUP BY migration_id HAVING count(*) > 1 ORDER BY 1"   ```   The upgrade in item 4 keeps one row for each identifier, so repeated   rows do not stop the conversion. A repeated row does mean that someone   wrote into the table outside a normal run of `dbmigrations`. One cause   is that someone restored a dump into the database without emptying it   first. In that case, every other table that has no primary key and no   unique index may hold repeated rows too. Another cause is two runs of   `dbmigrations` at the same time, because `dbmigrations` takes no lock.   When the command prints a row, list the tables that have no primary key   and no unique index:   ```sh   psql "HOST dbname=COPY" -Atc "SELECT c.oid::regclass FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'p') AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisunique) ORDER BY 1"   ```   Then stop and ask: give the owner the repeated identifiers and the list   of tables. The owner decides whether to look for repeated rows in those   tables.3. Check that every identifier in `before.txt` belongs to a migration of   the registry. `dbmigrations` ignores a row whose YAML file someone   deleted; `migrate` refuses to run while the tracking table holds such a   row. When there is one, stop and ask: the owner deletes the row, or sets   `allowUnregisteredApplied` in the run's `PlanOptions`.4. Run the project's version of `migrateProject` against the copy. The run   takes these steps, while it holds the run lock:   - it reads the tracking table and plans the run, and writes nothing when     either fails;   - in one transaction, it upgrades the table `installed_migrations`: it     deletes the row `root`, which `dbmigrations` writes for its own setup,     keeps one row for each identifier that the table holds in several     rows, makes `migration_id` `NOT NULL`, adds the columns `applied_at`,     `description` and `fingerprint`, adds a primary key on `migration_id`,     and writes the comment `dag-migrations:1` on the table. `applied_at`     and `description` stay null in the rows that `dbmigrations` wrote;   - in a second transaction, it records the fingerprint `1` of each     converted migration that the database has applied;   - it applies, each in its own transaction, the migrations of the     registry that the copy has not applied.5. Run the project's version of `inspectProject`, and check its result:   - every identifier in `before.txt` is applied in `inspectedStatus`;   - `inspectedUnregistered` is empty, unless the owner chose     `allowUnregisteredApplied` in item 3;   - `inspectedMismatches` and `inspectedToRecord` are empty.When `migrateProject` or `inspectProject` returns `Left`, stop and ask. Theadapter recognizes the tracking table only in the form that `dbmigrations`creates: a table without a comment. Its only column is `migration_id`, oftype `text`. When the table differs, `migrateProject` returns`Left (RunFailed (AdapterFailed e))`, with one of these errors `e`, andchanges nothing:| Error | Cause ||---|---|| `NullLegacyIdentifier` | The table holds a row without an identifier. || `UnrecognizedComment` | Someone wrote a comment on the table. || `UnrecognizedTrackingTable` | The table has no comment, and its columns differ from the one column `migration_id text`. || `NotATable` | The name `installed_migrations` belongs to a view or another relation that is not a table. |When the table already has a primary key, the upgrade fails withPostgreSQL's error, `AdapterFailed (SqlFailed ...)`, and the adapter rollsthe upgrade back. Other constraints, indexes and triggers do not stop theupgrade. Every remedy changes production data, and only the owner maydecide on such a change.## Step 6: remove `dbmigrations` from the projectIn one commit:- replace every call of `dbm-postgresql` or `moo-postgresql`, in deployment  scripts, CI configuration and documentation, with the executable of  step 3, and replace the start of the application's call of  `dbmigrations` with the project's version of `migrateProject`;- delete the directory of YAML files, and any `dbm.cfg` file;- remove `dbmigrations` from the project's dependencies;- remove the settings `DBM_DATABASE` and `DBM_MIGRATION_STORE`.## Step 7: upgrade the production databasesTell the owner that the branch is ready. The owner backs up eachproduction database, merges the branch, deploys the project, and checkseach database as in step 5. After a database is upgraded, nobody may run `dbm-postgresql` or`moo-postgresql` against it, for example from an old checkout of theproject. Those programs could apply migrations that the registry does nothave, and would record them without a time, a description, or afingerprint.