Add some basic error handling

This commit is contained in:
Paul Brinkmeier
2025-08-21 23:40:32 +02:00
parent b264b50b01
commit 4c5ff2f319
5 changed files with 127 additions and 64 deletions
+34 -10
View File
@@ -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
View File
@@ -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