-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathBlogDB.hs
60 lines (44 loc) · 1.47 KB
/
BlogDB.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module BlogDB where
import Database.SQLite
import Control.Exception
import Data.Typeable
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
-- -----------------------------------------------------------------------------
-- A monad
type Blog a = ReaderT SQLiteHandle IO a
run :: Blog a -> IO a
run m = do
db <- openConnection "blog.sqlite"
runReaderT m db
-- -----------------------------------------------------------------------------
-- An API
type PostId = Int
type PostContent = String
getPostIds :: Blog [PostId]
getPostContent :: PostId -> Blog PostContent
-- more operations...
-- -----------------------------------------------------------------------------
-- Implementation
sql :: String -> Blog (Either String [[Row Value]])
sql query = do
db <- ask
liftIO $ do
putStrLn query
execStatement db query
getPostIds = do
r <- sql "select postid from postinfo;"
case r of
Right [rows] -> return [ fromIntegral id | [(_,Int id)] <- rows ]
Left s -> liftIO $ throwIO (BlogDBException s)
_ -> liftIO $ throwIO (BlogDBException "invalid result")
getPostContent x = do
r <- sql ("select content from postcontent where postid = " ++
show x ++ ";")
case r of
Right [[[(_,Text str)]]] -> return str
Left s -> liftIO $ throwIO (BlogDBException s)
_ -> liftIO $ throwIO (BlogDBException "invalid result")
data BlogDBException = BlogDBException String
deriving (Show, Typeable)
instance Exception BlogDBException