module Database.DagMigrations.RunSpec (spec) whereimport Control.Exception (ErrorCall (..), throwIO)import Control.Monad.IO.Class (liftIO)import Data.IORef (IORef, modifyIORef', newIORef, readIORef)import Data.List.NonEmpty (NonEmpty (..))import Data.List.NonEmpty qualified as NonEmptyimport Data.Map.Strict qualified as Mapimport Data.Set (Set)import Data.Set qualified as Setimport Data.Text (Text)import Data.Text qualified as Textimport Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..))import Database.DagMigrations.Errorimport Database.DagMigrations.FakeAdapterimport Database.DagMigrations.Gen (RegistrySpec, genDownSet, genRegistry, isDownSet, validated)import Database.DagMigrations.Graph (MigrationGraph, downSet, linearOrder, registeredIdentifiers, upSet, validate)import Database.DagMigrations.Migrationimport Database.DagMigrations.Plan (PlanOptions (..), Target (..), defaultPlanOptions, plan, planIdentifiers)import Database.DagMigrations.Progressimport Database.DagMigrations.Runimport Hedgehog (Gen, PropertyT, annotateShow, evalIO, failure)import Hedgehog.Gen qualified as Genimport Test.Hspecimport Test.Hspec.Hedgehog (assert, forAll, hedgehog, (===))-- | A fake database in the given state, a migrator over it with the given-- settings and registry, and the events that runs report.data Harness = Harness { harnessDatabase :: IORef FakeDatabase, harnessEvents :: IORef [ProgressEvent Text], harnessMigrator :: Migrator Text FakeM FakeTx Text FakeError }harness :: FakeDatabase -> RunSettings -> IdentifierCodec Text -> [Migration Text FakeM] -> IO Harnessharness = harnessWith noFaults-- | Like 'harness', with the given faults in the fake adapter.harnessWith :: FakeFaults -> FakeDatabase -> RunSettings -> IdentifierCodec Text -> [Migration Text FakeM] -> IO HarnessharnessWith faults initial settings codec registry = do databaseRef <- newIORef initial eventsRef <- newIORef [] graph <- either (fail . show) pure (validate registry) pure Harness { harnessDatabase = databaseRef, harnessEvents = eventsRef, harnessMigrator = Migrator { migratorAdapter = fakeAdapterWith faults databaseRef, migratorCodec = codec, migratorInterpreter = fakeInterpreter, migratorProgress = Progress (\event -> modifyIORef' eventsRef (event :)), migratorSettings = settings, migratorGraph = graph } }events :: Harness -> IO [ProgressEvent Text]events h = reverse <$> readIORef (harnessEvents h)database :: Harness -> IO FakeDatabasedatabase = readIORef . harnessDatabase-- | A tracking table that holds the given rows, and no other tables.withRows :: [(Text, Maybe Fingerprint)] -> FakeDatabasewithRows rows = emptyDatabase {fakeTrackingTable = Just (Map.fromList rows)}fingerprinted :: Fingerprint -> Migration Text FakeM -> Migration Text FakeMfingerprinted fingerprint m = m {migrationFingerprint = Just fingerprint}v1, v2 :: Fingerprintv1 = Fingerprint "v1"v2 = Fingerprint "v2"abc :: [Migration Text FakeM]abc = [tableMigration "a" [], tableMigration "b" ["a"], tableMigration "c" ["a"]]spec :: Specspec = do describe "migrate" $ do it "creates the tracking table and applies every migration in order" $ do h <- harness emptyDatabase defaultRunSettings textIdentifiers abc migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () database h `shouldReturn` FakeDatabase { fakeTrackingTable = Just (Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]), fakeTables = Set.fromList ["a", "b", "c"] } events h `shouldReturn` [ TrackingTableCreated (TrackingVersion 1), MigrationStarted Up "a", MigrationFinished Up "a", MigrationStarted Up "b", MigrationFinished Up "b", MigrationStarted Up "c", MigrationFinished Up "c" ] it "does nothing when every migration is applied" $ do h <- harness emptyDatabase defaultRunSettings textIdentifiers abc _ <- migrate (harnessMigrator h) Up AllMigrations settled <- database h h' <- harness settled defaultRunSettings textIdentifiers abc migrate (harnessMigrator h') Up AllMigrations `shouldReturn` Right () database h' `shouldReturn` settled events h' `shouldReturn` [] it "stops at a failed migration and keeps the steps before it" $ do let failing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> failWith "boom"} h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], failing] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (MigrationFailed "b" Up (Right "boom")) database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]} it "rolls back a migration that throws, and rethrows" $ do let throwing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> liftIO (throwIO (ErrorCall "thrown"))} h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], throwing] migrate (harnessMigrator h) Up AllMigrations `shouldThrow` (== ErrorCall "thrown") database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]} it "reports a failure of the database library as the adapter's error, and rolls back" $ do let failing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> liftIO (throwIO (FakeError "sql"))} h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], failing] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (MigrationFailed "b" Up (Left (FakeError "sql"))) database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]} it "rolls back a migration whose row the adapter cannot record" $ do let faults = noFaults {faultRecordApplied = Just (FakeError "record")} h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" []] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (MigrationFailed "a" Up (Left (FakeError "record"))) database h `shouldReturn` withRows [] it "reports a failure of the run lock, and writes nothing" $ do let faults = noFaults {faultLock = Just (FakeError "locked")} h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers abc migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (AdapterFailed (FakeError "locked")) database h `shouldReturn` emptyDatabase it "reports an upgrade of the tracking table" $ do let faults = noFaults {faultUpgradeFrom = Just (TrackingVersion 0)} h <- harnessWith faults (withRows []) defaultRunSettings textIdentifiers [tableMigration "a" []] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () events h `shouldReturn` [ TrackingTableUpgraded (TrackingVersion 0) (TrackingVersion 1), MigrationStarted Up "a", MigrationFinished Up "a" ] it "reverts what depends on the target, and keeps the target" $ do h <- harness emptyDatabase defaultRunSettings textIdentifiers abc _ <- migrate (harnessMigrator h) Up AllMigrations migrate (harnessMigrator h) Down (TargetMigration "a") `shouldReturn` Right () database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]} it "writes nothing when planning fails" $ do h <- harness emptyDatabase defaultRunSettings textIdentifiers abc migrate (harnessMigrator h) Up (TargetMigration "zz") `shouldReturn` Left (PlanFailed (UnknownTarget "zz" :| [])) database h `shouldReturn` emptyDatabase it "records no first-use fingerprint when planning fails" $ do let initial = withRows [("a", Nothing)] h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" [])] migrate (harnessMigrator h) Up (TargetMigration "zz") `shouldReturn` Left (PlanFailed (UnknownTarget "zz" :| [])) database h `shouldReturn` initial it "rejects a fingerprint mismatch by default, and writes nothing" $ do let initial = withRows [("a", Just v1)] h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v2 (tableMigration "a" []), tableMigration "b" ["a"]] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (FingerprintsMismatched (FingerprintMismatch "a" (Just v1) (Just v2) :| [])) database h `shouldReturn` initial it "reports a mismatch and continues under the warning policy" $ do let settings = defaultRunSettings {runFingerprintPolicy = MismatchIsWarning} h <- harness (withRows [("a", Just v1)]) settings textIdentifiers [fingerprinted v2 (tableMigration "a" []), tableMigration "b" ["a"]] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () events h `shouldReturn` [ FingerprintMismatchIgnored (FingerprintMismatch "a" (Just v1) (Just v2)), MigrationStarted Up "b", MigrationFinished Up "b" ] it "records a fingerprint on first use" $ do h <- harness (withRows [("a", Nothing)]) defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" [])] migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Just v1)]) events h `shouldReturn` [FingerprintRecorded "a"] it "fails on an identifier that the codec does not decode" $ do let rejecting = textIdentifiers {decodeIdentifier = \raw -> if raw == "bad" then Nothing else Just raw} h <- harness (withRows [("bad", Nothing)]) defaultRunSettings rejecting abc migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (UndecodableIdentifier "bad") it "fails on text that decodes to an identifier with a different encoding" $ do -- Rows are written by encoding, so a row named "A" could never be -- removed or updated through the identifier "a". This codec breaks the -- codec law for upper-case identifiers on purpose; the registry has -- none, and no project should copy it. let lowering = textIdentifiers {decodeIdentifier = Just . Text.toLower} initial = withRows [("A", Nothing)] h <- harness initial defaultRunSettings lowering abc migrate (harnessMigrator h) Down AllMigrations `shouldReturn` Left (NonCanonicalIdentifier "A" "a") database h `shouldReturn` initial it "leaves an allowed unregistered row in place" $ do let settings = defaultRunSettings {runPlanOptions = defaultPlanOptions {allowUnregisteredApplied = True}} h <- harness (withRows [("old", Nothing)]) settings textIdentifiers abc migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () database h `shouldReturn` (withRows [("old", Nothing), ("a", Nothing), ("b", Nothing), ("c", Nothing)]) { fakeTables = Set.fromList ["a", "b", "c"] } describe "migrate, as a property" $ do it "reaches S ∪ ↓t under Up, and S ∩ (P ∖ (↑t ∖ {t})) under Down" $ hedgehog $ do RunCase specs graph applied direction target <- genRunCase h <- evalIO (harness (seeded applied) defaultRunSettings textIdentifiers (tableRegistry specs)) result <- evalIO (migrate (harnessMigrator h) direction target) result === Right () db <- evalIO (database h) let expected = reachedSet graph applied direction target fmap Map.keysSet (fakeTrackingTable db) === Just expected fakeTables db === expected it "keeps the steps before a failed step, and leaves a down-set" $ hedgehog $ do RunCase specs graph applied direction target <- genRunCase steps <- case plan defaultPlanOptions graph applied direction target of Left errors -> annotateShow errors >> failure Right p -> pure (planIdentifiers p) case NonEmpty.nonEmpty (zip [0 :: Int ..] steps) of Nothing -> pure () Just indexed -> do (k, failing) <- forAll (Gen.element indexed) let registry = map (failingIn direction failing) (tableRegistry specs) h <- evalIO (harness (seeded applied) defaultRunSettings textIdentifiers registry) result <- evalIO (migrate (harnessMigrator h) direction target) result === Left (MigrationFailed failing direction (Right "boom")) db <- evalIO (database h) let done = Set.fromList (take k steps) expected = case direction of Up -> Set.union applied done Down -> Set.difference applied done fmap Map.keysSet (fakeTrackingTable db) === Just expected fakeTables db === expected assert (isDownSet graph (fakeTables db)) describe "acceptFingerprints" $ do it "records the registered fingerprint, so that the next run succeeds" $ do h <- harness (withRows [("a", Just v1)]) defaultRunSettings textIdentifiers [fingerprinted v2 (tableMigration "a" [])] acceptFingerprints (harnessMigrator h) (Set.fromList ["a"]) `shouldReturn` Right () fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Just v2)]) migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right () it "records null for a migration whose registered fingerprint is Nothing" $ do h <- harness (withRows [("a", Just v1)]) defaultRunSettings textIdentifiers [tableMigration "a" []] acceptFingerprints (harnessMigrator h) (Set.fromList ["a"]) `shouldReturn` Right () fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Nothing)]) it "returns at once for an empty set: it takes no lock and writes nothing" $ do let faults = noFaults {faultLock = Just (FakeError "locked")} h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers abc acceptFingerprints (harnessMigrator h) Set.empty `shouldReturn` Right () database h `shouldReturn` emptyDatabase it "rejects every name that is not registered or not applied" $ do h <- harness (withRows []) defaultRunSettings textIdentifiers abc acceptFingerprints (harnessMigrator h) (Set.fromList ["a", "zz"]) `shouldReturn` Left (CannotAccept (NotApplied "a" :| [NotRegistered "zz"])) database h `shouldReturn` withRows [] describe "inspect" $ do it "reports status and fingerprints, and writes nothing" $ do let initial = withRows [("a", Nothing)] h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" []), tableMigration "b" ["a"]] inspect (harnessMigrator h) `shouldReturn` Right Inspection { inspectedStatus = [("a", True), ("b", False)], inspectedUnregistered = Set.empty, inspectedMismatches = [], inspectedToRecord = Map.fromList [("a", v1)] } database h `shouldReturn` initial it "does not create the tracking table" $ do h <- harness emptyDatabase defaultRunSettings textIdentifiers abc _ <- inspect (harnessMigrator h) database h `shouldReturn` emptyDatabase it "reports applied identifiers that no registered migration has" $ do h <- harness (withRows [("a", Nothing), ("old", Nothing)]) defaultRunSettings textIdentifiers abc inspect (harnessMigrator h) `shouldReturn` Right Inspection { inspectedStatus = [("a", True), ("b", False), ("c", False)], inspectedUnregistered = Set.fromList ["old"], inspectedMismatches = [], inspectedToRecord = Map.empty } it "fails on an identifier that the codec does not decode" $ do let rejecting = textIdentifiers {decodeIdentifier = \raw -> if raw == "bad" then Nothing else Just raw} h <- harness (withRows [("bad", Nothing)]) defaultRunSettings rejecting abc inspect (harnessMigrator h) `shouldReturn` Left (UndecodableIdentifier "bad") describe "the fake adapter" $ do it "fails to record a row that exists, and changes nothing" $ do let initial = withRows [("a", Just v1)] ref <- newIORef initial let adapter = fakeAdapter ref committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "" Nothing)) `shouldReturn` Right (Left (FakeError "row exists: a")) readIORef ref `shouldReturn` initial it "fails to remove a row that does not exist, and changes nothing" $ do let initial = withRows [("a", Nothing)] ref <- newIORef initial let adapter = fakeAdapter ref committing adapter (\tx -> removeApplied adapter tx "b") `shouldReturn` Right (Left (FakeError "no row: b")) readIORef ref `shouldReturn` initial-- | Runs the operation in a transaction of the fake adapter, and commits-- whatever the operation returns, so that a test sees both the operation's-- result and every change that the operation made.committing :: Adapter FakeTx FakeError -> (FakeTx -> IO (Either FakeError ())) -> IO (Either (Either FakeError ()) (Either FakeError ()))committing adapter operation = withTransaction adapter (fmap Right . operation)-- | A generated registry, a down-set of it, a direction, and a target.data RunCase = RunCase RegistrySpec (MigrationGraph Text FakeM) (Set Text) Direction (Target Text)genRunCase :: PropertyT IO RunCasegenRunCase = do specs <- forAll genRegistry graph <- validated (tableRegistry specs) applied <- forAll (genDownSet graph) direction <- forAll Gen.enumBounded target <- forAll (genTarget graph) pure (RunCase specs graph applied direction target)-- | 'AllMigrations', or a registered migration when the graph has one.genTarget :: MigrationGraph Text m -> Gen (Target Text)genTarget graph = case linearOrder graph of [] -> pure AllMigrations ids -> Gen.choice [pure AllMigrations, TargetMigration <$> Gen.element ids]-- | The migrations of the spec, each of which creates the table with its-- own name, and drops it when reverted.tableRegistry :: RegistrySpec -> [Migration Text FakeM]tableRegistry = map (uncurry tableMigration)-- | A database to which runs applied exactly the given migrations: it has-- a tracking row with no fingerprint for each, and the table that each-- created.seeded :: Set Text -> FakeDatabaseseeded applied = FakeDatabase {fakeTrackingTable = Just (Map.fromSet (const Nothing) applied), fakeTables = applied}-- | The migration with its action for the direction replaced by one that-- changes its table and then fails with @"boom"@, when it has the given-- identifier. Any other migration is unchanged.failingIn :: Direction -> Text -> Migration Text FakeM -> Migration Text FakeMfailingIn direction name m | migrationId m /= name = m | otherwise = case direction of Up -> m {migrationUp = createTable name >> failWith "boom"} Down -> m {migrationDown = Just (dropTable name >> failWith "boom")}-- | The applied set after a successful run from the applied set S in the-- direction, towards the target t: S ∪ ↓t under 'Up', and-- S ∩ (P ∖ (↑t ∖ {t})) under 'Down'.reachedSet :: MigrationGraph Text m -> Set Text -> Direction -> Target Text -> Set TextreachedSet graph applied Up AllMigrations = Set.union applied (registeredIdentifiers graph)reachedSet graph applied Up (TargetMigration t) = Set.union applied (downSet graph t)reachedSet _ _ Down AllMigrations = Set.emptyreachedSet graph applied Down (TargetMigration t) = Set.intersection applied (Set.difference (registeredIdentifiers graph) (Set.delete t (upSet graph t)))