Last active
December 16, 2015 02:49
-
-
Save mmakowski/5365695 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-} | |
module SQL where | |
import Control.Applicative | |
import Database.SQLite3 | |
import Data.Function | |
import Data.Int | |
import Data.Text | |
dbname = "chinook.sqlite" | |
query = "select * from album" | |
class HasHandler h where | |
getHandler :: h -> Statement -> ColumnIndex -> IO () | |
instance HasHandler (IO ()) where | |
getHandler h _ _ = h | |
instance (HasHandler a) => HasHandler (Int64 -> a) where | |
getHandler f s i = do | |
v <- columnInt64 s i | |
getHandler (f v) s (i + 1) | |
instance (HasHandler a) => HasHandler (Text -> a) where | |
getHandler f s i = do | |
v <- columnText s i | |
getHandler (f v) s (i + 1) | |
data Album = Album { albumId :: Int64 | |
, albumTitle :: Text | |
, albumtArtistId :: Int64 | |
} | |
deriving (Eq, Show) | |
main :: IO () | |
main = do | |
db <- open dbname | |
execQuery db query processRow | |
processRow :: Int64 -> Text -> Int64 -> IO () | |
processRow id title artistId = print (Album id title artistId) | |
execQuery :: (HasHandler a) => Database -> Text -> a -> IO () | |
execQuery db query proc = do | |
stmt <- prepare db query | |
fix $ \loop -> do | |
rslt <- step stmt | |
case rslt of | |
Row -> do | |
(getHandler proc) stmt 0 | |
loop | |
Done -> return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment