@@ -4,6 +4,7 @@
4{-# LANGUAGE PatternGuards #-}
4{-# LANGUAGE PatternGuards #-}
5{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE ViewPatterns #-}
6{-# LANGUAGE ViewPatterns #-}
7+{-# LANGUAGE QuasiQuotes #-}
8------------------------------------------------------------------------------
9------------------------------------------------------------------------------
@@ -13,6 +14,7 @@
13-- License: BSD3
14-- License: BSD3
14-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Stability: experimental
16-- Stability: experimental
17+-- Portability: portable
17-- A mid-level client library for the PostgreSQL database, aimed at ease of
19-- A mid-level client library for the PostgreSQL database, aimed at ease of
18-- use and high performance.
20-- use and high performance.
@@ -42,7 +44,7 @@ module Database.PostgreSQL.Simple
42 -- ** Modifying multiple rows at once
44 -- ** Modifying multiple rows at once
45− -- ** @RETURNING@: modifications that return results
47+ -- ** @RETURNING@: modifications that returns results
46 -- $returning
48 -- $returning
48 -- * Extracting results
50 -- * Extracting results
@@ -55,7 +57,8 @@ module Database.PostgreSQL.Simple
57 -- * Types
59 -- * Types
58− Connection
61+ , Connection
@@ -64,26 +67,19 @@ module Database.PostgreSQL.Simple
64 , Only(..)
67 , Only(..)
65 , (:.)(..)
68 , (:.)(..)
66 -- ** Exceptions
69 -- ** Exceptions
67− , SomePostgreSqlException(..)
68 , SqlError(..)
70 , SqlError(..)
70− , FormatError(..)
71+ , FormatError(fmtMessage, fmtQuery, fmtParams)
71− , QueryError(..)
72+ , QueryError(qeMessage, qeQuery)
72− , ResultError(..)
73+ , ResultError(errSQLType, errHaskellType, errMessage)
73 -- * Connection management
74 -- * Connection management
74− , Base.connectPostgreSQL
76 , Base.connect
75 , Base.connect
77− , Base.withConnect
76+ , Base.connectPostgreSQL
78− , Base.ConnectInfo(..)
79− , Base.defaultConnectInfo
80 , Base.postgreSQLConnectionString
77 , Base.postgreSQLConnectionString
78+ , Base.defaultConnectInfo
81 -- * Queries that return results
80 -- * Queries that return results
84− -- ** Queries taking parser as argument
87 -- * Queries that stream results
83 -- * Queries that stream results
88 , FoldOptions(..)
84 , FoldOptions(..)
89 , FetchQuantity(..)
85 , FetchQuantity(..)
@@ -95,14 +91,6 @@ module Database.PostgreSQL.Simple
96 , forEach_
92 , forEach_
97 , returning
93 , returning
98− -- ** Queries that stream results taking a parser as an argument
100− , foldWithOptionsAndParser
102− , foldWithOptionsAndParser_
106 -- * Statements that do not return results
94 -- * Statements that do not return results
107 , execute
95 , execute
108 , execute_
96 , execute_
@@ -110,9 +98,20 @@ module Database.PostgreSQL.Simple
110-- , Base.insertID
98-- , Base.insertID
111 -- * Transaction handling
99 -- * Transaction handling
112 , withTransaction
100 , withTransaction
113− , withSavepoint
101+ , withTransactionSerializable
102+ , TransactionMode(..)
103+ , IsolationLevel(..)
105+ , defaultTransactionMode
106+ , defaultIsolationLevel
107+ , defaultReadWriteMode
108+ , withTransactionLevel
109+ , withTransactionMode
110+ , withTransactionModeRetry
114-- , Base.autocommit
111-- , Base.autocommit
117 , rollback
116 , rollback
118 -- * Helper functions
117 -- * Helper functions
@@ -120,27 +119,50 @@ module Database.PostgreSQL.Simple
120 , formatQuery
119 , formatQuery
123−import Data.ByteString.Builder (Builder, byteString, char8)
122+import Blaze.ByteString.Builder
123+ ( Builder, fromByteString, toByteString )
124+import Blaze.ByteString.Builder.Char8 (fromChar)
124−import Control.Applicative ((<$>))
125+import Control.Applicative ((<$>), pure)
125−import Control.Exception as E
126+import Control.Concurrent.MVar
127+import Control.Exception
128+ ( Exception, onException, throw, throwIO, finally
129+ , try, SomeException, fromException )
130+import Control.Monad (foldM)
126import Data.ByteString (ByteString)
131import Data.ByteString (ByteString)
127import Data.Int (Int64)
132import Data.Int (Int64)
133+import qualified Data.IntMap as IntMap
128import Data.List (intersperse)
134import Data.List (intersperse)
129−import Data.Monoid (mconcat)
135+import Data.Monoid (mappend, mconcat)
136+import Data.Typeable (Typeable)
137+import Database.PostgreSQL.Simple.BuiltinTypes ( oid2typname )
130−import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
138+import Database.PostgreSQL.Simple.Compat ( mask )
131−import Database.PostgreSQL.Simple.Cursor
132import Database.PostgreSQL.Simple.FromField (ResultError(..))
139import Database.PostgreSQL.Simple.FromField (ResultError(..))
133import Database.PostgreSQL.Simple.FromRow (FromRow(..))
140import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134−import Database.PostgreSQL.Simple.ToField (Action(..))
141+import Database.PostgreSQL.Simple.Ok
142+import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
135import Database.PostgreSQL.Simple.ToRow (ToRow(..))
143import Database.PostgreSQL.Simple.ToRow (ToRow(..))
136import Database.PostgreSQL.Simple.Types
144import Database.PostgreSQL.Simple.Types
137 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
145 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
138import Database.PostgreSQL.Simple.Internal as Base
146import Database.PostgreSQL.Simple.Internal as Base
139−import Database.PostgreSQL.Simple.Internal.PQResultUtils
147+import Database.PostgreSQL.Simple.SqlQQ (sql)
140−import Database.PostgreSQL.Simple.Transaction
141import qualified Database.PostgreSQL.LibPQ as PQ
148import qualified Database.PostgreSQL.LibPQ as PQ
142import qualified Data.ByteString.Char8 as B
149import qualified Data.ByteString.Char8 as B
143−
150+import qualified Data.Text as T
151+import qualified Data.Text.Encoding as TE
152+import qualified Data.Vector as V
153+import Control.Monad.Trans.Reader
154+import Control.Monad.Trans.State.Strict
156+-- | Exception thrown if a 'Query' could not be formatted correctly.
157+-- This may occur if the number of \'@?@\' characters in the query
158+-- string does not match the number of parameters provided.
159+data FormatError = FormatError {
160+ fmtMessage :: String
162+ , fmtParams :: [ByteString]
163+ } deriving (Eq, Show, Typeable)
165+instance Exception FormatError
145-- | Format a query string.
167-- | Format a query string.
@@ -177,9 +199,9 @@ formatMany conn q@(Query template) qs = do
177 case parseTemplate template of
199 case parseTemplate template of
178 Just (before, qbits, after) -> do
200 Just (before, qbits, after) -> do
179 bs <- mapM (buildQuery conn q qbits . toRow) qs
201 bs <- mapM (buildQuery conn q qbits . toRow) qs
180− return . toByteString . mconcat $ byteString before :
202+ return . toByteString . mconcat $ fromByteString before :
181− intersperse (char8 ',') bs ++
203+ intersperse (fromChar ',') bs ++
182− [byteString after]
204+ [fromByteString after]
183 Nothing -> fmtError "syntax error in multi-row template" q []
205 Nothing -> fmtError "syntax error in multi-row template" q []
185-- Split the input string into three pieces, @before@, @qbits@, and @after@,
207-- Split the input string into three pieces, @before@, @qbits@, and @after@,
@@ -277,40 +299,43 @@ parseTemplate template =
278 skipSpace = B.dropWhile isSpace_ascii
300 skipSpace = B.dropWhile isSpace_ascii
302+escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
303+escapeStringConn conn s =
304+ withConnection conn $ \c ->
305+ PQ.escapeStringConn c s >>= checkError c
307+escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
308+escapeByteaConn conn s =
309+ withConnection conn $ \c ->
310+ PQ.escapeByteaConn c s >>= checkError c
312+checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
313+checkError _ (Just x) = return $ Right x
314+checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
316buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
282−buildQuery conn q template xs =
317+buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
283− zipParams (split template) <$> mapM (buildAction conn q xs) xs
318+ where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
284− where split s =
319+ (inQuotes . fromByteString)
285− -- This part escapes double '??'s to make literal '?'s possible
320+ utf8ToString = T.unpack . TE.decodeUtf8
286− -- in PostgreSQL queries using the JSON operators: @?@, @?|@ and @?&@
321+ sub (Plain b) = pure b
287− let (h,t) = breakOnSingleQuestionMark s
322+ sub (Escape s) = quote <$> escapeStringConn conn s
288− in byteString h
323+ sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
289− : if B.null t
324+ sub (Many ys) = mconcat <$> mapM sub ys
291− else split (B.tail t)
325+ split s = fromByteString h : if B.null t then [] else split (B.tail t)
326+ where (h,t) = B.break (=='?') s
292− zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
327+ zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
293 zipParams [t] [] = t
328 zipParams [t] [] = t
294− zipParams _ _ = fmtError (show countSingleQs ++
329+ zipParams _ _ = fmtError (show (B.count '?' template) ++
295− " single '?' characters, but " ++
330+ " '?' characters, but " ++
296 show (length xs) ++ " parameters") q xs
331 show (length xs) ++ " parameters") q xs
297− countSingleQs = go 0 template
298− where go i "" = (i :: Int)
299− go i bs = case qms of
300− ("?","?") -> go i nextQMBS
301− ("?",_) -> go (i+1) nextQMBS
303− where qms = B.splitAt 1 qmBS
304− (qmBS,nextQMBS) = B.splitAt 2 qmBS'
305− qmBS' = B.dropWhile (/= '?') bs
307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
333-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
308-- expected to return results.
334-- expected to return results.
310-- Returns the number of rows affected.
336-- Returns the number of rows affected.
312−-- Throws 'FormatError' if the query could not be formatted correctly, or
338+-- Throws 'FormatError' if the query could not be formatted correctly.
313−-- a 'SqlError' exception if the backend returns an error.
314execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
339execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
315execute conn template qs = do
340execute conn template qs = do
316 result <- exec conn =<< formatQuery conn template qs
341 result <- exec conn =<< formatQuery conn template qs
@@ -319,33 +344,9 @@ execute conn template qs = do
319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
344-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
320-- expected to return results.
345-- expected to return results.
322−-- Returns the number of rows affected. If the list of parameters is empty,
347+-- Returns the number of rows affected.
323−-- this function will simply return 0 without issuing the query to the backend.
324−-- If this is not desired, consider using the 'Values' constructor instead.
326−-- Throws 'FormatError' if the query could not be formatted correctly, or
327−-- a 'SqlError' exception if the backend returns an error.
329−-- For example, here's a command that inserts two rows into a table
333−-- executeMany c [sql|
334−-- INSERT INTO sometable VALUES (?,?)
335−-- |] [(1, \"hello\"),(2, \"world\")]
338−-- Here's an canonical example of a multi-row update command:
340−-- @
349+-- Throws 'FormatError' if the query could not be formatted correctly.
341−-- executeMany c [sql|
344−-- FROM (VALUES (?,?)) as upd(x,y)
345−-- WHERE sometable.x = upd.x
346−-- |] [(1, \"hello\"),(2, \"world\")]
349executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
350executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
350executeMany _ _ [] = return 0
351executeMany _ _ [] = return 0
351executeMany conn q qs = do
352executeMany conn q qs = do
@@ -359,20 +360,12 @@ executeMany conn q qs = do
359-- in cases where you are only inserting a single row, and do not need
360-- in cases where you are only inserting a single row, and do not need
360-- functionality analogous to 'executeMany'.
361-- functionality analogous to 'executeMany'.
362−-- If the list of parameters is empty, this function will simply return @[]@
363−-- without issuing the query to the backend. If this is not desired,
364−-- consider using the 'Values' constructor instead.
366-- Throws 'FormatError' if the query could not be formatted correctly.
363-- Throws 'FormatError' if the query could not be formatted correctly.
367returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
364returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
368−returning = returningWith fromRow
370−-- | A version of 'returning' taking parser as argument
371−returningWith :: (ToRow q) => RowParser r -> Connection -> Query -> [q] -> IO [r]
372−returningWith _ _ _ [] = return []
365+returning _ _ [] = return []
373−returningWith parser conn q qs = do
366+returning conn q qs = do
374 result <- exec conn =<< formatMany conn q qs
367 result <- exec conn =<< formatMany conn q qs
375− finishQueryWith parser conn q result
368+ finishQuery conn q result
377-- | Perform a @SELECT@ or other SQL query that is expected to return
370-- | Perform a @SELECT@ or other SQL query that is expected to return
378-- results. All results are retrieved and converted before this
371-- results. All results are retrieved and converted before this
@@ -389,27 +382,17 @@ returningWith parser conn q qs = do
389-- using 'execute' instead of 'query').
382-- using 'execute' instead of 'query').
391-- * 'ResultError': result conversion failed.
384-- * 'ResultError': result conversion failed.
393−-- * 'SqlError': the postgresql backend returned an error, e.g.
394−-- a syntax or type error, or an incorrect table or column name.
395−query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r]
385+query :: (ToRow q, FromRow r)
396−query = queryWith fromRow
386+ => Connection -> Query -> q -> IO [r]
387+query conn template qs = do
388+ result <- exec conn =<< formatQuery conn template qs
389+ finishQuery conn template result
398-- | A version of 'query' that does not perform query substitution.
391-- | A version of 'query' that does not perform query substitution.
399query_ :: (FromRow r) => Connection -> Query -> IO [r]
392query_ :: (FromRow r) => Connection -> Query -> IO [r]
400−query_ = queryWith_ fromRow
402−-- | A version of 'query' taking parser as argument
403−queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
404−queryWith parser conn template qs = do
405− result <- exec conn =<< formatQuery conn template qs
406− finishQueryWith parser conn template result
408−-- | A version of 'query_' taking parser as argument
409−queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
410−queryWith_ parser conn q@(Query que) = do
393+query_ conn q@(Query que) = do
411 result <- exec conn que
394 result <- exec conn que
412− finishQueryWith parser conn q result
395+ finishQuery conn q result
414-- | Perform a @SELECT@ or other SQL query that is expected to return
397-- | Perform a @SELECT@ or other SQL query that is expected to return
415-- results. Results are streamed incrementally from the server, and
398-- results. Results are streamed incrementally from the server, and
@@ -421,12 +404,6 @@ queryWith_ parser conn q@(Query que) = do
421-- This fold is /not/ strict. The stream consumer is responsible for
404-- This fold is /not/ strict. The stream consumer is responsible for
422-- forcing the evaluation of its result to avoid space leaks.
405-- forcing the evaluation of its result to avoid space leaks.
424−-- This is implemented using a database cursor. As such, this requires
425−-- a transaction. This function will detect whether or not there is a
426−-- transaction in progress, and will create a 'ReadCommitted' 'ReadOnly'
427−-- transaction if needed. The cursor is given a unique temporary name,
428−-- so the consumer may itself call fold.
430-- Exceptions that may be thrown:
407-- Exceptions that may be thrown:
432-- * 'FormatError': the query string could not be formatted correctly.
409-- * 'FormatError': the query string could not be formatted correctly.
@@ -435,9 +412,7 @@ queryWith_ parser conn q@(Query que) = do
435-- using 'execute' instead of 'query').
412-- using 'execute' instead of 'query').
437-- * 'ResultError': result conversion failed.
414-- * 'ResultError': result conversion failed.
439−-- * 'SqlError': the postgresql backend returned an error, e.g.
440−-- a syntax or type error, or an incorrect table or column name.
441fold :: ( FromRow row, ToRow params )
416fold :: ( FromRow row, ToRow params )
442 => Connection
417 => Connection
@@ -447,20 +422,6 @@ fold :: ( FromRow row, ToRow params )
448fold = foldWithOptions defaultFoldOptions
423fold = foldWithOptions defaultFoldOptions
450−-- | A version of 'fold' taking a parser as an argument
451−foldWith :: ( ToRow params )
457− -> (a -> row -> IO a)
459−foldWith = foldWithOptionsAndParser defaultFoldOptions
461−-- | Number of rows to fetch at a time. 'Automatic' currently defaults
462−-- to 256 rows, although it might be nice to make this more intelligent
463−-- based on e.g. the average size of the rows.
464data FetchQuantity
425data FetchQuantity
465 = Automatic
426 = Automatic
466 | Fixed !Int
427 | Fixed !Int
@@ -471,19 +432,12 @@ data FoldOptions
471 transactionMode :: !TransactionMode
432 transactionMode :: !TransactionMode
474−-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475defaultFoldOptions :: FoldOptions
435defaultFoldOptions :: FoldOptions
476defaultFoldOptions = FoldOptions {
436defaultFoldOptions = FoldOptions {
477 fetchQuantity = Automatic,
437 fetchQuantity = Automatic,
478 transactionMode = TransactionMode ReadCommitted ReadOnly
438 transactionMode = TransactionMode ReadCommitted ReadOnly
481−-- | The same as 'fold', but this provides a bit more control over
482−-- lower-level details. Currently, the number of rows fetched per
483−-- round-trip to the server and the transaction mode may be adjusted
484−-- accordingly. If the connection is already in a transaction,
485−-- then the existing transaction is used and thus the 'transactionMode'
486−-- option is ignored.
487foldWithOptions :: ( FromRow row, ToRow params )
441foldWithOptions :: ( FromRow row, ToRow params )
488 => FoldOptions
442 => FoldOptions
489 -> Connection
443 -> Connection
@@ -492,21 +446,9 @@ foldWithOptions :: ( FromRow row, ToRow params )
493 -> (a -> row -> IO a)
447 -> (a -> row -> IO a)
495−foldWithOptions opts = foldWithOptionsAndParser opts fromRow
449+foldWithOptions opts conn template qs a f = do
497−-- | A version of 'foldWithOptions' taking a parser as an argument
498−foldWithOptionsAndParser :: (ToRow params)
505− -> (a -> row -> IO a)
507−foldWithOptionsAndParser opts parser conn template qs a f = do
508 q <- formatQuery conn template qs
450 q <- formatQuery conn template qs
509− doFold opts parser conn template (Query q) a f
451+ doFold opts conn template (Query q) a f
511-- | A version of 'fold' that does not perform query substitution.
453-- | A version of 'fold' that does not perform query substitution.
512fold_ :: (FromRow r) =>
454fold_ :: (FromRow r) =>
@@ -517,14 +459,6 @@ fold_ :: (FromRow r) =>
518fold_ = foldWithOptions_ defaultFoldOptions
460fold_ = foldWithOptions_ defaultFoldOptions
520−-- | A version of 'fold_' taking a parser as an argument
521−foldWith_ :: RowParser r
527−foldWith_ = foldWithOptionsAndParser_ defaultFoldOptions
529foldWithOptions_ :: (FromRow r) =>
463foldWithOptions_ :: (FromRow r) =>
530 FoldOptions
464 FoldOptions
@@ -533,27 +467,18 @@ foldWithOptions_ :: (FromRow r) =>
533 -> a -- ^ Initial state for result consumer.
467 -> a -- ^ Initial state for result consumer.
534 -> (a -> r -> IO a) -- ^ Result consumer.
468 -> (a -> r -> IO a) -- ^ Result consumer.
536−foldWithOptions_ opts conn query' a f = doFold opts fromRow conn query' query' a f
470+foldWithOptions_ opts conn query a f = doFold opts conn query query a f
538−-- | A version of 'foldWithOptions_' taking a parser as an argument
472+
539−foldWithOptionsAndParser_ :: FoldOptions
473+doFold :: ( FromRow row )
540− -> RowParser r
474+ => FoldOptions
542− -> Query -- ^ Query.
543− -> a -- ^ Initial state for result consumer.
544− -> (a -> r -> IO a) -- ^ Result consumer.
546−foldWithOptionsAndParser_ opts parser conn query' a f = doFold opts parser conn query' query' a f
548−doFold :: FoldOptions
550 -> Connection
475 -> Connection
554 -> (a -> row -> IO a)
479 -> (a -> row -> IO a)
556−doFold FoldOptions{..} parser conn _template q a0 f = do
481+doFold FoldOptions{..} conn _template q a f = do
557 stat <- withConnection conn PQ.transactionStatus
482 stat <- withConnection conn PQ.transactionStatus
558 case stat of
483 case stat of
559 PQ.TransIdle -> withTransactionMode transactionMode conn go
484 PQ.TransIdle -> withTransactionMode transactionMode conn go
@@ -571,17 +496,11 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
571 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
496 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572 -- Not sure what this means.
497 -- Not sure what this means.
574− declare =
499+ go = do
575− declareCursor conn q
500+ -- FIXME: what about name clashes with already-declared cursors?
576− fetch cursor a =
501+ _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
577− foldForwardWithParser cursor parser chunkSize f a
502+ `mappend` q)
578−
503+ loop a `finally` execute_ conn "CLOSE fold"
579− go = bracket declare closeCursor $ \cursor ->
580− let loop a = fetch cursor a >>=
586-- FIXME: choose the Automatic chunkSize more intelligently
505-- FIXME: choose the Automatic chunkSize more intelligently
587-- One possibility is to use the type of the results, although this
506-- One possibility is to use the type of the results, although this
@@ -592,6 +511,9 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
592 chunkSize = case fetchQuantity of
511 chunkSize = case fetchQuantity of
593 Automatic -> 256
512 Automatic -> 256
594 Fixed n -> n
513 Fixed n -> n
515+ rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
516+ if null rs then return a else foldM f a rs >>= loop
596-- | A version of 'fold' that does not transform a state value.
518-- | A version of 'fold' that does not transform a state value.
597forEach :: (ToRow q, FromRow r) =>
519forEach :: (ToRow q, FromRow r) =>
@@ -600,37 +522,237 @@ forEach :: (ToRow q, FromRow r) =>
600 -> q -- ^ Query parameters.
522 -> q -- ^ Query parameters.
601 -> (r -> IO ()) -- ^ Result consumer.
523 -> (r -> IO ()) -- ^ Result consumer.
603−forEach = forEachWith fromRow
525+forEach conn template qs = fold conn template qs () . const
604{-# INLINE forEach #-}
526{-# INLINE forEach #-}
606−-- | A version of 'forEach' taking a parser as an argument
607−forEachWith :: ( ToRow q )
614−forEachWith parser conn template qs = foldWith parser conn template qs () . const
615−{-# INLINE forEachWith #-}
617-- | A version of 'forEach' that does not perform query substitution.
528-- | A version of 'forEach' that does not perform query substitution.
618forEach_ :: (FromRow r) =>
529forEach_ :: (FromRow r) =>
619 Connection
530 Connection
620 -> Query -- ^ Query template.
531 -> Query -- ^ Query template.
621 -> (r -> IO ()) -- ^ Result consumer.
532 -> (r -> IO ()) -- ^ Result consumer.
623−forEach_ = forEachWith_ fromRow
534+forEach_ conn template = fold_ conn template () . const
624{-# INLINE forEach_ #-}
535{-# INLINE forEach_ #-}
626−forEachWith_ :: RowParser r
537+forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
627− -> Connection
538+forM' lo hi m = loop hi []
629− -> (r -> IO ())
540+ loop !n !as
630− -> IO ()
541+ | n < lo = return as
631−forEachWith_ parser conn template = foldWith_ parser conn template () . const
542+ | otherwise = do
632−{-# INLINE forEachWith_ #-}
543+ a <- m n
633−
544+ loop (n-1) (a:as)
546+finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
547+finishQuery conn q result = do
548+ status <- PQ.resultStatus result
551+ throwIO $ QueryError "query: Empty query" q
553+ throwIO $ QueryError "query resulted in a command response" q
555+ ncols <- PQ.nfields result
556+ let unCol (PQ.Col x) = fromIntegral x :: Int
557+ typeinfos <- V.generateM (unCol ncols)
558+ (\(PQ.Col . fromIntegral -> col) -> do
559+ getTypeInfo conn =<< PQ.ftype result col)
560+ nrows <- PQ.ntuples result
561+ ncols <- PQ.nfields result
562+ forM' 0 (nrows-1) $ \row -> do
563+ let rw = Row row typeinfos result
564+ case runStateT (runReaderT (unRP fromRow) rw) 0 of
565+ Ok (val,col) | col == ncols -> return val
567+ vals <- forM' 0 (ncols-1) $ \c -> do
568+ v <- PQ.getvalue result row c
569+ return ( typeinfos V.! unCol c
571+ throw (ConversionFailed
572+ (show (unCol ncols) ++ " values: " ++ show vals)
573+ (show (unCol col) ++ " slots in target type")
574+ "mismatch between number of columns to \
575+ \convert and number in target type")
576+ Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
577+ Errors [x] -> throwIO x
578+ Errors xs -> throwIO $ ManyErrors xs
580+ throwIO $ QueryError "query: COPY TO is not supported" q
582+ throwIO $ QueryError "query: COPY FROM is not supported" q
583+ PQ.BadResponse -> throwResultError "query" result status
584+ PQ.NonfatalError -> throwResultError "query" result status
585+ PQ.FatalError -> throwResultError "query" result status
587+ellipsis :: ByteString -> ByteString
589+ | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
593+-- | Of the four isolation levels defined by the SQL standard,
594+-- these are the three levels distinguished by PostgreSQL as of version 9.0.
595+-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
596+-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
597+-- was equivalent to 'Serializable'.
600+ = DefaultIsolationLevel -- ^ the isolation level will be taken from
601+ -- PostgreSQL's per-connection
602+ -- @default_transaction_isolation@ variable,
603+ -- which is initialized according to the
604+ -- server's config. The default configuration
605+ -- is 'ReadCommitted'.
609+ deriving (Show, Eq, Ord, Enum, Bounded)
612+ = DefaultReadWriteMode -- ^ the read-write mode will be taken from
613+ -- PostgreSQL's per-connection
614+ -- @default_transaction_read_only@ variable,
615+ -- which is initialized according to the
616+ -- server's config. The default configuration
620+ deriving (Show, Eq, Ord, Enum, Bounded)
622+data TransactionMode = TransactionMode {
623+ isolationLevel :: !IsolationLevel,
624+ readWriteMode :: !ReadWriteMode
625+ } deriving (Show, Eq)
627+defaultTransactionMode :: TransactionMode
628+defaultTransactionMode = TransactionMode
629+ defaultIsolationLevel
630+ defaultReadWriteMode
632+defaultIsolationLevel :: IsolationLevel
633+defaultIsolationLevel = DefaultIsolationLevel
635+defaultReadWriteMode :: ReadWriteMode
636+defaultReadWriteMode = DefaultReadWriteMode
638+-- | Execute an action inside a SQL transaction.
640+-- This function initiates a transaction with a \"@begin
641+-- transaction@\" statement, then executes the supplied action. If
642+-- the action succeeds, the transaction will be completed with
643+-- 'Base.commit' before this function returns.
645+-- If the action throws /any/ kind of exception (not just a
646+-- PostgreSQL-related exception), the transaction will be rolled back using
647+-- 'rollback', then the exception will be rethrown.
648+withTransaction :: Connection -> IO a -> IO a
649+withTransaction = withTransactionMode defaultTransactionMode
651+-- | Execute an action inside of a 'Serializable' transaction. If a
652+-- serialization failure occurs, roll back the transaction and try again.
653+-- Be warned that this may execute the IO action multiple times.
655+-- A 'Serializable' transaction creates the illusion that your program has
656+-- exclusive access to the database. This means that, even in a concurrent
657+-- setting, you can perform queries in sequence without having to worry about
658+-- what might happen between one statement and the next.
660+-- Think of it as STM, but without @retry@.
661+withTransactionSerializable :: Connection -> IO a -> IO a
662+withTransactionSerializable =
663+ withTransactionModeRetry
665+ { isolationLevel = Serializable
666+ , readWriteMode = ReadWrite
669+-- | Execute an action inside a SQL transaction with a given isolation level.
670+withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
671+withTransactionLevel lvl
672+ = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
674+-- | Execute an action inside a SQL transaction with a given transaction mode.
675+withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
676+withTransactionMode mode conn act =
677+ mask $ \restore -> do
679+ r <- restore act `onException` rollback conn
683+-- | Like 'withTransactionMode', but if a 'SqlError' arises whose 'sqlState' is
684+-- @\"40001\"@ (@serialization_failure@), this will issue a @ROLLBACK@, then
685+-- try the action again. If any other exception arises, this will issue a
686+-- @ROLLBACK@, but will propagate the exception instead of retrying.
688+-- This is used to implement 'withTransactionSerializable'.
689+withTransactionModeRetry :: TransactionMode -> Connection -> IO a -> IO a
690+withTransactionModeRetry mode conn act =
692+ retryLoop $ try $ do
697+ retryLoop :: IO (Either SomeException a) -> IO a
704+ case fromException e of
705+ Just SqlError{..} | sqlState == serialization_failure
711+ -- http://www.postgresql.org/docs/current/static/errcodes-appendix.html
712+ serialization_failure = "40001"
714+-- | Rollback a transaction.
715+rollback :: Connection -> IO ()
716+rollback conn = execute_ conn "ABORT" >> return ()
718+-- | Commit a transaction.
719+commit :: Connection -> IO ()
720+commit conn = execute_ conn "COMMIT" >> return ()
722+-- | Begin a transaction.
723+begin :: Connection -> IO ()
724+begin = beginMode defaultTransactionMode
726+-- | Begin a transaction with a given isolation level
727+beginLevel :: IsolationLevel -> Connection -> IO ()
728+beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
730+-- | Begin a transaction with a given transaction mode
731+beginMode :: TransactionMode -> Connection -> IO ()
732+beginMode mode conn = do
733+ _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
736+ isolevel = case isolationLevel mode of
737+ DefaultIsolationLevel -> ""
738+ ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
739+ RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
740+ Serializable -> " ISOLATION LEVEL SERIALIZABLE"
741+ readmode = case readWriteMode mode of
742+ DefaultReadWriteMode -> ""
743+ ReadWrite -> " READ WRITE"
744+ ReadOnly -> " READ ONLY"
746+fmtError :: String -> Query -> [Action] -> a
747+fmtError msg q xs = throw FormatError {
750+ , fmtParams = map twiddle xs
752+ where twiddle (Plain b) = toByteString b
753+ twiddle (Escape s) = s
754+ twiddle (EscapeByteA s) = s
755+ twiddle (Many ys) = B.concat (map twiddle ys)
@@ -658,11 +780,9 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
659-- > import Database.PostgreSQL.Simple
781-- > import Database.PostgreSQL.Simple
662-- > hello = do
783-- > hello = do
663−-- > conn <- connectPostgreSQL ""
784+-- > conn <- connect defaultConnectInfo
664−-- > [Only i] <- query_ conn "select 2 + 2"
785+-- > query conn "select 2 + 2"
667-- A 'Query' value does not represent the actual query that will be
787-- A 'Query' value does not represent the actual query that will be
668-- executed, but is a template for constructing the final query.
788-- executed, but is a template for constructing the final query.
@@ -723,30 +843,15 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
723-- The same kind of problem can arise with string literals if you have
843-- The same kind of problem can arise with string literals if you have
724-- the @OverloadedStrings@ language extension enabled. Again, just
844-- the @OverloadedStrings@ language extension enabled. Again, just
725-- use an explicit type signature if this happens.
845-- use an explicit type signature if this happens.
727−-- Finally, remember that the compiler must be able to infer the type
728−-- of a query's /results/ as well as its parameters. We might like
729−-- the following example to work:
731−-- > print =<< query_ conn "select 2 + 2"
733−-- Unfortunately, while a quick glance tells us that the result type
734−-- should be a single row containing a single numeric column, the
735−-- compiler has no way to infer what the types are. We can easily fix
736−-- this by providing an explicit type annotation:
738−-- > xs <- query_ conn "select 2 + 2"
739−-- > print (xs :: [Only Int])
741-- $only_param
847-- $only_param
743-- Haskell lacks a single-element tuple type, so if you have just one
849-- Haskell lacks a single-element tuple type, so if you have just one
744−-- value you want substituted into a query or a single-column result,
850+-- value you want substituted into a query, what should you do?
745−-- what should you do?
747-- The obvious approach would appear to be something like this:
852-- The obvious approach would appear to be something like this:
749−-- > instance (ToField a) => ToRow a where
854+-- > instance (Param a) => QueryParam a where
752-- Unfortunately, this wreaks havoc with type inference, so we take a
857-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -757,9 +862,6 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
758-- > execute conn "insert into users (first_name) values (?)"
863-- > execute conn "insert into users (first_name) values (?)"
759-- > ["Nuala"]
864-- > ["Nuala"]
761−-- A row of /n/ query results is represented using an /n/-tuple, so
762−-- you should use 'Only' to represent a single-column result.
@@ -777,7 +879,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
777-- Here's an example:
879-- Here's an example:
779-- > query conn "select * from users where first_name in ?" $
881-- > query conn "select * from users where first_name in ?" $
780−-- > Only $ In ["Anna", "Boris", "Carla"]
882+-- > In ["Anna", "Boris", "Carla"]
782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
884-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
783-- substituted instead, to ensure that your clause remains
885-- substituted instead, to ensure that your clause remains
@@ -805,7 +907,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
805-- * There must be no other \"@?@\" characters anywhere in your
907-- * There must be no other \"@?@\" characters anywhere in your
806-- template.
908-- template.
808−-- * There must be one or more \"@?@\" in the parentheses.
910+-- * There must one or more \"@?@\" in the parentheses.
810-- * Extra white space is fine.
912-- * Extra white space is fine.
@@ -828,10 +930,9 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
829-- $returning
931-- $returning
831−-- PostgreSQL supports returning values from data manipulation statements
933+-- The 'returning' function is similar to 'executeMany' but is
832−-- such as @INSERT@ and @UPDATE@. You can use these statements by
934+-- intended for use with multi-tuple @INSERT@ or @UPDATE@ statements
833−-- using 'query' instead of 'execute'. For multi-tuple inserts,
935+-- that make use of @RETURNING@.
834−-- use 'returning' instead of 'executeMany'.
836-- For example, were there an auto-incrementing @id@ column and
937-- For example, were there an auto-incrementing @id@ column and
837-- timestamp column @t@ that defaulted to the present time for the
938-- timestamp column @t@ that defaulted to the present time for the
@@ -839,8 +940,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
839-- sales records and also return their new @id@s and timestamps.
940-- sales records and also return their new @id@s and timestamps.
841-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
942-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
842−-- > xs :: [(Int, UTCTime)] <- query conn q (15,"Sawdust")
843−-- > ys :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
943+-- > xs :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
845-- $result
945-- $result
@@ -876,7 +976,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
877-- Although SQL can accommodate @NULL@ as a value for any of these
977-- Although SQL can accommodate @NULL@ as a value for any of these
878-- types, Haskell cannot. If your result contains columns that may be
978-- types, Haskell cannot. If your result contains columns that may be
879−-- @NULL@, be sure that you use 'Maybe' in those positions of your
979+-- @NULL@, be sure that you use 'Maybe' in those positions of of your
882-- > (Text, Maybe Int, Int)
982-- > (Text, Maybe Int, Int)
@@ -902,7 +1002,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
902-- all values of the given PostgreSQL type is considered \"compatible\".
1002-- all values of the given PostgreSQL type is considered \"compatible\".
903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
1003-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
1004-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
905−-- represent a @SMALLINT@, so it is considered compatible with those types.
1005+-- represent a @SMALLINT@, so it is considered compatble with those types.
907-- * A numeric compatibility check is based only on the type of a
1007-- * A numeric compatibility check is based only on the type of a
908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
1008-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -916,3 +1016,37 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
916-- UTF-8. If you use some other encoding, decoding may fail or give
1016-- UTF-8. If you use some other encoding, decoding may fail or give
917-- wrong results. In such cases, write a @newtype@ wrapper and a
1017-- wrong results. In such cases, write a @newtype@ wrapper and a
918-- custom 'Result' instance to handle your encoding.
1018-- custom 'Result' instance to handle your encoding.
1020+getTypeInfo :: Connection -> PQ.Oid -> IO TypeInfo
1021+getTypeInfo conn@Connection{..} oid =
1022+ case oid2typname oid of
1023+ Just name -> return $! TypeInfo { typ = NamedOid oid name
1024+ , typelem = Nothing
1026+ Nothing -> modifyMVar connectionObjects $ \oidmap -> do
1027+ case IntMap.lookup (oid2int oid) oidmap of
1028+ Just typeinfo -> return (oidmap, typeinfo)
1030+ names <- query conn
1031+ [sql| SELECT p.oid, p.typname, c.oid, c.typname
1032+ FROM pg_type AS p LEFT OUTER JOIN pg_type AS c
1033+ ON c.oid = p.typelem
1036+ typinf <- case names of
1037+ [] -> return $ throw SqlError {
1038+ sqlNativeError = -1,
1039+ sqlErrorMsg = "invalid type oid",
1042+ [(pOid, pTypName, mbCOid, mbCTypName)] ->
1043+ return $! TypeInfo { typ = NamedOid pOid pTypName
1046+ cTypName <- mbCTypName
1047+ return $ NamedOid cOid cTypName
1049+ _ -> fail "typename query returned more than one result"
1050+ -- oid is a primary key, so the query should
1051+ -- never return more than one result
1052+ return (IntMap.insert (oid2int oid) typinf oidmap, typinf)