No title

Anonymous Coward 2018-04-26 05:27:02.697021 UTC

1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE DeriveGeneric #-}
4{-# LANGUAGE DataKinds #-}
5{-# LANGUAGE TypeOperators #-}
6
7module Main where
8
9import Control.Monad
10import Data.Text (Text)
11import Database.PostgreSQL.Simple
12import GHC.Generics
13import Database.PostgreSQL.Simple.FromRow
14import Database.PostgreSQL.Simple.FromField
15
16-- types
17
18type BookmarkId = Int
19
20data BookmarkStatus = Active | Archived
21
22instance Show BookmarkStatus where
23 show Active = "Active"
24 show Archived = "Archived"
25
26instance FromField BookmarkStatus where
27 fromField f bs
28 | bs == Just "1" = pure Active
29 | bs == Just "0" = pure Archived
30 | otherwise = returnError ConversionFailed f ""
31
32instance Eq BookmarkStatus where
33 (==) Active Active = True
34 (==) Archived Archived = True
35 (==) _ _ = False
36
37data Bookmark = Bookmark
38 { bid :: BookmarkId
39 , title :: Text
40 , url :: Text
41 , status :: BookmarkStatus
42 }
43 deriving (Eq, Generic, Show)
44
45instance FromRow Bookmark where
46 fromRow = Bookmark <$> field <*> field <*> field <*> field
47
48main :: IO ()
49main = do
50 db <- hDB
51 listItems db
52 putStrLn "FINISHED"
53
54listItems :: Connection -> IO ()
55listItems db = do
56 res <- query_ db "select id, title, url, status from bookmarks"
57 forM_ res $ \(bookmark) -> putStrLn bookmark
58
59connectDB :: String -> IO Connection
60connectDB dbname = connect defaultConnectInfo { connectDatabase = dbname, connectUser = "root" }
61
62hDB :: IO Connection
63hDB = connectDB "dbname"