{-|
Module: IHP.ScriptSupport
Description: Run scripts inside the framework context, but outside of the usual web request response lifecycle
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.ScriptSupport (runScript, Script, module IHP.FrameworkConfig) where

import IHP.Prelude
import IHP.FrameworkConfig
import qualified IHP.Environment as Env
import IHP.ModelSupport
import IHP.ApplicationContext
import qualified Database.PostgreSQL.Simple as PG
import Control.Exception (finally)
import IHP.Log (Logger(cleanup))

-- | A script is just an IO action which requires a database connection and framework config
type Script = (?modelContext :: ModelContext, ?context :: FrameworkConfig) => IO ()

-- | Initializes IHP and then runs the script inside the framework context
runScript :: ConfigBuilder -> Script -> IO ()
runScript :: ConfigBuilder -> Script -> IO ()
runScript ConfigBuilder
configBuilder Script
taskMain = do
    frameworkConfig :: FrameworkConfig
frameworkConfig@FrameworkConfig { Environment
$sel:environment:FrameworkConfig :: FrameworkConfig -> Environment
environment :: Environment
environment, NominalDiffTime
$sel:dbPoolIdleTime:FrameworkConfig :: FrameworkConfig -> NominalDiffTime
dbPoolIdleTime :: NominalDiffTime
dbPoolIdleTime, Int
$sel:dbPoolMaxConnections:FrameworkConfig :: FrameworkConfig -> Int
dbPoolMaxConnections :: Int
dbPoolMaxConnections, ByteString
$sel:databaseUrl:FrameworkConfig :: FrameworkConfig -> ByteString
databaseUrl :: ByteString
databaseUrl, Logger
$sel:logger:FrameworkConfig :: FrameworkConfig -> Logger
logger :: Logger
logger } <- ConfigBuilder -> IO FrameworkConfig
buildFrameworkConfig ConfigBuilder
configBuilder
    ModelContext
modelContext <- NominalDiffTime -> Int -> ByteString -> Logger -> IO ModelContext
createModelContext NominalDiffTime
dbPoolIdleTime Int
dbPoolMaxConnections ByteString
databaseUrl Logger
logger

    let ?modelContext = modelContext
    let ?context = frameworkConfig
    IO ()
Script
taskMain IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` Logger -> IO ()
cleanup Logger
logger
{-# INLINABLE runScript #-}