@@ -1,18 +1,14 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE NamedFieldPuns #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE PatternGuards #-}
5−{-# LANGUAGE RecordWildCards #-}
6−{-# LANGUAGE ViewPatterns #-}
1+{-# LANGUAGE DeriveDataTypeable, RecordWildCards, NamedFieldPuns #-}
72
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,35 +48,26 @@ 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
8872 , FoldOptions(..)
8973 , FetchQuantity(..)
@@ -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,18 @@ module Database.PostgreSQL.Simple
11085-- , Base.insertID
11186 -- * Transaction handling
11287 , withTransaction
113− , withSavepoint
88+ , TransactionMode(..)
89+ , IsolationLevel(..)
90+ , ReadWriteMode(..)
91+ , defaultTransactionMode
92+ , defaultIsolationLevel
93+ , defaultReadWriteMode
94+ , withTransactionLevel
95+ , withTransactionMode
11496-- , Base.autocommit
11597 , begin
98+ , beginLevel
99+ , beginMode
116100 , commit
117101 , rollback
118102 -- * Helper functions
@@ -120,27 +104,60 @@ module Database.PostgreSQL.Simple
120104 , formatQuery
121105 ) where
122106
123−import Data.ByteString.Builder (Builder, byteString, char8)
124−import Control.Applicative ((<$>))
125−import Control.Exception as E
107+import Blaze.ByteString.Builder
108+ ( Builder, fromByteString, toByteString )
109+import Blaze.ByteString.Builder.Char8 (fromChar)
110+import Control.Applicative ((<$>), pure)
111+import Control.Concurrent.MVar
112+import Control.Exception
113+ ( Exception, onException, throw, throwIO, finally )
114+import Control.Monad (foldM)
126115import Data.ByteString (ByteString)
116+import Data.Char(ord)
127117import Data.Int (Int64)
118+import qualified Data.IntMap as IntMap
128119import Data.List (intersperse)
129−import Data.Monoid (mconcat)
130−import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
131−import Database.PostgreSQL.Simple.Cursor
120+import Data.Monoid (mappend, mconcat)
121+import Data.Typeable (Typeable)
122+import Database.PostgreSQL.Simple.BuiltinTypes
123+ ( oid2builtin, builtin2typname )
124+import Database.PostgreSQL.Simple.Compat ( mask )
132125import Database.PostgreSQL.Simple.FromField (ResultError(..))
133126import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134−import Database.PostgreSQL.Simple.ToField (Action(..))
127+import Database.PostgreSQL.Simple.Ok
128+import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
135129import Database.PostgreSQL.Simple.ToRow (ToRow(..))
136130import Database.PostgreSQL.Simple.Types
137− ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
131+ ( Binary(..), In(..), Only(..), Query(..) )
138132import Database.PostgreSQL.Simple.Internal as Base
139−import Database.PostgreSQL.Simple.Internal.PQResultUtils
140−import Database.PostgreSQL.Simple.Transaction
141133import qualified Database.PostgreSQL.LibPQ as PQ
134+import Text.Regex.PCRE.Light (compile, caseless, match)
142135import qualified Data.ByteString.Char8 as B
143−
136+import qualified Data.Text as T
137+import qualified Data.Text.Encoding as TE
138+import qualified Data.Vector as V
139+import Control.Monad.Trans.Reader
140+import Control.Monad.Trans.State.Strict
141+
142+-- | Exception thrown if a 'Query' could not be formatted correctly.
143+-- This may occur if the number of \'@?@\' characters in the query
144+-- string does not match the number of parameters provided.
145+data FormatError = FormatError {
146+ fmtMessage :: String
147+ , fmtQuery :: Query
148+ , fmtParams :: [ByteString]
149+ } deriving (Eq, Show, Typeable)
150+
151+instance Exception FormatError
152+
153+-- | Exception thrown if 'query' is used to perform an @INSERT@-like
154+-- operation, or 'execute' is used to perform a @SELECT@-like operation.
155+data QueryError = QueryError {
156+ qeMessage :: String
157+ , qeQuery :: Query
158+ } deriving (Eq, Show, Typeable)
159+
160+instance Exception QueryError
144161
145162-- | Format a query string.
146163--
@@ -174,205 +191,116 @@ formatQuery conn q@(Query template) qs
174191formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
175192formatMany _ q [] = fmtError "no rows supplied" q []
176193formatMany conn q@(Query template) qs = do
177− case parseTemplate template of
178− Just (before, qbits, after) -> do
194+ case match re template [] of
195+ Just [_,before,qbits,after] -> do
179196 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
197+ return . toByteString . mconcat $ fromByteString before :
198+ intersperse (fromChar ',') bs ++
199+ [fromByteString after]
200+ _ -> error "foo"
203201 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
202+ re = compile "^([^?]+\\bvalues\\s*)\
203+ \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
204+ \([^?]*)$"
205+ [caseless]
206+
207+escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
208+escapeStringConn conn s =
209+ withConnection conn $ \c ->
210+ PQ.escapeStringConn c s >>= checkError c
279211
212+escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
213+escapeByteaConn conn s =
214+ withConnection conn $ \c ->
215+ PQ.escapeByteaConn c s >>= checkError c
216+
217+checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
218+checkError c (Just x) = return $ Right x
219+checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
280220
281221buildQuery :: 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
222+buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
223+ where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
224+ (inQuotes . fromByteString)
225+ utf8ToString = T.unpack . TE.decodeUtf8
226+ sub (Plain b) = pure b
227+ sub (Escape s) = quote <$> escapeStringConn conn s
228+ sub (EscapeBytea s) = quote <$> escapeByteaConn conn s
229+ sub (Many ys) = mconcat <$> mapM sub ys
230+ split s = fromByteString h : if B.null t then [] else split (B.tail t)
231+ where (h,t) = B.break (=='?') s
232+ zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
293233 zipParams [t] [] = t
294− zipParams _ _ = fmtError (show countSingleQs ++
295− " single '?' characters, but " ++
234+ zipParams _ _ = fmtError (show (B.count '?' template) ++
235+ " '?' characters, but " ++
296236 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
306237
307238-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
308239-- expected to return results.
309240--
310241-- Returns the number of rows affected.
311242--
312−-- Throws 'FormatError' if the query could not be formatted correctly, or
313−-- a 'SqlError' exception if the backend returns an error.
243+-- Throws 'FormatError' if the query could not be formatted correctly.
314244execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
315245execute conn template qs = do
316246 result <- exec conn =<< formatQuery conn template qs
317247 finishExecute conn template result
318248
249+-- | A version of 'execute' that does not perform query substitution.
250+execute_ :: Connection -> Query -> IO Int64
251+execute_ conn q@(Query stmt) = do
252+ result <- exec conn stmt
253+ finishExecute conn q result
254+
319255-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
320256-- expected to return results.
321257--
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:
258+-- Returns the number of rows affected.
339259--
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−
260+-- Throws 'FormatError' if the query could not be formatted correctly.
349261executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
350262executeMany _ _ [] = return 0
351263executeMany conn q qs = do
352264 result <- exec conn =<< formatMany conn q qs
353265 finishExecute conn q result
354266
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
267+finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
268+finishExecute _conn q result = do
269+ status <- PQ.resultStatus result
270+ case status of
271+ PQ.CommandOk -> do
272+ ncols <- PQ.nfields result
273+ if ncols /= 0
274+ then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
275+ "-column result") q
276+ else do
277+ nstr <- PQ.cmdTuples result
278+ return $ case nstr of
279+ Nothing -> 0 -- is this appropriate?
280+ Just str -> toInteger str
281+ PQ.TuplesOk -> do
282+ ncols <- PQ.nfields result
283+ throwIO $ QueryError ("execute resulted in " ++ show ncols ++
284+ "-column result") q
285+ PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
286+ PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
287+ _ -> do
288+ errormsg <- maybe "" id <$> PQ.resultErrorMessage result
289+ statusmsg <- PQ.resStatus status
290+ state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
291+ throwIO $ SqlError { sqlState = state
292+ , sqlNativeError = fromEnum status
293+ , sqlErrorMsg = B.concat [ "execute: ", statusmsg
294+ , ": ", errormsg ]}
295+ where
296+ toInteger str = B.foldl' delta 0 str
297+ where
298+ delta acc c =
299+ if '0' <= c && c <= '9'
300+ then 10 * acc + fromIntegral (ord c - ord '0')
301+ else error ("finishExecute: not an int: " ++ B.unpack str)
302+
369303
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
376304
377305-- | Perform a @SELECT@ or other SQL query that is expected to return
378306-- results. All results are retrieved and converted before this
@@ -389,27 +317,17 @@ returningWith parser conn q qs = do
389317-- using 'execute' instead of 'query').
390318--
391319-- * '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
320+query :: (ToRow q, FromRow r)
321+ => Connection -> Query -> q -> IO [r]
322+query conn template qs = do
323+ result <- exec conn =<< formatQuery conn template qs
324+ finishQuery conn template result
397325
398326-- | A version of 'query' that does not perform query substitution.
399327query_ :: (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
405− result <- exec conn =<< formatQuery conn template qs
406− finishQueryWith parser conn template result
407−
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
328+query_ conn q@(Query que) = do
411329 result <- exec conn que
412− finishQueryWith parser conn q result
330+ finishQuery conn q result
413331
414332-- | Perform a @SELECT@ or other SQL query that is expected to return
415333-- results. Results are streamed incrementally from the server, and
@@ -421,12 +339,6 @@ queryWith_ parser conn q@(Query que) = do
421339-- This fold is /not/ strict. The stream consumer is responsible for
422340-- forcing the evaluation of its result to avoid space leaks.
423341--
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−--
430342-- Exceptions that may be thrown:
431343--
432344-- * 'FormatError': the query string could not be formatted correctly.
@@ -435,9 +347,7 @@ queryWith_ parser conn q@(Query que) = do
435347-- using 'execute' instead of 'query').
436348--
437349-- * '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.
350+
441351fold :: ( FromRow row, ToRow params )
442352 => Connection
443353 -> Query
@@ -447,20 +357,6 @@ fold :: ( FromRow row, ToRow params )
447357 -> IO a
448358fold = foldWithOptions defaultFoldOptions
449359
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.
464360data FetchQuantity
465361 = Automatic
466362 | Fixed !Int
@@ -471,19 +367,12 @@ data FoldOptions
471367 transactionMode :: !TransactionMode
472368 }
473369
474−-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475370defaultFoldOptions :: FoldOptions
476371defaultFoldOptions = FoldOptions {
477372 fetchQuantity = Automatic,
478373 transactionMode = TransactionMode ReadCommitted ReadOnly
479374 }
480375
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.
487376foldWithOptions :: ( FromRow row, ToRow params )
488377 => FoldOptions
489378 -> Connection
@@ -492,21 +381,9 @@ foldWithOptions :: ( FromRow row, ToRow params )
492381 -> a
493382 -> (a -> row -> IO a)
494383 -> 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
384+foldWithOptions opts conn template qs a f = do
508385 q <- formatQuery conn template qs
509− doFold opts parser conn template (Query q) a f
386+ doFold opts conn template (Query q) a f
510387
511388-- | A version of 'fold' that does not perform query substitution.
512389fold_ :: (FromRow r) =>
@@ -517,14 +394,6 @@ fold_ :: (FromRow r) =>
517394 -> IO a
518395fold_ = foldWithOptions_ defaultFoldOptions
519396
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
528397
529398foldWithOptions_ :: (FromRow r) =>
530399 FoldOptions
@@ -533,27 +402,18 @@ foldWithOptions_ :: (FromRow r) =>
533402 -> a -- ^ Initial state for result consumer.
534403 -> (a -> r -> IO a) -- ^ Result consumer.
535404 -> 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
405+foldWithOptions_ opts conn query a f = doFold opts conn query query a f
406+
407+
408+doFold :: ( FromRow row )
409+ => FoldOptions
550410 -> Connection
551411 -> Query
552412 -> Query
553413 -> a
554414 -> (a -> row -> IO a)
555415 -> IO a
556−doFold FoldOptions{..} parser conn _template q a0 f = do
416+doFold FoldOptions{..} conn _template q a f = do
557417 stat <- withConnection conn PQ.transactionStatus
558418 case stat of
559419 PQ.TransIdle -> withTransactionMode transactionMode conn go
@@ -571,17 +431,11 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
571431 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572432 -- Not sure what this means.
573433 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
434+ go = do
435+ -- FIXME: what about name clashes with already-declared cursors?
436+ _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
437+ `mappend` q)
438+ loop a `finally` execute_ conn "CLOSE fold"
585439
586440-- FIXME: choose the Automatic chunkSize more intelligently
587441-- One possibility is to use the type of the results, although this
@@ -592,6 +446,9 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
592446 chunkSize = case fetchQuantity of
593447 Automatic -> 256
594448 Fixed n -> n
449+ loop a = do
450+ rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
451+ if null rs then return a else foldM f a rs >>= loop
595452
596453-- | A version of 'fold' that does not transform a state value.
597454forEach :: (ToRow q, FromRow r) =>
@@ -600,37 +457,179 @@ forEach :: (ToRow q, FromRow r) =>
600457 -> q -- ^ Query parameters.
601458 -> (r -> IO ()) -- ^ Result consumer.
602459 -> IO ()
603−forEach = forEachWith fromRow
460+forEach conn template qs = fold conn template qs () . const
604461{-# INLINE forEach #-}
605462
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−
617463-- | A version of 'forEach' that does not perform query substitution.
618464forEach_ :: (FromRow r) =>
619465 Connection
620466 -> Query -- ^ Query template.
621467 -> (r -> IO ()) -- ^ Result consumer.
622468 -> IO ()
623−forEach_ = forEachWith_ fromRow
469+forEach_ conn template = fold_ conn template () . const
624470{-# INLINE forEach_ #-}
625471
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−
472+forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
473+forM' lo hi m = loop hi []
474+ where
475+ loop !n !as
476+ | n < lo = return as
477+ | otherwise = do
478+ a <- m n
479+ loop (n-1) (a:as)
480+
481+finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
482+finishQuery conn q result = do
483+ status <- PQ.resultStatus result
484+ case status of
485+ PQ.CommandOk -> do
486+ throwIO $ QueryError "query resulted in a command response" q
487+ PQ.TuplesOk -> do
488+ ncols <- PQ.nfields result
489+ let unCol (PQ.Col x) = fromIntegral x :: Int
490+ typenames <- V.generateM (unCol ncols)
491+ (\(PQ.Col . fromIntegral -> col) -> do
492+ getTypename conn =<< PQ.ftype result col)
493+ nrows <- PQ.ntuples result
494+ ncols <- PQ.nfields result
495+ forM' 0 (nrows-1) $ \row -> do
496+ let rw = Row row typenames result
497+ case runStateT (runReaderT (unRP fromRow) rw) 0 of
498+ Ok (val,col) | col == ncols -> return val
499+ | otherwise -> do
500+ vals <- forM' 0 (ncols-1) $ \c -> do
501+ v <- PQ.getvalue result row c
502+ return ( typenames V.! unCol c
503+ , fmap ellipsis v )
504+ throw (ConversionFailed
505+ (show (unCol ncols) ++ " values: " ++ show vals)
506+ (show (unCol col) ++ " slots in target type")
507+ "mismatch between number of columns to \
508+ \convert and number in target type")
509+ Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
510+ Errors [x] -> throwIO x
511+ Errors xs -> throwIO $ ManyErrors xs
512+
513+ellipsis :: ByteString -> ByteString
514+ellipsis bs
515+ | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
516+ | otherwise = bs
517+
518+
519+-- | Of the four isolation levels defined by the SQL standard,
520+-- these are the three levels distinguished by PostgreSQL as of version 9.0.
521+-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
522+-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
523+-- was equivalent to 'Serializable'.
524+
525+data IsolationLevel
526+ = DefaultIsolationLevel -- ^ the isolation level will be taken from
527+ -- PostgreSQL's per-connection
528+ -- @default_transaction_isolation@ variable,
529+ -- which is initialized according to the
530+ -- server's config. The default configuration
531+ -- is 'ReadCommitted'.
532+ | ReadCommitted
533+ | RepeatableRead
534+ | Serializable
535+ deriving (Show, Eq, Ord, Enum, Bounded)
536+
537+data ReadWriteMode
538+ = DefaultReadWriteMode -- ^ the read-write mode will be taken from
539+ -- PostgreSQL's per-connection
540+ -- @default_transaction_read_only@ variable,
541+ -- which is initialized according to the
542+ -- server's config. The default configuration
543+ -- is 'ReadWrite'.
544+ | ReadWrite
545+ | ReadOnly
546+ deriving (Show, Eq, Ord, Enum, Bounded)
547+
548+data TransactionMode = TransactionMode {
549+ isolationLevel :: !IsolationLevel,
550+ readWriteMode :: !ReadWriteMode
551+ } deriving (Show, Eq)
552+
553+defaultTransactionMode :: TransactionMode
554+defaultTransactionMode = TransactionMode
555+ defaultIsolationLevel
556+ defaultReadWriteMode
557+
558+defaultIsolationLevel :: IsolationLevel
559+defaultIsolationLevel = DefaultIsolationLevel
560+
561+defaultReadWriteMode :: ReadWriteMode
562+defaultReadWriteMode = DefaultReadWriteMode
563+
564+-- | Execute an action inside a SQL transaction.
565+--
566+-- This function initiates a transaction with a \"@begin
567+-- transaction@\" statement, then executes the supplied action. If
568+-- the action succeeds, the transaction will be completed with
569+-- 'Base.commit' before this function returns.
570+--
571+-- If the action throws /any/ kind of exception (not just a
572+-- PostgreSQL-related exception), the transaction will be rolled back using
573+-- 'rollback', then the exception will be rethrown.
574+withTransaction :: Connection -> IO a -> IO a
575+withTransaction = withTransactionMode defaultTransactionMode
576+
577+-- | Execute an action inside a SQL transaction with a given isolation level.
578+withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
579+withTransactionLevel lvl
580+ = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
581+
582+-- | Execute an action inside a SQL transaction with a given transaction mode.
583+withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
584+withTransactionMode mode conn act =
585+ mask $ \restore -> do
586+ beginMode mode conn
587+ r <- restore act `onException` rollback conn
588+ commit conn
589+ return r
590+
591+-- | Rollback a transaction.
592+rollback :: Connection -> IO ()
593+rollback conn = execute_ conn "ABORT" >> return ()
594+
595+-- | Commit a transaction.
596+commit :: Connection -> IO ()
597+commit conn = execute_ conn "COMMIT" >> return ()
598+
599+-- | Begin a transaction.
600+begin :: Connection -> IO ()
601+begin = beginMode defaultTransactionMode
602+
603+-- | Begin a transaction with a given isolation level
604+beginLevel :: IsolationLevel -> Connection -> IO ()
605+beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
606+
607+-- | Begin a transaction with a given transaction mode
608+beginMode :: TransactionMode -> Connection -> IO ()
609+beginMode mode conn = do
610+ _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
611+ return ()
612+ where
613+ isolevel = case isolationLevel mode of
614+ DefaultIsolationLevel -> ""
615+ ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
616+ RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
617+ Serializable -> " ISOLATION LEVEL SERIALIZABLE"
618+ readmode = case readWriteMode mode of
619+ DefaultReadWriteMode -> ""
620+ ReadWrite -> " READ WRITE"
621+ ReadOnly -> " READ ONLY"
622+
623+fmtError :: String -> Query -> [Action] -> a
624+fmtError msg q xs = throw FormatError {
625+ fmtMessage = msg
626+ , fmtQuery = q
627+ , fmtParams = map twiddle xs
628+ }
629+ where twiddle (Plain b) = toByteString b
630+ twiddle (Escape s) = s
631+ twiddle (EscapeBytea s) = s
632+ twiddle (Many ys) = B.concat (map twiddle ys)
634633
635634-- $use
636635--
@@ -658,11 +657,9 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
658657-- >
659658-- > import Database.PostgreSQL.Simple
660659-- >
661−-- > hello :: IO Int
662660-- > hello = do
663−-- > conn <- connectPostgreSQL ""
664−-- > [Only i] <- query_ conn "select 2 + 2"
665−-- > return i
661+-- > conn <- connect defaultConnectInfo
662+-- > query conn "select 2 + 2"
666663--
667664-- A 'Query' value does not represent the actual query that will be
668665-- executed, but is a template for constructing the final query.
@@ -709,7 +706,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
709706-- Automated type inference means that you will often be able to avoid
710707-- supplying explicit type signatures for the elements of a tuple.
711708-- However, sometimes the compiler will not be able to infer your
712−-- types. Consider a case where you write a numeric literal in a
709+-- types. Consider a care where you write a numeric literal in a
713710-- parameter tuple:
714711--
715712-- > query conn "select ? + ?" (40,2)
@@ -723,30 +720,15 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
723720-- The same kind of problem can arise with string literals if you have
724721-- the @OverloadedStrings@ language extension enabled. Again, just
725722-- 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])
740723
741724-- $only_param
742725--
743726-- 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?
727+-- value you want substituted into a query, what should you do?
746728--
747729-- The obvious approach would appear to be something like this:
748730--
749−-- > instance (ToField a) => ToRow a where
731+-- > instance (Param a) => QueryParam a where
750732-- > ...
751733--
752734-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -757,9 +739,6 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
757739--
758740-- > execute conn "insert into users (first_name) values (?)"
759741-- > ["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.
763742
764743-- $in
765744--
@@ -777,7 +756,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
777756-- Here's an example:
778757--
779758-- > query conn "select * from users where first_name in ?" $
780−-- > Only $ In ["Anna", "Boris", "Carla"]
759+-- > In ["Anna", "Boris", "Carla"]
781760--
782761-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
783762-- substituted instead, to ensure that your clause remains
@@ -805,7 +784,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
805784-- * There must be no other \"@?@\" characters anywhere in your
806785-- template.
807786--
808−-- * There must be one or more \"@?@\" in the parentheses.
787+-- * There must one or more \"@?@\" in the parentheses.
809788--
810789-- * Extra white space is fine.
811790--
@@ -826,22 +805,6 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
826805-- > insert into users (first_name,last_name) values
827806-- > ('Boris','Karloff'),('Ed','Wood')
828807
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−
845808-- $result
846809--
847810-- The 'query' and 'query_' functions return a list of values in the
@@ -876,7 +839,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
876839--
877840-- Although SQL can accommodate @NULL@ as a value for any of these
878841-- types, Haskell cannot. If your result contains columns that may be
879−-- @NULL@, be sure that you use 'Maybe' in those positions of your
842+-- @NULL@, be sure that you use 'Maybe' in those positions of of your
880843-- tuple.
881844--
882845-- > (Text, Maybe Int, Int)
@@ -902,7 +865,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
902865-- all values of the given PostgreSQL type is considered \"compatible\".
903866-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
904867-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
905−-- represent a @SMALLINT@, so it is considered compatible with those types.
868+-- represent a @SMALLINT@, so it is considered compatble with those types.
906869--
907870-- * A numeric compatibility check is based only on the type of a
908871-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -916,3 +879,25 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
916879-- UTF-8. If you use some other encoding, decoding may fail or give
917880-- wrong results. In such cases, write a @newtype@ wrapper and a
918881-- custom 'Result' instance to handle your encoding.
882+
883+getTypename :: Connection -> PQ.Oid -> IO ByteString
884+getTypename conn@Connection{..} oid =
885+ case oid2builtin oid of
886+ Just builtin -> return $! builtin2typname builtin
887+ Nothing -> modifyMVar connectionObjects $ \oidmap -> do
888+ case IntMap.lookup (oid2int oid) oidmap of
889+ Just name -> return (oidmap, name)
890+ Nothing -> do
891+ names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
892+ (Only oid)
893+ name <- case names of
894+ [] -> return $ throw SqlError {
895+ sqlNativeError = -1,
896+ sqlErrorMsg = "invalid type oid",
897+ sqlState = ""
898+ }
899+ [Only x] -> return x
900+ _ -> fail "typename query returned more than one result"
901+ -- oid is a primary key, so the query should
902+ -- never return more than one result
903+ return (IntMap.insert (oid2int oid) name oidmap, name)