@@ -1,18 +1,14 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE NamedFieldPuns #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE PatternGuards #-}
5−{-# LANGUAGE RecordWildCards #-}
6−{-# LANGUAGE ViewPatterns #-}
7−
1+{-# LANGUAGE BangPatterns, DeriveDataTypeable, OverloadedStrings #-}
2+{-# LANGUAGE DoAndIfThenElse, RecordWildCards, NamedFieldPuns #-}
83------------------------------------------------------------------------------
94-- |
105-- Module: Database.PostgreSQL.Simple
116-- Copyright: (c) 2011 MailRank, Inc.
12−-- (c) 2011-2012 Leon P Smith
7+-- (c) 2011 Leon P Smith
138-- License: BSD3
149-- Maintainer: Leon P Smith <leon@melding-monads.com>
1510-- Stability: experimental
11+-- Portability: portable
1612--
1713-- A mid-level client library for the PostgreSQL database, aimed at ease of
1814-- use and high performance.
@@ -42,9 +38,6 @@ module Database.PostgreSQL.Simple
4238 -- ** Modifying multiple rows at once
4339 -- $many
4440
45− -- ** @RETURNING@: modifications that return results
46− -- $returning
47−
4841 -- * Extracting results
4942 -- $result
5043
@@ -55,38 +48,29 @@ module Database.PostgreSQL.Simple
5548 -- $types
5649
5750 -- * Types
58− Connection
51+ Base.ConnectInfo(..)
52+ , Connection
5953 , Query
60− , ToRow
61− , FromRow
6254 , In(..)
6355 , Binary(..)
6456 , Only(..)
65− , (:.)(..)
6657 -- ** Exceptions
67− , SomePostgreSqlException(..)
6858 , SqlError(..)
69− , PQ.ExecStatus(..)
70− , FormatError(..)
71− , QueryError(..)
72− , ResultError(..)
59+ , FormatError(fmtMessage, fmtQuery, fmtParams)
60+ , QueryError(qeMessage, qeQuery)
61+ , ResultError(errSQLType, errHaskellType, errMessage)
7362 -- * Connection management
74− , Base.connectPostgreSQL
75− , Base.close
7663 , Base.connect
77− , Base.withConnect
78− , Base.ConnectInfo(..)
79− , Base.defaultConnectInfo
64+ , Base.connectPostgreSQL
8065 , Base.postgreSQLConnectionString
66+ , Base.defaultConnectInfo
67+ , Base.close
8168 -- * Queries that return results
8269 , query
8370 , query_
84− -- ** Queries taking parser as argument
85− , queryWith
86− , queryWith_
8771 -- * Queries that stream results
88− , FoldOptions(..)
8972 , FetchQuantity(..)
73+ , FoldOptions(..)
9074 , defaultFoldOptions
9175 , fold
9276 , foldWithOptions
@@ -94,15 +78,6 @@ module Database.PostgreSQL.Simple
9478 , foldWithOptions_
9579 , forEach
9680 , forEach_
97− , returning
98− -- ** Queries that stream results taking a parser as an argument
99− , foldWith
100− , foldWithOptionsAndParser
101− , foldWith_
102− , foldWithOptionsAndParser_
103− , forEachWith
104− , forEachWith_
105− , returningWith
10681 -- * Statements that do not return results
10782 , execute
10883 , execute_
@@ -110,9 +85,11 @@ module Database.PostgreSQL.Simple
11085-- , Base.insertID
11186 -- * Transaction handling
11287 , withTransaction
113− , withSavepoint
88+ , withTransactionLevel
89+ , IsolationLevel(..)
11490-- , Base.autocommit
11591 , begin
92+ , beginLevel
11693 , commit
11794 , rollback
11895 -- * Helper functions
@@ -120,27 +97,50 @@ module Database.PostgreSQL.Simple
12097 , formatQuery
12198 ) where
12299
123−import Data.ByteString.Builder (Builder, byteString, char8)
124−import Control.Applicative ((<$>))
125−import Control.Exception as E
126−import Data.ByteString (ByteString)
127−import Data.Int (Int64)
128−import Data.List (intersperse)
129−import Data.Monoid (mconcat)
130−import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
131−import Database.PostgreSQL.Simple.Cursor
132−import Database.PostgreSQL.Simple.FromField (ResultError(..))
133−import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134−import Database.PostgreSQL.Simple.ToField (Action(..))
135−import Database.PostgreSQL.Simple.ToRow (ToRow(..))
136−import Database.PostgreSQL.Simple.Types
137− ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
138−import Database.PostgreSQL.Simple.Internal as Base
139−import Database.PostgreSQL.Simple.Internal.PQResultUtils
140−import Database.PostgreSQL.Simple.Transaction
100+import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
101+import Blaze.ByteString.Builder.Char8 (fromChar)
102+import Control.Applicative ((<$>), pure)
103+import Control.Concurrent.MVar
104+import Control.Exception (Exception, bracket, onException, throw, throwIO, finally)
105+import Control.Monad (foldM)
106+import Control.Monad.Fix (fix)
107+import Data.ByteString (ByteString)
108+import Data.Char(ord)
109+import Data.Int (Int64)
110+import qualified Data.IntMap as IntMap
111+import Data.List (intersperse)
112+import Data.Monoid (mappend, mconcat)
113+import Data.Typeable (Typeable)
114+import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
115+import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
116+import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
117+import Database.PostgreSQL.Simple.Result (ResultError(..))
118+import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
119+import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
120+import Database.PostgreSQL.Simple.Internal as Base
141121import qualified Database.PostgreSQL.LibPQ as PQ
122+import Text.Regex.PCRE.Light (compile, caseless, match)
142123import qualified Data.ByteString.Char8 as B
143124
125+-- | Exception thrown if a 'Query' could not be formatted correctly.
126+-- This may occur if the number of \'@?@\' characters in the query
127+-- string does not match the number of parameters provided.
128+data FormatError = FormatError {
129+ fmtMessage :: String
130+ , fmtQuery :: Query
131+ , fmtParams :: [ByteString]
132+ } deriving (Eq, Show, Typeable)
133+
134+instance Exception FormatError
135+
136+-- | Exception thrown if 'query' is used to perform an @INSERT@-like
137+-- operation, or 'execute' is used to perform a @SELECT@-like operation.
138+data QueryError = QueryError {
139+ qeMessage :: String
140+ , qeQuery :: Query
141+ } deriving (Eq, Show, Typeable)
142+
143+instance Exception QueryError
144144
145145-- | Format a query string.
146146--
@@ -152,11 +152,11 @@ import qualified Data.ByteString.Char8 as B
152152--
153153-- Throws 'FormatError' if the query string could not be formatted
154154-- correctly.
155−formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
155+formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
156156formatQuery conn q@(Query template) qs
157157 | null xs && '?' `B.notElem` template = return template
158158 | otherwise = toByteString <$> buildQuery conn q template xs
159− where xs = toRow qs
159+ where xs = renderParams qs
160160
161161-- | Format a query string with a variable number of rows.
162162--
@@ -171,208 +171,105 @@ formatQuery conn q@(Query template) qs
171171--
172172-- Throws 'FormatError' if the query string could not be formatted
173173-- correctly.
174−formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
174+formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
175175formatMany _ q [] = fmtError "no rows supplied" q []
176176formatMany conn q@(Query template) qs = do
177− case parseTemplate template of
178− Just (before, qbits, after) -> do
179− bs <- mapM (buildQuery conn q qbits . toRow) qs
180− return . toByteString . mconcat $ byteString before :
181− intersperse (char8 ',') bs ++
182− [byteString after]
183− Nothing -> fmtError "syntax error in multi-row template" q []
184−
185−-- Split the input string into three pieces, @before@, @qbits@, and @after@,
186−-- following this grammar:
187−--
188−-- start: ^ before qbits after $
189−-- before: ([^?]* [^?\w])? 'VALUES' \s*
190−-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
191−-- after: [^?]*
192−--
193−-- \s: [ \t\n\r\f]
194−-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
195−--
196−-- This would be much more concise with some sort of regex engine.
197−-- 'formatMany' used to use pcre-light instead of this hand-written parser,
198−-- but pcre is a hassle to install on Windows.
199−parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
200−parseTemplate template =
201− -- Convert input string to uppercase, to facilitate searching.
202− search $ B.map toUpper_ascii template
177+ case match re template [] of
178+ Just [_,before,qbits,after] -> do
179+ bs <- mapM (buildQuery conn q qbits . renderParams) qs
180+ return . toByteString . mconcat $ fromByteString before :
181+ intersperse (fromChar ',') bs ++
182+ [fromByteString after]
183+ _ -> error "foo"
203184 where
204− -- Search for the next occurrence of "VALUES"
205− search bs =
206− case B.breakSubstring "VALUES" bs of
207− (x, y)
208− -- If "VALUES" is not present in the string, or any '?' characters
209− -- were encountered prior to it, fail.
210− | B.null y || ('?' `B.elem` x)
211− -> Nothing
212−
213− -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
214− -- try the next occurrence.
215− | not (B.null x) && isIdent (B.last x)
216− -> search $ B.drop 6 y
217−
218− -- Otherwise, we have a legitimate "VALUES" token.
219− | otherwise
220− -> parseQueryBits $ skipSpace $ B.drop 6 y
221−
222− -- Parse '(' \s* '?' \s* . If this doesn't match
223− -- (and we don't consume a '?'), look for another "VALUES".
224− --
225− -- qb points to the open paren (if present), meaning it points to the
226− -- beginning of the "qbits" production described above. This is why we
227− -- pass it down to finishQueryBits.
228− parseQueryBits qb
229− | Just ('(', skipSpace -> bs1) <- B.uncons qb
230− , Just ('?', skipSpace -> bs2) <- B.uncons bs1
231− = finishQueryBits qb bs2
232− | otherwise
233− = search qb
234−
235− -- Parse (',' \s* '?' \s*)* ')' [^?]* .
236− --
237− -- Since we've already consumed at least one '?', there's no turning back.
238− -- The parse has to succeed here, or the whole thing fails
239− -- (because we don't allow '?' to appear outside of the VALUES list).
240− finishQueryBits qb bs0
241− | Just (')', bs1) <- B.uncons bs0
242− = if '?' `B.elem` bs1
243− then Nothing
244− else Just $ slice3 template qb bs1
245− | Just (',', skipSpace -> bs1) <- B.uncons bs0
246− , Just ('?', skipSpace -> bs2) <- B.uncons bs1
247− = finishQueryBits qb bs2
248− | otherwise
249− = Nothing
250−
251− -- Slice a string into three pieces, given the start offset of the second
252− -- and third pieces. Each "offset" is actually a tail of the uppercase
253− -- version of the template string. Its length is used to infer the offset.
254− --
255− -- It is important to note that we only slice the original template.
256− -- We don't want our all-caps trick messing up the actual query string.
257− slice3 source p1 p2 =
258− (s1, s2, source'')
259− where
260− (s1, source') = B.splitAt (B.length source - B.length p1) source
261− (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
262−
263− toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
264− | otherwise = c
265−
266− -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
267− -- in the PostgreSQL source. No need to check [a-z], since we converted
268− -- the whole string to uppercase.
269− isIdent c = (c >= '0' && c <= '9')
270− || (c >= 'A' && c <= 'Z')
271− || (c >= '\x80' && c <= '\xFF')
272− || c == '_'
273− || c == '$'
274−
275− -- Based on {space} in scan.l
276− isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
277−
278− skipSpace = B.dropWhile isSpace_ascii
185+ re = compile "^([^?]+\\bvalues\\s*)\
186+ \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
187+ \([^?]*)$"
188+ [caseless]
279189
190+escapeStringConn conn s = withConnection conn $ \c -> do
191+ PQ.escapeStringConn c s
280192
281193buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
282−buildQuery conn q template xs =
283− zipParams (split template) <$> mapM (buildAction conn q xs) xs
284− where split s =
285− -- This part escapes double '??'s to make literal '?'s possible
286− -- in PostgreSQL queries using the JSON operators: @?@, @?|@ and @?&@
287− let (h,t) = breakOnSingleQuestionMark s
288− in byteString h
289− : if B.null t
290− then []
291− else split (B.tail t)
292− zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
194+buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
195+ where quote = inQuotes . fromByteString . maybe undefined id
196+ sub (Plain b) = pure b
197+ sub (Escape s) = quote <$> escapeStringConn conn s
198+ sub (Many ys) = mconcat <$> mapM sub ys
199+ split s = fromByteString h : if B.null t then [] else split (B.tail t)
200+ where (h,t) = B.break (=='?') s
201+ zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
293202 zipParams [t] [] = t
294− zipParams _ _ = fmtError (show countSingleQs ++
295− " single '?' characters, but " ++
203+ zipParams _ _ = fmtError (show (B.count '?' template) ++
204+ " '?' characters, but " ++
296205 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
302− _ -> i
303− where qms = B.splitAt 1 qmBS
304− (qmBS,nextQMBS) = B.splitAt 2 qmBS'
305− qmBS' = B.dropWhile (/= '?') bs
306206
307207-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
308208-- expected to return results.
309209--
310210-- Returns the number of rows affected.
311211--
312−-- Throws 'FormatError' if the query could not be formatted correctly, or
313−-- a 'SqlError' exception if the backend returns an error.
314−execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
212+-- Throws 'FormatError' if the query could not be formatted correctly.
213+execute :: (QueryParams q) => Connection -> Query -> q -> IO Int64
315214execute conn template qs = do
316215 result <- exec conn =<< formatQuery conn template qs
317216 finishExecute conn template result
318217
218+-- | A version of 'execute' that does not perform query substitution.
219+execute_ :: Connection -> Query -> IO Int64
220+execute_ conn q@(Query stmt) = do
221+ result <- exec conn stmt
222+ finishExecute conn q result
223+
319224-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
320225-- expected to return results.
321226--
322−-- Returns the number of rows affected. If the list of parameters is empty,
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.
325−--
326−-- Throws 'FormatError' if the query could not be formatted correctly, or
327−-- a 'SqlError' exception if the backend returns an error.
328−--
329−-- For example, here's a command that inserts two rows into a table
330−-- with two columns:
331−--
332−-- @
333−-- executeMany c [sql|
334−-- INSERT INTO sometable VALUES (?,?)
335−-- |] [(1, \"hello\"),(2, \"world\")]
336−-- @
337−--
338−-- Here's an canonical example of a multi-row update command:
227+-- Returns the number of rows affected.
339228--
340−-- @
341−-- executeMany c [sql|
342−-- UPDATE sometable
343−-- SET y = upd.y
344−-- FROM (VALUES (?,?)) as upd(x,y)
345−-- WHERE sometable.x = upd.x
346−-- |] [(1, \"hello\"),(2, \"world\")]
347−-- @
348−
349−executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
229+-- Throws 'FormatError' if the query could not be formatted correctly.
230+executeMany :: (QueryParams q) => Connection -> Query -> [q] -> IO Int64
350231executeMany _ _ [] = return 0
351232executeMany conn q qs = do
352233 result <- exec conn =<< formatMany conn q qs
353234 finishExecute conn q result
354235
355−-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
356−-- query that accepts multi-row input and is expected to return results.
357−-- Note that it is possible to write
358−-- @'query' conn "INSERT ... RETURNING ..." ...@
359−-- in cases where you are only inserting a single row, and do not need
360−-- functionality analogous to 'executeMany'.
361−--
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.
365−--
366−-- Throws 'FormatError' if the query could not be formatted correctly.
367−returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
368−returning = returningWith fromRow
236+finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
237+finishExecute conn q result = do
238+ status <- PQ.resultStatus result
239+ case status of
240+ PQ.CommandOk -> do
241+ ncols <- PQ.nfields result
242+ if ncols /= 0
243+ then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
244+ "-column result") q
245+ else do
246+ nstr <- PQ.cmdTuples result
247+ return $ case nstr of
248+ Nothing -> 0 -- is this appropriate?
249+ Just str -> toInteger str
250+ PQ.TuplesOk -> do
251+ ncols <- PQ.nfields result
252+ throwIO $ QueryError ("execute resulted in " ++ show ncols ++
253+ "-column result") q
254+ PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
255+ PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
256+ _ -> do
257+ errormsg <- maybe "" id <$> PQ.resultErrorMessage result
258+ statusmsg <- PQ.resStatus status
259+ state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
260+ throwIO $ SqlError { sqlState = state
261+ , sqlNativeError = fromEnum status
262+ , sqlErrorMsg = B.concat [ "execute: ", statusmsg
263+ , ": ", errormsg ]}
264+ where
265+ toInteger str = B.foldl' delta 0 str
266+ where
267+ delta acc c =
268+ if '0' <= c && c <= '9'
269+ then 10 * acc + fromIntegral (ord c - ord '0')
270+ else error ("finishExecute: not an int: " ++ B.unpack str)
271+
369272
370−-- | A version of 'returning' taking parser as argument
371−returningWith :: (ToRow q) => RowParser r -> Connection -> Query -> [q] -> IO [r]
372−returningWith _ _ _ [] = return []
373−returningWith parser conn q qs = do
374− result <- exec conn =<< formatMany conn q qs
375− finishQueryWith parser conn q result
376273
377274-- | Perform a @SELECT@ or other SQL query that is expected to return
378275-- results. All results are retrieved and converted before this
@@ -389,44 +286,33 @@ returningWith parser conn q qs = do
389286-- using 'execute' instead of 'query').
390287--
391288-- * 'ResultError': result conversion failed.
392−--
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]
396−query = queryWith fromRow
397−
398−-- | A version of 'query' that does not perform query substitution.
399−query_ :: (FromRow r) => Connection -> Query -> IO [r]
400−query_ = queryWith_ fromRow
401−
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
289+query :: (QueryParams q, QueryResults r)
290+ => Connection -> Query -> q -> IO [r]
291+query conn template qs = do
405292 result <- exec conn =<< formatQuery conn template qs
406− finishQueryWith parser conn template result
293+ finishQuery conn template result
407294
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
295+-- | A version of 'query' that does not perform query substitution.
296+query_ :: (QueryResults r) => Connection -> Query -> IO [r]
297+query_ conn q@(Query que) = do
411298 result <- exec conn que
412− finishQueryWith parser conn q result
299+ finishQuery conn q result
413300
414301-- | Perform a @SELECT@ or other SQL query that is expected to return
415302-- results. Results are streamed incrementally from the server, and
416303-- consumed via a left fold.
417304--
305+-- The result consumer must be carefully written to execute
306+-- quickly. If the consumer is slow, server resources will be tied up,
307+-- and other clients may not be able to update the tables from which
308+-- the results are being streamed.
309+--
418310-- When dealing with small results, it may be simpler (and perhaps
419311-- faster) to use 'query' instead.
420312--
421313-- This fold is /not/ strict. The stream consumer is responsible for
422314-- forcing the evaluation of its result to avoid space leaks.
423315--
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.
429−--
430316-- Exceptions that may be thrown:
431317--
432318-- * 'FormatError': the query string could not be formatted correctly.
@@ -435,10 +321,8 @@ queryWith_ parser conn q@(Query que) = do
435321-- using 'execute' instead of 'query').
436322--
437323-- * 'ResultError': result conversion failed.
438−--
439−-- * 'SqlError': the postgresql backend returned an error, e.g.
440−-- a syntax or type error, or an incorrect table or column name.
441−fold :: ( FromRow row, ToRow params )
324+
325+fold :: ( QueryResults row, QueryParams params )
442326 => Connection
443327 -> Query
444328 -> params
@@ -447,44 +331,20 @@ fold :: ( FromRow row, ToRow params )
447331 -> IO a
448332fold = foldWithOptions defaultFoldOptions
449333
450−-- | A version of 'fold' taking a parser as an argument
451−foldWith :: ( ToRow params )
452− => RowParser row
453− -> Connection
454− -> Query
455− -> params
456− -> a
457− -> (a -> row -> IO a)
458− -> IO a
459−foldWith = foldWithOptionsAndParser defaultFoldOptions
460−
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.
464334data FetchQuantity
465335 = Automatic
466336 | Fixed !Int
467337
468338data FoldOptions
469339 = FoldOptions {
470− fetchQuantity :: !FetchQuantity,
471− transactionMode :: !TransactionMode
340+ fetchQuantity :: !FetchQuantity,
341+ isolationLevel :: !IsolationLevel
472342 }
473343
474−-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475−defaultFoldOptions :: FoldOptions
476−defaultFoldOptions = FoldOptions {
477− fetchQuantity = Automatic,
478− transactionMode = TransactionMode ReadCommitted ReadOnly
479− }
480−
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.
487−foldWithOptions :: ( FromRow row, ToRow params )
344+defaultFoldOptions = FoldOptions { fetchQuantity = Automatic
345+ , isolationLevel = ReadCommitted }
346+
347+foldWithOptions :: ( QueryResults row, QueryParams params )
488348 => FoldOptions
489349 -> Connection
490350 -> Query
@@ -492,24 +352,12 @@ foldWithOptions :: ( FromRow row, ToRow params )
492352 -> a
493353 -> (a -> row -> IO a)
494354 -> IO a
495−foldWithOptions opts = foldWithOptionsAndParser opts fromRow
496−
497−-- | A version of 'foldWithOptions' taking a parser as an argument
498−foldWithOptionsAndParser :: (ToRow params)
499− => FoldOptions
500− -> RowParser row
501− -> Connection
502− -> Query
503− -> params
504− -> a
505− -> (a -> row -> IO a)
506− -> IO a
507−foldWithOptionsAndParser opts parser conn template qs a f = do
355+foldWithOptions opts conn template qs a f = do
508356 q <- formatQuery conn template qs
509− doFold opts parser conn template (Query q) a f
357+ doFold opts conn template (Query q) a f
510358
511359-- | A version of 'fold' that does not perform query substitution.
512−fold_ :: (FromRow r) =>
360+fold_ :: (QueryResults r) =>
513361 Connection
514362 -> Query -- ^ Query.
515363 -> a -- ^ Initial state for result consumer.
@@ -517,46 +365,29 @@ fold_ :: (FromRow r) =>
517365 -> IO a
518366fold_ = foldWithOptions_ defaultFoldOptions
519367
520−-- | A version of 'fold_' taking a parser as an argument
521−foldWith_ :: RowParser r
522− -> Connection
523− -> Query
524− -> a
525− -> (a -> r -> IO a)
526− -> IO a
527−foldWith_ = foldWithOptionsAndParser_ defaultFoldOptions
528368
529−foldWithOptions_ :: (FromRow r) =>
369+foldWithOptions_ :: (QueryResults r) =>
530370 FoldOptions
531371 -> Connection
532372 -> Query -- ^ Query.
533373 -> a -- ^ Initial state for result consumer.
534374 -> (a -> r -> IO a) -- ^ Result consumer.
535375 -> IO a
536−foldWithOptions_ opts conn query' a f = doFold opts fromRow conn query' query' a f
537−
538−-- | A version of 'foldWithOptions_' taking a parser as an argument
539−foldWithOptionsAndParser_ :: FoldOptions
540− -> RowParser r
541− -> Connection
542− -> Query -- ^ Query.
543− -> a -- ^ Initial state for result consumer.
544− -> (a -> r -> IO a) -- ^ Result consumer.
545− -> IO a
546−foldWithOptionsAndParser_ opts parser conn query' a f = doFold opts parser conn query' query' a f
547−
548−doFold :: FoldOptions
549− -> RowParser row
376+foldWithOptions_ opts conn query a f = doFold opts conn query query a f
377+
378+
379+doFold :: ( QueryResults row )
380+ => FoldOptions
550381 -> Connection
551382 -> Query
552383 -> Query
553384 -> a
554385 -> (a -> row -> IO a)
555386 -> IO a
556−doFold FoldOptions{..} parser conn _template q a0 f = do
387+doFold FoldOptions{..} conn _template q a f = do
557388 stat <- withConnection conn PQ.transactionStatus
558389 case stat of
559− PQ.TransIdle -> withTransactionMode transactionMode conn go
390+ PQ.TransIdle -> withTransactionLevel isolationLevel conn go
560391 PQ.TransInTrans -> go
561392 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
562393 -- This _shouldn't_ occur in the current incarnation of
@@ -571,17 +402,11 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
571402 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572403 -- Not sure what this means.
573404 where
574− declare =
575− declareCursor conn q
576− fetch cursor a =
577− foldForwardWithParser cursor parser chunkSize f a
578−
579− go = bracket declare closeCursor $ \cursor ->
580− let loop a = fetch cursor a >>=
581− \r -> case r of
582− Left x -> return x
583− Right x -> loop x
584− in loop a0
405+ go = do
406+ -- FIXME: what about name clashes with already-declared cursors?
407+ _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
408+ `mappend` q)
409+ loop a `finally` execute_ conn "CLOSE fold"
585410
586411-- FIXME: choose the Automatic chunkSize more intelligently
587412-- One possibility is to use the type of the results, although this
@@ -592,45 +417,130 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
592417 chunkSize = case fetchQuantity of
593418 Automatic -> 256
594419 Fixed n -> n
420+ loop a = do
421+ rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
422+ if null rs then return a else foldM f a rs >>= loop
595423
596424-- | A version of 'fold' that does not transform a state value.
597−forEach :: (ToRow q, FromRow r) =>
425+forEach :: (QueryParams q, QueryResults r) =>
598426 Connection
599427 -> Query -- ^ Query template.
600428 -> q -- ^ Query parameters.
601429 -> (r -> IO ()) -- ^ Result consumer.
602430 -> IO ()
603−forEach = forEachWith fromRow
431+forEach conn template qs = fold conn template qs () . const
604432{-# INLINE forEach #-}
605433
606−-- | A version of 'forEach' taking a parser as an argument
607−forEachWith :: ( ToRow q )
608− => RowParser r
609− -> Connection
610− -> Query
611− -> q
612− -> (r -> IO ())
613− -> IO ()
614−forEachWith parser conn template qs = foldWith parser conn template qs () . const
615−{-# INLINE forEachWith #-}
616−
617434-- | A version of 'forEach' that does not perform query substitution.
618−forEach_ :: (FromRow r) =>
435+forEach_ :: (QueryResults r) =>
619436 Connection
620437 -> Query -- ^ Query template.
621438 -> (r -> IO ()) -- ^ Result consumer.
622439 -> IO ()
623−forEach_ = forEachWith_ fromRow
440+forEach_ conn template = fold_ conn template () . const
624441{-# INLINE forEach_ #-}
625442
626−forEachWith_ :: RowParser r
627− -> Connection
628− -> Query
629− -> (r -> IO ())
630− -> IO ()
631−forEachWith_ parser conn template = foldWith_ parser conn template () . const
632−{-# INLINE forEachWith_ #-}
633−
443+forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
444+forM' lo hi m = loop hi []
445+ where
446+ loop !n !as
447+ | n < lo = return as
448+ | otherwise = do
449+ a <- m n
450+ loop (n-1) (a:as)
451+
452+finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
453+finishQuery conn q result = do
454+ status <- PQ.resultStatus result
455+ case status of
456+ PQ.CommandOk -> do
457+ throwIO $ QueryError "query resulted in a command response" q
458+ PQ.TuplesOk -> do
459+ ncols <- PQ.nfields result
460+ fields <- forM' 0 (ncols-1) $ \column -> do
461+ type_oid <- PQ.ftype result column
462+ typename <- getTypename conn type_oid
463+ return Field{..}
464+ nrows <- PQ.ntuples result
465+ forM' 0 (nrows-1) $ \row -> do
466+ values <- forM' 0 (ncols-1) (\col -> PQ.getvalue result row col)
467+ case convertResults fields values of
468+ Left err -> throwIO err
469+ Right a -> return a
470+ PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
471+ PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
472+ _ -> do
473+ errormsg <- maybe "" id <$> PQ.resultErrorMessage result
474+ statusmsg <- PQ.resStatus status
475+ state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
476+ throwIO $ SqlError { sqlState = state
477+ , sqlNativeError = fromEnum status
478+ , sqlErrorMsg = B.concat [ "query: ", statusmsg
479+ , ": ", errormsg ]}
480+
481+-- | Of the four isolation levels defined by the SQL standard,
482+-- these are the three levels distinguished by PostgreSQL as of version 9.0.
483+-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
484+-- for more information.
485+
486+data IsolationLevel
487+ = ReadCommitted
488+ | RepeatableRead
489+ | Serializable
490+ deriving (Show, Eq, Ord, Enum, Bounded)
491+
492+-- | Execute an action inside a SQL transaction.
493+--
494+-- This function initiates a transaction with a \"@begin
495+-- transaction@\" statement, then executes the supplied action. If
496+-- the action succeeds, the transaction will be completed with
497+-- 'Base.commit' before this function returns.
498+--
499+-- If the action throws /any/ kind of exception (not just a
500+-- PostgreSQL-related exception), the transaction will be rolled back using
501+-- 'rollback', then the exception will be rethrown.
502+withTransaction :: Connection -> IO a -> IO a
503+withTransaction = withTransactionLevel ReadCommitted
504+
505+-- | Execute an action inside a SQL transaction with a given isolation level.
506+withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
507+withTransactionLevel isolationLevel conn act = do
508+ beginLevel isolationLevel conn
509+ r <- act `onException` rollback conn
510+ commit conn
511+ return r
512+
513+-- | Rollback a transaction.
514+-- rollback :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
515+rollback :: Connection -> IO ()
516+rollback conn = execute_ conn "ABORT" >> return ()
517+
518+-- | Commit a transaction.
519+commit :: Connection -> IO ()
520+commit conn = execute_ conn "COMMIT" >> return ()
521+
522+-- | Begin a transaction.
523+begin :: Connection -> IO ()
524+begin = beginLevel ReadCommitted
525+
526+-- | Begin a transaction with a given isolation level
527+beginLevel :: IsolationLevel -> Connection -> IO ()
528+beginLevel isolationLevel conn = do
529+ execute_ conn $! case isolationLevel of
530+ ReadCommitted -> "BEGIN"
531+ RepeatableRead -> "BEGIN ISOLATION LEVEL REPEATABLE READ"
532+ Serializable -> "BEGIN ISOLATION LEVEL SERIALIZABLE"
533+ return ()
534+
535+fmtError :: String -> Query -> [Action] -> a
536+fmtError msg q xs = throw FormatError {
537+ fmtMessage = msg
538+ , fmtQuery = q
539+ , fmtParams = map twiddle xs
540+ }
541+ where twiddle (Plain b) = toByteString b
542+ twiddle (Escape s) = s
543+ twiddle (Many ys) = B.concat (map twiddle ys)
634544
635545-- $use
636546--
@@ -658,11 +568,9 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
658568-- >
659569-- > import Database.PostgreSQL.Simple
660570-- >
661−-- > hello :: IO Int
662571-- > hello = do
663−-- > conn <- connectPostgreSQL ""
664−-- > [Only i] <- query_ conn "select 2 + 2"
665−-- > return i
572+-- > conn <- connect defaultConnectInfo
573+-- > query conn "select 2 + 2"
666574--
667575-- A 'Query' value does not represent the actual query that will be
668576-- executed, but is a template for constructing the final query.
@@ -709,7 +617,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
709617-- Automated type inference means that you will often be able to avoid
710618-- supplying explicit type signatures for the elements of a tuple.
711619-- However, sometimes the compiler will not be able to infer your
712−-- types. Consider a case where you write a numeric literal in a
620+-- types. Consider a care where you write a numeric literal in a
713621-- parameter tuple:
714622--
715623-- > query conn "select ? + ?" (40,2)
@@ -723,30 +631,15 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
723631-- The same kind of problem can arise with string literals if you have
724632-- the @OverloadedStrings@ language extension enabled. Again, just
725633-- use an explicit type signature if this happens.
726−--
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:
730−--
731−-- > print =<< query_ conn "select 2 + 2"
732−--
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:
737−--
738−-- > xs <- query_ conn "select 2 + 2"
739−-- > print (xs :: [Only Int])
740634
741635-- $only_param
742636--
743637-- 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,
745−-- what should you do?
638+-- value you want substituted into a query, what should you do?
746639--
747640-- The obvious approach would appear to be something like this:
748641--
749−-- > instance (ToField a) => ToRow a where
642+-- > instance (Param a) => QueryParam a where
750643-- > ...
751644--
752645-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -757,9 +650,6 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
757650--
758651-- > execute conn "insert into users (first_name) values (?)"
759652-- > ["Nuala"]
760−--
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.
763653
764654-- $in
765655--
@@ -777,7 +667,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
777667-- Here's an example:
778668--
779669-- > query conn "select * from users where first_name in ?" $
780−-- > Only $ In ["Anna", "Boris", "Carla"]
670+-- > In ["Anna", "Boris", "Carla"]
781671--
782672-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
783673-- substituted instead, to ensure that your clause remains
@@ -805,7 +695,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
805695-- * There must be no other \"@?@\" characters anywhere in your
806696-- template.
807697--
808−-- * There must be one or more \"@?@\" in the parentheses.
698+-- * There must one or more \"@?@\" in the parentheses.
809699--
810700-- * Extra white space is fine.
811701--
@@ -826,26 +716,10 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
826716-- > insert into users (first_name,last_name) values
827717-- > ('Boris','Karloff'),('Ed','Wood')
828718
829−-- $returning
830−--
831−-- PostgreSQL supports returning values from data manipulation statements
832−-- such as @INSERT@ and @UPDATE@. You can use these statements by
833−-- using 'query' instead of 'execute'. For multi-tuple inserts,
834−-- use 'returning' instead of 'executeMany'.
835−--
836−-- For example, were there an auto-incrementing @id@ column and
837−-- timestamp column @t@ that defaulted to the present time for the
838−-- @sales@ table, then the following query would insert two new
839−-- sales records and also return their new @id@s and timestamps.
840−--
841−-- > 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")]
844−
845719-- $result
846720--
847721-- The 'query' and 'query_' functions return a list of values in the
848−-- 'FromRow' typeclass. This class performs automatic extraction
722+-- 'QueryResults' typeclass. This class performs automatic extraction
849723-- and type conversion of rows from a query result.
850724--
851725-- Here is a simple example of how to extract results:
@@ -876,7 +750,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
876750--
877751-- Although SQL can accommodate @NULL@ as a value for any of these
878752-- types, Haskell cannot. If your result contains columns that may be
879−-- @NULL@, be sure that you use 'Maybe' in those positions of your
753+-- @NULL@, be sure that you use 'Maybe' in those positions of of your
880754-- tuple.
881755--
882756-- > (Text, Maybe Int, Int)
@@ -902,7 +776,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
902776-- all values of the given PostgreSQL type is considered \"compatible\".
903777-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
904778-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
905−-- represent a @SMALLINT@, so it is considered compatible with those types.
779+-- represent a @SMALLINT@, so it is considered compatble with those types.
906780--
907781-- * A numeric compatibility check is based only on the type of a
908782-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -916,3 +790,25 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
916790-- UTF-8. If you use some other encoding, decoding may fail or give
917791-- wrong results. In such cases, write a @newtype@ wrapper and a
918792-- custom 'Result' instance to handle your encoding.
793+
794+getTypename :: Connection -> PQ.Oid -> IO ByteString
795+getTypename conn@Connection{..} oid =
796+ case oid2builtin oid of
797+ Just builtin -> return $! builtin2typname builtin
798+ Nothing -> modifyMVar connectionObjects $ \oidmap -> do
799+ case IntMap.lookup (oid2int oid) oidmap of
800+ Just name -> return (oidmap, name)
801+ Nothing -> do
802+ names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
803+ (Only oid)
804+ name <- case names of
805+ [] -> return $ throw SqlError {
806+ sqlNativeError = -1,
807+ sqlErrorMsg = "invalid type oid",
808+ sqlState = ""
809+ }
810+ [Only x] -> return x
811+ _ -> fail "typename query returned more than one result"
812+ -- oid is a primary key, so the query should
813+ -- never return more than one result
814+ return (IntMap.insert (oid2int oid) name oidmap, name)