-- | The tests of what is specific to the PostgreSQL adapter, and the-- 'Fixture' that runs the conformance suite against it.module Database.DagMigrations.PostgreSQL.SimpleSpec ( postgresFixture, spec, )whereimport Control.Exception (IOException, throwIO, try)import Control.Monad (void)import Data.ByteString (ByteString)import Data.Either (isLeft)import Data.Foldable (for_)import Data.IORef (newIORef, readIORef, writeIORef)import Data.Int (Int64)import Data.Map.Strict qualified as Mapimport Data.Text (Text)import Data.Void (Void, absurd)import Database.DagMigrations.Adapter ( Adapter (..), AppliedRow (..), BootstrapOutcome (..), Fingerprint (..), TrackingVersion (..), )import Database.DagMigrations.Conformance (Fixture (..))import Database.DagMigrations.PostgreSQL.Simpleimport Database.DagMigrations.PostgreSQL.TestDatabaseimport Database.PostgreSQL.Simple (Connection, Only (..), SqlError (..), execute, executeMany, execute_, query, query_)import Database.PostgreSQL.Simple.Types (Identifier (..), QualifiedIdentifier (..))import System.Timeout (timeout)import Test.Hspec-- | The 'Fixture' over databases on the test server, with the default-- settings. A marker is a table.postgresFixture :: TestServer -> Fixture TestDatabase Transaction PgErrorpostgresFixture server = Fixture { withEmptyDatabase = withTestDatabase server, withAdapter = \database use -> withConnection database (use . postgresAdapter defaultAdapterSettings), createMarker = \tx name -> void (execute (transactionConnection tx) "CREATE TABLE ? ()" (Only (Identifier name))), dropMarker = \tx name -> void (execute (transactionConnection tx) "DROP TABLE ?" (Only (Identifier name))), markerExists = \database name -> withConnection database (`tableExists` name), failInLibrary = \tx -> executeSqlIn tx "SELECT 1 / 0", seedVersion0 = Just $ \database identifiers -> withConnection database (\connection -> seedVersion0Table connection (map Just identifiers)) }-- | The cases that are specific to PostgreSQL.spec :: TestServer -> Specspec server = describe "the PostgreSQL adapter" $ do describe "the tracking table" $ do it "creates version 1, with its columns and its comment" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do bootstrap adapter `shouldReturn` Right (Created (TrackingVersion 1)) columnsOf connection "installed_migrations" `shouldReturn` version1Columns commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1" it "stores the description, the fingerprint, and the database's time of an applied migration" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- bootstrap adapter committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "the first" (Just (Fingerprint "f")))) `shouldReturn` Right () query_ connection "SELECT description, fingerprint, applied_at BETWEEN now() - interval '1 minute' AND now() FROM installed_migrations" `shouldReturn` [(Just "the first" :: Maybe Text, Just "f" :: Maybe Text, True)] it "keeps its table in the schema that its settings name" $ do let settings = defaultAdapterSettings {trackingTable = QualifiedIdentifier (Just "migrations") "applied"} onDatabase server settings $ \_ connection adapter -> do _ <- execute_ connection "CREATE SCHEMA migrations" bootstrap adapter `shouldReturn` Right (Created (TrackingVersion 1)) committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "the first" Nothing)) `shouldReturn` Right () readApplied adapter `shouldReturn` Right (Map.fromList [("a", Nothing)]) commentOf connection "migrations.applied" `shouldReturn` Just "dag-migrations:1" tableExists connection "installed_migrations" `shouldReturn` False describe "version 0" $ do it "upgrades the rows of version 0 without a time, a description, or a fingerprint" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do seedVersion0Table connection [Just "root", Just "a", Just "b"] bootstrap adapter `shouldReturn` Right (Upgraded (TrackingVersion 0) (TrackingVersion 1)) query_ connection "SELECT migration_id, applied_at IS NULL, description IS NULL, fingerprint IS NULL FROM installed_migrations ORDER BY migration_id" `shouldReturn` [("a" :: Text, True, True, True), ("b", True, True, True)] columnsOf connection "installed_migrations" `shouldReturn` version1Columns commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1" it "upgrades a version 0 table that holds identifiers in several rows, and keeps one row for each identifier" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do seedVersion0Table connection [Just "root", Just "a", Just "b", Just "a", Just "root", Just "a"] bootstrap adapter `shouldReturn` Right (Upgraded (TrackingVersion 0) (TrackingVersion 1)) query_ connection "SELECT migration_id, applied_at IS NULL, description IS NULL, fingerprint IS NULL FROM installed_migrations ORDER BY migration_id" `shouldReturn` [("a" :: Text, True, True, True), ("b", True, True, True)] columnsOf connection "installed_migrations" `shouldReturn` version1Columns commentOf connection "installed_migrations" `shouldReturn` Just "dag-migrations:1" it "rolls back a version 0 upgrade that fails, and leaves the table as it was" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text PRIMARY KEY); INSERT INTO installed_migrations VALUES ('root'), ('a')" upgraded <- bootstrap adapter sqlStateOf upgraded `shouldBe` Just "42P16" legacyRows connection `shouldReturn` [Just "a", Just "root"] commentOf connection "installed_migrations" `shouldReturn` Nothing it "reports a version 0 row without an identifier, and leaves the table as it was" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do seedVersion0Table connection [Just "root", Nothing, Just "a"] readApplied adapter `shouldReturn` Left NullLegacyIdentifier bootstrap adapter `shouldReturn` Left NullLegacyIdentifier legacyRows connection `shouldReturn` [Just "a", Just "root", Nothing] describe "recognizing the table" $ do it "reports a version newer than its own" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- bootstrap adapter _ <- execute_ connection "COMMENT ON TABLE installed_migrations IS 'dag-migrations:2'" readApplied adapter `shouldReturn` Left (NewerTrackingVersion (TrackingVersion 2)) bootstrap adapter `shouldReturn` Left (NewerTrackingVersion (TrackingVersion 2)) it "reports a comment that names no version" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- bootstrap adapter for_ ["dag-migrations:01", "dag-migrations:0", "dag-migrations:", "dag-migrations:1 ", "made by hand"] $ \comment -> do _ <- execute connection "COMMENT ON TABLE installed_migrations IS ?" (Only (comment :: Text)) readApplied adapter `shouldReturn` Left (UnrecognizedComment comment) bootstrap adapter `shouldReturn` Left (UnrecognizedComment comment) it "reports a relation that is not a table" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- execute_ connection "CREATE VIEW installed_migrations AS SELECT 'a'::text AS migration_id" readApplied adapter `shouldReturn` Left NotATable bootstrap adapter `shouldReturn` Left NotATable it "reports a table without a comment whose columns are not those of version 0" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text, extra integer)" let columns = [("migration_id", "text"), ("extra", "integer")] readApplied adapter `shouldReturn` Left (UnrecognizedTrackingTable columns) bootstrap adapter `shouldReturn` Left (UnrecognizedTrackingTable columns) describe "the run lock" $ do it "derives its default key from the quoted name of the table" $ do defaultRunLockKey (QualifiedIdentifier Nothing "installed_migrations") `shouldBe` (-5832889685011756295) defaultRunLockKey (QualifiedIdentifier (Just "migrations") "applied") `shouldBe` 448998094553880189 it "holds the advisory lock with the default key while the action runs" $ onDatabase server defaultAdapterSettings $ \database _ adapter -> withRunLock adapter (withConnection database advisoryLocks) `shouldReturn` Right [-5832889685011756295] it "holds the advisory lock with the key of its settings" $ onDatabase server defaultAdapterSettings {runLockKey = Just 42} $ \database _ adapter -> withRunLock adapter (withConnection database advisoryLocks) `shouldReturn` Right [42] it "returns the error of an expired lock_timeout, and does not run the action" $ onDatabase server defaultAdapterSettings $ \database _ first -> withConnection database $ \other -> do _ <- execute_ other "SET lock_timeout = '100ms'" let second = postgresAdapter defaultAdapterSettings other ran <- newIORef False outcome <- timeout 10000000 (withRunLock first (withRunLock second (writeIORef ran True))) fmap (fmap sqlStateOf) outcome `shouldBe` Just (Right (Just "55P03")) readIORef ran `shouldReturn` False it "returns a lost connection as the adapter's error" $ onDatabase server defaultAdapterSettings $ \database connection adapter -> do pids <- query_ connection "SELECT pg_backend_pid()" withConnection database $ \other -> for_ pids $ \(Only pid) -> void (query other "SELECT pg_terminate_backend(?)" (Only (pid :: Int)) :: IO [Only Bool]) first <- withRunLock adapter (pure ()) first `shouldSatisfy` isLeft second <- withRunLock adapter (pure ()) second `shouldSatisfy` isConnectionFailure readApplied adapter >>= (`shouldSatisfy` isConnectionFailure) it "throws when the action released the lock" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> withRunLock adapter (void (query_ connection "SELECT pg_advisory_unlock_all()" :: IO [Only ()])) `shouldThrow` (== RunLockNotHeld (-5832889685011756295)) describe "transactions" $ do it "runs several statements in one text" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do committing adapter (\tx -> Right <$> executeSqlIn tx "CREATE TABLE first (); CREATE TABLE second ()") `shouldReturn` Right () traverse (tableExists connection) ["first", "second"] `shouldReturn` [True, True] it "runs a text that ends in a query, or holds no statement" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do committing adapter (\tx -> Right <$> executeSqlIn tx "CREATE TABLE third (); SELECT 1") `shouldReturn` Right () committing adapter (\tx -> Right <$> executeSqlIn tx "-- nothing to do") `shouldReturn` Right () tableExists connection "third" `shouldReturn` True it "rethrows an asynchronous exception that interrupts a statement" $ onDatabase server defaultAdapterSettings $ \database _ adapter -> do timeout 300000 (withRunLock adapter (withTransaction adapter (\tx -> Right @Void <$> executeSqlIn tx "SELECT pg_sleep(5)"))) `shouldReturn` Nothing withConnection database $ \other -> query_ other "SELECT query FROM pg_stat_activity WHERE datname = current_database() AND state = 'active' AND pid <> pg_backend_pid()" `shouldReturn` [Only ("SELECT pg_sleep(5)" :: Text)] it "rethrows an IOException that a migration throws" $ onDatabase server defaultAdapterSettings $ \_ _ adapter -> void (withTransaction adapter (\_ -> throwIO (userError "file missing") >> pure (Right @Void ()))) `shouldThrow` (\(_ :: IOException) -> True) it "reports a transaction that the action ended itself" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do outcome <- withTransaction adapter (\tx -> Left () <$ executeSqlIn tx "CREATE TABLE fifth (); COMMIT; CREATE TABLE sixth ()") outcome `shouldBe` (Left (Left TransactionEnded) :: Either (Either PgError ()) ()) traverse (tableExists connection) ["fifth", "sixth"] `shouldReturn` [True, True] it "rolls back, and reports, a transaction in which the action caught a failed statement" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do outcome <- withTransaction adapter $ \tx -> do executeSqlIn tx "CREATE TABLE fourth ()" _ <- try @SqlError (executeSqlIn tx "SELECT 1 / 0") pure (Right @Void ()) outcome `shouldBe` Left (Left TransactionAborted) tableExists connection "fourth" `shouldReturn` False it "returns a failed commit as the adapter's error" $ onDatabase server defaultAdapterSettings $ \_ connection adapter -> do _ <- execute_ connection "CREATE TABLE parent (id integer PRIMARY KEY); CREATE TABLE child (parent integer REFERENCES parent DEFERRABLE INITIALLY DEFERRED)" outcome <- withTransaction adapter (\tx -> Right @Void <$> executeSqlIn tx "INSERT INTO child VALUES (1)") either (either (Just . sqlStateOf . Left) absurd) (const Nothing) outcome `shouldBe` Just (Just "23503") query_ connection "SELECT count(*) FROM child" `shouldReturn` [Only (0 :: Int64)]-- | Opens a connection to a new empty database, and passes the database,-- the connection, and an adapter over the connection with these settings-- to the action.onDatabase :: TestServer -> AdapterSettings -> (TestDatabase -> Connection -> Adapter Transaction PgError -> IO a) -> IO aonDatabase server settings use = withTestDatabase server $ \database -> withConnection database (\connection -> use database connection (postgresAdapter settings connection))-- | 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-- | Returns whether the operation failed because libpq lost the-- connection.isConnectionFailure :: Either PgError a -> BoolisConnectionFailure (Left (ConnectionFailed _)) = TrueisConnectionFailure _ = False-- | Returns the SQLSTATE of a rejected statement.sqlStateOf :: Either PgError a -> Maybe ByteStringsqlStateOf (Left (SqlFailed err)) = Just (sqlState err)sqlStateOf _ = Nothing-- | Creates the table of @dbmigrations@, with these rows.seedVersion0Table :: Connection -> [Maybe Text] -> IO ()seedVersion0Table connection identifiers = do _ <- execute_ connection "CREATE TABLE installed_migrations (migration_id text)" void (executeMany connection "INSERT INTO installed_migrations (migration_id) VALUES (?)" (map Only identifiers))-- | The identifiers of a version 0 table, in order, with nulls last.legacyRows :: Connection -> IO [Maybe Text]legacyRows connection = map fromOnly <$> query_ connection "SELECT migration_id FROM installed_migrations ORDER BY migration_id"-- | The columns of version 1, by name and type.version1Columns :: [(Text, Text)]version1Columns = [ ("migration_id", "text"), ("applied_at", "timestamp with time zone"), ("description", "text"), ("fingerprint", "text") ]-- | Returns the names and types of the columns of the named table, in-- order.columnsOf :: Connection -> Text -> IO [(Text, Text)]columnsOf connection table = query connection "SELECT attname::text, format_type(atttypid, atttypmod) FROM pg_attribute WHERE attrelid = to_regclass(?) AND attnum > 0 AND NOT attisdropped ORDER BY attnum" (Only table)-- | Returns the comment of the named table.commentOf :: Connection -> Text -> IO (Maybe Text)commentOf connection table = do rows <- query connection "SELECT obj_description(to_regclass(?), 'pg_class')" (Only table) pure (case rows of [Only comment] -> comment; _ -> Nothing)-- | Returns whether a table with this name exists on the search path.tableExists :: Connection -> Text -> IO BooltableExists connection table = (== [Only True]) <$> query connection "SELECT to_regclass(quote_ident(?)) IS NOT NULL" (Only table)-- | Returns the keys of the advisory locks that sessions hold in the-- connection's database.advisoryLocks :: Connection -> IO [Int64]advisoryLocks connection = map fromOnly <$> query_ connection "SELECT (classid::bigint << 32) | objid::bigint FROM pg_locks WHERE locktype = 'advisory' AND granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())"