-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Start and stop a temporary postgres -- -- Start and stop a temporary postgres. See README.md @package tmp-postgres @version 1.32.0.0 -- | This module provides the low level functionality for running -- initdb, postgres and createdb to make a -- database. -- -- See startPlan for more details. module Database.Postgres.Temp.Internal.Core -- | Internal events for debugging data Event -- | The first event. This useful for debugging what is actual passed to -- the initdb, createdb and postgres. StartPlan :: String -> Event -- | The second event. Postgres is about to get called StartPostgres :: Event -- | The third event. Postgres started. We are now about to setup a -- reconnect loop (racing with a process checker) WaitForDB :: Event -- | The fourth event and (possibly all subsequent events). We are looping -- trying to successfully connect to the postgres process. TryToConnect :: Event -- | A list of failures that can occur when starting. This is not and -- exhaustive list but covers the errors that the system catches for the -- user. data StartError -- | postgres failed before a connection succeeded. Most likely -- this is due to invalid configuration StartPostgresFailed :: ExitCode -> StartError -- | initdb failed. This can be from invalid configuration or -- using a non-empty data directory InitDbFailed :: String -> String -> ExitCode -> StartError [startErrorStdOut] :: StartError -> String [startErrorStdErr] :: StartError -> String [startErrorExitCode] :: StartError -> ExitCode -- | createdb failed. This can be from invalid configuration or -- the database might already exist. CreateDbFailed :: String -> String -> ExitCode -> StartError [startErrorStdOut] :: StartError -> String [startErrorStdErr] :: StartError -> String [startErrorExitCode] :: StartError -> ExitCode -- | The Plan was missing info and a complete Plan could not -- be created. PlanFailed :: String -> [String] -> StartError -- | The ProcessConfig was missing info and a -- CompleteProcessConfig could not be created. CompleteProcessConfigFailed :: String -> [String] -> StartError -- | Timed out waiting for postgres to accept a connection ConnectionTimedOut :: StartError DeleteDbError :: SqlError -> StartError -- | This will happen if a Plan is missing a initDbConfig. EmptyDataDirectory :: StartError -- | This is called if copying a folder cache fails. CopyCachedInitDbFailed :: String -> ExitCode -> StartError -- | Failed to find a data directory when trying to get a cached -- initdb folder. FailedToFindDataDirectory :: String -> StartError -- | We tried to copy a data directory to a snapshot folder and it failed SnapshotCopyFailed :: String -> ExitCode -> StartError -- | A way to log internal Events type Logger = Event -> IO () -- | postgres is not ready until we are able to successfully -- connect. waitForDB attempts to connect over and over again and -- returns after the first successful connection. waitForDB :: Logger -> Options -> IO () -- | CompleteProcessConfig contains the configuration necessary for -- starting a process. It is essentially a stripped down -- CreateProcess. data CompleteProcessConfig CompleteProcessConfig :: [(String, String)] -> [String] -> Handle -> Handle -> Handle -> CompleteProcessConfig -- | Environment variables [completeProcessConfigEnvVars] :: CompleteProcessConfig -> [(String, String)] -- | Command line arguements [completeProcessConfigCmdLine] :: CompleteProcessConfig -> [String] -- | The Handle for standard input [completeProcessConfigStdIn] :: CompleteProcessConfig -> Handle -- | The Handle for standard output [completeProcessConfigStdOut] :: CompleteProcessConfig -> Handle -- | The Handle for standard error [completeProcessConfigStdErr] :: CompleteProcessConfig -> Handle -- | Start a process interactively and return the ProcessHandle startProcess :: String -> CompleteProcessConfig -> IO ProcessHandle -- | Stop a ProcessHandle. An alias for waitForProcess stopProcess :: ProcessHandle -> IO ExitCode -- | Start a process and block until it finishes return the -- ExitCode. executeProcess :: String -> CompleteProcessConfig -> IO ExitCode -- | Start a process and block until it finishes return the ExitCode -- and the stderr output. executeProcessAndTee :: String -> CompleteProcessConfig -> IO (ExitCode, String, String) -- | CompletePostgresPlan is used be startPostgresProcess to -- start the postgres and then attempt to connect to it. data CompletePostgresPlan CompletePostgresPlan :: CompleteProcessConfig -> Options -> CompletePostgresPlan -- | The process config for postgres [completePostgresPlanProcessConfig] :: CompletePostgresPlan -> CompleteProcessConfig -- | Connection options. Used to verify that postgres is ready. [completePostgresPlanClientOptions] :: CompletePostgresPlan -> Options -- | The output of calling startPostgresProcess. data PostgresProcess PostgresProcess :: Options -> ProcessHandle -> PostgresProcess -- | Connection options [postgresProcessClientOptions] :: PostgresProcess -> Options -- | postgres process handle [postgresProcessHandle] :: PostgresProcess -> ProcessHandle -- | Stop the postgres process after attempting to terminate all -- the connections. stopPostgresProcess :: Bool -> PostgresProcess -> IO ExitCode -- | Start the postgres process and block until a successful -- connection occurs. A separate thread we continously check to see if -- the postgres process has crashed. startPostgresProcess :: Int -> Logger -> CompletePostgresPlan -> IO PostgresProcess -- | Call createdb and tee the output to return if there is an an -- exception. Throws CreateDbFailed. executeCreateDb :: CompleteProcessConfig -> IO () -- | Plan is the low level configuration necessary for initializing -- a database cluster starting postgres and creating a database. -- There is no validation done on the Plan. It is recommend that -- one use the higher level functions such as start which will -- generate plans that are valid. Plans are used internally but -- are exposed if the higher level plan generation is not sufficent. data Plan Plan :: Logger -> Maybe CompleteProcessConfig -> Maybe CompleteCopyDirectoryCommand -> Maybe CompleteProcessConfig -> CompletePostgresPlan -> String -> FilePath -> Int -> Plan [completePlanLogger] :: Plan -> Logger [completePlanInitDb] :: Plan -> Maybe CompleteProcessConfig [completePlanCopy] :: Plan -> Maybe CompleteCopyDirectoryCommand [completePlanCreateDb] :: Plan -> Maybe CompleteProcessConfig [completePlanPostgres] :: Plan -> CompletePostgresPlan [completePlanConfig] :: Plan -> String [completePlanDataDirectory] :: Plan -> FilePath [completePlanConnectionTimeout] :: Plan -> Int -- | startPlan optionally calls initdb, optionally calls -- createdb and unconditionally calls postgres. -- Additionally it writes a "postgresql.conf" and does not return until -- the postgres process is ready. See -- startPostgresProcess for more details. startPlan :: Plan -> IO PostgresProcess -- | Stop the postgres process. See stopPostgresProcess for -- more details. stopPlan :: PostgresProcess -> IO ExitCode instance GHC.Classes.Ord Database.Postgres.Temp.Internal.Core.CompleteCopyDirectoryCommand instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Core.CompleteCopyDirectoryCommand instance GHC.Show.Show Database.Postgres.Temp.Internal.Core.CompleteCopyDirectoryCommand instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Core.StartError instance GHC.Show.Show Database.Postgres.Temp.Internal.Core.StartError instance GHC.Classes.Ord Database.Postgres.Temp.Internal.Core.Event instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Core.Event instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Core.Plan instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Core.CompleteCopyDirectoryCommand instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Core.PostgresProcess instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Core.CompletePostgresPlan instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Core.CompleteProcessConfig instance GHC.Exception.Type.Exception Database.Postgres.Temp.Internal.Core.StartError instance GHC.Show.Show Database.Postgres.Temp.Internal.Core.Event -- | This module provides types and functions for combining partial configs -- into a complete configs to ultimately make a Plan. -- -- This module has two classes of types. -- -- Types like ProcessConfig that could be used by any library that -- needs to combine process options. -- -- Finally it has types and functions for creating Plans that use -- temporary resources. This is used to create the default behavior of -- startConfig and related functions. | module Database.Postgres.Temp.Internal.Config -- | Accum is a monoid. -- -- It's <> behavior is analogous to 1 and 0 with *. -- Think of DontCare as 1 and Zlich as 0. -- -- The behavior of Merge is like Justs. data Accum a DontCare :: Accum a Zlich :: Accum a Merge :: a -> Accum a -- | The environment variables can be declared to inherit from the running -- process or they can be specifically added. data EnvironmentVariables EnvironmentVariables :: Last Bool -> Map String String -> EnvironmentVariables [inherit] :: EnvironmentVariables -> Last Bool [specific] :: EnvironmentVariables -> Map String String -- | Combine the current environment (if indicated by inherit) with -- specific. completeEnvironmentVariables :: [(String, String)] -> EnvironmentVariables -> Either [String] [(String, String)] -- | A type to help combine command line Args. data CommandLineArgs CommandLineArgs :: Map String (Maybe String) -> Map Int String -> CommandLineArgs -- | Args of the form -h foo, --host=foo and -- --switch. The key is mappended with value so the key -- should include the space or equals (as shown in the first two examples -- respectively). The Dual monoid is used so the last key wins. [keyBased] :: CommandLineArgs -> Map String (Maybe String) -- | Args that appear at the end of the key based Args. The Dual -- monoid is used so the last key wins. [indexBased] :: CommandLineArgs -> Map Int String -- | This convert the CommandLineArgs to '[String]'. completeCommandLineArgs :: CommandLineArgs -> [String] -- | Process configuration data ProcessConfig ProcessConfig :: EnvironmentVariables -> CommandLineArgs -> Last Handle -> Last Handle -> Last Handle -> ProcessConfig -- | A monoid for combine environment variables or replacing them. for the -- maps the Dual monoid is used. So the last key wins. [environmentVariables] :: ProcessConfig -> EnvironmentVariables -- | A monoid for combine command line Args or replacing them. [commandLine] :: ProcessConfig -> CommandLineArgs -- | A monoid for configuring the standard input Handle. [stdIn] :: ProcessConfig -> Last Handle -- | A monoid for configuring the standard output Handle. [stdOut] :: ProcessConfig -> Last Handle -- | A monoid for configuring the standard error Handle. [stdErr] :: ProcessConfig -> Last Handle -- | The standardProcessConfig sets the handles to stdin, -- stdout and stderr and inherits the environment variables -- from the calling process. standardProcessConfig :: ProcessConfig -- | A global reference to /dev/null Handle. devNull :: Handle -- | silentProcessConfig sets the handles to /dev/null and -- inherits the environment variables from the calling process. silentProcessConfig :: ProcessConfig -- | Turn a ProcessConfig into a ProcessConfig. Fails if any -- values are missing. completeProcessConfig :: [(String, String)] -> ProcessConfig -> Either [String] CompleteProcessConfig -- | A type to track whether a file is temporary and needs to be cleaned -- up. data CompleteDirectoryType CPermanent :: FilePath -> CompleteDirectoryType CTemporary :: FilePath -> CompleteDirectoryType -- | Get the file path of a CompleteDirectoryType, regardless if it -- is a CPermanent or CTemporary type. toFilePath :: CompleteDirectoryType -> FilePath -- | Used to specify a Temporary folder that is automatically -- cleaned up or a Permanent folder which is not automatically -- cleaned up. data DirectoryType -- | A permanent file that should not be generated. Permanent :: FilePath -> DirectoryType -- | A temporary file that needs to generated. Temporary :: DirectoryType -- | Either create aCTemporary directory or do create the directory -- if it does not exist to a CPermanent one. setupDirectoryType :: String -> String -> DirectoryType -> IO CompleteDirectoryType -- | Either remove a CTemporary directory or do nothing to a -- CPermanent one. cleanupDirectoryType :: CompleteDirectoryType -> IO () -- | Turn a Config into a CompletePostgresPlan. Fails if any -- values are missing. completePostgresPlan :: [(String, String)] -> Config -> Either [String] CompletePostgresPlan -- | Turn a Config into a Plan. Fails if any values are -- missing. completePlan :: [(String, String)] -> String -> Config -> Either [String] Plan -- | The high level options for overriding default behavior. data Config Config :: Last Logger -> Accum ProcessConfig -> Last (Maybe CopyDirectoryCommand) -> Accum ProcessConfig -> ProcessConfig -> Options -> [(String, String)] -> Last Int -> DirectoryType -> DirectoryType -> Last (Maybe Int) -> Last FilePath -> Last (Maybe (Bool, FilePath)) -> Config -- | Internal Event logger. [logger] :: Config -> Last Logger -- | Monoid for accumulating initdb configuration. [initDbConfig] :: Config -> Accum ProcessConfig -- | An optional data directory copy command. [copyConfig] :: Config -> Last (Maybe CopyDirectoryCommand) -- | Monoid for accumulating createdb configuration. [createDbConfig] :: Config -> Accum ProcessConfig -- | The postgres process configuration. [postgresConfig] :: Config -> ProcessConfig -- | The additional client connection options. [connectionOptions] :: Config -> Options -- | The postgresql.conf configuration file. [postgresConfigFile] :: Config -> [(String, String)] -- | The amount of microseconds to attempt to connect to postgres -- before throwing ConnectionTimedOut [connectionTimeout] :: Config -> Last Int -- | Override the default temporary UNIX socket directory by setting this. [socketDirectory] :: Config -> DirectoryType -- | Override the default temporary data directory by passing in -- Permanent DIRECTORY. [dataDirectory] :: Config -> DirectoryType -- | A monoid for using an existing port (via Just -- PORT_NUMBER) or requesting a free port (via a -- Nothing). [port] :: Config -> Last (Maybe Int) -- | The directory used to create other temporary directories. Defaults to -- /tmp. [temporaryDirectory] :: Config -> Last FilePath [initDbCache] :: Config -> Last (Maybe (Bool, FilePath)) -- | Copy command used to create a data directory. If initdb used -- to create the data directory directly this is not needed. -- -- If destinationDirectory is Nothing then the -- dataDirectory (which might be generated) is used. data CopyDirectoryCommand CopyDirectoryCommand :: FilePath -> Maybe FilePath -> Bool -> CopyDirectoryCommand [sourceDirectory] :: CopyDirectoryCommand -> FilePath [destinationDirectory] :: CopyDirectoryCommand -> Maybe FilePath [useCopyOnWrite] :: CopyDirectoryCommand -> Bool -- | Create a Config that sets the command line options of all -- processes (initdb, postgres and createdb). -- This the generated plan that is combined with the -- extra plan from startConfig. toPlan :: Bool -> Bool -> Int -> FilePath -> FilePath -> Config -- | Create all the temporary resources from a Config. This also -- combines the Config from toPlan with the extra -- Config passed in. setupConfig :: Config -> IO Resources -- | Free the temporary resources created by setupConfig. cleanupConfig :: Resources -> IO () -- | Display a Config. prettyPrintConfig :: Config -> String -- | Resources holds a description of the temporary folders (if -- there are any) and includes the final Plan that can be used -- with startPlan. See setupConfig for an example of how to -- create a Resources. data Resources Resources :: Plan -> CompleteDirectoryType -> CompleteDirectoryType -> FilePath -> Maybe (Bool, FilePath) -> Resources -- | Final Plan. See startPlan for information on -- Plans. [resourcesPlan] :: Resources -> Plan -- | The used to potentially cleanup the temporary unix socket directory. [resourcesSocketDirectory] :: Resources -> CompleteDirectoryType -- | The data directory. Used to track if a temporary directory was used. [resourcesDataDir] :: Resources -> CompleteDirectoryType -- | The directory where other temporary directories are created. Usually -- @/tmp. [resourcesTemporaryDir] :: Resources -> FilePath [resourcesInitDbCache] :: Resources -> Maybe (Bool, FilePath) -- | Make the resourcesDataDir CPermanent so it will not get -- cleaned up. makeResourcesDataDirPermanent :: Resources -> Resources -- | Attempt to create a config from a Options. This is useful if -- want to create a database owned by a specific user you will also log -- in as among other use cases. It is possible some Options are -- not supported so don't hesitate to open an issue on github if you find -- one. optionsToConfig :: Options -> Config instance GHC.Base.Monoid Database.Postgres.Temp.Internal.Config.Config instance GHC.Base.Semigroup Database.Postgres.Temp.Internal.Config.Config instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Config.Config instance GHC.Classes.Ord Database.Postgres.Temp.Internal.Config.CopyDirectoryCommand instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.CopyDirectoryCommand instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.CopyDirectoryCommand instance GHC.Classes.Ord Database.Postgres.Temp.Internal.Config.DirectoryType instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.DirectoryType instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.DirectoryType instance Control.DeepSeq.NFData Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance GHC.Classes.Ord Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance GHC.Base.Monoid Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Base.Semigroup Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Base.Monoid Database.Postgres.Temp.Internal.Config.CommandLineArgs instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.CommandLineArgs instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.CommandLineArgs instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Config.CommandLineArgs instance GHC.Classes.Eq Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance GHC.Show.Show Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance GHC.Base.Functor Database.Postgres.Temp.Internal.Config.Accum instance GHC.Classes.Ord a => GHC.Classes.Ord (Database.Postgres.Temp.Internal.Config.Accum a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Database.Postgres.Temp.Internal.Config.Accum a) instance GHC.Show.Show a => GHC.Show.Show (Database.Postgres.Temp.Internal.Config.Accum a) instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.Resources instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.Config instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.CopyDirectoryCommand instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.DirectoryType instance GHC.Base.Semigroup Database.Postgres.Temp.Internal.Config.DirectoryType instance GHC.Base.Monoid Database.Postgres.Temp.Internal.Config.DirectoryType instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.CompleteDirectoryType instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.ProcessConfig instance GHC.Base.Semigroup Database.Postgres.Temp.Internal.Config.CommandLineArgs instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.CommandLineArgs instance GHC.Base.Semigroup Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance GHC.Base.Monoid Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.Config.EnvironmentVariables instance GHC.Base.Applicative Database.Postgres.Temp.Internal.Config.Accum instance GHC.Base.Semigroup a => GHC.Base.Semigroup (Database.Postgres.Temp.Internal.Config.Accum a) instance GHC.Base.Monoid a => GHC.Base.Monoid (Database.Postgres.Temp.Internal.Config.Accum a) -- | This module provides the high level functions that are re-exported by -- Database.Postgres.Temp. Additionally it includes some -- identifiers that are used for testing but are not exported. module Database.Postgres.Temp.Internal -- | Handle for holding temporary resources, the postgres process -- handle and postgres connection information. The DB -- also includes the final plan used to start initdb, -- createdb and postgres. data DB DB :: Resources -> PostgresProcess -> DB -- | Temporary resources and the final Plan. [dbResources] :: DB -> Resources -- | postgres process handle and the connection options. [dbPostgresProcess] :: DB -> PostgresProcess -- | Convert a DB to a connection string. Alternatively one can -- access the Options using toConnectionOptions. toConnectionString :: DB -> ByteString -- | Convert a DB to a connection Options type. toConnectionOptions :: DB -> Options -- | Access the data directory. This was either generated or specified -- explicitly when creating the Config toDataDirectory :: DB -> FilePath -- | Make the data directory permanent. Useful for debugging. If you are -- using with or withConfig this function will not modify -- the DB that is passed for cleanup. You will need to setup your -- own bracket like -- --
--   bracket (fmap makeDataDirectoryPermanent start) (either mempty stop)
--   
makeDataDirectoryPermanent :: DB -> DB -- | Get the directory that is used to create other temporary directories toTemporaryDirectory :: DB -> FilePath -- | Get the final postgresql.conf toPostgresqlConfigFile :: DB -> String -- | The fastest config we can make. -- --
--   shared_buffers = 12MB
--   fsync = off
--   synchronous_commit = off
--   full_page_writes = off
--   log_min_messages = PANIC
--   log_min_error_statement = PANIC
--   log_statement = none
--   client_min_messages = ERROR
--   
fastPostgresConfig :: [(String, String)] -- | The default configuration. This will create a database called -- "postgres" via initdb (it's default behavior). It will create -- a temporary directory for the data and a temporary directory for a -- unix socket and listen on 127.0.0.1 and ::1 on a random port. -- Additionally it will use the following "postgresql.conf" which is -- optimized for performance. -- --
--   shared_buffers = 12MB
--   fsync = off
--   synchronous_commit = off
--   full_page_writes = off
--   log_min_messages = PANIC
--   log_min_error_statement = PANIC
--   log_statement = none
--   client_min_messages = ERROR
--   commit_delay = 100000
--   wal_level = minimal
--   archive_mode = off
--   max_wal_senders = 0
--   
-- -- defaultConfig also passes the --no-sync flag to -- initdb. -- -- If you would like to customize this behavior you can start with the -- defaultConfig and overwrite fields or combine a -- defaultConfig with another Config using <> -- (mappend). -- -- Alternatively you can eschew defaultConfig altogether, however -- your postgres might start and run faster if you use -- defaultConfig. -- -- The defaultConfig redirects all output to /dev/null. -- See verboseConfig for a version that logs more output. -- -- To append additional lines to "postgresql.conf" file create a custom -- Config like the following. -- --
--   custom = defaultConfig <> mempty
--     { postgresConfigFile =
--         [ ("wal_level, "replica")
--         , ("archive_mode", on")
--         , ("max_wal_senders", "2")
--         , ("fsync", "on")
--         , ("synchronous_commit", "on")
--         ]
--     }
--   
-- -- As an alternative to using defaultConfig one could create a -- config from connections parameters using -- optionsToDefaultConfig. defaultConfig :: Config -- | Default configuration for PostgreSQL versions 9.3 and greater but less -- than 10. -- -- If you get an error that "--no-sync" is an invalid parameter then you -- should use this config. defaultConfig_9_3_10 :: Config -- | Default postgres options verbosePostgresConfig :: [(String, String)] -- | This is similar to defaultConfig but it logs as much as -- possible.. verboseConfig :: Config -- | Create zero or more temporary resources and use them to make a -- Config. -- -- The passed in config is inspected and a generated config is created. -- The final config is built by -- --
--   generated <> extra
--   
-- -- Based on the value of socketDirectory a "postgresql.conf" is -- created with: -- --
--   listen_addresses = '127.0.0.1, ::1'
--   unix_socket_directories = 'SOCKET_DIRECTORY'
--   
-- -- Additionally the generated Config also: -- -- -- -- All of these values can be overrided by the extra config. -- -- The returned DB requires cleanup. startConfig should be -- used with a bracket and stop, e.g. -- --
--   withConfig :: Config -> (DB -> IO a) -> IO (Either StartError a)
--   withConfig plan f = bracket (startConfig plan) (either mempty stop) $
--     either (pure . Left) (fmap Right . f)
--   
-- -- or just use withConfig. If you are calling startConfig -- you probably want withConfig anyway. startConfig :: Config -> IO (Either StartError DB) -- | Default start behavior. Equivalent to calling startConfig with -- the defaultConfig. start :: IO (Either StartError DB) -- | Stop the postgres process and cleanup any temporary resources -- that might have been created. stop :: DB -> IO () -- | Only stop the postgres process but leave any temporary -- resources. Useful for testing backup strategies when used in -- conjunction with restart or withRestart. stopPostgres :: DB -> IO ExitCode -- | Only stop the postgres process but leave any temporary -- resources. In contrast to stopPostgres this function makes sure -- postgres has time to properly write files to the data -- directory. stopPostgresGracefully :: DB -> IO ExitCode -- | Restart the postgres from DB using the prior -- Config. This will also start an instance previously stoppped -- with stopPostgres. restart :: DB -> IO (Either StartError DB) -- | Exception safe database create with options. See startConfig -- for more details. Calls stop even in the face of exceptions. withConfig :: Config -> (DB -> IO a) -> IO (Either StartError a) -- | Default expectation safe interface. Equivalent to -- --
--   with = withConfig defaultConfig
--   
with :: (DB -> IO a) -> IO (Either StartError a) -- | Exception safe version of restart. withRestart :: DB -> (DB -> IO a) -> IO (Either StartError a) -- | Attempt to create a Config from a Options. Useful if you -- want to create a database owned by a specific user you will also login -- with among other use cases. optionsToDefaultConfig :: Options -> Config -- | Display a DB. prettyPrintDB :: DB -> String -- | Configuration for the initdb data directory cache. data CacheConfig CacheConfig :: FilePath -> DirectoryType -> Bool -> CacheConfig -- | Root temporary directory used if cacheDirectoryType is set to -- Temporary. /tmp is a good default. [cacheTemporaryDirectory] :: CacheConfig -> FilePath -- | Used to specify is a Permanent or Temporary directory -- should be used. defaultCacheConfig uses Permanent -- ~/.tmp-postgres by default. [cacheDirectoryType] :: CacheConfig -> DirectoryType -- | Some operatoring system versions support flags for cp that -- allow "copy on write" which is about 2x faster. -- defaultCacheConfig attempts to determine if the cp on -- the path supports copy on write and sets this to True if it -- does. [cacheUseCopyOnWrite] :: CacheConfig -> Bool -- | A handle to cache temporary resources and configuration. data Cache Cache :: Bool -> CompleteDirectoryType -> Cache [cacheResourcesCow] :: Cache -> Bool [cacheResourcesDirectory] :: Cache -> CompleteDirectoryType -- | A bool that is True if the cp on the path supports -- "copy on write" flags. cowCheck :: Bool -- | defaultCacheConfig attempts to determine if the cp on -- the path supports "copy on write" flags and if it does, sets -- cacheUseCopyOnWrite to True. -- -- It sets cacheDirectoryType to Permanent -- ~/.tmp-postgres and cacheTemporaryDirectory to -- /tmp (but this is not used when Permanent is set). defaultCacheConfig :: CacheConfig -- | Setup the initdb cache folder. setupInitDbCache :: CacheConfig -> IO Cache -- | Cleanup the cache directory if it was Temporary. cleanupInitDbCache :: Cache -> IO () -- | Enable initdb data directory caching. This can lead to a 4x -- speedup. -- -- Exception safe version of setupInitDbCache. Equivalent to -- --
--   withDbCacheConfig = bracket (setupInitDbCache config) cleanupInitDbCache
--   
withDbCacheConfig :: CacheConfig -> (Cache -> IO a) -> IO a -- | Equivalent to withDbCacheConfig with the CacheConfig -- defaultCacheConfig makes. -- -- Here is an example using caching: -- --
--   withDbCache $ \cache -> do
--     withCache (cacheConfig cache) $ \db -> ...
--     withCache (cacheConfig cache) $ \db -> ...
--   
withDbCache :: (Cache -> IO a) -> IO a -- | Helper to make a Config out of caching info. cacheConfig :: Cache -> Config -- | A type to track a possibly temporary snapshot directory newtype Snapshot Snapshot :: CompleteDirectoryType -> Snapshot [unSnapshot] :: Snapshot -> CompleteDirectoryType -- | Shutdown the database and copy the directory to a folder. takeSnapshot :: DB -> IO (Either StartError Snapshot) -- | Cleanup any temporary resources used for the snapshot. cleanupSnapshot :: Snapshot -> IO () -- | Exception safe method for taking a file system level copy of the -- database cluster. -- -- Snapshots are useful if you would like to start every test from a -- migrated database and the migration process is more time consuming -- then copying the additional data. -- -- Here is an example with caching and snapshots: -- --
--   withDbCache $ \cache -> withConfig (cacheConfig cache) $ \db ->
--     migrate db
--     withSnapshot Temporary db $ \snapshot -> do
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--   
-- -- The Snapshots are ephemeral. If you would like the -- Snapshots to persistent consider using cacheAction -- instead. withSnapshot :: DB -> (Snapshot -> IO a) -> IO (Either StartError a) -- | Convert a snapshot into a Config that includes a -- copyConfig for copying the snapshot directory to a temporary -- directory. snapshotConfig :: Snapshot -> Config -- | Check to see if a cached data directory exists. -- -- If the file path does not exist the initial config is used to -- start a postgres instance. After which the action is -- applied, the data directory is cached and postgres is -- shutdown. -- -- cacheAction mappends a config to copy the cached data -- directory on startup onto the initial config and returns it. -- In other words: -- --
--   initialConfig <> configFromCachePath
--   
-- -- cacheAction can be used to create a snapshot of migrated -- database and not remigrate as long as the migration does not change. -- See withSnapshot for a ephemeral version of taking snapshots. cacheAction :: FilePath -> (DB -> IO ()) -> Config -> IO (Either StartError Config) instance Control.DeepSeq.NFData Database.Postgres.Temp.Internal.Snapshot instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Snapshot instance Control.DeepSeq.NFData Database.Postgres.Temp.Internal.Cache instance GHC.Generics.Generic Database.Postgres.Temp.Internal.Cache instance Text.PrettyPrint.ANSI.Leijen.Internal.Pretty Database.Postgres.Temp.Internal.DB -- | This module provides functions for creating a temporary -- postgres instance. By default it will create a temporary data -- directory and a temporary directory for a UNIX domain socket for -- postgres to listen on in addition to listening on -- 127.0.0.1 and ::1. -- -- Here is an example using the expection safe with function: -- --
--   with $ \db -> bracket
--      (connectPostgreSQL (toConnectionString db))
--      close $
--      \conn -> execute_ conn "CREATE TABLE foo (id int)"
--   
-- -- To extend or override the defaults use withConfig (or -- startConfig). -- -- tmp-postgres ultimately calls initdb (optionally), -- postgres and createdb (optionally). -- -- All of the command line, environment variables and configuration files -- that are generated by default for the respective executables can be -- extended or overriden. -- -- In general tmp-postgres is useful if you want a clean -- temporary postgres and do not want to worry about clashing -- with an existing postgres instance (or needing to ensure -- postgres is already running). -- -- Here are some different use cases for tmp-postgres and their -- respective configurations: -- -- -- -- WARNING! Ubuntu's PostgreSQL installation does not put initdb -- on the PATH. We need to add it manually. The necessary -- binaries are in the /usr/lib/postgresql/VERSION/bin/ -- directory, and should be added to the PATH -- --
--   echo "export PATH=$PATH:/usr/lib/postgresql/VERSION/bin/" >> /home/ubuntu/.bashrc
--   
module Database.Postgres.Temp -- | Default expectation safe interface. Equivalent to -- --
--   with = withConfig defaultConfig
--   
with :: (DB -> IO a) -> IO (Either StartError a) -- | Exception safe database create with options. See startConfig -- for more details. Calls stop even in the face of exceptions. withConfig :: Config -> (DB -> IO a) -> IO (Either StartError a) -- | Exception safe version of restart. withRestart :: DB -> (DB -> IO a) -> IO (Either StartError a) -- | The default configuration. This will create a database called -- "postgres" via initdb (it's default behavior). It will create -- a temporary directory for the data and a temporary directory for a -- unix socket and listen on 127.0.0.1 and ::1 on a random port. -- Additionally it will use the following "postgresql.conf" which is -- optimized for performance. -- --
--   shared_buffers = 12MB
--   fsync = off
--   synchronous_commit = off
--   full_page_writes = off
--   log_min_messages = PANIC
--   log_min_error_statement = PANIC
--   log_statement = none
--   client_min_messages = ERROR
--   commit_delay = 100000
--   wal_level = minimal
--   archive_mode = off
--   max_wal_senders = 0
--   
-- -- defaultConfig also passes the --no-sync flag to -- initdb. -- -- If you would like to customize this behavior you can start with the -- defaultConfig and overwrite fields or combine a -- defaultConfig with another Config using <> -- (mappend). -- -- Alternatively you can eschew defaultConfig altogether, however -- your postgres might start and run faster if you use -- defaultConfig. -- -- The defaultConfig redirects all output to /dev/null. -- See verboseConfig for a version that logs more output. -- -- To append additional lines to "postgresql.conf" file create a custom -- Config like the following. -- --
--   custom = defaultConfig <> mempty
--     { postgresConfigFile =
--         [ ("wal_level, "replica")
--         , ("archive_mode", on")
--         , ("max_wal_senders", "2")
--         , ("fsync", "on")
--         , ("synchronous_commit", "on")
--         ]
--     }
--   
-- -- As an alternative to using defaultConfig one could create a -- config from connections parameters using -- optionsToDefaultConfig. defaultConfig :: Config -- | Default configuration for PostgreSQL versions 9.3 and greater but less -- than 10. -- -- If you get an error that "--no-sync" is an invalid parameter then you -- should use this config. defaultConfig_9_3_10 :: Config -- | This is similar to defaultConfig but it logs as much as -- possible.. verboseConfig :: Config -- | Attempt to create a Config from a Options. Useful if you -- want to create a database owned by a specific user you will also login -- with among other use cases. optionsToDefaultConfig :: Options -> Config -- | Handle for holding temporary resources, the postgres process -- handle and postgres connection information. The DB -- also includes the final plan used to start initdb, -- createdb and postgres. data DB -- | Convert a DB to a connection string. Alternatively one can -- access the Options using toConnectionOptions. toConnectionString :: DB -> ByteString -- | Convert a DB to a connection Options type. toConnectionOptions :: DB -> Options -- | Access the data directory. This was either generated or specified -- explicitly when creating the Config toDataDirectory :: DB -> FilePath -- | Get the directory that is used to create other temporary directories toTemporaryDirectory :: DB -> FilePath -- | Get the final postgresql.conf toPostgresqlConfigFile :: DB -> String -- | Make the data directory permanent. Useful for debugging. If you are -- using with or withConfig this function will not modify -- the DB that is passed for cleanup. You will need to setup your -- own bracket like -- --
--   bracket (fmap makeDataDirectoryPermanent start) (either mempty stop)
--   
makeDataDirectoryPermanent :: DB -> DB -- | Display a DB. prettyPrintDB :: DB -> String -- | Default start behavior. Equivalent to calling startConfig with -- the defaultConfig. start :: IO (Either StartError DB) -- | Create zero or more temporary resources and use them to make a -- Config. -- -- The passed in config is inspected and a generated config is created. -- The final config is built by -- --
--   generated <> extra
--   
-- -- Based on the value of socketDirectory a "postgresql.conf" is -- created with: -- --
--   listen_addresses = '127.0.0.1, ::1'
--   unix_socket_directories = 'SOCKET_DIRECTORY'
--   
-- -- Additionally the generated Config also: -- -- -- -- All of these values can be overrided by the extra config. -- -- The returned DB requires cleanup. startConfig should be -- used with a bracket and stop, e.g. -- --
--   withConfig :: Config -> (DB -> IO a) -> IO (Either StartError a)
--   withConfig plan f = bracket (startConfig plan) (either mempty stop) $
--     either (pure . Left) (fmap Right . f)
--   
-- -- or just use withConfig. If you are calling startConfig -- you probably want withConfig anyway. startConfig :: Config -> IO (Either StartError DB) -- | Stop the postgres process and cleanup any temporary resources -- that might have been created. stop :: DB -> IO () -- | Restart the postgres from DB using the prior -- Config. This will also start an instance previously stoppped -- with stopPostgres. restart :: DB -> IO (Either StartError DB) -- | Only stop the postgres process but leave any temporary -- resources. Useful for testing backup strategies when used in -- conjunction with restart or withRestart. stopPostgres :: DB -> IO ExitCode -- | Equivalent to withDbCacheConfig with the CacheConfig -- defaultCacheConfig makes. -- -- Here is an example using caching: -- --
--   withDbCache $ \cache -> do
--     withCache (cacheConfig cache) $ \db -> ...
--     withCache (cacheConfig cache) $ \db -> ...
--   
withDbCache :: (Cache -> IO a) -> IO a -- | Enable initdb data directory caching. This can lead to a 4x -- speedup. -- -- Exception safe version of setupInitDbCache. Equivalent to -- --
--   withDbCacheConfig = bracket (setupInitDbCache config) cleanupInitDbCache
--   
withDbCacheConfig :: CacheConfig -> (Cache -> IO a) -> IO a -- | Configuration for the initdb data directory cache. data CacheConfig CacheConfig :: FilePath -> DirectoryType -> Bool -> CacheConfig -- | Root temporary directory used if cacheDirectoryType is set to -- Temporary. /tmp is a good default. [cacheTemporaryDirectory] :: CacheConfig -> FilePath -- | Used to specify is a Permanent or Temporary directory -- should be used. defaultCacheConfig uses Permanent -- ~/.tmp-postgres by default. [cacheDirectoryType] :: CacheConfig -> DirectoryType -- | Some operatoring system versions support flags for cp that -- allow "copy on write" which is about 2x faster. -- defaultCacheConfig attempts to determine if the cp on -- the path supports copy on write and sets this to True if it -- does. [cacheUseCopyOnWrite] :: CacheConfig -> Bool -- | defaultCacheConfig attempts to determine if the cp on -- the path supports "copy on write" flags and if it does, sets -- cacheUseCopyOnWrite to True. -- -- It sets cacheDirectoryType to Permanent -- ~/.tmp-postgres and cacheTemporaryDirectory to -- /tmp (but this is not used when Permanent is set). defaultCacheConfig :: CacheConfig -- | A handle to cache temporary resources and configuration. data Cache -- | Helper to make a Config out of caching info. cacheConfig :: Cache -> Config -- | Setup the initdb cache folder. setupInitDbCache :: CacheConfig -> IO Cache -- | Cleanup the cache directory if it was Temporary. cleanupInitDbCache :: Cache -> IO () -- | Exception safe method for taking a file system level copy of the -- database cluster. -- -- Snapshots are useful if you would like to start every test from a -- migrated database and the migration process is more time consuming -- then copying the additional data. -- -- Here is an example with caching and snapshots: -- --
--   withDbCache $ \cache -> withConfig (cacheConfig cache) $ \db ->
--     migrate db
--     withSnapshot Temporary db $ \snapshot -> do
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--       withConfig (snapshotConfig db) $ \migratedDb -> ...
--   
-- -- The Snapshots are ephemeral. If you would like the -- Snapshots to persistent consider using cacheAction -- instead. withSnapshot :: DB -> (Snapshot -> IO a) -> IO (Either StartError a) -- | A type to track a possibly temporary snapshot directory data Snapshot -- | Convert a snapshot into a Config that includes a -- copyConfig for copying the snapshot directory to a temporary -- directory. snapshotConfig :: Snapshot -> Config -- | Shutdown the database and copy the directory to a folder. takeSnapshot :: DB -> IO (Either StartError Snapshot) -- | Cleanup any temporary resources used for the snapshot. cleanupSnapshot :: Snapshot -> IO () -- | Check to see if a cached data directory exists. -- -- If the file path does not exist the initial config is used to -- start a postgres instance. After which the action is -- applied, the data directory is cached and postgres is -- shutdown. -- -- cacheAction mappends a config to copy the cached data -- directory on startup onto the initial config and returns it. -- In other words: -- --
--   initialConfig <> configFromCachePath
--   
-- -- cacheAction can be used to create a snapshot of migrated -- database and not remigrate as long as the migration does not change. -- See withSnapshot for a ephemeral version of taking snapshots. cacheAction :: FilePath -> (DB -> IO ()) -> Config -> IO (Either StartError Config) -- | A list of failures that can occur when starting. This is not and -- exhaustive list but covers the errors that the system catches for the -- user. data StartError -- | postgres failed before a connection succeeded. Most likely -- this is due to invalid configuration StartPostgresFailed :: ExitCode -> StartError -- | initdb failed. This can be from invalid configuration or -- using a non-empty data directory InitDbFailed :: String -> String -> ExitCode -> StartError [startErrorStdOut] :: StartError -> String [startErrorStdErr] :: StartError -> String [startErrorExitCode] :: StartError -> ExitCode -- | createdb failed. This can be from invalid configuration or -- the database might already exist. CreateDbFailed :: String -> String -> ExitCode -> StartError [startErrorStdOut] :: StartError -> String [startErrorStdErr] :: StartError -> String [startErrorExitCode] :: StartError -> ExitCode -- | The Plan was missing info and a complete Plan could not -- be created. PlanFailed :: String -> [String] -> StartError -- | The ProcessConfig was missing info and a -- CompleteProcessConfig could not be created. CompleteProcessConfigFailed :: String -> [String] -> StartError -- | Timed out waiting for postgres to accept a connection ConnectionTimedOut :: StartError DeleteDbError :: SqlError -> StartError -- | This will happen if a Plan is missing a initDbConfig. EmptyDataDirectory :: StartError -- | This is called if copying a folder cache fails. CopyCachedInitDbFailed :: String -> ExitCode -> StartError -- | Failed to find a data directory when trying to get a cached -- initdb folder. FailedToFindDataDirectory :: String -> StartError -- | We tried to copy a data directory to a snapshot folder and it failed SnapshotCopyFailed :: String -> ExitCode -> StartError -- | The high level options for overriding default behavior. data Config Config :: Last Logger -> Accum ProcessConfig -> Last (Maybe CopyDirectoryCommand) -> Accum ProcessConfig -> ProcessConfig -> Options -> [(String, String)] -> Last Int -> DirectoryType -> DirectoryType -> Last (Maybe Int) -> Last FilePath -> Last (Maybe (Bool, FilePath)) -> Config -- | Internal Event logger. [logger] :: Config -> Last Logger -- | Monoid for accumulating initdb configuration. [initDbConfig] :: Config -> Accum ProcessConfig -- | An optional data directory copy command. [copyConfig] :: Config -> Last (Maybe CopyDirectoryCommand) -- | Monoid for accumulating createdb configuration. [createDbConfig] :: Config -> Accum ProcessConfig -- | The postgres process configuration. [postgresConfig] :: Config -> ProcessConfig -- | The additional client connection options. [connectionOptions] :: Config -> Options -- | The postgresql.conf configuration file. [postgresConfigFile] :: Config -> [(String, String)] -- | The amount of microseconds to attempt to connect to postgres -- before throwing ConnectionTimedOut [connectionTimeout] :: Config -> Last Int -- | Override the default temporary UNIX socket directory by setting this. [socketDirectory] :: Config -> DirectoryType -- | Override the default temporary data directory by passing in -- Permanent DIRECTORY. [dataDirectory] :: Config -> DirectoryType -- | A monoid for using an existing port (via Just -- PORT_NUMBER) or requesting a free port (via a -- Nothing). [port] :: Config -> Last (Maybe Int) -- | The directory used to create other temporary directories. Defaults to -- /tmp. [temporaryDirectory] :: Config -> Last FilePath [initDbCache] :: Config -> Last (Maybe (Bool, FilePath)) -- | Display a Config. prettyPrintConfig :: Config -> String -- | Process configuration data ProcessConfig ProcessConfig :: EnvironmentVariables -> CommandLineArgs -> Last Handle -> Last Handle -> Last Handle -> ProcessConfig -- | A monoid for combine environment variables or replacing them. for the -- maps the Dual monoid is used. So the last key wins. [environmentVariables] :: ProcessConfig -> EnvironmentVariables -- | A monoid for combine command line Args or replacing them. [commandLine] :: ProcessConfig -> CommandLineArgs -- | A monoid for configuring the standard input Handle. [stdIn] :: ProcessConfig -> Last Handle -- | A monoid for configuring the standard output Handle. [stdOut] :: ProcessConfig -> Last Handle -- | A monoid for configuring the standard error Handle. [stdErr] :: ProcessConfig -> Last Handle -- | The environment variables can be declared to inherit from the running -- process or they can be specifically added. data EnvironmentVariables EnvironmentVariables :: Last Bool -> Map String String -> EnvironmentVariables [inherit] :: EnvironmentVariables -> Last Bool [specific] :: EnvironmentVariables -> Map String String -- | A type to help combine command line Args. data CommandLineArgs CommandLineArgs :: Map String (Maybe String) -> Map Int String -> CommandLineArgs -- | Args of the form -h foo, --host=foo and -- --switch. The key is mappended with value so the key -- should include the space or equals (as shown in the first two examples -- respectively). The Dual monoid is used so the last key wins. [keyBased] :: CommandLineArgs -> Map String (Maybe String) -- | Args that appear at the end of the key based Args. The Dual -- monoid is used so the last key wins. [indexBased] :: CommandLineArgs -> Map Int String -- | Used to specify a Temporary folder that is automatically -- cleaned up or a Permanent folder which is not automatically -- cleaned up. data DirectoryType -- | A permanent file that should not be generated. Permanent :: FilePath -> DirectoryType -- | A temporary file that needs to generated. Temporary :: DirectoryType -- | A type to track whether a file is temporary and needs to be cleaned -- up. data CompleteDirectoryType CPermanent :: FilePath -> CompleteDirectoryType CTemporary :: FilePath -> CompleteDirectoryType -- | Accum is a monoid. -- -- It's <> behavior is analogous to 1 and 0 with *. -- Think of DontCare as 1 and Zlich as 0. -- -- The behavior of Merge is like Justs. data Accum a DontCare :: Accum a Zlich :: Accum a Merge :: a -> Accum a -- | A way to log internal Events type Logger = Event -> IO () -- | Internal events for debugging data Event -- | The first event. This useful for debugging what is actual passed to -- the initdb, createdb and postgres. StartPlan :: String -> Event -- | The second event. Postgres is about to get called StartPostgres :: Event -- | The third event. Postgres started. We are now about to setup a -- reconnect loop (racing with a process checker) WaitForDB :: Event -- | The fourth event and (possibly all subsequent events). We are looping -- trying to successfully connect to the postgres process. TryToConnect :: Event