2 Module : Gargantext.Database.Prelude
3 Description : Specific Prelude for Database management
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
12 {-# LANGUAGE ConstraintKinds #-}
14 module Gargantext.Database.Prelude where
16 import Control.Exception
17 import Control.Lens (Getter, view)
18 import Control.Monad.Except
19 --import Control.Monad.Logger (MonadLogger)
20 import Control.Monad.Random
21 import Control.Monad.Reader
22 import Control.Monad.Trans.Control (MonadBaseControl)
23 import Data.Aeson (Result(Error,Success), fromJSON, FromJSON)
24 import Data.ByteString.Char8 (hPutStrLn)
25 import Data.Either.Extra (Either)
26 import Data.Pool (Pool, withResource)
27 import Data.Profunctor.Product.Default (Default)
28 import Data.Text (pack, unpack, Text)
29 import Data.Word (Word16)
30 import Database.PostgreSQL.Simple (Connection, connect)
31 import Database.PostgreSQL.Simple.FromField ( Conversion, ResultError(ConversionFailed), fromField, returnError)
32 import Database.PostgreSQL.Simple.Internal (Field)
33 import Gargantext.Core.Mail.Types (HasMail)
34 import Gargantext.Prelude
35 import Gargantext.Prelude.Config (readIniFile', val)
36 import Opaleye (Unpackspec, showSql, FromFields, Select, runSelect, SqlJsonb, DefaultFromField)
37 import Opaleye.Aggregate (countRows)
38 import System.IO (FilePath)
39 import System.IO (stderr)
40 import Text.Read (readMaybe)
41 import qualified Data.ByteString as DB
42 import qualified Data.List as DL
43 import qualified Database.PostgreSQL.Simple as PGS
45 import Gargantext.Prelude.Config (GargConfig())
47 -------------------------------------------------------
48 class HasConnectionPool env where
49 connPool :: Getter env (Pool Connection)
51 instance HasConnectionPool (Pool Connection) where
54 class HasConfig env where
55 hasConfig :: Getter env GargConfig
57 instance HasConfig GargConfig where
60 -------------------------------------------------------
61 type JSONB = DefaultFromField SqlJsonb
62 -------------------------------------------------------
64 type CmdM'' env err m =
67 , MonadBaseControl IO m
72 type CmdM' env err m =
75 , MonadBaseControl IO m
82 , HasConnectionPool env
87 type CmdRandom env err m =
89 , HasConnectionPool env
95 type Cmd'' env err a = forall m. CmdM'' env err m => m a
96 type Cmd' env err a = forall m. CmdM' env err m => m a
97 type Cmd err a = forall m env. CmdM env err m => m a
98 type CmdR err a = forall m env. CmdRandom env err m => m a
102 fromInt64ToInt :: Int64 -> Int
103 fromInt64ToInt = fromIntegral
105 -- TODO: ideally there should be very few calls to this functions.
106 mkCmd :: (Connection -> IO a) -> Cmd err a
108 pool <- view connPool
109 withResource pool (liftBase . k)
111 runCmd :: (HasConnectionPool env)
115 runCmd env m = runExceptT $ runReaderT m env
117 runOpaQuery :: Default FromFields fields haskells
119 -> Cmd err [haskells]
120 runOpaQuery q = mkCmd $ \c -> runSelect c q
122 runCountOpaQuery :: Select a -> Cmd err Int
123 runCountOpaQuery q = do
124 counts <- mkCmd $ \c -> runSelect c $ countRows q
125 -- countRows is guaranteed to return a list with exactly one row so DL.head is safe here
126 pure $ fromInt64ToInt $ DL.head counts
128 formatPGSQuery :: PGS.ToRow a => PGS.Query -> a -> Cmd err DB.ByteString
129 formatPGSQuery q a = mkCmd $ \conn -> PGS.formatQuery conn q a
131 -- TODO use runPGSQueryDebug everywhere
132 runPGSQuery' :: (PGS.ToRow a, PGS.FromRow b) => PGS.Query -> a -> Cmd err [b]
133 runPGSQuery' q a = mkCmd $ \conn -> PGS.query conn q a
135 runPGSQuery :: ( CmdM env err m
136 , PGS.FromRow r, PGS.ToRow q
138 => PGS.Query -> q -> m [r]
139 runPGSQuery q a = mkCmd $ \conn -> catch (PGS.query conn q a) (printError conn)
141 printError c (SomeException e) = do
142 q' <- PGS.formatQuery c q a
144 throw (SomeException e)
148 runPGSQueryFold :: ( CmdM env err m
151 => PGS.Query -> a -> (a -> r -> IO a) -> m a
152 runPGSQueryFold q initialState consume = mkCmd $ \conn -> catch (PGS.fold_ conn initialState consume) (printError conn)
154 printError c (SomeException e) = do
155 q' <- PGS.formatQuery c q
157 throw (SomeException e)
162 -- | TODO catch error
163 runPGSQuery_ :: ( CmdM env err m
166 => PGS.Query -> m [r]
167 runPGSQuery_ q = mkCmd $ \conn -> catch (PGS.query_ conn q) printError
169 printError (SomeException e) = do
170 printDebug "[G.D.P.runPGSQuery_]" ("TODO: format query error" :: Text)
171 throw (SomeException e)
174 execPGSQuery :: PGS.ToRow a => PGS.Query -> a -> Cmd err Int64
175 execPGSQuery q a = mkCmd $ \conn -> PGS.execute conn q a
177 ------------------------------------------------------------------------
178 databaseParameters :: FilePath -> IO PGS.ConnectInfo
179 databaseParameters fp = do
180 ini <- readIniFile' fp
181 let val' key = unpack $ val ini "database" key
182 let dbPortRaw = val' "DB_PORT"
183 let dbPort = case (readMaybe dbPortRaw :: Maybe Word16) of
184 Nothing -> panic $ "DB_PORT incorrect: " <> (pack dbPortRaw)
187 pure $ PGS.ConnectInfo { PGS.connectHost = val' "DB_HOST"
188 , PGS.connectPort = dbPort
189 , PGS.connectUser = val' "DB_USER"
190 , PGS.connectPassword = val' "DB_PASS"
191 , PGS.connectDatabase = val' "DB_NAME"
194 connectGargandb :: FilePath -> IO Connection
195 connectGargandb fp = databaseParameters fp >>= \params -> connect params
197 fromField' :: (Typeable b, FromJSON b) => Field -> Maybe DB.ByteString -> Conversion b
198 fromField' field mb = do
199 v <- fromField field mb
202 valueToHyperdata v = case fromJSON v of
204 Error _err -> returnError ConversionFailed field
205 $ DL.intercalate " " [ "cannot parse hyperdata for JSON: "
209 printSqlOpa :: Default Unpackspec a a => Select a -> IO ()
210 printSqlOpa = putStrLn . maybe "Empty query" identity . showSql