2 Module : Gargantext.Database.Util
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 Here is a longer description of this module, containing some
11 commentary with @some markup@.
14 {-# LANGUAGE FlexibleContexts #-}
15 {-# LANGUAGE NoImplicitPrelude #-}
16 {-# LANGUAGE OverloadedStrings #-}
18 module Gargantext.Database.Utils where
20 import qualified Database.PostgreSQL.Simple as PGS
22 import Data.Aeson (Result(Error,Success), fromJSON, FromJSON)
23 import Data.Typeable (Typeable)
24 import Data.Monoid ((<>))
25 import Data.Either.Extra (Either(Left, Right))
26 import Database.PostgreSQL.Simple.Internal (Field)
27 import qualified Data.ByteString as DB
28 import Database.PostgreSQL.Simple.FromField ( Conversion
29 , ResultError(ConversionFailed)
34 import Data.Ini (readIniFile, lookupValue)
35 import Data.Text (unpack, pack)
36 import Data.Word (Word16)
37 import Database.PostgreSQL.Simple (Connection, connect)
38 import Gargantext.Prelude
39 import System.IO (FilePath)
40 import Text.Read (read)
43 import Opaleye (Query, Unpackspec, showSqlForPostgres)
44 import Data.Profunctor.Product.Default (Default)
45 import Data.Maybe (maybe)
46 -- TODO add a reader Monad here
47 -- read this in the init file
49 databaseParameters :: FilePath -> IO PGS.ConnectInfo
50 databaseParameters fp = do
52 let ini'' = case ini of
53 Left e -> panic (pack $ "No ini file error" <> show e)
56 let val x = case (lookupValue (pack "django") (pack x) ini'') of
57 Left _ -> panic (pack $ "no" <> x)
60 pure $ PGS.ConnectInfo { PGS.connectHost = val "DB_HOST"
61 , PGS.connectPort = read (val "DB_PORT") :: Word16
62 , PGS.connectUser = val "DB_USER"
63 , PGS.connectPassword = val "DB_PASS"
64 , PGS.connectDatabase = val "DB_NAME"
67 connectGargandb :: FilePath -> IO Connection
68 connectGargandb fp = databaseParameters fp >>= \params -> connect params
70 printSql :: Default Unpackspec a a => Query a -> IO ()
71 printSql = putStrLn . maybe "Empty query" identity . showSqlForPostgres
73 fromField' :: (Typeable b, FromJSON b) => Field -> Maybe DB.ByteString -> Conversion b
74 fromField' field mb = do
75 v <- fromField field mb
78 valueToHyperdata v = case fromJSON v of
80 Error _err -> returnError ConversionFailed field "cannot parse hyperdata"
82 -- | Opaleye leftJoin* functions