git.iko.soy/typeable/postgresql-simple
on master help sign in
Add overview and example code to FromField
commit53112fba2c707e2fa9cc42973693d6ed349f5980 authorLeon P Smith <leon@melding-monads.com> dateSun 27 Jan 2013, 23:24 (14 years ago) parente2ec894
1 file changed+40−1
src/Database/PostgreSQL/Simple/FromField.hs+40−1
src/Database/PostgreSQL/Simple/FromField.hs+40−1
@@ -23,12 +23,51 @@
2323-- since a 'Double' might lose precision if representing a 64-bit @BigInt@,
2424-- the two are /not/ considered compatible.
2525--
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+--
2660------------------------------------------------------------------------------
2761
2862module Database.PostgreSQL.Simple.FromField
2963 (
3064 FromField(..)
3165 , FieldParser
66+ , Conversion()
67+
68+ , runConversion
69+ , conversionMap
70+ , conversionError
3271 , ResultError(..)
3372 , returnError
3473
@@ -294,7 +333,7 @@ instance FromField LocalTimestamp where
294333instance FromField Date where
295334 fromField = ff Date parseDate
296335
297−ff :: Typeable a
336+ff :: Typeable a
298337 => BuiltinType -> (B8.ByteString -> Either String a)
299338 -> Field -> Maybe B8.ByteString -> Conversion a
300339ff pgType parse f mstr =