Basic example of using HaskellDB to unmap records of a table
Asked Answered
S

1

12

Suppose that I have the following (PostgreSQL) table definition:

CREATE TABLE books (
    id serial NOT NULL,
    title character varying NOT NULL,

    PRIMARY KEY (id)
);

And the following record definition:

data Book = 
  { id :: Int
  , title :: String
  }

What is a basic example of an "unmap" function to query all books in the database, allBooks :: Database -> IO [Book]?

Selfdeprecating answered 8/10, 2011 at 14:57 Comment(0)
S
8

It turns out that I was going about this the wrong way.

After stumbling upon Mats Rauhala's exceedingly helpful blog post titled Example on using HaskellDB, I was able to write a test project to read the records of the books table.

I first needed to define the "layout", which, using haskelldb-th, is not too bad:

{-# LANGUAGE TemplateHaskell #-}

module Tables.Books (
    books
  , id
  , title
  , Books
  ) where

import Database.HaskellDB.CodeGen
import Prelude hiding (id)

mkDBDirectTable "Books" [
    ("id", [t|Int|])
  , ("title", [t|String|])
  ]

From there, the allBooks function is:

allBooks db = query db $ do
    books <- table B.books
    return books

where B is the qualified name of imported module Tables.Books. allBooks has the type:

allBooks :: Database
            -> IO
                 [Record
                    (Database.HaskellDB.HDBRec.RecCons
                       Tables.Books.Id
                       Int
                       (Database.HaskellDB.HDBRec.RecCons
                          Tables.Books.Title
                          String
                          Database.HaskellDB.HDBRec.RecNil))]

To print out each title, I used:

main :: IO ()
main = do
    books <- postgresqlConnect [("host", "localhost"), ("user", "test"), ("password", "********")] allBooks
    mapM_ putStrLn (map (\r -> r!B.title) books)
    return ()

EDIT: I created a git repository containing the complete sources of this example: dtrebbien/haskelldb-example

Selfdeprecating answered 8/10, 2011 at 22:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.