-- | 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, )whereimport 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 Mapimport Data.Set (Set)import Data.Set qualified as Setimport 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 InMemoryDatabasenewInMemoryDatabase = 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 InMemoryErrorinMemoryAdapter 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 InMemoryErrorinMemoryFixture = 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.emptyappliedRows (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}