Skip to content

Instantly share code, notes, and snippets.

@mmakowski
Last active December 16, 2015 02:49
Show Gist options
  • Save mmakowski/5365695 to your computer and use it in GitHub Desktop.
Save mmakowski/5365695 to your computer and use it in GitHub Desktop.
{-# 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