Add some basic error handling
This commit is contained in:
+34
-10
@@ -1,10 +1,15 @@
|
||||
{-# LANGUAGE DeriveAnyClass #-}
|
||||
{-# LANGUAGE DuplicateRecordFields #-}
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-deriving-defaults #-}
|
||||
|
||||
module Yore.DB
|
||||
( DayIndex (..)
|
||||
( DB
|
||||
, Error (..)
|
||||
, initDB
|
||||
, withConn
|
||||
, DayIndex (..)
|
||||
, DayFile (..)
|
||||
, createDayFile
|
||||
, createDayIndex
|
||||
@@ -12,25 +17,44 @@ module Yore.DB
|
||||
, readDayPaths
|
||||
, getDayFileByIssue
|
||||
, getNumberOfIssues
|
||||
, Table (..)
|
||||
, getTables
|
||||
) where
|
||||
|
||||
import Control.Concurrent (getNumCapabilities)
|
||||
import Data.Functor.Identity (Identity (..))
|
||||
import Data.Pool (Pool, defaultPoolConfig, newPool, withResource)
|
||||
import Data.Text (Text)
|
||||
import Data.Time (Day)
|
||||
import GHC.Generics (Generic)
|
||||
|
||||
import qualified Database.PostgreSQL.Opium as Opium
|
||||
|
||||
data Table = Table
|
||||
{ schema :: String
|
||||
, name :: String
|
||||
}
|
||||
deriving (Show, Generic, Opium.FromRow)
|
||||
newtype DB = DB (Pool (Either Opium.ConnectionError Opium.Connection))
|
||||
|
||||
getTables :: Opium.Connection -> IO (Either Opium.Error [Table])
|
||||
getTables = Opium.fetch_ "SELECT table_schema AS schema, table_name AS name FROM information_schema.tables"
|
||||
data Error
|
||||
= ConnectionError Opium.ConnectionError
|
||||
| Error Opium.Error
|
||||
deriving (Show)
|
||||
|
||||
initDB :: Text -> IO DB
|
||||
initDB connString = do
|
||||
capabilities <- getNumCapabilities
|
||||
let maxResources = capabilities
|
||||
DB
|
||||
<$> newPool
|
||||
( defaultPoolConfig
|
||||
(Opium.connect connString)
|
||||
(either (const $ pure ()) Opium.close)
|
||||
10
|
||||
maxResources
|
||||
)
|
||||
|
||||
withConn :: DB -> (Opium.Connection -> IO (Either Opium.Error a)) -> IO (Either Error a)
|
||||
withConn (DB connPool) f =
|
||||
withResource connPool $ \case
|
||||
Left connectionError ->
|
||||
pure $ Left $ ConnectionError connectionError
|
||||
Right conn ->
|
||||
either (Left . Error) Right <$> f conn
|
||||
|
||||
data DayIndex = DayIndex
|
||||
{ day_index_id :: Int
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
module Yore.Log (info) where
|
||||
module Yore.Log (Yore.Log.error, info) where
|
||||
|
||||
import Data.Time (getZonedTime)
|
||||
import GHC.Stack (HasCallStack, SrcLoc (..), callStack, getCallStack)
|
||||
@@ -7,6 +7,9 @@ import Text.Printf (printf)
|
||||
info :: (HasCallStack) => String -> IO ()
|
||||
info = doLog "INF"
|
||||
|
||||
error :: (HasCallStack) => String -> IO ()
|
||||
error = doLog "ERR"
|
||||
|
||||
doLog :: (HasCallStack) => String -> String -> IO ()
|
||||
doLog level msg = do
|
||||
now <- getZonedTime
|
||||
|
||||
Reference in New Issue
Block a user