Skip to content
This repository
Browse code

Add overview and example code to FromField

  • Loading branch information...
commit 53112fba2c707e2fa9cc42973693d6ed349f5980 1 parent e2ec894
Leon P Smith authored

Showing 1 changed file with 40 additions and 1 deletion. Show diff stats Hide diff stats

  1. +40 1 src/Database/PostgreSQL/Simple/FromField.hs
41 src/Database/PostgreSQL/Simple/FromField.hs
@@ -23,12 +23,51 @@
23 23 -- since a 'Double' might lose precision if representing a 64-bit @BigInt@,
24 24 -- the two are /not/ considered compatible.
25 25 --
  26 +-- Because 'FromField' is a typeclass, one may provide conversions to
  27 +-- additional Haskell types without modifying postgresql-simple. This is
  28 +-- particularly useful for supporting PostgreSQL types that postgresql-simple
  29 +-- does not support out-of-box. Here's an example of what such an instance
  30 +-- might look like for a UUID type that implements the @Read@ class:
  31 +--
  32 +-- @
  33 +-- import Data.UUID ( UUID )
  34 +-- import Database.PostgreSQL.Simple.BuiltinTypes
  35 +-- ( BuiltinType(UUID), builtin2oid )
  36 +-- import qualified Data.ByteString as B
  37 +--
  38 +-- instance FromField UUID where
  39 +-- fromField f mdata =
  40 +-- if typeOid f /= builtin2oid UUID
  41 +-- then returnError Incompatible f ""
  42 +-- else case B.unpack `fmap` mdata of
  43 +-- Nothing -> returnError UnexpectedNull f ""
  44 +-- Just data ->
  45 +-- case [ x | (x,t) <- reads data, ("","") <- lex t ] of
  46 +-- [x] -> Ok x
  47 +-- _ -> returnError ConversionError f data
  48 +-- @
  49 +--
  50 +-- Note that because PostgreSQL's @uuid@ type is built into postgres and is
  51 +-- not provided by an extension, the 'typeOid' of @uuid@ does not change and
  52 +-- thus we can examine it directly. Here, we simply pull the type oid out
  53 +-- of the static table provided by postgresql-simple.
  54 +--
  55 +-- On the other hand if the type is provided by an extension, such as
  56 +-- @PostGIS@ or @hstore@, then the 'typeOid' is not stable and can vary from
  57 +-- database to database. In this case it is recommended that FromField
  58 +-- instances use 'typename' instead.
  59 +--
26 60 ------------------------------------------------------------------------------
27 61
28 62 module Database.PostgreSQL.Simple.FromField
29 63 (
30 64 FromField(..)
31 65 , FieldParser
  66 + , Conversion()
  67 +
  68 + , runConversion
  69 + , conversionMap
  70 + , conversionError
32 71 , ResultError(..)
33 72 , returnError
34 73
@@ -294,7 +333,7 @@ instance FromField LocalTimestamp where
294 333 instance FromField Date where
295 334 fromField = ff Date parseDate
296 335
297   -ff :: Typeable a
  336 +ff :: Typeable a
298 337 => BuiltinType -> (B8.ByteString -> Either String a)
299 338 -> Field -> Maybe B8.ByteString -> Conversion a
300 339 ff pgType parse f mstr =

0 comments on commit 53112fb

Please sign in to comment.
Something went wrong with that request. Please try again.