dag-migrations-conformance (empty) → 0.1.0.0
raw patch · 6 files changed · show whitespace changes · browse dag-migrations-conformance-0.1.0.0
+762/−0 lines, 6 filesdep +basedep +containersdep +dag-migrations
Dependencies added: base, containers, dag-migrations, dag-migrations-conformance, hspec, text, transformers
Files
- CHANGELOG.md +9/−0
- LICENSE +21/−0
- dag-migrations-conformance.cabal +58/−0
- src/Database/DagMigrations/Conformance.hs +474/−0
- src/Database/DagMigrations/Conformance/InMemory.hs +192/−0
- test/Main.hs +8/−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-conformance.cabal view
@@ -0,0 +1,58 @@+cabal-version: 3.0+name: dag-migrations-conformance+version: 0.1.0.0+synopsis: The conformance test suite for dag-migrations adapters+description:+ A test suite that every adapter for dag-migrations runs against its+ database, to show that it satisfies the adapter contract, and an+ in-memory reference adapter that passes it.++category: Database, Testing+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+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-conformance++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.Conformance+ Database.DagMigrations.Conformance.InMemory++ build-depends:+ , base >=4.18 && <5+ , containers >=0.6 && <0.9+ , dag-migrations ==0.1.*+ , hspec >=2.11 && <2.12+ , text >=2.0 && <2.2+ , transformers >=0.6 && <0.7++test-suite dag-migrations-conformance-test+ import: language+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , base+ , dag-migrations-conformance+ , hspec
+ src/Database/DagMigrations/Conformance.hs view
@@ -0,0 +1,474 @@+-- | A test suite that every adapter runs against its database, to show that+-- it satisfies the adapter contract of "Database.DagMigrations.Adapter".+-- An adapter's test suite builds a t'Fixture' for its database, and runs+-- 'adapterConformance' on it with hspec.+module Database.DagMigrations.Conformance+ ( Fixture (..),+ adapterConformance,+ )+where++import Control.Concurrent (forkFinally, threadDelay)+import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, readMVar, tryPutMVar, tryReadMVar)+import Control.Exception (ErrorCall (..), SomeException, finally, throwIO)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Class (lift)+import Control.Monad.Trans.Except (ExceptT (..), runExceptT, throwE)+import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)+import Data.Either (isLeft)+import Data.Foldable (traverse_)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.List.NonEmpty (NonEmpty (..))+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Void (Void, absurd)+import Database.DagMigrations+import Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..), BootstrapOutcome (..))+import System.Timeout (timeout)+import Test.Hspec++-- | The operations that the suite needs from the database under test. @db@+-- is a handle to one database, @tx@ is the adapter's transaction value, and+-- @ae@ is the adapter's error type. The suite names its markers with short+-- lowercase ASCII words, such as @a@.+data Fixture db tx ae = Fixture+ { -- | Creates an empty database, passes it to the action, and removes the+ -- database when the action returns or throws.+ withEmptyDatabase :: forall a. (db -> IO a) -> IO a,+ -- | Opens a session on the database, passes the adapter over it to the+ -- action, and closes the session when the action returns or throws.+ -- The suite uses sessions from separate calls at the same time, on+ -- separate threads, to test the run lock. A session sets no limit on+ -- the wait for the run lock, such as PostgreSQL's @lock_timeout@, that+ -- is shorter than the suite's waits of five seconds.+ withAdapter :: forall a. db -> (Adapter tx ae -> IO a) -> IO a,+ -- | Creates the marker with this name inside the transaction. For an+ -- SQL database, a marker is a table. When the marker exists, the call+ -- throws the exception of the adapter's database library.+ createMarker :: tx -> Text -> IO (),+ -- | Drops the marker with this name inside the transaction. When the+ -- marker does not exist, the call throws the exception of the+ -- adapter's database library.+ dropMarker :: tx -> Text -> IO (),+ -- | Returns whether the database holds the marker with this name in+ -- committed state, as another session sees it.+ markerExists :: db -> Text -> IO Bool,+ -- | Throws the exception of the adapter's database library inside the+ -- transaction, as the library does when the database rejects a+ -- statement.+ failInLibrary :: tx -> IO (),+ -- | Commits a @dbmigrations@ tracking table that holds these rows, in a+ -- database that has no tracking table. 'Nothing' means that the+ -- adapter does not recognize that table, and the suite skips its+ -- version 0 cases.+ seedVersion0 :: Maybe (db -> [Text] -> IO ())+ }++-- | The monad of the suite's test migrations: they read the transaction,+-- and fail with text.+type ConformanceM tx = ReaderT tx (ExceptT Text IO)++-- | The specification that every adapter must pass. Each case calls+-- 'withEmptyDatabase' once. Run the cases one at a time, not in hspec's+-- parallel mode. The lock cases need the adapter's blocking calls to let+-- other Haskell threads run, so build the test suite with @-threaded@. The+-- suite waits at most five seconds for any session.+adapterConformance :: (Eq ae, Show ae) => Fixture db tx ae -> Spec+adapterConformance fixture = describe "adapter conformance" $ do+ describe "bootstrap" $ do+ it "creates the tracking table, and then does nothing" $+ session fixture $ \_ adapter -> do+ created <- bootstrap adapter+ created `shouldSatisfy` isCreated+ bootstrap adapter `shouldReturn` Right AlreadyCurrent++ it "reads nothing, and creates nothing, before the table exists" $+ session fixture $ \_ adapter -> do+ readApplied adapter `shouldReturn` Right Map.empty+ run <- newRun adapter defaultRunSettings (abc fixture)+ fmap appliedSet <$> inspect (runMigrator run) `shouldReturn` Right Set.empty+ -- 'Created' shows that neither call created the table.+ created <- bootstrap adapter+ created `shouldSatisfy` isCreated++ describe "migrate" $ do+ it "applies every migration, and records a row for each" $+ session fixture $ \db adapter -> do+ run <- newRun adapter defaultRunSettings (abc fixture)+ migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()+ Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a", "b", "c"]+ traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [True, True, True]++ it "reverts what depends on the target, and keeps the target" $+ session fixture $ \db adapter -> do+ run <- newRun adapter defaultRunSettings (abc fixture)+ migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()+ migrate (runMigrator run) Down (TargetMigration "a") `shouldReturn` Right ()+ Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]+ traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [True, False, False]++ describe "atomicity" $ do+ it "rolls back a migration that fails, and keeps the steps before it" $+ session fixture $ \db adapter -> do+ let failing = (markerMigration fixture "b" ["a"]) {migrationUp = mark fixture "b" >> lift (throwE "boom")}+ run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], failing]+ migrate (runMigrator run) Up AllMigrations+ `shouldReturn` Left (MigrationFailed "b" Up (Right "boom"))+ commitNothing adapter+ Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]+ traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]++ it "rolls back a failure of the database library, and reports the adapter's error" $+ session fixture $ \db adapter -> do+ let failing =+ (markerMigration fixture "b" ["a"])+ { migrationUp = mark fixture "b" >> (ask >>= liftIO . failInLibrary fixture)+ }+ run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], failing]+ result <- migrate (runMigrator run) Up AllMigrations+ result `shouldSatisfy` isAdapterFailureOf "b"+ commitNothing adapter+ Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]+ traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]++ it "rolls back and rethrows any other exception, and releases the lock" $+ session fixture $ \db adapter -> do+ let throwing =+ (markerMigration fixture "b" ["a"])+ { migrationUp = mark fixture "b" >> liftIO (throwIO (ErrorCall "thrown"))+ }+ run <- newRun adapter defaultRunSettings [markerMigration fixture "a" [], throwing]+ migrate (runMigrator run) Up AllMigrations `shouldThrow` (== ErrorCall "thrown")+ commitNothing adapter+ Map.keysSet <$> applied adapter `shouldReturn` Set.fromList ["a"]+ traverse (markerExists fixture db) ["a", "b"] `shouldReturn` [True, False]+ released <- timeout lockWait (withAdapter fixture db (\other -> withRunLock other (pure ())))+ released `shouldBe` Just (Right ())++ describe "the run lock" $ do+ it "keeps a second session waiting until the first releases the lock" $+ withEmptyDatabase fixture $ \db -> do+ entered <- newEmptyMVar+ attempting <- newEmptyMVar+ release <- newEmptyMVar+ firstDone <- newEmptyMVar+ secondDone <- newEmptyMVar+ let holder = withAdapter fixture db $ \first ->+ withRunLock first (putMVar entered () >> readMVar release)+ contender = withAdapter fixture db $ \second ->+ putMVar attempting () >> withRunLock second (pure ())+ -- Lets the first session finish, and waits for both sessions+ -- to close, so that the database can be removed.+ finish = do+ _ <- tryPutMVar release ()+ traverse_ (timeout lockWait . readMVar) [firstDone, secondDone]+ flip finally finish $ do+ _ <- forkFinally holder (putMVar firstDone)+ timeout lockWait (readMVar entered) `shouldReturn` Just ()+ _ <- forkFinally contender (putMVar secondDone)+ timeout lockWait (readMVar attempting) `shouldReturn` Just ()+ threadDelay contentionDelay+ early <- tryReadMVar secondDone+ traverse_ (expectationFailure . contentionFailure) early+ _ <- tryPutMVar release ()+ awaitSession firstDone+ awaitSession secondDone++ it "frees the lock after an interrupted wait, once that session closes" $+ withEmptyDatabase fixture $ \db -> do+ entered <- newEmptyMVar+ release <- newEmptyMVar+ firstDone <- newEmptyMVar+ interruptedDone <- newEmptyMVar+ let holder = withAdapter fixture db $ \first ->+ withRunLock first (putMVar entered () >> readMVar release)+ interrupted = withAdapter fixture db $ \second ->+ timeout contentionDelay (withRunLock second (pure ()))+ -- Lets the first session finish, and waits for both sessions+ -- to close, so that the database can be removed.+ finish = do+ _ <- tryPutMVar release ()+ _ <- timeout lockWait (readMVar firstDone)+ timeout lockWait (readMVar interruptedDone)+ flip finally finish $ do+ _ <- forkFinally holder (putMVar firstDone)+ timeout lockWait (readMVar entered) `shouldReturn` Just ()+ _ <- forkFinally interrupted (putMVar interruptedDone)+ outcome <- timeout lockWait (readMVar interruptedDone)+ traverse_ expectationFailure (interruptionFailure outcome)+ _ <- tryPutMVar release ()+ awaitSession firstDone+ third <- timeout lockWait (withAdapter fixture db (\other -> withRunLock other (pure ())))+ third `shouldBe` Just (Right ())++ describe "rows" $ do+ it "fails to record a row that exists, and changes nothing" $+ session fixture $ \_ adapter -> do+ _ <- bootstrap adapter+ recordRow adapter (markerRow "a" Nothing) `shouldReturn` Right ()+ again <- recordRow adapter (markerRow "a" (Just (Fingerprint "other")))+ again `shouldSatisfy` isLeft+ applied adapter `shouldReturn` Map.fromList [("a", Nothing)]++ it "fails to remove a row that does not exist, and changes nothing" $+ session fixture $ \_ adapter -> do+ _ <- bootstrap adapter+ recordRow adapter (markerRow "b" Nothing) `shouldReturn` Right ()+ removed <- committing adapter (\tx -> removeApplied adapter tx "a")+ removed `shouldSatisfy` isLeft+ applied adapter `shouldReturn` Map.fromList [("b", Nothing)]++ it "undoes the row changes of a transaction that rolls back" $+ session fixture $ \_ adapter -> do+ _ <- bootstrap adapter+ recordRow adapter (markerRow "a" Nothing) `shouldReturn` Right ()+ rollingBack+ adapter+ ( \tx -> runExceptT $ do+ ExceptT (recordApplied adapter tx (markerRow "b" Nothing))+ ExceptT (recordFingerprints adapter tx (Map.fromList [("a", Just (Fingerprint "v1"))]))+ ExceptT (removeApplied adapter tx "a")+ )+ `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Nothing)]++ describe "fingerprints" $+ it "records fingerprints, rejects a mismatch, and accepts a change" $+ session fixture $ \_ adapter -> do+ let v1 = Fingerprint "v1"+ v2 = Fingerprint "v2"+ vb = Fingerprint "vb"+ -- Migration a has the given fingerprint, and b always has vb.+ runWith fingerprintA =+ newRun+ adapter+ defaultRunSettings+ [ (markerMigration fixture "a" []) {migrationFingerprint = fingerprintA},+ (markerMigration fixture "b" []) {migrationFingerprint = Just vb}+ ]+ plain <- runWith Nothing+ migrate (runMigrator plain) Up AllMigrations `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]+ first <- runWith (Just v1)+ migrate (runMigrator first) Up AllMigrations `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Just v1), ("b", Just vb)]+ second <- runWith (Just v2)+ migrate (runMigrator second) Up AllMigrations+ `shouldReturn` Left (FingerprintsMismatched (FingerprintMismatch "a" (Just v1) (Just v2) :| []))+ applied adapter `shouldReturn` Map.fromList [("a", Just v1), ("b", Just vb)]+ acceptFingerprints (runMigrator second) (Set.fromList ["a"]) `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Just v2), ("b", Just vb)]+ cleared <- runWith Nothing+ acceptFingerprints (runMigrator cleared) (Set.fromList ["a"]) `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]+ committing adapter (\tx -> recordFingerprints adapter tx (Map.fromList [("z", Just v1)]))+ `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Just vb)]++ traverse_ (version0 fixture) (seedVersion0 fixture)++-- | The cases for an adapter that recognizes the @dbmigrations@ table. They+-- read the table only through the adapter, which leaves out the row+-- @root@, so they cannot show that a failed upgrade kept that row. The+-- adapter's own tests check it.+version0 :: (Eq ae, Show ae) => Fixture db tx ae -> (db -> [Text] -> IO ()) -> Spec+version0 fixture seed = describe "version 0" $ do+ it "reads a version 0 table without its root row" $+ withEmptyDatabase fixture $ \db -> do+ seed db ["root", "a"]+ withAdapter fixture db $ \adapter ->+ applied adapter `shouldReturn` Map.fromList [("a", Nothing)]++ it "upgrades a version 0 table to the current version, and keeps its rows without root" $+ withEmptyDatabase fixture $ \db -> do+ seed db ["root", "a", "b"]+ withAdapter fixture db $ \adapter -> do+ run <- newRun adapter defaultRunSettings (abc fixture)+ migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()+ firstEvent <- take 1 <$> readEvents run+ map isUpgradeFromVersion0 firstEvent `shouldBe` [True]+ applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]+ traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [False, False, True]+ bootstrap adapter `shouldReturn` Right AlreadyCurrent+ again <- recordRow adapter (markerRow "a" Nothing)+ again `shouldSatisfy` isLeft+ committing adapter (\tx -> recordFingerprints adapter tx (Map.fromList [("a", Just (Fingerprint "v1"))]))+ `shouldReturn` Right ()+ applied adapter+ `shouldReturn` Map.fromList [("a", Just (Fingerprint "v1")), ("b", Nothing), ("c", Nothing)]++ it "upgrades a version 0 table that holds identifiers in several rows, and keeps one row for each identifier" $+ withEmptyDatabase fixture $ \db -> do+ seed db ["root", "a", "b", "a", "root"]+ withAdapter fixture db $ \adapter -> do+ run <- newRun adapter defaultRunSettings (abc fixture)+ migrate (runMigrator run) Up AllMigrations `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]+ traverse (markerExists fixture db) ["a", "b", "c"] `shouldReturn` [False, False, True]+ again <- recordRow adapter (markerRow "a" Nothing)+ again `shouldSatisfy` isLeft+ committing adapter (\tx -> removeApplied adapter tx "a") `shouldReturn` Right ()+ applied adapter `shouldReturn` Map.fromList [("b", Nothing), ("c", Nothing)]++-- | A migrator over an adapter, and the events that its runs report, in+-- the order of reporting.+data Run tx ae = Run+ { runMigrator :: Migrator Text (ConformanceM tx) tx Text ae,+ runEvents :: IORef [ProgressEvent Text]+ }++-- | Validates the registry, and builds a migrator over the adapter that+-- records its events. Throws an 'IOError', which fails the test, when the+-- registry is not valid.+newRun ::+ Adapter tx ae ->+ RunSettings ->+ [Migration Text (ConformanceM tx)] ->+ IO (Run tx ae)+newRun adapter settings registry = do+ events <- newIORef []+ graph <- either (ioError . userError . show) pure (validate registry)+ pure+ Run+ { runMigrator =+ Migrator+ { migratorAdapter = adapter,+ migratorCodec = textIdentifiers,+ migratorInterpreter = Interpreter (\tx action -> runExceptT (runReaderT action tx)),+ migratorProgress = Progress (\event -> modifyIORef' events (event :)),+ migratorSettings = settings,+ migratorGraph = graph+ },+ runEvents = events+ }++-- | The events of a run's migrator, in the order of reporting.+readEvents :: Run tx ae -> IO [ProgressEvent Text]+readEvents run = reverse <$> readIORef (runEvents run)++-- | Opens a session on a new empty database.+session :: Fixture db tx ae -> (db -> Adapter tx ae -> IO a) -> IO a+session fixture use = withEmptyDatabase fixture $ \db -> withAdapter fixture db (use db)++-- | The applied rows, or a test failure that shows the adapter's error.+applied :: (Show ae) => Adapter tx ae -> IO (Map Text (Maybe Fingerprint))+applied adapter =+ readApplied adapter >>= either (\err -> expectationFailure (show err) >> pure Map.empty) pure++-- | 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++-- | Runs the operation in a transaction that rolls back whatever the+-- operation returns, and gives back the operation's result.+rollingBack :: Adapter tx ae -> (tx -> IO (Either ae a)) -> IO (Either ae a)+rollingBack adapter operation = do+ result <- withTransaction adapter (fmap (Left @_ @Void) . operation)+ pure $ case result of+ Left (Left err) -> Left err+ Left (Right outcome) -> outcome+ Right impossible -> absurd impossible++-- | Commits an empty transaction in the session, and fails the test when+-- the adapter reports an error. When the adapter left an earlier+-- transaction open instead of rolling it back, this commit makes that+-- transaction's writes visible to the checks that follow.+commitNothing :: (Eq ae, Show ae) => Adapter tx ae -> Expectation+commitNothing adapter = committing adapter (\_ -> pure (Right ())) `shouldReturn` Right ()++-- | Records the row in a transaction of its own.+recordRow :: Adapter tx ae -> AppliedRow -> IO (Either ae ())+recordRow adapter row = committing adapter (\tx -> recordApplied adapter tx row)++-- | The row of the marker migration with this name.+markerRow :: Text -> Maybe Fingerprint -> AppliedRow+markerRow name = AppliedRow name ("marker " <> name)++-- | Waits for a session of the lock test to finish. Fails the test when the+-- session does not finish in time, when it threw, or when the run lock+-- returned the adapter's error.+awaitSession :: (Show ae) => MVar (Either SomeException (Either ae ())) -> Expectation+awaitSession done = do+ outcome <- timeout lockWait (readMVar done)+ case outcome of+ Nothing -> expectationFailure "the session did not finish in time"+ Just finished -> traverse_ expectationFailure (sessionFailure finished)++-- | Describes a session of the lock test that threw, or whose run lock+-- returned the adapter's error. Returns 'Nothing' for a session that took+-- and released the lock.+sessionFailure :: (Show ae) => Either SomeException (Either ae ()) -> Maybe String+sessionFailure (Left err) = Just ("the session threw " <> show err)+sessionFailure (Right (Left err)) = Just ("the run lock failed with " <> show err)+sessionFailure (Right (Right ())) = Nothing++-- | Describes a session whose wait for the lock should have been+-- interrupted. Returns 'Nothing' when the wait was interrupted, and the+-- session closed, in time.+interruptionFailure :: (Show ae) => Maybe (Either SomeException (Maybe (Either ae ()))) -> Maybe String+interruptionFailure Nothing = Just "the interrupted session did not finish in time"+interruptionFailure (Just (Left err)) = Just ("the interrupted session threw " <> show err)+interruptionFailure (Just (Right (Just taken))) =+ Just ("the wait for the lock returned " <> show taken <> " while another session held it")+interruptionFailure (Just (Right Nothing)) = Nothing++-- | Describes a second session that finished while the first session held+-- the lock.+contentionFailure :: (Show ae) => Either SomeException (Either ae ()) -> String+contentionFailure finished =+ fromMaybe "the second session took the lock while the first held it" (sessionFailure finished)++-- | Migrations @a@, @b@ and @c@, where @b@ and @c@ depend on @a@.+abc :: Fixture db tx ae -> [Migration Text (ConformanceM tx)]+abc fixture =+ [markerMigration fixture "a" [], markerMigration fixture "b" ["a"], markerMigration fixture "c" ["a"]]++-- | A migration that creates the marker with its own name, and drops it+-- when reverted.+markerMigration :: Fixture db tx ae -> Text -> [Text] -> Migration Text (ConformanceM tx)+markerMigration fixture name dependencies =+ Migration+ { migrationId = name,+ migrationDependencies = Set.fromList dependencies,+ migrationDescription = "marker " <> name,+ migrationFingerprint = Nothing,+ migrationUp = mark fixture name,+ migrationDown = Just (ask >>= \tx -> liftIO (dropMarker fixture tx name))+ }++-- | Creates the marker with this name in the migration's transaction.+mark :: Fixture db tx ae -> Text -> ConformanceM tx ()+mark fixture name = ask >>= \tx -> liftIO (createMarker fixture tx name)++-- | Returns whether 'bootstrap' created the tracking table.+isCreated :: Either ae BootstrapOutcome -> Bool+isCreated (Right (Created _)) = True+isCreated _ = False++-- | Returns whether the event reports an upgrade of a version 0 table.+isUpgradeFromVersion0 :: ProgressEvent Text -> Bool+isUpgradeFromVersion0 (TrackingTableUpgraded (TrackingVersion 0) _) = True+isUpgradeFromVersion0 _ = False++-- | Returns whether the run failed in the given migration's @Up@ step with+-- the adapter's error.+isAdapterFailureOf :: Text -> Either (RunError Text Text ae) () -> Bool+isAdapterFailureOf identifier (Left (MigrationFailed failed Up (Left _))) = failed == identifier+isAdapterFailureOf _ _ = False++-- | How long the lock tests wait for a thread, in microseconds.+lockWait :: Int+lockWait = 5000000++-- | How long the lock test lets the second session wait, in microseconds.+contentionDelay :: Int+contentionDelay = 200000
+ src/Database/DagMigrations/Conformance/InMemory.hs view
@@ -0,0 +1,192 @@+-- | An adapter over a database held in memory, which satisfies the whole+-- adapter contract of "Database.DagMigrations.Adapter", and the t'Fixture'+-- that runs the conformance suite against it. The conformance package's own+-- tests use it to show that the suite passes on a correct adapter. The+-- adapter keeps no description and no applied time for a row, because no+-- operation of t'Adapter' reads them.+module Database.DagMigrations.Conformance.InMemory+ ( InMemoryDatabase,+ newInMemoryDatabase,+ InMemoryTx,+ InMemoryError (..),+ inMemoryAdapter,+ inMemoryFixture,+ )+where++import Control.Concurrent.MVar (MVar, newMVar, withMVar)+import Control.Exception (Exception, throwIO, try)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Set (Set)+import Data.Set qualified as Set+import Data.Text (Text)+import Database.DagMigrations.Adapter+ ( Adapter (..),+ AppliedRow (..),+ BootstrapOutcome (..),+ Fingerprint,+ TrackingVersion (..),+ )+import Database.DagMigrations.Conformance (Fixture (..))++-- | The tracking table, in the version that the database holds.+data TrackingTable+ = -- | The table does not exist.+ NoTable+ | -- | The table of @dbmigrations@: one identifier per row, which may+ -- repeat, and a row @root@ for its bootstrap migration.+ Version0 [Text]+ | -- | The current table: one row per identifier, with its fingerprint.+ Version1 (Map Text (Maybe Fingerprint))++-- | The committed contents of a database.+data DatabaseState = DatabaseState+ { stateTable :: TrackingTable,+ -- | The markers that test migrations created.+ stateMarkers :: Set Text+ }++-- | A database held in memory, with the lock that keeps two runs apart.+data InMemoryDatabase = InMemoryDatabase+ { databaseState :: IORef DatabaseState,+ databaseLock :: MVar ()+ }++-- | A transaction: a working copy of the database's state, which the+-- adapter writes back when the transaction commits.+newtype InMemoryTx = InMemoryTx (IORef DatabaseState)++-- | The errors of the in-memory database. The fixture's 'failInLibrary',+-- 'createMarker' and 'dropMarker' throw them inside a transaction, as a+-- database library throws when the database rejects a statement, and+-- 'withTransaction' returns a thrown error as the adapter's error. The+-- adapter's other operations return them.+data InMemoryError+ = -- | 'failInLibrary' throws this.+ LibraryFailure Text+ | -- | 'createMarker' found a marker with this name.+ MarkerExists Text+ | -- | 'dropMarker' found no marker with this name.+ NoMarker Text+ | -- | 'recordApplied' found a row for this identifier.+ RowExists Text+ | -- | 'removeApplied' found no row for this identifier.+ NoRow Text+ | -- | An operation that needs the current tracking table found another+ -- version, or none.+ NoCurrentTrackingTable+ deriving (Eq, Show)++instance Exception InMemoryError++-- | Creates an empty database: no tracking table, and no markers.+newInMemoryDatabase :: IO InMemoryDatabase+newInMemoryDatabase =+ InMemoryDatabase+ <$> newIORef (DatabaseState {stateTable = NoTable, stateMarkers = Set.empty})+ <*> newMVar ()++-- | Returns an adapter over the database. Every adapter over the same+-- database shares its lock, so two adapters behave like two sessions. Only+-- the run lock keeps transactions apart: a transaction writes back its+-- whole working copy when it commits, so of two transactions that run at+-- once without the lock, one loses its writes.+inMemoryAdapter :: InMemoryDatabase -> Adapter InMemoryTx InMemoryError+inMemoryAdapter database =+ Adapter+ { withRunLock = \action -> Right <$> withMVar (databaseLock database) (const action),+ readApplied = Right . appliedRows . stateTable <$> readIORef (databaseState database),+ bootstrap = atomicModifyIORef' (databaseState database) bootstrapState,+ withTransaction = \action -> do+ working <- newIORef =<< readIORef (databaseState database)+ result <- try @InMemoryError (action (InMemoryTx working))+ case result of+ Left err -> pure (Left (Left err))+ Right (Left err) -> pure (Left (Right err))+ Right (Right a) -> do+ writeIORef (databaseState database) =<< readIORef working+ pure (Right a),+ recordApplied = \tx row ->+ changeRows tx $ \rows ->+ if Map.member (appliedIdentifier row) rows+ then Left (RowExists (appliedIdentifier row))+ else Right (Map.insert (appliedIdentifier row) (appliedFingerprint row) rows),+ removeApplied = \tx identifier ->+ changeRows tx $ \rows ->+ if Map.member identifier rows+ then Right (Map.delete identifier rows)+ else Left (NoRow identifier),+ recordFingerprints = \tx fingerprints ->+ changeRows tx $ \rows -> Right (Map.union (Map.intersection fingerprints rows) rows)+ }++-- | The conformance suite runs against in-memory databases through this+-- t'Fixture'.+inMemoryFixture :: Fixture InMemoryDatabase InMemoryTx InMemoryError+inMemoryFixture =+ Fixture+ { withEmptyDatabase = \use -> newInMemoryDatabase >>= use,+ withAdapter = \database use -> use (inMemoryAdapter database),+ createMarker = \tx name ->+ changeMarkers tx $ \markers ->+ if Set.member name markers+ then Left (MarkerExists name)+ else Right (Set.insert name markers),+ dropMarker = \tx name ->+ changeMarkers tx $ \markers ->+ if Set.member name markers+ then Right (Set.delete name markers)+ else Left (NoMarker name),+ markerExists = \database name -> Set.member name . stateMarkers <$> readIORef (databaseState database),+ failInLibrary = \_ -> throwIO (LibraryFailure "rejected"),+ seedVersion0 = Just $ \database identifiers ->+ modifyIORef' (databaseState database) (\state -> state {stateTable = Version0 identifiers})+ }++-- | Returns the applied identifiers and their fingerprints from any+-- version of the table. A version 0 table has no fingerprints, and the+-- function leaves out its row @root@, which @dbmigrations@ writes for its+-- own bootstrap migration.+appliedRows :: TrackingTable -> Map Text (Maybe Fingerprint)+appliedRows NoTable = Map.empty+appliedRows (Version0 identifiers) = Map.fromList [(i, Nothing) | i <- identifiers, i /= "root"]+appliedRows (Version1 rows) = rows++-- | Creates the current table, upgrades a version 0 table, or does nothing.+-- The upgrade keeps one row for an identifier that a version 0 table holds+-- in several rows.+bootstrapState :: DatabaseState -> (DatabaseState, Either InMemoryError BootstrapOutcome)+bootstrapState state = case stateTable state of+ NoTable -> (state {stateTable = Version1 Map.empty}, Right (Created (TrackingVersion 1)))+ Version1 _ -> (state, Right AlreadyCurrent)+ Version0 identifiers ->+ ( state {stateTable = Version1 (appliedRows (Version0 identifiers))},+ Right (Upgraded (TrackingVersion 0) (TrackingVersion 1))+ )++-- | Applies a change to the rows of the current table in the transaction's+-- working copy. Writes nothing when the change fails, or when the table is+-- not current.+changeRows ::+ InMemoryTx ->+ (Map Text (Maybe Fingerprint) -> Either InMemoryError (Map Text (Maybe Fingerprint))) ->+ IO (Either InMemoryError ())+changeRows (InMemoryTx working) change = do+ state <- readIORef working+ case stateTable state of+ Version1 rows -> case change rows of+ Left err -> pure (Left err)+ Right rows' -> Right <$> writeIORef working state {stateTable = Version1 rows'}+ _ -> pure (Left NoCurrentTrackingTable)++-- | Applies a change to the markers in the transaction's working copy.+-- When the change fails, writes nothing and throws the change's error, as+-- a database library throws when the database rejects a statement.+changeMarkers :: InMemoryTx -> (Set Text -> Either InMemoryError (Set Text)) -> IO ()+changeMarkers (InMemoryTx working) change = do+ state <- readIORef working+ case change (stateMarkers state) of+ Left err -> throwIO err+ Right markers -> writeIORef working state {stateMarkers = markers}
+ test/Main.hs view
@@ -0,0 +1,8 @@+module Main (main) where++import Database.DagMigrations.Conformance (adapterConformance)+import Database.DagMigrations.Conformance.InMemory (inMemoryFixture)+import Test.Hspec (hspec)++main :: IO ()+main = hspec (adapterConformance inMemoryFixture)