packages feed

dag-migrations-postgresql-simple-0.1.0.0 / src / Database / DagMigrations / PostgreSQL / Simple.hs

-- | 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 (..),  )whereimport 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 ByteStringimport Data.Foldable (traverse_)import Data.Int (Int64)import Data.Map.Strict (Map)import Data.Map.Strict qualified as Mapimport Data.Maybe (fromMaybe)import Data.Text (Text)import Data.Text qualified as Textimport Data.Text.Encoding qualified as Textimport Data.Text.Read qualified as Textimport Data.Word (Word64)import Database.DagMigrations.Adapter  ( Adapter (..),    AppliedRow (..),    BootstrapOutcome (..),    Fingerprint (..),    TrackingVersion (..),  )import Database.PostgreSQL.LibPQ qualified as PQimport Database.PostgreSQL.Simple  ( Connection,    FormatError,    Only (..),    QueryError,    ResultError,    SqlError,    execute,    execute_,    query,  )import Database.PostgreSQL.Simple.Internal qualified as Internalimport 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 :: AdapterSettingsdefaultAdapterSettings =  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 -> Int64defaultRunLockKey table =  fromIntegral (fnv1a64 (Text.encodeUtf8 ("dag-migrations:" <> quotedName table)))-- | The version of the tracking table that 'postgresAdapter' creates.currentTrackingVersion :: TrackingVersioncurrentTrackingVersion = 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 -> ConnectiontransactionConnection (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 PgErrorpostgresAdapter 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 Boolunlock 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 BootstrapOutcomebootstrapTable 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 TableVersiontableVersion 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 TableVersionclassifyTable False _ _ = Left NotATableclassifyTable 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 Version0classifyTable True Nothing columns = Left (UnrecognizedTrackingTable columns)-- | The comment that marks a table of this version.versionComment :: TrackingVersion -> TextversionComment (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 TrackingVersioncommentVersion 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 -> TextquotedName (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 -> Word64fnv1a64 = ByteString.foldl' step 0xcbf29ce484222325  where    step hash byte = (hash `xor` fromIntegral byte) * 0x100000001b3-- | The text of a fingerprint.fingerprintText :: Fingerprint -> TextfingerprintText (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 aliftPg = ExceptT . catchPg