-- | Pure planning: which migrations a run applies or reverts, and in what-- order; which fingerprints it records or rejects; and the status of each-- migration. A project imports "Database.DagMigrations", which re-exports-- everything that this module exports.module Database.DagMigrations.Plan ( Target (..), PlanOptions (..), defaultPlanOptions, Step (..), Plan (..), planIdentifiers, plan, checkFingerprints, status, )whereimport Data.Either (partitionEithers)import Data.List.NonEmpty (NonEmpty)import Data.List.NonEmpty qualified as NonEmptyimport Data.Map.Strict (Map)import Data.Map.Strict qualified as Mapimport Data.Set (Set)import Data.Set qualified as Setimport Database.DagMigrations.Error (Direction (..), FingerprintMismatch (..), PlanError (..))import Database.DagMigrations.Graph ( MigrationGraph, downSet, inLinearOrder, linearOrder, lookupMigration, registeredIdentifiers, upSet, )import Database.DagMigrations.Migration (Fingerprint, Migration (..))-- | What a run moves the database towards.data Target i = -- | Every registered migration under 'Up'; no migration under 'Down'. AllMigrations | -- | Under 'Up', this migration and everything that it depends on. Under -- 'Down', the state in which nothing that depends on this migration is -- applied; the migration itself stays applied. TargetMigration i deriving (Eq, Show)-- | The caller's choices about what 'plan' accepts.newtype PlanOptions = PlanOptions { -- | Whether 'plan' accepts an applied identifier that no registered -- migration has. When it does, 'plan' leaves such identifiers out. -- Their dependencies are unknown, so 'plan' cannot check them: a 'Down' -- plan may revert a migration that an unregistered applied migration -- depends on, and 'Down' to 'AllMigrations' leaves every unregistered -- applied identifier applied. allowUnregisteredApplied :: Bool } deriving (Eq, Show)-- | The default options, under which 'plan' rejects unregistered applied-- identifiers.defaultPlanOptions :: PlanOptionsdefaultPlanOptions = PlanOptions {allowUnregisteredApplied = False}-- | One migration of a plan, and the action that the run performs for it.data Step i m = Step (Migration i m) (m ())-- | The steps of a run, in the order in which they run.data Plan i m = Plan Direction [Step i m]-- | The identifiers of a plan's steps, in order.planIdentifiers :: Plan i m -> [i]planIdentifiers (Plan _ steps) = [migrationId m | Step m _ <- steps]-- | Computes the plan that moves a database with the given applied set-- towards the target. It is pure. The steps of an 'Up' plan follow-- 'linearOrder'; the steps of a 'Down' plan follow its reverse.---- It reports errors in two phases. First, in this order, every unregistered-- applied identifier (unless the options allow them), every inconsistency,-- and an unknown target. Only when it finds none of these, and only for-- 'Down', it reports every migration to revert that has no down action, in-- the order of reversion.plan :: (Ord i) => PlanOptions -> MigrationGraph i m -> Set i -> Direction -> Target i -> Either (NonEmpty (PlanError i)) (Plan i m)plan options graph applied direction target = do failWith (unregisteredErrors <> inconsistencyErrors <> targetErrors) case direction of Up -> pure (Plan Up [Step m (migrationUp m) | m <- migrationsOf (inLinearOrder graph toApply)]) Down -> do let (irreversible, steps) = partitionEithers (map revertStep (migrationsOf (reverse (inLinearOrder graph toRevert)))) failWith irreversible pure (Plan Down steps) where registered = registeredIdentifiers graph registeredApplied = Set.intersection applied registered unregisteredErrors | allowUnregisteredApplied options = [] | otherwise = map UnregisteredApplied (Set.toAscList (Set.difference applied registered)) inconsistencyErrors = [ InconsistentApplied i d | i <- Set.toAscList registeredApplied, Just m <- [lookupMigration i graph], d <- Set.toAscList (migrationDependencies m), not (Set.member d applied) ] targetErrors = case target of TargetMigration t | not (Set.member t registered) -> [UnknownTarget t] _ -> [] toApply = case target of AllMigrations -> Set.difference registered applied TargetMigration t -> Set.difference (downSet graph t) applied toRevert = case target of AllMigrations -> registeredApplied TargetMigration t -> Set.intersection registeredApplied (Set.delete t (upSet graph t)) migrationsOf ids = [m | i <- ids, Just m <- [lookupMigration i graph]] revertStep m = maybe (Left (Irreversible (migrationId m))) (Right . Step m) (migrationDown m)-- | Succeeds on an empty list, and fails with the errors otherwise.failWith :: [e] -> Either (NonEmpty e) ()failWith = maybe (Right ()) Left . NonEmpty.nonEmpty-- | Compares the recorded fingerprints of applied migrations with the-- registered ones. Returns the fingerprints to record under trust on first-- use (recorded none, registered one), and every mismatch (recorded one,-- registered a different one or none). Unregistered identifiers are left-- out.checkFingerprints :: (Ord i) => MigrationGraph i m -> Map i (Maybe Fingerprint) -> (Map i Fingerprint, [FingerprintMismatch i])checkFingerprints graph recorded = (toRecord, mismatches) where pairs = [ (i, stored, migrationFingerprint m) | (i, stored) <- Map.toAscList recorded, Just m <- [lookupMigration i graph] ] toRecord = Map.fromList [(i, f) | (i, Nothing, Just f) <- pairs] mismatches = [ FingerprintMismatch i (Just stored) registeredFingerprint | (i, Just stored, registeredFingerprint) <- pairs, registeredFingerprint /= Just stored ]-- | Every registered identifier in the order of 'linearOrder', with whether-- it is applied, and the applied identifiers that are not registered.status :: (Ord i) => MigrationGraph i m -> Set i -> ([(i, Bool)], Set i)status graph applied = ( [(i, Set.member i applied) | i <- linearOrder graph], Set.difference applied (registeredIdentifiers graph) )