]> Git — Sourcephile - gargantext.git/blob - src/Gargantext/Database/Utils.hs
[SQL/OPALEYE] leftJoin3. thanks to tomjaguarpaw https://github.com/tomjaguarpaw/haske...
[gargantext.git] / src / Gargantext / Database / Utils.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE FlexibleContexts #-}
3
4 module Gargantext.Database.Utils where
5
6 import qualified Database.PostgreSQL.Simple as PGS
7
8 import Data.Monoid ((<>))
9 import Data.Either.Extra (Either(Left, Right))
10 import Gargantext.Prelude
11 import Data.Text (unpack, pack)
12 import Text.Read (read)
13 import Data.Ini (readIniFile, lookupValue)
14 import Data.Word (Word16)
15 import System.IO (FilePath)
16 import Database.PostgreSQL.Simple (Connection, connect)
17
18 -- Utilities
19 import Opaleye (Query, Unpackspec, showSqlForPostgres)
20 import Data.Profunctor.Product.Default (Default)
21 import Data.Maybe (maybe)
22 import Prelude (id, putStrLn)
23 -- TODO add a reader Monad here
24 -- read this in the init file
25
26 databaseParameters :: FilePath -> IO PGS.ConnectInfo
27 databaseParameters fp = do
28 ini <- readIniFile fp
29 let ini'' = case ini of
30 Left e -> panic (pack $ "No ini file error" <> show e)
31 Right ini' -> ini'
32
33 let val x = case (lookupValue (pack "django") (pack x) ini'') of
34 Left _ -> panic (pack $ "no" <> x)
35 Right p' -> unpack p'
36
37 pure $ PGS.ConnectInfo { PGS.connectHost = val "DB_HOST"
38 , PGS.connectPort = read (val "DB_PORT") :: Word16
39 , PGS.connectUser = val "DB_USER"
40 , PGS.connectPassword = val "DB_PASS"
41 , PGS.connectDatabase = val "DB_NAME"
42 }
43
44 connectGargandb :: FilePath -> IO Connection
45 connectGargandb fp = do
46 parameters <- databaseParameters fp
47 connect parameters
48
49 printSql :: Default Unpackspec a a => Query a -> IO ()
50 printSql = putStrLn . maybe "Empty query" id . showSqlForPostgres
51