-- | An adapter that keeps its database in an 'IORef', for testing the-- runner without a database server.module Database.DagMigrations.FakeAdapter ( FakeDatabase (..), emptyDatabase, FakeTx, FakeError (..), FakeFaults (..), noFaults, fakeAdapter, fakeAdapterWith, FakeM, fakeInterpreter, createTable, dropTable, failWith, tableMigration, )whereimport Control.Exception (Exception, try)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.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 (..))import Database.DagMigrations.Migration (Fingerprint, Interpreter (..), Migration (..))import Database.DagMigrations.Progress (TrackingVersion (..))-- | The state of a fake database.data FakeDatabase = FakeDatabase { -- | The tracking table, or 'Nothing' when it does not exist. fakeTrackingTable :: Maybe (Map Text (Maybe Fingerprint)), -- | The tables that test migrations created. fakeTables :: Set Text } deriving (Eq, Show)emptyDatabase :: FakeDatabaseemptyDatabase = FakeDatabase {fakeTrackingTable = Nothing, fakeTables = Set.empty}-- | A transaction: a working copy of the database, which the adapter-- writes back on commit.newtype FakeTx = FakeTx (IORef FakeDatabase)-- | The error of the fake database. Test migrations throw it to stand for a-- failure of a database library, such as rejected SQL.newtype FakeError = FakeError Text deriving (Eq, Show)instance Exception FakeError-- | Failures and outcomes that a test switches on.data FakeFaults = FakeFaults { -- | 'withRunLock' fails with this error, and runs nothing. faultLock :: Maybe FakeError, -- | 'recordApplied' fails with this error. faultRecordApplied :: Maybe FakeError, -- | 'bootstrap' reports an upgrade from this version, when the table -- exists. faultUpgradeFrom :: Maybe TrackingVersion }-- | No faults: every operation succeeds.noFaults :: FakeFaultsnoFaults = FakeFaults {faultLock = Nothing, faultRecordApplied = Nothing, faultUpgradeFrom = Nothing}-- | An adapter over the given database, with no faults. Its lock does-- nothing.fakeAdapter :: IORef FakeDatabase -> Adapter FakeTx FakeErrorfakeAdapter = fakeAdapterWith noFaults-- | An adapter over the given database, with the given faults. Like a real-- adapter, its 'withTransaction' turns a 'FakeError' that the action throws-- into the adapter's error, after it discards the transaction's changes.fakeAdapterWith :: FakeFaults -> IORef FakeDatabase -> Adapter FakeTx FakeErrorfakeAdapterWith faults database = Adapter { withRunLock = \action -> maybe (Right <$> action) (pure . Left) (faultLock faults), readApplied = Right . maybe Map.empty id . fakeTrackingTable <$> readIORef database, bootstrap = atomicModifyIORef' database $ \db -> case fakeTrackingTable db of Nothing -> (db {fakeTrackingTable = Just Map.empty}, Right (Created (TrackingVersion 1))) Just _ -> (db, Right (maybe AlreadyCurrent (\from -> Upgraded from (TrackingVersion 1)) (faultUpgradeFrom faults))), withTransaction = \action -> do working <- newIORef =<< readIORef database result <- try (action (FakeTx working)) case result of Left err -> pure (Left (Left err)) Right (Left err) -> pure (Left (Right err)) Right (Right a) -> do writeIORef database =<< readIORef working pure (Right a), recordApplied = \(FakeTx working) row -> case faultRecordApplied faults of Just err -> pure (Left err) Nothing -> -- Like an SQL INSERT into a table keyed by identifier, this fails -- when the row exists. modifyTrackingTable working $ \table -> if Map.member (appliedIdentifier row) table then Left (FakeError ("row exists: " <> appliedIdentifier row)) else Right (Map.insert (appliedIdentifier row) (appliedFingerprint row) table), removeApplied = \(FakeTx working) identifier -> modifyTrackingTable working $ \table -> if Map.member identifier table then Right (Map.delete identifier table) else Left (FakeError ("no row: " <> identifier)), recordFingerprints = \(FakeTx working) fingerprints -> -- Like an SQL UPDATE, this changes only rows that exist. modifyTrackingTable working (\table -> Right (Map.union (Map.intersection fingerprints table) table)) }-- | Applies the change to the tracking table of the transaction's working-- copy. Fails, and writes nothing, when the table does not exist or the-- change fails.modifyTrackingTable :: IORef FakeDatabase -> (Map Text (Maybe Fingerprint) -> Either FakeError (Map Text (Maybe Fingerprint))) -> IO (Either FakeError ())modifyTrackingTable working change = do db <- readIORef working case change =<< maybe (Left (FakeError "no tracking table")) Right (fakeTrackingTable db) of Left err -> pure (Left err) Right table -> Right <$> writeIORef working db {fakeTrackingTable = Just table}-- | The monad of test migrations: they read the transaction, and fail-- with text.type FakeM = ReaderT FakeTx (ExceptT Text IO)fakeInterpreter :: Interpreter FakeTx FakeM TextfakeInterpreter = Interpreter (\tx action -> runExceptT (runReaderT action tx))createTable :: Text -> FakeM ()createTable name = changeTables (Set.insert name)dropTable :: Text -> FakeM ()dropTable name = changeTables (Set.delete name)failWith :: Text -> FakeM afailWith = lift . throwEchangeTables :: (Set Text -> Set Text) -> FakeM ()changeTables change = do FakeTx working <- ask liftIO (modifyIORef' working (\db -> db {fakeTables = change (fakeTables db)}))-- | A migration that creates the table with its own name, and drops it-- when reverted.tableMigration :: Text -> [Text] -> Migration Text FakeMtableMigration name dependencies = Migration { migrationId = name, migrationDependencies = Set.fromList dependencies, migrationDescription = "create " <> name, migrationFingerprint = Nothing, migrationUp = createTable name, migrationDown = Just (dropTable name) }