-- | Running migrations against a database through an adapter. A project-- imports "Database.DagMigrations", which re-exports everything that this-- module exports.module Database.DagMigrations.Run ( Migrator (..), RunSettings (..), defaultRunSettings, FingerprintPolicy (..), migrate, Inspection (..), appliedSet, inspect, acceptFingerprints, )whereimport Control.Monad (unless)import Control.Monad.IO.Class (liftIO)import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE, withExceptT)import Data.Bifunctor (first)import Data.Foldable (for_, traverse_)import Data.List.NonEmpty qualified as NonEmptyimport Data.Map.Strict (Map)import Data.Map.Strict qualified as Mapimport Data.Maybe (isNothing)import Data.Set (Set)import Data.Set qualified as Setimport Data.Traversable (for)import Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..), BootstrapOutcome (..))import Database.DagMigrations.Error ( AcceptError (..), Direction (..), FingerprintMismatch, RunError (..), )import Database.DagMigrations.Graph (MigrationGraph, lookupMigration)import Database.DagMigrations.Migration ( Fingerprint, IdentifierCodec (..), Interpreter (..), Migration (..), )import Database.DagMigrations.Plan ( Plan (..), PlanOptions, Step (..), Target, checkFingerprints, defaultPlanOptions, plan, status, )import Database.DagMigrations.Progress (Progress (..), ProgressEvent (..))-- | What a run does when a recorded fingerprint differs from a registered-- one.data FingerprintPolicy = -- | The run fails, and changes nothing. MismatchIsError | -- | The run reports each mismatch through t'Progress', and continues. MismatchIsWarning deriving (Eq, Show)-- | The choices of a run.data RunSettings = RunSettings { runPlanOptions :: PlanOptions, runFingerprintPolicy :: FingerprintPolicy } deriving (Eq, Show)-- | The default settings, under which a run rejects unregistered applied-- identifiers and fingerprint mismatches.defaultRunSettings :: RunSettingsdefaultRunSettings = RunSettings {runPlanOptions = defaultPlanOptions, runFingerprintPolicy = MismatchIsError}-- | Everything that a run needs. A project builds one, and passes it to-- 'migrate', 'inspect', or 'acceptFingerprints'.data Migrator i m tx e ae = Migrator { migratorAdapter :: Adapter tx ae, migratorCodec :: IdentifierCodec i, migratorInterpreter :: Interpreter tx m e, migratorProgress :: Progress i, migratorSettings :: RunSettings, migratorGraph :: MigrationGraph i m }-- | Moves the database towards the target. While it holds the adapter's-- run lock, it reads the applied migrations, checks fingerprints and plans-- (writing nothing if either fails), bootstraps the tracking table, records-- fingerprints on first use, and runs each step in its own transaction.-- The first failed step ends the run; the steps before it stay committed.-- Under 'MismatchIsWarning', it reports each mismatch after it bootstraps-- the table. An exception that a migration throws, other than one of the-- adapter's database library, propagates after the adapter rolls back the-- step's transaction and releases the lock. An asynchronous exception,-- such as the one that 'System.Timeout.timeout' throws, propagates too, but-- may leave the session with a statement running or a transaction open;-- the caller then closes the session.migrate :: (Ord i) => Migrator i m tx e ae -> Direction -> Target i -> IO (Either (RunError i e ae) ())migrate migrator direction target = underRunLock migrator $ do recorded <- readDecoded migrator let (toRecord, mismatches) = checkFingerprints graph recorded case (runFingerprintPolicy settings, NonEmpty.nonEmpty mismatches) of (MismatchIsError, Just found) -> throwE (FingerprintsMismatched found) _ -> pure () Plan _ steps <- except (first PlanFailed (plan (runPlanOptions settings) graph (Map.keysSet recorded) direction target)) bootstrapAndReport migrator liftIO (traverse_ (report . FingerprintMismatchIgnored) mismatches) unless (Map.null toRecord) $ do writeFingerprints migrator (Map.map Just toRecord) liftIO (traverse_ (report . FingerprintRecorded) (Map.keys toRecord)) for_ steps (runStep migrator direction) where graph = migratorGraph migrator settings = migratorSettings migrator report = reportProgress (migratorProgress migrator)-- | What 'inspect' found.data Inspection i = Inspection { -- | Every registered migration in the order of the linear extension, -- with whether it is applied. inspectedStatus :: [(i, Bool)], -- | Applied identifiers that no registered migration has. inspectedUnregistered :: Set i, -- | Applied migrations whose recorded fingerprint differs from the -- registered one. inspectedMismatches :: [FingerprintMismatch i], -- | The fingerprints that a run would record on first use. inspectedToRecord :: Map i Fingerprint } deriving (Eq, Show)-- | The applied set that 'inspect' found: the applied registered-- migrations and the unregistered applied identifiers.appliedSet :: (Ord i) => Inspection i -> Set iappliedSet inspection = Set.union (inspectedUnregistered inspection) (Set.fromList [i | (i, True) <- inspectedStatus inspection])-- | Reads the database's state without the run lock, and writes nothing.-- Without the lock, its result may reflect a run in progress.inspect :: (Ord i) => Migrator i m tx e ae -> IO (Either (RunError i e ae) (Inspection i))inspect migrator = runExceptT $ do recorded <- readDecoded migrator let graph = migratorGraph migrator (toRecord, mismatches) = checkFingerprints graph recorded (statuses, unregistered) = status graph (Map.keysSet recorded) pure (Inspection statuses unregistered mismatches toRecord)-- | Records the registered fingerprint of each named migration, which must-- be registered and applied. While it holds the run lock, it reads the-- applied migrations, checks every name (writing nothing if any fails),-- bootstraps the tracking table, and records the fingerprints in one-- transaction. When the registered fingerprint is 'Nothing', it records-- null. Given an empty set, it returns 'Right' at once: it takes no lock,-- and reads and writes nothing.acceptFingerprints :: (Ord i) => Migrator i m tx e ae -> Set i -> IO (Either (RunError i e ae) ())acceptFingerprints migrator names | Set.null names = pure (Right ()) | otherwise = underRunLock migrator $ do recorded <- readDecoded migrator let problems = [ problem | name <- Set.toAscList names, Just problem <- [acceptProblem recorded name] ] traverse_ (throwE . CannotAccept) (NonEmpty.nonEmpty problems) bootstrapAndReport migrator writeFingerprints migrator ( Map.fromList [ (name, migrationFingerprint m) | name <- Set.toList names, Just m <- [lookupMigration name graph] ] ) where graph = migratorGraph migrator acceptProblem recorded name | isNothing (lookupMigration name graph) = Just (NotRegistered name) | not (Map.member name recorded) = Just (NotApplied name) | otherwise = Nothing-- Steps shared by the operations above.-- | Runs the action under the adapter's run lock, and reports a failure of-- the lock as 'AdapterFailed'.underRunLock :: Migrator i m tx e ae -> ExceptT (RunError i e ae) IO () -> IO (Either (RunError i e ae) ())underRunLock migrator action = either (Left . AdapterFailed) id <$> withRunLock (migratorAdapter migrator) (runExceptT action)-- | Reads the applied rows through the adapter, and decodes their-- identifiers with the codec. Returns each decoded identifier with its-- recorded fingerprint. Fails with 'UndecodableIdentifier' on the first row-- whose text the codec does not decode, and with 'NonCanonicalIdentifier'-- on the first row whose text the codec decodes to an identifier whose-- encoding is different text: the run later writes rows by the encoding,-- so the two must match. Writes nothing.readDecoded :: (Ord i) => Migrator i m tx e ae -> ExceptT (RunError i e ae) IO (Map i (Maybe Fingerprint))readDecoded migrator = do rows <- withExceptT AdapterFailed (ExceptT (readApplied (migratorAdapter migrator))) decoded <- for (Map.toList rows) $ \(raw, fingerprint) -> case decodeIdentifier codec raw of Nothing -> throwE (UndecodableIdentifier raw) Just i | encodeIdentifier codec i /= raw -> throwE (NonCanonicalIdentifier raw i) | otherwise -> pure (i, fingerprint) pure (Map.fromList decoded) where codec = migratorCodec migrator-- | Bootstraps the tracking table, and reports a creation or an upgrade.bootstrapAndReport :: Migrator i m tx e ae -> ExceptT (RunError i e ae) IO ()bootstrapAndReport migrator = do outcome <- withExceptT AdapterFailed (ExceptT (bootstrap (migratorAdapter migrator))) liftIO $ case outcome of AlreadyCurrent -> pure () Created version -> report (TrackingTableCreated version) Upgraded from to -> report (TrackingTableUpgraded from to) where report = reportProgress (migratorProgress migrator)-- | Records the given fingerprints in one transaction.writeFingerprints :: Migrator i m tx e ae -> Map i (Maybe Fingerprint) -> ExceptT (RunError i e ae) IO ()writeFingerprints migrator fingerprints = withExceptT (AdapterFailed . either id id) . ExceptT $ withTransaction adapter (\tx -> recordFingerprints adapter tx encoded) where adapter = migratorAdapter migrator encoded = Map.mapKeys (encodeIdentifier (migratorCodec migrator)) fingerprints-- | Runs one step and its bookkeeping in one transaction, and reports its-- start and its end.runStep :: Migrator i m tx e ae -> Direction -> Step i m -> ExceptT (RunError i e ae) IO ()runStep migrator direction (Step migration action) = do liftIO (report (MigrationStarted direction identifier)) result <- liftIO . withTransaction adapter $ \tx -> do outcome <- runInterpreter (migratorInterpreter migrator) tx action case outcome of Left err -> pure (Left (Right err)) Right () -> first Left <$> bookkeeping tx case result of Left (Left adapterError) -> throwE (MigrationFailed identifier direction (Left adapterError)) Left (Right failure) -> throwE (MigrationFailed identifier direction failure) Right () -> liftIO (report (MigrationFinished direction identifier)) where adapter = migratorAdapter migrator report = reportProgress (migratorProgress migrator) identifier = migrationId migration encoded = encodeIdentifier (migratorCodec migrator) identifier bookkeeping tx = case direction of Up -> recordApplied adapter tx (AppliedRow encoded (migrationDescription migration) (migrationFingerprint migration)) Down -> removeApplied adapter tx encoded