structured-mongoDB-0.3: Structured MongoDB interface

Safe HaskellNone

Database.MongoDB.Structured.Deriving.TH

Description

This module exports a Structued type class which can be used to convert from Haskel "record types" to BSON objects and vice versa. We use Templace Haskell to provide a function deriveStructured which can be used to automatically generate an instance of such types for the Structured and BSON's Val classes.

For instance:

 data User = User { userId :: Int
                  , userFirstName :: String
                  , userLastName :: String
                  }
             deriving(Show, Read, Eq, Ord, Typeable)
 $(deriveStructured ''User)
 

deriveStrctured used used to create the following instance of Structured:

 instance Structured User where
   toBSON x = [ (u "_id")           := val (userId x)
              , (u "userFirstName") := val (userFirstName x)
              , (u "userLastName")  := val (userLastName x)
              ]
   
   fromBSON doc = lookup (u "_id")             doc >>= \val_1 ->
                  lookup (u "userFirstName")   doc >>= \val_2 ->
                  lookup (u "userLastName")    doc >>= \val_3 ->
                  return User { userId        = val_1
                              , userFirstName = val_2
                              , userLastname  = val_3
                              }

To allow for structured and well-typed queies, it also generates types corresponding to each field (which are made an instance of Selectable). Specifically, for the above data type, it creates:

  data UserId = UserId deriving (Show, Eq)
  instance Selectable User UserId SObjId where s _ _ = "_id"
  
  data FirstName = FirstName deriving (Show, Eq)
  instance Selectable User FirstName String where s _ _ = "firstName"
  
  data LastName = LastName deriving (Show, Eq)
  instance Selectable User LastName String where s _ _ = "lastName"

Synopsis

Documentation

deriveStructured :: Name -> Q [Dec]Source

This function generates Structured and Val instances for record types.