dag-migrations-postgresql-simple (empty) → 0.1.0.0
raw patch · 13 files changed · show whitespace changes · browse dag-migrations-postgresql-simple-0.1.0.0
+2147/−0 lines, 13 filesdep +basedep +bytestringdep +containers
Dependencies added: base, bytestring, containers, dag-migrations, dag-migrations-conformance, dag-migrations-postgresql-simple, hedgehog, hspec, hspec-hedgehog, postgresql-libpq, postgresql-simple, template-haskell, text, transformers, unix
Files
- CHANGELOG.md +9/−0
- LICENSE +21/−0
- dag-migrations-postgresql-simple.cabal +87/−0
- docs/converting-from-dbmigrations.md +626/−0
- src/Database/DagMigrations/PostgreSQL/Simple.hs +429/−0
- src/Database/DagMigrations/PostgreSQL/SqlText.hs +123/−0
- test/Database/DagMigrations/PostgreSQL/Example.hs +205/−0 · folded
- test/Database/DagMigrations/PostgreSQL/Example/Migration.hs +79/−0 · folded
- test/Database/DagMigrations/PostgreSQL/ExampleSpec.hs +77/−0 · folded
- test/Database/DagMigrations/PostgreSQL/SimpleSpec.hs +312/−0 · folded
- test/Database/DagMigrations/PostgreSQL/SqlTextSpec.hs +89/−0 · folded
- test/Database/DagMigrations/PostgreSQL/TestDatabase.hs +66/−0 · folded
- test/Main.hs +24/−0 · folded
+ CHANGELOG.md view
@@ -0,0 +1,9 @@+# Changelog++## [Unreleased]++## [0.1.0.0] - 2026-12-03++### Added++- Initial release.
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kris Nuttycombe++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ dag-migrations-postgresql-simple.cabal view
@@ -0,0 +1,87 @@+cabal-version: 3.0+name: dag-migrations-postgresql-simple+version: 0.1.0.0+synopsis: A PostgreSQL adapter for dag-migrations+description:+ An adapter that runs dag-migrations against PostgreSQL through+ postgresql-simple. It keeps the tracking table installed_migrations,+ upgrades the table of dbmigrations in place, and holds an advisory lock+ for the length of a run. The package includes the guide+ <https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/docs/converting-from-dbmigrations.md docs/converting-from-dbmigrations.md>,+ with the steps by which a project moves from dbmigrations. The adapter+ needs PostgreSQL 9.6 or later, and is tested on PostgreSQL 13 and later.++category: Database+license: MIT+license-file: LICENSE+author: Kris Nuttycombe+maintainer: Kris Nuttycombe <kris@nutty.land>+homepage: https://github.com/nuttycom/dag-migrations+bug-reports: https://github.com/nuttycom/dag-migrations/issues+build-type: Simple+extra-doc-files:+ CHANGELOG.md+ docs/converting-from-dbmigrations.md+tested-with: GHC ==9.6.* || ==9.8.* || ==9.10.* || ==9.12.*++source-repository head+ type: git+ location: https://github.com/nuttycom/dag-migrations.git+ subdir: dag-migrations-postgresql-simple++common language+ default-language: GHC2021+ default-extensions: OverloadedStrings+ ghc-options:+ -Wall -Wcompat -Widentities -Wincomplete-record-updates+ -Wincomplete-uni-patterns -Wmissing-export-lists -Wpartial-fields+ -Wredundant-constraints -Wunused-packages++library+ import: language+ hs-source-dirs: src+ exposed-modules:+ Database.DagMigrations.PostgreSQL.Simple+ Database.DagMigrations.PostgreSQL.SqlText++ build-depends:+ , base >=4.18 && <5+ , bytestring >=0.11 && <0.13+ , containers >=0.6 && <0.9+ , dag-migrations ==0.1.*+ , postgresql-libpq >=0.10 && <0.12+ -- The adapter uses exec, throwResultError and withConnection from+ -- Database.PostgreSQL.Simple.Internal, which does not follow the PVP.+ , postgresql-simple >=0.7 && <0.8+ , template-haskell >=2.20 && <2.24+ , text >=2.0 && <2.2+ , transformers >=0.6 && <0.7++test-suite dag-migrations-postgresql-simple-test+ import: language+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ other-modules:+ Database.DagMigrations.PostgreSQL.Example+ Database.DagMigrations.PostgreSQL.Example.Migration+ Database.DagMigrations.PostgreSQL.ExampleSpec+ Database.DagMigrations.PostgreSQL.SimpleSpec+ Database.DagMigrations.PostgreSQL.SqlTextSpec+ Database.DagMigrations.PostgreSQL.TestDatabase++ build-depends:+ , base+ , bytestring+ , containers+ , dag-migrations+ , dag-migrations-conformance+ , dag-migrations-postgresql-simple+ , hedgehog >=1.4 && <1.8+ , hspec >=2.11 && <2.12+ , hspec-hedgehog >=0.3 && <0.4+ , postgresql-simple+ , text+ , transformers+ , unix >=2.8 && <2.9
+ docs/converting-from-dbmigrations.md view
@@ -0,0 +1,626 @@+# Converting from `dbmigrations`++[`dbmigrations`](https://hackage.haskell.org/package/dbmigrations) keeps a+project's migrations as YAML files. It records the migrations that it has+applied to a database in the table `installed_migrations`, the tracking+table. This guide converts the YAML files into `dag-migrations` values, and+replaces `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` applied+stays applied.++An AI coding agent follows the steps in order; a person can follow them+too. 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 guide+fails, the agent stops and asks. The agent does not change a production+database; 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 start++Stop 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 before+step 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 a+PostgreSQL server on which it may create databases. Below, `HOST` stands+for 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 monad++Add `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 the+module and the monad to fit the project, and replace the module's header+comment, which describes the example. Its `runSql` calls `executeSqlIn`+from `Database.DagMigrations.PostgreSQL.Simple`. `executeSqlIn` runs text+that holds several statements, and text that ends in a query. It discards+the query's rows. When the project already has a migration monad, stop and+ask instead.++## Step 2: generate the migration modules++Do 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) where++import Control.Monad (filterM, unless, when)+import Data.Aeson ((.:), (.:?))+import qualified Data.Aeson as Aeson+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.Aeson.Types as Aeson+import Data.Char (isAlphaNum, isAscii, toLower)+import Data.Either (partitionEithers)+import Data.List (intercalate, sort, sortOn)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, maybeToList)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Yaml as Yaml+import 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 Converted+migration 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 String+moduleComponent 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)] -> String+renderRegistry 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 -> String+renderMigration 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 -> Bool+quotable 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 the+directory of YAML files, a directory for the output that does not exist+yet, the start of the name of each module, and the module and the name of+the project's migration monad. Copy the modules into the project's source+tree only when the program succeeds. For example:++```sh+cabal 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 program+prints the name of each module that it wrote. Add the names to the+package's `other-modules` or `exposed-modules`.++The program reads each file whose name ends in `.yml` or `.txt` with a YAML+parser, and writes a module for it. The module's name is the start that+the 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 SQL+of `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 a+project whose files do, each line of SQL in a module equals its line in+the YAML file, so `git blame -C -C` gives each line of SQL the commit that+wrote it in the YAML file. GitHub's blame view and its diffs do not look+for copied lines, and show the modules as new files.++The program also writes the module `Registry` under the same start, which+exports `registry`: the list of every migration, in the order of their+identifiers.++The program leaves out `Created`. It writes each SQL text in a quotation+`[sqlText| ... |]`, one line of SQL to a line of the module. The+quasiquoter `sqlText`, from the module+`Database.DagMigrations.PostgreSQL.SqlText`, gives back each such text+exactly, with its quotes, backslashes and line breaks. The program writes+a SQL text as a Haskell string literal instead when `sqlText` could not+give it back exactly. That is the case for a text that does not end in a+line break, a text that holds `|]` or a carriage return, and a text in+which 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 writes+later gets a module of its own, of the same form, and goes at the end of+`registry`.++## Step 3: write the project's runner++Add a type and three functions to the package, modelled on these+definitions of the module `Database.DagMigrations.PostgreSQL.Example`. In+the project's version, `ProjectMigration` is the monad of step 1, and the+project imports `registry` from the module `Registry` of step 2. The+example module's import list, which the guide *Writing Haskell+migrations* 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 PgError+projectMigrator 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 but+inside the application, such as from a deployment script, from CI, or by+hand as its documentation says, also add an executable to the package. The+executable reads a connection string from an environment variable, which+the 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 status+1. Do not change the deployment script, or the start of the application,+yet: step 6 does that.++## Step 4: check the conversion++Write 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 the+one-off check of item 2.++## Step 5: check the upgrade on a copy++Ask the owner for a copy of each production database, restored from a+backup 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. The+adapter recognizes the tracking table only in the form that `dbmigrations`+creates: a table without a comment. Its only column is `migration_id`, of+type `text`. When the table differs, `migrateProject` returns+`Left (RunFailed (AdapterFailed e))`, with one of these errors `e`, and+changes 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 with+PostgreSQL's error, `AdapterFailed (SqlFailed ...)`, and the adapter rolls+the upgrade back. Other constraints, indexes and triggers do not stop the+upgrade. Every remedy changes production data, and only the owner may+decide on such a change.++## Step 6: remove `dbmigrations` from the project++In 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 databases++Tell the owner that the branch is ready. The owner backs up each+production database, merges the branch, deploys the project, and checks+each 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 the+project. Those programs could apply migrations that the registry does not+have, and would record them without a time, a description, or a+fingerprint.
+ src/Database/DagMigrations/PostgreSQL/Simple.hs view
@@ -0,0 +1,429 @@+-- | An adapter for PostgreSQL, over @postgresql-simple@. A project passes+-- 'postgresAdapter' to the runner of "Database.DagMigrations", and builds+-- the capabilities of its migrations from 'transactionConnection' and+-- 'executeSqlIn'.+--+-- The adapter needs PostgreSQL 9.6 or later; its tests run on PostgreSQL 13+-- and later. It keeps the tracking table of+-- @dbmigrations@, and upgrades it on the first run against a database that+-- holds that table. The guide+-- <https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/docs/converting-from-dbmigrations.md Converting from dbmigrations>+-- has the steps by which a project moves its migrations and its databases+-- from @dbmigrations@.+module Database.DagMigrations.PostgreSQL.Simple+ ( -- * The adapter+ AdapterSettings (..),+ defaultAdapterSettings,+ defaultRunLockKey,+ postgresAdapter,+ currentTrackingVersion,++ -- * Transactions+ Transaction,+ transactionConnection,+ executeSqlIn,++ -- * Errors+ PgError (..),+ )+where++import Control.Exception (Exception, Handler (..), IOException, SomeException, catches, mask, onException, throwIO, try)+import Control.Monad (void, when)+import Control.Monad.Trans.Except (ExceptT (..), runExceptT, throwE)+import Data.Bits (xor)+import Data.ByteString qualified as ByteString+import Data.Foldable (traverse_)+import Data.Int (Int64)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as Text+import Data.Text.Read qualified as Text+import Data.Word (Word64)+import Database.DagMigrations.Adapter+ ( Adapter (..),+ AppliedRow (..),+ BootstrapOutcome (..),+ Fingerprint (..),+ TrackingVersion (..),+ )+import Database.PostgreSQL.LibPQ qualified as PQ+import Database.PostgreSQL.Simple+ ( Connection,+ FormatError,+ Only (..),+ QueryError,+ ResultError,+ SqlError,+ execute,+ execute_,+ query,+ )+import Database.PostgreSQL.Simple.Internal qualified as Internal+import Database.PostgreSQL.Simple.Types (Oid, QualifiedIdentifier (..))++-- | The settings of an adapter.+data AdapterSettings = AdapterSettings+ { -- | The tracking table. Without a schema, PostgreSQL finds the table on+ -- the connection's search path. Every process that shares the table+ -- names it the same way, or sets the same 'runLockKey', because the+ -- default key depends on how the name is written.+ trackingTable :: QualifiedIdentifier,+ -- | The key of the advisory lock that keeps two runs apart. 'Nothing'+ -- means the key that 'defaultRunLockKey' derives from the table.+ runLockKey :: Maybe Int64+ }+ deriving (Eq, Show)++-- | The table @installed_migrations@ on the search path, and the lock key+-- derived from it.+defaultAdapterSettings :: AdapterSettings+defaultAdapterSettings =+ AdapterSettings+ { trackingTable = QualifiedIdentifier Nothing "installed_migrations",+ runLockKey = Nothing+ }++-- | Returns the 64-bit FNV-1a hash of the UTF-8 bytes of+-- @dag-migrations:@ followed by the table's quoted name, such as+-- @dag-migrations:"installed_migrations"@, read as a signed integer.+-- Projects that share a database and use different tables get different+-- keys, so their runs do not wait for each other. The key depends on how+-- the name is written: @installed_migrations@ and+-- @public.installed_migrations@ give different keys, even when they name+-- the same table.+defaultRunLockKey :: QualifiedIdentifier -> Int64+defaultRunLockKey table =+ fromIntegral (fnv1a64 (Text.encodeUtf8 ("dag-migrations:" <> quotedName table)))++-- | The version of the tracking table that 'postgresAdapter' creates.+currentTrackingVersion :: TrackingVersion+currentTrackingVersion = TrackingVersion 1++-- | A transaction of the adapter, open on its connection.+newtype Transaction = Transaction Connection++-- | Returns the connection on which the transaction is open. A migration+-- runs its statements on this connection, and does not commit or roll+-- back; the adapter does both.+transactionConnection :: Transaction -> Connection+transactionConnection (Transaction connection) = connection++-- | Runs the text in the transaction, and discards any rows that it+-- returns. The text may hold several statements, end in a query, or hold+-- no statement at all. Throws 'SqlError' when PostgreSQL rejects a+-- statement; the adapter's 'withTransaction' turns it into the adapter's+-- error. Throws an 'IOException' when libpq cannot send the text or read+-- its result, for example because the connection is lost; that exception+-- propagates out of 'withTransaction'. A text that copies data between the client and the server, with+-- @COPY ... FROM STDIN@ or @COPY ... TO STDOUT@, is not supported: the call+-- throws, and leaves the session unusable, so the caller closes it. The+-- text must not commit or roll back; see 'transactionConnection'.+executeSqlIn :: Transaction -> Text -> IO ()+executeSqlIn (Transaction connection) sql = do+ result <- Internal.exec connection (Text.encodeUtf8 sql)+ status <- PQ.resultStatus result+ case status of+ PQ.CommandOk -> pure ()+ PQ.TuplesOk -> pure ()+ PQ.EmptyQuery -> pure ()+ _ -> Internal.throwResultError "executeSqlIn" result status++-- | The errors of the adapter.+data PgError+ = -- | PostgreSQL rejected a statement.+ SqlFailed SqlError+ | -- | @postgresql-simple@ rejected a query.+ QueryFailed QueryError+ | -- | @postgresql-simple@ could not convert a result.+ ResultFailed ResultError+ | -- | @postgresql-simple@ could not substitute a query's parameters.+ FormatFailed FormatError+ | -- | libpq could not send one of the adapter's own statements or read+ -- its result, for example because the connection to the server is+ -- lost. The first statement after the server ends a session may+ -- instead fail as 'SqlFailed', with empty fields.+ ConnectionFailed IOException+ | -- | A statement in the transaction failed, and the action caught the+ -- exception and returned 'Right'. PostgreSQL would have answered the+ -- commit with a rollback, so the adapter rolled back.+ TransactionAborted+ | -- | The action ended the transaction itself, with @COMMIT@ or+ -- @ROLLBACK@, so the adapter can neither commit nor roll back what the+ -- action did. Some of its changes may be committed.+ TransactionEnded+ | -- | The relation with the tracking table's name is not a table; it is,+ -- for example, a view.+ NotATable+ | -- | The table has no comment, and its columns, given by name and type,+ -- are not those of version 0.+ UnrecognizedTrackingTable [(Text, Text)]+ | -- | The table has this comment, which names no version.+ UnrecognizedComment Text+ | -- | The table has a version newer than 'currentTrackingVersion'.+ NewerTrackingVersion TrackingVersion+ | -- | A version 0 table holds a row without an identifier.+ NullLegacyIdentifier+ | -- | 'removeApplied' found no row for this identifier.+ MissingAppliedRow Text+ | -- | When 'withRunLock' released the lock with this key, the session no+ -- longer held it, because the action released it.+ RunLockNotHeld Int64+ deriving (Eq, Show)++-- | 'withRunLock' throws 'RunLockNotHeld' as an exception.+instance Exception PgError++-- | Returns an adapter over the connection. Every operation uses this one+-- connection, because the run lock belongs to it, so no other code may use+-- the connection during a run. The connection must be idle, not inside a+-- transaction, when the run starts. The adapter is valid while the+-- connection is open. When an asynchronous exception interrupts one of its+-- operations, the operation rethrows the exception, and the session may+-- still be running a statement; the caller then closes the connection.+postgresAdapter :: AdapterSettings -> Connection -> Adapter Transaction PgError+postgresAdapter settings connection =+ Adapter+ { withRunLock = holdingRunLock connection lockKey,+ readApplied = runExceptT (readAppliedRows connection table),+ bootstrap = merge <$> inTransaction connection (\_ -> runExceptT (bootstrapTable connection table)),+ withTransaction = inTransaction connection,+ recordApplied = \tx row ->+ void+ <$> catchPg+ ( execute+ (transactionConnection tx)+ "INSERT INTO ? (migration_id, applied_at, description, fingerprint) VALUES (?, now(), ?, ?)"+ (table, appliedIdentifier row, appliedDescription row, fingerprintText <$> appliedFingerprint row)+ ),+ removeApplied = \tx identifier -> runExceptT $ do+ removed <- liftPg (execute (transactionConnection tx) "DELETE FROM ? WHERE migration_id = ?" (table, identifier))+ when (removed == 0) (throwE (MissingAppliedRow identifier)),+ recordFingerprints = \tx fingerprints ->+ catchPg $+ traverse_+ ( \(identifier, fingerprint) ->+ execute+ (transactionConnection tx)+ "UPDATE ? SET fingerprint = ? WHERE migration_id = ?"+ (table, fingerprintText <$> fingerprint, identifier)+ )+ (Map.toList fingerprints)+ }+ where+ table = trackingTable settings+ lockKey = fromMaybe (defaultRunLockKey table) (runLockKey settings)+ merge = either (Left . either id id) Right++-- | Holds the session-level advisory lock with this key while the action+-- runs. Returns 'Left' when PostgreSQL refuses the lock, for example when+-- @lock_timeout@ expires. When the action throws, releases the lock if it+-- can, and rethrows. When the action returns and the session no longer+-- holds the lock, throws 'RunLockNotHeld'.+holdingRunLock :: Connection -> Int64 -> IO a -> IO (Either PgError a)+holdingRunLock connection key action = mask $ \restore -> do+ acquired <- catchPg (query connection "SELECT pg_advisory_lock(?)" (Only key) :: IO [Only ()])+ case acquired of+ Left err -> pure (Left err)+ Right _ -> do+ result <- restore action `onException` catchPg (unlock connection key)+ released <- unlock connection key+ if released then pure (Right result) else throwIO (RunLockNotHeld key)++-- | Releases the advisory lock with this key, and returns whether the+-- session held it.+unlock :: Connection -> Int64 -> IO Bool+unlock connection key = (== [Only True]) <$> query connection "SELECT pg_advisory_unlock(?)" (Only key)++-- | Runs the action between @BEGIN@ and @COMMIT@, or @ROLLBACK@. Returns+-- 'Left' without running the action when @BEGIN@ fails. Commits only when+-- the action returns 'Right' and every statement in the transaction+-- succeeded; otherwise rolls back, and returns 'TransactionAborted' for an+-- action that returned 'Right'. Returns 'TransactionEnded', and neither+-- commits nor rolls back, when the action ended the transaction itself.+-- Returns a 'SqlError', 'QueryError', 'ResultError', or 'FormatError' that+-- the action threw as 'Left' ('Left' @PgError@), after a rollback, and a+-- failed commit as 'Left', after which PostgreSQL has ended the+-- transaction. Rolls back and rethrows any other exception.+inTransaction :: Connection -> (Transaction -> IO (Either e a)) -> IO (Either (Either PgError e) a)+inTransaction connection action = mask $ \restore -> do+ begun <- catchPg (execute_ connection "BEGIN")+ case begun of+ Left err -> pure (Left (Left err))+ Right _ -> do+ outcome <- try @SomeException (restore (catchLibrary (action (Transaction connection))))+ case outcome of+ Left other -> rollBack >> throwIO other+ Right (Left err) -> Left (Left err) <$ rollBack+ Right (Right result) -> do+ status <- catchPg (Internal.withConnection connection PQ.transactionStatus)+ case (status, result) of+ (Left err, _) -> Left (Left err) <$ rollBack+ (Right PQ.TransIdle, _) -> pure (Left (Left TransactionEnded))+ (Right PQ.TransInError, Right _) -> Left (Left TransactionAborted) <$ rollBack+ (Right _, Left err) -> Left (Right err) <$ rollBack+ (Right _, Right a) -> either (Left . Left) (const (Right a)) <$> catchPg (execute_ connection "COMMIT")+ where+ rollBack = catchPg (execute_ connection "ROLLBACK")++-- | The version of the tracking table, as the database holds it.+data TableVersion+ = NoTable+ | Version0+ | Version1++-- | Reads the applied identifiers and their fingerprints from any version+-- of the table.+readAppliedRows :: Connection -> QualifiedIdentifier -> ExceptT PgError IO (Map Text (Maybe Fingerprint))+readAppliedRows connection table = do+ version <- tableVersion connection table+ case version of+ NoTable -> pure Map.empty+ Version0 -> do+ rows <- liftPg (query connection "SELECT migration_id FROM ? WHERE migration_id IS DISTINCT FROM 'root'" (Only table))+ identifiers <- maybe (throwE NullLegacyIdentifier) pure (traverse fromOnly rows)+ pure (Map.fromList [(identifier, Nothing) | identifier <- identifiers])+ Version1 -> do+ rows <- liftPg (query connection "SELECT migration_id, fingerprint FROM ?" (Only table))+ pure (Map.fromList [(identifier, Fingerprint <$> fingerprint) | (identifier, fingerprint) <- rows])++-- | Creates the current table, upgrades a version 0 table, or does+-- nothing. Writes on the connection, which must be in a transaction. The+-- upgrade deletes the row @root@, and keeps one row for each identifier+-- that the table holds in several rows.+bootstrapTable :: Connection -> QualifiedIdentifier -> ExceptT PgError IO BootstrapOutcome+bootstrapTable connection table = do+ version <- tableVersion connection table+ case version of+ Version1 -> pure AlreadyCurrent+ NoTable -> do+ _ <-+ liftPg $+ execute+ connection+ "CREATE TABLE ? (migration_id text PRIMARY KEY, applied_at timestamptz NULL, description text NULL, fingerprint text NULL)"+ (Only table)+ markCurrent+ pure (Created currentTrackingVersion)+ Version0 -> do+ nulls <- liftPg (query connection "SELECT count(*) FROM ? WHERE migration_id IS NULL" (Only table))+ when (nulls /= [Only (0 :: Int64)]) (throwE NullLegacyIdentifier)+ _ <- liftPg (execute connection "DELETE FROM ? WHERE migration_id = 'root'" (Only table))+ -- Deletes every row of an identifier that the table holds in+ -- several rows, and inserts one row for that identifier.+ _ <-+ liftPg $+ execute+ connection+ "WITH repeated AS (DELETE FROM ? WHERE migration_id IN (SELECT migration_id FROM ? GROUP BY migration_id HAVING count(*) > 1) RETURNING migration_id) INSERT INTO ? (migration_id) SELECT DISTINCT migration_id FROM repeated"+ (table, table, table)+ _ <-+ liftPg $+ execute+ connection+ "ALTER TABLE ? ALTER COLUMN migration_id SET NOT NULL, ADD COLUMN applied_at timestamptz NULL, ADD COLUMN description text NULL, ADD COLUMN fingerprint text NULL, ADD PRIMARY KEY (migration_id)"+ (Only table)+ markCurrent+ pure (Upgraded (TrackingVersion 0) currentTrackingVersion)+ where+ markCurrent =+ void (liftPg (execute connection "COMMENT ON TABLE ? IS ?" (table, versionComment currentTrackingVersion)))++-- | Finds the table, and reads its version from its comment, or from its+-- columns when it has no comment. A relation that is not a table, such as+-- a view, is not a tracking table.+tableVersion :: Connection -> QualifiedIdentifier -> ExceptT PgError IO TableVersion+tableVersion connection table = do+ found <-+ liftPg $+ query+ connection+ "SELECT oid, obj_description(oid, 'pg_class'), relkind IN ('r', 'p') FROM pg_class WHERE oid = to_regclass(?)"+ (Only (quotedName table))+ case found of+ [] -> pure NoTable+ (oid, comment, isTable) : _ -> do+ columns <- liftPg (tableColumns connection oid)+ ExceptT (pure (classifyTable isTable comment columns))++-- | Reads the names and types of the table's columns, in order.+tableColumns :: Connection -> Oid -> IO [(Text, Text)]+tableColumns connection oid =+ query+ connection+ "SELECT attname::text, format_type(atttypid, atttypmod) FROM pg_attribute WHERE attrelid = ? AND attnum > 0 AND NOT attisdropped ORDER BY attnum"+ (Only oid)++-- | Returns the version of a relation from whether it is a table, its+-- comment, and its columns.+classifyTable :: Bool -> Maybe Text -> [(Text, Text)] -> Either PgError TableVersion+classifyTable False _ _ = Left NotATable+classifyTable True (Just comment) _ = case commentVersion comment of+ Just (TrackingVersion 1) -> Right Version1+ Just version | version > currentTrackingVersion -> Left (NewerTrackingVersion version)+ _ -> Left (UnrecognizedComment comment)+classifyTable True Nothing [("migration_id", "text")] = Right Version0+classifyTable True Nothing columns = Left (UnrecognizedTrackingTable columns)++-- | The comment that marks a table of this version.+versionComment :: TrackingVersion -> Text+versionComment (TrackingVersion version) = "dag-migrations:" <> Text.pack (show version)++-- | Returns the version that a comment names, when the comment is exactly+-- 'versionComment' of a version.+commentVersion :: Text -> Maybe TrackingVersion+commentVersion comment = do+ digits <- Text.stripPrefix "dag-migrations:" comment+ case Text.decimal digits of+ Right (version, "") | versionComment (TrackingVersion version) == comment -> Just (TrackingVersion version)+ _ -> Nothing++-- | Writes the table's name as SQL quotes it, such as+-- @"public"."installed_migrations"@.+quotedName :: QualifiedIdentifier -> Text+quotedName (QualifiedIdentifier schema name) =+ Text.intercalate "." (map quote (maybe [] pure schema <> [name]))+ where+ quote part = "\"" <> Text.replace "\"" "\"\"" part <> "\""++-- | The 64-bit FNV-1a hash of the bytes.+fnv1a64 :: ByteString.ByteString -> Word64+fnv1a64 = ByteString.foldl' step 0xcbf29ce484222325+ where+ step hash byte = (hash `xor` fromIntegral byte) * 0x100000001b3++-- | The text of a fingerprint.+fingerprintText :: Fingerprint -> Text+fingerprintText (Fingerprint text) = text++-- | Runs one of the adapter's own statements, and returns 'SqlError',+-- 'QueryError', 'ResultError', 'FormatError', or an 'IOException' of libpq+-- as the adapter's error.+catchPg :: IO a -> IO (Either PgError a)+catchPg action =+ (Right <$> action)+ `catches` (Handler (pure . Left . ConnectionFailed) : libraryHandlers)++-- | Runs a migration's action, and returns 'SqlError', 'QueryError',+-- 'ResultError', or 'FormatError' as the adapter's error. Any other+-- exception, such as an 'IOException' from a migration's own file access,+-- propagates.+catchLibrary :: IO a -> IO (Either PgError a)+catchLibrary action = (Right <$> action) `catches` libraryHandlers++-- | Handlers that turn the exceptions of @postgresql-simple@ into the+-- adapter's errors.+libraryHandlers :: [Handler (Either PgError a)]+libraryHandlers =+ [ Handler (pure . Left . SqlFailed),+ Handler (pure . Left . QueryFailed),+ Handler (pure . Left . ResultFailed),+ Handler (pure . Left . FormatFailed)+ ]++-- | 'catchPg' in t'ExceptT'.+liftPg :: IO a -> ExceptT PgError IO a+liftPg = ExceptT . catchPg
+ src/Database/DagMigrations/PostgreSQL/SqlText.hs view
@@ -0,0 +1,123 @@+-- | A quasiquoter for SQL text that spans several lines of a Haskell+-- source file. A migration writes+--+-- > migrationUp =+-- > runSql+-- > [sqlText|+-- > CREATE TABLE saved_views (+-- > name text PRIMARY KEY+-- > );+-- > |]+--+-- and 'sqlText' gives the 'Text'+-- @"CREATE TABLE saved_views (\\n name text PRIMARY KEY\\n);\\n"@. The+-- module that uses 'sqlText' turns on the extension @QuasiQuotes@.+module Database.DagMigrations.PostgreSQL.SqlText+ ( sqlText,+ unquoteSqlText,+ SqlTextError (..),+ )+where++import Data.List.NonEmpty (NonEmpty (..))+import Data.List.NonEmpty qualified as NonEmpty+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as Text+import Language.Haskell.TH.Quote (QuasiQuoter (..))+import Language.Haskell.TH.Syntax (lift)++-- | The quasiquoter for SQL text. GHC calls it at compile time for each+-- quotation @[sqlText| ... |]@, which then stands for a 'Text'.+--+-- Preconditions: the quotation follows the layout that 'unquoteSqlText'+-- describes, and is in the place of an expression.+--+-- Inputs: the characters between @[sqlText|@ and @|]@.+--+-- Output: the 'Text' that 'unquoteSqlText' gives. When the quotation does+-- not follow the layout, or stands in the place of a pattern, a type or a+-- declaration, compilation fails with a message that names the problem.+--+-- Side effects: none at run time.+sqlText :: QuasiQuoter+sqlText =+ QuasiQuoter+ { quoteExp = either (fail . describeSqlTextError) lift . unquoteSqlText,+ quotePat = const (fail "sqlText: a quotation [sqlText| ... |] stands for an expression, not a pattern"),+ quoteType = const (fail "sqlText: a quotation [sqlText| ... |] stands for an expression, not a type"),+ quoteDec = const (fail "sqlText: a quotation [sqlText| ... |] stands for an expression, not a declaration")+ }++-- | Gives the text for which a quotation @[sqlText| ... |]@ stands.+--+-- Preconditions: none.+--+-- Inputs: the characters between @[sqlText|@ and @|]@. The quotation+-- follows this layout:+--+-- * The opening line, from @[sqlText|@ to the first line break, holds+-- only spaces.+-- * The closing line, from the last line break to @|]@, holds only+-- spaces.+-- * The lines between the opening line and the closing line hold the+-- SQL.+--+-- A carriage return before a line break is part of the line break.+-- Backslashes and quotation marks stand for themselves. The characters+-- @|]@ end the quotation, so the SQL cannot hold them.+--+-- Output: the lines of the SQL, each followed by a line feed. The+-- function removes the indentation from each line. The indentation is+-- the least number of spaces at the start of a line that holds a+-- character other than a space. A tab is such a character, not+-- indentation. A line that holds only spaces keeps the spaces beyond the+-- indentation. When no line holds a character other than a space, each+-- line gives an empty line. When the quotation does not follow the+-- layout, the result is the first problem that the function finds, as a+-- 'SqlTextError'.+--+-- Side effects: none.+unquoteSqlText :: String -> Either SqlTextError Text+unquoteSqlText quotation =+ case Text.splitOn "\n" (Text.pack quotation) of+ opening : afterOpening : rest+ | not (onlySpaces (withoutCarriageReturn opening)) -> Left SqlTextAfterOpening+ | not (onlySpaces closing) -> Left SqlTextBeforeClosing+ | otherwise -> Right (foldMap (\line -> Text.drop indentation line <> "\n") sqlLines)+ where+ linesAfterOpening = afterOpening :| rest+ closing = NonEmpty.last linesAfterOpening+ sqlLines = map withoutCarriageReturn (NonEmpty.init linesAfterOpening)+ -- With no line that holds a character other than a space, the+ -- indentation is maxBound, and each line gives an empty line.+ indentation =+ minimum (maxBound :| [Text.length (Text.takeWhile (== ' ') line) | line <- sqlLines, not (onlySpaces line)])+ _ -> Left SqlTextOnOneLine+ where+ onlySpaces = Text.all (== ' ')+ withoutCarriageReturn line = fromMaybe line (Text.stripSuffix "\r" line)++-- | A reason why 'unquoteSqlText' refuses a quotation.+data SqlTextError+ = -- | The quotation holds no line break, so it has no opening line and+ -- no closing line.+ SqlTextOnOneLine+ | -- | The opening line holds a character other than a space after+ -- @[sqlText|@.+ SqlTextAfterOpening+ | -- | The closing line holds a character other than a space before+ -- @|]@.+ SqlTextBeforeClosing+ deriving (Eq, Show)++-- | The message of a compilation error for a quotation that does not+-- follow the layout.+describeSqlTextError :: SqlTextError -> String+describeSqlTextError problem = case problem of+ SqlTextOnOneLine ->+ "sqlText: the quotation holds no line break. Start the SQL on the line after [sqlText|, and put |] on a line of its own."+ SqlTextAfterOpening ->+ "sqlText: the line of [sqlText| holds more than spaces after it. Start the SQL on the next line."+ SqlTextBeforeClosing ->+ "sqlText: the line of |] holds more than spaces before it. Put |] on a line of its own, after spaces only."
+ test/Database/DagMigrations/PostgreSQL/Example.hs view
@@ -0,0 +1,205 @@+{-# 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,+ )+where++import 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 Map+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as Text+import 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 ProjectMigration+createViews =+ 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 ProjectMigration+addViewFilters =+ 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 ProjectMigration+splitViewFilters =+ 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 SavedViewV1+decodeSavedViewV1 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 ProjectMigration+normalizeViewNames =+ 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 -> Text+quoted 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 -> Text+normalizeViewName = 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 PgError+projectMigrator connection graph =+ Migrator+ { migratorAdapter = postgresAdapter defaultAdapterSettings connection,+ migratorCodec = textIdentifiers,+ migratorInterpreter = projectInterpreter,+ migratorProgress = silentProgress,+ migratorSettings = defaultRunSettings,+ migratorGraph = graph+ }
+ test/Database/DagMigrations/PostgreSQL/Example/Migration.hs view
@@ -0,0 +1,79 @@+{-# LANGUAGE GHC2021 #-}+{-# LANGUAGE OverloadedStrings #-}++-- | The monad of the example project's migrations, and its operations.+-- "Database.DagMigrations.PostgreSQL.Example" holds the migrations; the+-- guides @writing-haskell-migrations.md@ and+-- @converting-from-dbmigrations.md@ quote both modules verbatim.+--+-- This module does not export the constructor of 'ProjectMigration', and+-- 'ProjectMigration' has no 'Control.Monad.IO.Class.MonadIO' instance. So+-- a migration in another module reaches the database only through+-- 'runSql', 'queryRows' and 'executeRow'. Some code can still run other+-- 'IO': code that imports "Database.PostgreSQL.Simple.Internal" or+-- "System.IO.Unsafe", and a 'Database.PostgreSQL.Simple.FromRow.FromRow'+-- instance that runs 'IO'. SQL also runs with the privileges of the+-- database role. A reviewer of a migration checks its imports, the+-- instances of the row types that it reads and writes, the application+-- functions that it calls, and its SQL.+module Database.DagMigrations.PostgreSQL.Example.Migration+ ( ProjectMigration,+ runSql,+ queryRows,+ executeRow,+ failMigration,+ projectInterpreter,+ )+where++import 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 monad in which the project's migrations run.+newtype ProjectMigration a = ProjectMigration (ReaderT Transaction (ExceptT Text IO) a)+ deriving (Functor, Applicative, Monad)++-- | 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)))++-- | Runs a query in the migration's transaction, with the parameters in+-- place of its @?@ marks, and returns its rows. The query holds one @?@ for+-- each parameter, writes a literal question mark as @??@, and does not hold+-- @COMMIT@ or @ROLLBACK@; its columns match the row type. Otherwise, or+-- when PostgreSQL rejects the query, the migration fails with the adapter's+-- error, and the adapter rolls back its transaction.+queryRows :: (ToRow q, FromRow r) => Query -> q -> ProjectMigration [r]+queryRows sql parameters =+ ProjectMigration (ReaderT (\tx -> lift (query (transactionConnection tx) sql parameters)))++-- | Runs a statement in the migration's transaction, with the parameters in+-- place of its @?@ marks. The statement holds one @?@ for each parameter,+-- writes a literal question mark as @??@, and is not @COMMIT@ or+-- @ROLLBACK@. Otherwise, or when PostgreSQL rejects the statement, the+-- migration fails with the adapter's error, and the adapter rolls back its+-- transaction.+executeRow :: (ToRow q) => Query -> q -> ProjectMigration ()+executeRow sql parameters =+ ProjectMigration (ReaderT (\tx -> lift (void (execute (transactionConnection tx) sql parameters))))++-- | 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 a+failMigration = ProjectMigration . lift . throwE++-- | Runs a 'ProjectMigration' in a transaction of the PostgreSQL adapter.+projectInterpreter :: Interpreter Transaction ProjectMigration Text+projectInterpreter = Interpreter (\tx (ProjectMigration action) -> runExceptT (runReaderT action tx))
+ test/Database/DagMigrations/PostgreSQL/ExampleSpec.hs view
@@ -0,0 +1,77 @@+-- | Runs the example project of "Database.DagMigrations.PostgreSQL.Example"+-- against the test server, and checks what each of its migrations does.+module Database.DagMigrations.PostgreSQL.ExampleSpec (spec) where++import Data.List.NonEmpty (NonEmpty (..))+import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.Text (Text)+import Database.DagMigrations (Direction (..), Inspection (..), PlanError (..), RunError (..), Target (..))+import Database.DagMigrations.PostgreSQL.Example (ProjectError (..), inspectProject, migrateProject)+import Database.DagMigrations.PostgreSQL.TestDatabase+import Database.PostgreSQL.Simple (Connection, Only (..), execute_, query_)+import Test.Hspec++-- | The cases of the example project.+spec :: TestServer -> Spec+spec server = describe "the example project" $ do+ it "migrates an empty database, moves each view's filter to its own column, and normalizes view names" $+ onExample server $ \connection -> do+ migrateProject connection Up (TargetMigration addViewFilters) `shouldReturn` Right ()+ _ <- execute_ connection "INSERT INTO saved_views (name, definition) VALUES (' Open ', 'title,owner|status = open')"+ migrateProject connection Up AllMigrations `shouldReturn` Right ()+ views connection `shouldReturn` [("open", "title,owner", Just "status = open")]+ inspectProject connection+ `shouldReturn` Right (Inspection (map (,True) allMigrations) Set.empty [] Map.empty)++ it "fails the data migration, names every view that is not of version 1, and changes nothing" $+ onExample server $ \connection -> do+ migrateProject connection Up (TargetMigration addViewFilters) `shouldReturn` Right ()+ _ <- execute_ connection "INSERT INTO saved_views (name, definition) VALUES ('a', 'title|status = open'), ('b', 'title,owner'), ('c', 'owner')"+ migrateProject connection Up AllMigrations+ `shouldReturn` Left (RunFailed (MigrationFailed splitViewFilters Up (Right "saved views whose definition is not of version 1: \"b\", \"c\"")))+ views connection `shouldReturn` [("a", "title|status = open", Nothing), ("b", "title,owner", Nothing), ("c", "owner", Nothing)]+ fmap inspectedStatus <$> inspectProject connection+ `shouldReturn` Right (zip allMigrations [True, True, False, False])++ it "fails the name migration when two names normalize to the same name, and changes nothing" $+ onExample server $ \connection -> do+ migrateProject connection Up (TargetMigration createViews) `shouldReturn` Right ()+ _ <- execute_ connection "INSERT INTO saved_views (name, definition) VALUES (' Open ', 'a'), ('open', 'b'), ('Closed', 'c')"+ migrateProject connection Up (TargetMigration normalizeViewNames)+ `shouldReturn` Left (RunFailed (MigrationFailed normalizeViewNames Up (Right "saved views whose names normalize to the same name: \" Open \", \"open\"")))+ query_ connection "SELECT name FROM saved_views ORDER BY name COLLATE \"C\"" `shouldReturn` map Only [" Open ", "Closed", "open" :: Text]++ it "reverts a schema migration" $+ onExample server $ \connection -> do+ migrateProject connection Up (TargetMigration addViewFilters) `shouldReturn` Right ()+ migrateProject connection Down (TargetMigration createViews) `shouldReturn` Right ()+ query_ connection "SELECT count(*) FROM information_schema.columns WHERE table_name = 'saved_views' AND column_name = 'filter'"+ `shouldReturn` [Only (0 :: Int)]++ it "refuses to revert past the migrations that cannot be reverted" $+ onExample server $ \connection -> do+ migrateProject connection Up AllMigrations `shouldReturn` Right ()+ migrateProject connection Down (TargetMigration createViews)+ `shouldReturn` Left (RunFailed (PlanFailed (Irreversible normalizeViewNames :| [Irreversible splitViewFilters])))+ fmap inspectedStatus <$> inspectProject connection `shouldReturn` Right (map (,True) allMigrations)++-- | The identifiers of the example's migrations, in the order in which the+-- runner applies them.+allMigrations :: [Text]+allMigrations = [createViews, addViewFilters, splitViewFilters, normalizeViewNames]++createViews, addViewFilters, splitViewFilters, normalizeViewNames :: Text+createViews = "2022-11-27_22-28-18_create-views"+addViewFilters = "2026-03-08_00-00-00_add-view-filters"+splitViewFilters = "2026-03-09_00-00-00_split-view-filters"+normalizeViewNames = "2026-03-10_00-00-00_normalize-view-names"++-- | Opens a connection to a new empty database, and passes the connection+-- to the action.+onExample :: TestServer -> (Connection -> IO a) -> IO a+onExample server use = withTestDatabase server (`withConnection` use)++-- | The name, the definition, and the filter of every saved view, by name.+views :: Connection -> IO [(Text, Text, Maybe Text)]+views connection = query_ connection "SELECT name, definition, filter FROM saved_views ORDER BY name"
+ test/Database/DagMigrations/PostgreSQL/SimpleSpec.hs view
@@ -0,0 +1,312 @@+-- | The tests of what is specific to the PostgreSQL adapter, and the+-- 'Fixture' that runs the conformance suite against it.+module Database.DagMigrations.PostgreSQL.SimpleSpec+ ( postgresFixture,+ spec,+ )+where++import Control.Exception (IOException, throwIO, try)+import Control.Monad (void)+import Data.ByteString (ByteString)+import Data.Either (isLeft)+import Data.Foldable (for_)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Int (Int64)+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Void (Void, absurd)+import Database.DagMigrations.Adapter+ ( Adapter (..),+ AppliedRow (..),+ BootstrapOutcome (..),+ Fingerprint (..),+ TrackingVersion (..),+ )+import Database.DagMigrations.Conformance (Fixture (..))+import Database.DagMigrations.PostgreSQL.Simple+import Database.DagMigrations.PostgreSQL.TestDatabase+import Database.PostgreSQL.Simple (Connection, Only (..), SqlError (..), execute, executeMany, execute_, query, query_)+import Database.PostgreSQL.Simple.Types (Identifier (..), QualifiedIdentifier (..))+import System.Timeout (timeout)+import Test.Hspec++-- | The 'Fixture' over databases on the test server, with the default+-- settings. A marker is a table.+postgresFixture :: TestServer -> Fixture TestDatabase Transaction PgError+postgresFixture server =+ Fixture+ { withEmptyDatabase = withTestDatabase server,+ withAdapter = \database use -> withConnection database (use . postgresAdapter defaultAdapterSettings),+ createMarker = \tx name ->+ void (execute (transactionConnection tx) "CREATE TABLE ? ()" (Only (Identifier name))),+ dropMarker = \tx name ->+ void (execute (transactionConnection tx) "DROP TABLE ?" (Only (Identifier name))),+ markerExists = \database name -> withConnection database (`tableExists` name),+ failInLibrary = \tx -> executeSqlIn tx "SELECT 1 / 0",+ seedVersion0 = Just $ \database identifiers ->+ withConnection database (\connection -> seedVersion0Table connection (map Just identifiers))+ }++-- | The cases that are specific to PostgreSQL.+spec :: TestServer -> Spec+spec server = describe "the PostgreSQL adapter" $ do+ describe "the tracking table" $ do+ it "creates version 1, with its columns and its comment" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ bootstrap adapter `shouldReturn` Right (Created (TrackingVersion 1))+ columnsOf connection "installed_migrations" `shouldReturn` version1Columns+ commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1"++ it "stores the description, the fingerprint, and the database's time of an applied migration" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- bootstrap adapter+ committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "the first" (Just (Fingerprint "f"))))+ `shouldReturn` Right ()+ query_ connection "SELECT description, fingerprint, applied_at BETWEEN now() - interval '1 minute' AND now() FROM installed_migrations"+ `shouldReturn` [(Just "the first" :: Maybe Text, Just "f" :: Maybe Text, True)]++ it "keeps its table in the schema that its settings name" $ do+ let settings = defaultAdapterSettings {trackingTable = QualifiedIdentifier (Just "migrations") "applied"}+ onDatabase server settings $ \_ connection adapter -> do+ _ <- execute_ connection "CREATE SCHEMA migrations"+ bootstrap adapter `shouldReturn` Right (Created (TrackingVersion 1))+ committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "the first" Nothing)) `shouldReturn` Right ()+ readApplied adapter `shouldReturn` Right (Map.fromList [("a", Nothing)])+ commentOf connection "migrations.applied" `shouldReturn` Just "dag-migrations:1"+ tableExists connection "installed_migrations" `shouldReturn` False++ describe "version 0" $ do+ it "upgrades the rows of version 0 without a time, a description, or a fingerprint" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ seedVersion0Table connection [Just "root", Just "a", Just "b"]+ bootstrap adapter `shouldReturn` Right (Upgraded (TrackingVersion 0) (TrackingVersion 1))+ query_ connection "SELECT migration_id, applied_at IS NULL, description IS NULL, fingerprint IS NULL FROM installed_migrations ORDER BY migration_id"+ `shouldReturn` [("a" :: Text, True, True, True), ("b", True, True, True)]+ columnsOf connection "installed_migrations" `shouldReturn` version1Columns+ commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1"++ it "upgrades a version 0 table that holds identifiers in several rows, and keeps one row for each identifier" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ seedVersion0Table connection [Just "root", Just "a", Just "b", Just "a", Just "root", Just "a"]+ bootstrap adapter `shouldReturn` Right (Upgraded (TrackingVersion 0) (TrackingVersion 1))+ query_ connection "SELECT migration_id, applied_at IS NULL, description IS NULL, fingerprint IS NULL FROM installed_migrations ORDER BY migration_id"+ `shouldReturn` [("a" :: Text, True, True, True), ("b", True, True, True)]+ columnsOf connection "installed_migrations" `shouldReturn` version1Columns+ commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1"++ it "rolls back a version 0 upgrade that fails, and leaves the table as it was" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text PRIMARY KEY); INSERT INTO installed_migrations VALUES ('root'), ('a')"+ upgraded <- bootstrap adapter+ sqlStateOf upgraded `shouldBe` Just "42P16"+ legacyRows connection `shouldReturn` [Just "a", Just "root"]+ commentOf connection "installed_migrations" `shouldReturn` Nothing++ it "reports a version 0 row without an identifier, and leaves the table as it was" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ seedVersion0Table connection [Just "root", Nothing, Just "a"]+ readApplied adapter `shouldReturn` Left NullLegacyIdentifier+ bootstrap adapter `shouldReturn` Left NullLegacyIdentifier+ legacyRows connection `shouldReturn` [Just "a", Just "root", Nothing]++ describe "recognizing the table" $ do+ it "reports a version newer than its own" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- bootstrap adapter+ _ <- execute_ connection "COMMENT ON TABLE installed_migrations IS 'dag-migrations:2'"+ readApplied adapter `shouldReturn` Left (NewerTrackingVersion (TrackingVersion 2))+ bootstrap adapter `shouldReturn` Left (NewerTrackingVersion (TrackingVersion 2))++ it "reports a comment that names no version" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- bootstrap adapter+ for_ ["dag-migrations:01", "dag-migrations:0", "dag-migrations:", "dag-migrations:1 ", "made by hand"] $ \comment -> do+ _ <- execute connection "COMMENT ON TABLE installed_migrations IS ?" (Only (comment :: Text))+ readApplied adapter `shouldReturn` Left (UnrecognizedComment comment)+ bootstrap adapter `shouldReturn` Left (UnrecognizedComment comment)++ it "reports a relation that is not a table" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- execute_ connection "CREATE VIEW installed_migrations AS SELECT 'a'::text AS migration_id"+ readApplied adapter `shouldReturn` Left NotATable+ bootstrap adapter `shouldReturn` Left NotATable++ it "reports a table without a comment whose columns are not those of version 0" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text, extra integer)"+ let columns = [("migration_id", "text"), ("extra", "integer")]+ readApplied adapter `shouldReturn` Left (UnrecognizedTrackingTable columns)+ bootstrap adapter `shouldReturn` Left (UnrecognizedTrackingTable columns)++ describe "the run lock" $ do+ it "derives its default key from the quoted name of the table" $ do+ defaultRunLockKey (QualifiedIdentifier Nothing "installed_migrations") `shouldBe` (-5832889685011756295)+ defaultRunLockKey (QualifiedIdentifier (Just "migrations") "applied") `shouldBe` 448998094553880189++ it "holds the advisory lock with the default key while the action runs" $+ onDatabase server defaultAdapterSettings $ \database _ adapter ->+ withRunLock adapter (withConnection database advisoryLocks) `shouldReturn` Right [-5832889685011756295]++ it "holds the advisory lock with the key of its settings" $+ onDatabase server defaultAdapterSettings {runLockKey = Just 42} $ \database _ adapter ->+ withRunLock adapter (withConnection database advisoryLocks) `shouldReturn` Right [42]++ it "returns the error of an expired lock_timeout, and does not run the action" $+ onDatabase server defaultAdapterSettings $ \database _ first ->+ withConnection database $ \other -> do+ _ <- execute_ other "SET lock_timeout = '100ms'"+ let second = postgresAdapter defaultAdapterSettings other+ ran <- newIORef False+ outcome <- timeout 10000000 (withRunLock first (withRunLock second (writeIORef ran True)))+ fmap (fmap sqlStateOf) outcome `shouldBe` Just (Right (Just "55P03"))+ readIORef ran `shouldReturn` False++ it "returns a lost connection as the adapter's error" $+ onDatabase server defaultAdapterSettings $ \database connection adapter -> do+ pids <- query_ connection "SELECT pg_backend_pid()"+ withConnection database $ \other ->+ for_ pids $ \(Only pid) -> void (query other "SELECT pg_terminate_backend(?)" (Only (pid :: Int)) :: IO [Only Bool])+ first <- withRunLock adapter (pure ())+ first `shouldSatisfy` isLeft+ second <- withRunLock adapter (pure ())+ second `shouldSatisfy` isConnectionFailure+ readApplied adapter >>= (`shouldSatisfy` isConnectionFailure)++ it "throws when the action released the lock" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter ->+ withRunLock adapter (void (query_ connection "SELECT pg_advisory_unlock_all()" :: IO [Only ()]))+ `shouldThrow` (== RunLockNotHeld (-5832889685011756295))++ describe "transactions" $ do+ it "runs several statements in one text" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ committing adapter (\tx -> Right <$> executeSqlIn tx "CREATE TABLE first (); CREATE TABLE second ()")+ `shouldReturn` Right ()+ traverse (tableExists connection) ["first", "second"] `shouldReturn` [True, True]++ it "runs a text that ends in a query, or holds no statement" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ committing adapter (\tx -> Right <$> executeSqlIn tx "CREATE TABLE third (); SELECT 1")+ `shouldReturn` Right ()+ committing adapter (\tx -> Right <$> executeSqlIn tx "-- nothing to do")+ `shouldReturn` Right ()+ tableExists connection "third" `shouldReturn` True++ it "rethrows an asynchronous exception that interrupts a statement" $+ onDatabase server defaultAdapterSettings $ \database _ adapter -> do+ timeout 300000 (withRunLock adapter (withTransaction adapter (\tx -> Right @Void <$> executeSqlIn tx "SELECT pg_sleep(5)")))+ `shouldReturn` Nothing+ withConnection database $ \other ->+ query_ other "SELECT query FROM pg_stat_activity WHERE datname = current_database() AND state = 'active' AND pid <> pg_backend_pid()"+ `shouldReturn` [Only ("SELECT pg_sleep(5)" :: Text)]++ it "rethrows an IOException that a migration throws" $+ onDatabase server defaultAdapterSettings $ \_ _ adapter ->+ void (withTransaction adapter (\_ -> throwIO (userError "file missing") >> pure (Right @Void ())))+ `shouldThrow` (\(_ :: IOException) -> True)++ it "reports a transaction that the action ended itself" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ outcome <- withTransaction adapter (\tx -> Left () <$ executeSqlIn tx "CREATE TABLE fifth (); COMMIT; CREATE TABLE sixth ()")+ outcome `shouldBe` (Left (Left TransactionEnded) :: Either (Either PgError ()) ())+ traverse (tableExists connection) ["fifth", "sixth"] `shouldReturn` [True, True]++ it "rolls back, and reports, a transaction in which the action caught a failed statement" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ outcome <- withTransaction adapter $ \tx -> do+ executeSqlIn tx "CREATE TABLE fourth ()"+ _ <- try @SqlError (executeSqlIn tx "SELECT 1 / 0")+ pure (Right @Void ())+ outcome `shouldBe` Left (Left TransactionAborted)+ tableExists connection "fourth" `shouldReturn` False++ it "returns a failed commit as the adapter's error" $+ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do+ _ <- execute_ connection "CREATE TABLE parent (id integer PRIMARY KEY); CREATE TABLE child (parent integer REFERENCES parent DEFERRABLE INITIALLY DEFERRED)"+ outcome <- withTransaction adapter (\tx -> Right @Void <$> executeSqlIn tx "INSERT INTO child VALUES (1)")+ either (either (Just . sqlStateOf . Left) absurd) (const Nothing) outcome+ `shouldBe` Just (Just "23503")+ query_ connection "SELECT count(*) FROM child" `shouldReturn` [Only (0 :: Int64)]++-- | Opens a connection to a new empty database, and passes the database,+-- the connection, and an adapter over the connection with these settings+-- to the action.+onDatabase ::+ TestServer ->+ AdapterSettings ->+ (TestDatabase -> Connection -> Adapter Transaction PgError -> IO a) ->+ IO a+onDatabase server settings use =+ withTestDatabase server $ \database ->+ withConnection database (\connection -> use database connection (postgresAdapter settings connection))++-- | Runs the operation in a transaction that commits whatever the+-- operation returns, and gives back the operation's result.+committing :: Adapter tx ae -> (tx -> IO (Either ae a)) -> IO (Either ae a)+committing adapter operation = do+ result <- withTransaction adapter (fmap (Right @Void) . operation)+ pure $ case result of+ Left (Left err) -> Left err+ Left (Right impossible) -> absurd impossible+ Right outcome -> outcome++-- | Returns whether the operation failed because libpq lost the+-- connection.+isConnectionFailure :: Either PgError a -> Bool+isConnectionFailure (Left (ConnectionFailed _)) = True+isConnectionFailure _ = False++-- | Returns the SQLSTATE of a rejected statement.+sqlStateOf :: Either PgError a -> Maybe ByteString+sqlStateOf (Left (SqlFailed err)) = Just (sqlState err)+sqlStateOf _ = Nothing++-- | Creates the table of @dbmigrations@, with these rows.+seedVersion0Table :: Connection -> [Maybe Text] -> IO ()+seedVersion0Table connection identifiers = do+ _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text)"+ void (executeMany connection "INSERT INTO installed_migrations (migration_id) VALUES (?)" (map Only identifiers))++-- | The identifiers of a version 0 table, in order, with nulls last.+legacyRows :: Connection -> IO [Maybe Text]+legacyRows connection =+ map fromOnly <$> query_ connection "SELECT migration_id FROM installed_migrations ORDER BY migration_id"++-- | The columns of version 1, by name and type.+version1Columns :: [(Text, Text)]+version1Columns =+ [ ("migration_id", "text"),+ ("applied_at", "timestamp with time zone"),+ ("description", "text"),+ ("fingerprint", "text")+ ]++-- | Returns the names and types of the columns of the named table, in+-- order.+columnsOf :: Connection -> Text -> IO [(Text, Text)]+columnsOf connection table =+ query+ connection+ "SELECT attname::text, format_type(atttypid, atttypmod) FROM pg_attribute WHERE attrelid = to_regclass(?) AND attnum > 0 AND NOT attisdropped ORDER BY attnum"+ (Only table)++-- | Returns the comment of the named table.+commentOf :: Connection -> Text -> IO (Maybe Text)+commentOf connection table = do+ rows <- query connection "SELECT obj_description(to_regclass(?), 'pg_class')" (Only table)+ pure (case rows of [Only comment] -> comment; _ -> Nothing)++-- | Returns whether a table with this name exists on the search path.+tableExists :: Connection -> Text -> IO Bool+tableExists connection table =+ (== [Only True]) <$> query connection "SELECT to_regclass(quote_ident(?)) IS NOT NULL" (Only table)++-- | Returns the keys of the advisory locks that sessions hold in the+-- connection's database.+advisoryLocks :: Connection -> IO [Int64]+advisoryLocks connection =+ map fromOnly+ <$> query_+ connection+ "SELECT (classid::bigint << 32) | objid::bigint FROM pg_locks WHERE locktype = 'advisory' AND granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())"
+ test/Database/DagMigrations/PostgreSQL/SqlTextSpec.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE QuasiQuotes #-}++-- | The tests of the quasiquoter 'sqlText', and of the layout of its+-- quotations, which 'unquoteSqlText' reads.+module Database.DagMigrations.PostgreSQL.SqlTextSpec (spec) where++import Data.List qualified as List+import Data.Text (Text)+import Data.Text qualified as Text+import Database.DagMigrations.PostgreSQL.SqlText (SqlTextError (..), sqlText, unquoteSqlText)+import Hedgehog (Gen)+import Hedgehog.Gen qualified as Gen+import Hedgehog.Range qualified as Range+import Test.Hspec+import Test.Hspec.Hedgehog (forAll, hedgehog, (===))++spec :: Spec+spec = describe "sqlText" $ do+ it "gives the quoted lines without their shared indentation, each ending in a line feed" $+ [sqlText|+ CREATE TABLE saved_views (+ name text PRIMARY KEY,+ definition text NOT NULL DEFAULT '{"version": 1}'+ );++ COMMENT ON TABLE saved_views IS 'a \n stays a backslash and an n';+ |]+ `shouldBe` ( "CREATE TABLE saved_views (\n name text PRIMARY KEY,\n definition text NOT NULL DEFAULT '{\"version\": 1}'\n);\n\n"+ <> "COMMENT ON TABLE saved_views IS 'a \\n stays a backslash and an n';\n"+ )++ it "gives empty text for a quotation with no line between the opening line and the closing line" $+ unquoteSqlText "\n " `shouldBe` Right ""++ it "removes only the indentation that every line holds, and ignores the indentation of the closing line" $+ unquoteSqlText "\n SELECT\n 1\n " `shouldBe` Right "SELECT\n 1\n"++ it "keeps the spaces at the end of a line" $+ unquoteSqlText "\n SELECT 1 \n " `shouldBe` Right "SELECT 1 \n"++ it "gives an empty line for a line of spaces shorter than the indentation, and keeps the spaces beyond it" $+ unquoteSqlText "\n SELECT 1;\n \n\n \n SELECT 2;\n " `shouldBe` Right "SELECT 1;\n\n\n \nSELECT 2;\n"++ it "gives an empty line for each line when no line holds more than spaces" $+ unquoteSqlText "\n \n\n " `shouldBe` Right "\n\n"++ it "counts a tab as a character of the line, not as indentation" $+ unquoteSqlText "\n SELECT 1;\n\tSELECT 2;\n " `shouldBe` Right " SELECT 1;\n\tSELECT 2;\n"++ it "treats a carriage return before a line feed as part of the line break" $+ unquoteSqlText "\r\n SELECT 1;\r\n SELECT 2;\r\n " `shouldBe` Right "SELECT 1;\nSELECT 2;\n"++ it "accepts spaces after the opening of the quotation" $+ unquoteSqlText " \n SELECT 1;\n " `shouldBe` Right "SELECT 1;\n"++ it "refuses a quotation without a line break" $+ unquoteSqlText " SELECT 1; " `shouldBe` Left SqlTextOnOneLine++ it "refuses SQL on the line of the opening" $+ unquoteSqlText " SELECT 1;\n " `shouldBe` Left SqlTextAfterOpening++ it "refuses SQL on the line of the closing" $+ unquoteSqlText "\n SELECT 1;\n SELECT 2; " `shouldBe` Left SqlTextBeforeClosing++ it "gives back text whose lines end in line feeds, when one of its lines starts with a character other than a space" $ hedgehog $ do+ indentation <- forAll (Gen.int (Range.linear 0 16))+ flushLine <- forAll (Text.cons <$> Gen.filter (/= ' ') lineCharacter <*> lineText)+ otherLines <- forAll (Gen.list (Range.linear 0 12) lineText)+ position <- forAll (Gen.int (Range.linear 0 (length otherLines)))+ let (linesBefore, linesAfter) = List.splitAt position otherLines+ sqlLines = linesBefore <> [flushLine] <> linesAfter+ indent line = if Text.null line then line else Text.replicate indentation " " <> line+ quotation = Text.intercalate "\n" ([" "] <> map indent sqlLines <> [Text.replicate indentation " "])+ unquoteSqlText (Text.unpack quotation) === Right (foldMap (<> "\n") sqlLines)++-- | A character of a line of SQL: anything but a line feed or a carriage+-- return, with spaces, tabs, quotation marks, backslashes and the+-- characters of @|]@ often.+lineCharacter :: Gen Char+lineCharacter =+ Gen.frequency+ [ (3, Gen.element [' ', '\t', '|', ']', '\\', '"', '\'']),+ (10, Gen.alphaNum),+ (1, Gen.filter (`notElem` ['\n', '\r']) Gen.unicode)+ ]++-- | The text of a line of SQL.+lineText :: Gen Text+lineText = Gen.text (Range.linear 0 40) lineCharacter
+ test/Database/DagMigrations/PostgreSQL/TestDatabase.hs view
@@ -0,0 +1,66 @@+-- | Databases for the tests, on the server whose connection string+-- @scripts/with-test-postgres@ exports.+module Database.DagMigrations.PostgreSQL.TestDatabase+ ( TestServer,+ TestDatabase,+ findTestServer,+ withTestDatabase,+ withConnection,+ )+where++import Control.Exception (bracket, bracket_)+import Control.Monad (void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as Char8+import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Data.Text qualified as Text+import Database.PostgreSQL.Simple (Connection, Only (..), close, connectPostgreSQL, execute, execute_)+import Database.PostgreSQL.Simple.Types (Identifier (..))+import System.Environment (lookupEnv)+import System.Posix.Process (getProcessID)++-- | A server for tests, and the counter that names its databases.+data TestServer = TestServer+ { serverConnectionString :: ByteString,+ serverDatabases :: IORef Int+ }++-- | The connection string of one database on the server.+newtype TestDatabase = TestDatabase ByteString++-- | Reads the server's connection string from the environment variable+-- @DAG_MIGRATIONS_TEST_DATABASE@. The string is in libpq's keyword/value+-- form, not a URI, and names no database. Returns 'Nothing' when the+-- variable is not set.+findTestServer :: IO (Maybe TestServer)+findTestServer = do+ found <- lookupEnv "DAG_MIGRATIONS_TEST_DATABASE"+ traverse (\connectionString -> TestServer (Char8.pack connectionString) <$> newIORef 0) found++-- | Creates an empty database on the server, passes it to the action, and+-- drops the database when the action returns or throws. The drop ends any+-- session that is still open on the database. A database of the same name+-- that an earlier, killed run left behind is dropped first.+withTestDatabase :: TestServer -> (TestDatabase -> IO a) -> IO a+withTestDatabase server use = do+ number <- atomicModifyIORef' (serverDatabases server) (\next -> (next + 1, next))+ process <- getProcessID+ let name = "dag_migrations_test_" <> show process <> "_" <> show number+ identifier = Only (Identifier (Text.pack name))+ onServer = withConnection (databaseNamed "postgres")+ databaseNamed database =+ TestDatabase (serverConnectionString server <> " dbname=" <> Char8.pack database)+ create connection = do+ _ <- execute_ connection "SET client_min_messages = warning"+ _ <- execute connection "DROP DATABASE IF EXISTS ? WITH (FORCE)" identifier+ void (execute connection "CREATE DATABASE ?" identifier)+ bracket_+ (onServer create)+ (onServer (\connection -> void (execute connection "DROP DATABASE ? WITH (FORCE)" identifier)))+ (use (databaseNamed name))++-- | Opens a connection to the database, passes it to the action, and+-- closes it when the action returns or throws.+withConnection :: TestDatabase -> (Connection -> IO a) -> IO a+withConnection (TestDatabase connectionString) = bracket (connectPostgreSQL connectionString) close
+ test/Main.hs view
@@ -0,0 +1,24 @@+module Main (main) where++import Database.DagMigrations.Conformance (adapterConformance)+import Database.DagMigrations.PostgreSQL.ExampleSpec qualified as ExampleSpec+import Database.DagMigrations.PostgreSQL.SimpleSpec (postgresFixture, spec)+import Database.DagMigrations.PostgreSQL.SqlTextSpec qualified as SqlTextSpec+import Database.DagMigrations.PostgreSQL.TestDatabase (findTestServer)+import System.Exit (exitFailure)+import System.IO (hPutStrLn, stderr)+import Test.Hspec (hspec)++main :: IO ()+main = do+ found <- findTestServer+ case found of+ Nothing -> do+ hPutStrLn stderr "DAG_MIGRATIONS_TEST_DATABASE is not set. In the repository, run the tests through scripts/with-test-postgres, for example: scripts/with-test-postgres cabal test all"+ hPutStrLn stderr "Otherwise, set it to a libpq keyword/value connection string that names no database, for a role that can create databases, on a PostgreSQL 13 or later server that has a database named postgres."+ exitFailure+ Just server -> hspec $ do+ adapterConformance (postgresFixture server)+ spec server+ ExampleSpec.spec server+ SqlTextSpec.spec