-- | Databases for the tests, on the server whose connection string-- @scripts/with-test-postgres@ exports.module Database.DagMigrations.PostgreSQL.TestDatabase ( TestServer, TestDatabase, findTestServer, withTestDatabase, withConnection, )whereimport Control.Exception (bracket, bracket_)import Control.Monad (void)import Data.ByteString (ByteString)import Data.ByteString.Char8 qualified as Char8import Data.IORef (IORef, atomicModifyIORef', newIORef)import Data.Text qualified as Textimport Database.PostgreSQL.Simple (Connection, Only (..), close, connectPostgreSQL, execute, execute_)import Database.PostgreSQL.Simple.Types (Identifier (..))import System.Environment (lookupEnv)import System.Posix.Process (getProcessID)-- | A server for tests, and the counter that names its databases.data TestServer = TestServer { serverConnectionString :: ByteString, serverDatabases :: IORef Int }-- | The connection string of one database on the server.newtype TestDatabase = TestDatabase ByteString-- | Reads the server's connection string from the environment variable-- @DAG_MIGRATIONS_TEST_DATABASE@. The string is in libpq's keyword/value-- form, not a URI, and names no database. Returns 'Nothing' when the-- variable is not set.findTestServer :: IO (Maybe TestServer)findTestServer = do found <- lookupEnv "DAG_MIGRATIONS_TEST_DATABASE" traverse (\connectionString -> TestServer (Char8.pack connectionString) <$> newIORef 0) found-- | Creates an empty database on the server, passes it to the action, and-- drops the database when the action returns or throws. The drop ends any-- session that is still open on the database. A database of the same name-- that an earlier, killed run left behind is dropped first.withTestDatabase :: TestServer -> (TestDatabase -> IO a) -> IO awithTestDatabase server use = do number <- atomicModifyIORef' (serverDatabases server) (\next -> (next + 1, next)) process <- getProcessID let name = "dag_migrations_test_" <> show process <> "_" <> show number identifier = Only (Identifier (Text.pack name)) onServer = withConnection (databaseNamed "postgres") databaseNamed database = TestDatabase (serverConnectionString server <> " dbname=" <> Char8.pack database) create connection = do _ <- execute_ connection "SET client_min_messages = warning" _ <- execute connection "DROP DATABASE IF EXISTS ? WITH (FORCE)" identifier void (execute connection "CREATE DATABASE ?" identifier) bracket_ (onServer create) (onServer (\connection -> void (execute connection "DROP DATABASE ? WITH (FORCE)" identifier))) (use (databaseNamed name))-- | Opens a connection to the database, passes it to the action, and-- closes it when the action returns or throws.withConnection :: TestDatabase -> (Connection -> IO a) -> IO awithConnection (TestDatabase connectionString) = bracket (connectPostgreSQL connectionString) close