@@ -1,14 +1,18 @@
1−{-# LANGUAGE BangPatterns, DeriveDataTypeable, OverloadedStrings #-}
2−{-# LANGUAGE DoAndIfThenElse, RecordWildCards, NamedFieldPuns #-}
1+{-# LANGUAGE DeriveDataTypeable #-}
2+{-# LANGUAGE NamedFieldPuns #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE PatternGuards #-}
5+{-# LANGUAGE RecordWildCards #-}
6+{-# LANGUAGE ViewPatterns #-}
7+
38------------------------------------------------------------------------------
49-- |
510-- Module: Database.PostgreSQL.Simple
611-- Copyright: (c) 2011 MailRank, Inc.
7−-- (c) 2011 Leon P Smith
12+-- (c) 2011-2012 Leon P Smith
813-- License: BSD3
914-- Maintainer: Leon P Smith <leon@melding-monads.com>
1015-- Stability: experimental
11−-- Portability: portable
1216--
1317-- A mid-level client library for the PostgreSQL database, aimed at ease of
1418-- use and high performance.
@@ -38,6 +42,9 @@ module Database.PostgreSQL.Simple
3842 -- ** Modifying multiple rows at once
3943 -- $many
4044
45+ -- ** @RETURNING@: modifications that return results
46+ -- $returning
47+
4148 -- * Extracting results
4249 -- $result
4350
@@ -48,31 +55,54 @@ module Database.PostgreSQL.Simple
4855 -- $types
4956
5057 -- * Types
51− Base.ConnectInfo(..)
52− , Connection
58+ Connection
5359 , Query
60+ , ToRow
61+ , FromRow
5462 , In(..)
5563 , Binary(..)
5664 , Only(..)
65+ , (:.)(..)
5766 -- ** Exceptions
67+ , SomePostgreSqlException(..)
5868 , SqlError(..)
59− , FormatError(fmtMessage, fmtQuery, fmtParams)
60− , QueryError(qeMessage, qeQuery)
61− , ResultError(errSQLType, errHaskellType, errMessage)
69+ , PQ.ExecStatus(..)
70+ , FormatError(..)
71+ , QueryError(..)
72+ , ResultError(..)
6273 -- * Connection management
63− , Base.connect
6474 , Base.connectPostgreSQL
65− , Base.postgreSQLConnectionString
66− , Base.defaultConnectInfo
6775 , Base.close
76+ , Base.connect
77+ , Base.withConnect
78+ , Base.ConnectInfo(..)
79+ , Base.defaultConnectInfo
80+ , Base.postgreSQLConnectionString
6881 -- * Queries that return results
6982 , query
7083 , query_
84+ -- ** Queries taking parser as argument
85+ , queryWith
86+ , queryWith_
7187 -- * Queries that stream results
88+ , FoldOptions(..)
89+ , FetchQuantity(..)
90+ , defaultFoldOptions
7291 , fold
92+ , foldWithOptions
7393 , fold_
94+ , foldWithOptions_
7495 , forEach
7596 , 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
76106 -- * Statements that do not return results
77107 , execute
78108 , execute_
@@ -80,6 +110,7 @@ module Database.PostgreSQL.Simple
80110-- , Base.insertID
81111 -- * Transaction handling
82112 , withTransaction
113+ , withSavepoint
83114-- , Base.autocommit
84115 , begin
85116 , commit
@@ -89,50 +120,27 @@ module Database.PostgreSQL.Simple
89120 , formatQuery
90121 ) where
91122
92−import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
93−import Blaze.ByteString.Builder.Char8 (fromChar)
94−import Control.Applicative ((<$>), pure)
95−import Control.Concurrent.MVar
96−import Control.Exception (Exception, bracket, onException, throw, throwIO)
97−import Control.Monad (foldM)
98−import Control.Monad.Fix (fix)
99−import Data.ByteString (ByteString)
100−import Data.Char(ord)
101−import Data.Int (Int64)
102−import qualified Data.IntMap as IntMap
103−import Data.List (intersperse)
104−import Data.Monoid (mappend, mconcat)
105−import Data.Typeable (Typeable)
106−import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
107−import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
108−import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
109−import Database.PostgreSQL.Simple.Result (ResultError(..))
110−import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
111−import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
112−import Database.PostgreSQL.Simple.Internal as Base
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
113141import qualified Database.PostgreSQL.LibPQ as PQ
114−import Text.Regex.PCRE.Light (compile, caseless, match)
115142import qualified Data.ByteString.Char8 as B
116143
117−-- | Exception thrown if a 'Query' could not be formatted correctly.
118−-- This may occur if the number of \'@?@\' characters in the query
119−-- string does not match the number of parameters provided.
120−data FormatError = FormatError {
121− fmtMessage :: String
122− , fmtQuery :: Query
123− , fmtParams :: [ByteString]
124− } deriving (Eq, Show, Typeable)
125−
126−instance Exception FormatError
127−
128−-- | Exception thrown if 'query' is used to perform an @INSERT@-like
129−-- operation, or 'execute' is used to perform a @SELECT@-like operation.
130−data QueryError = QueryError {
131− qeMessage :: String
132− , qeQuery :: Query
133− } deriving (Eq, Show, Typeable)
134−
135−instance Exception QueryError
136144
137145-- | Format a query string.
138146--
@@ -144,11 +152,11 @@ instance Exception QueryError
144152--
145153-- Throws 'FormatError' if the query string could not be formatted
146154-- correctly.
147−formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
155+formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
148156formatQuery conn q@(Query template) qs
149157 | null xs && '?' `B.notElem` template = return template
150158 | otherwise = toByteString <$> buildQuery conn q template xs
151− where xs = renderParams qs
159+ where xs = toRow qs
152160
153161-- | Format a query string with a variable number of rows.
154162--
@@ -163,105 +171,208 @@ formatQuery conn q@(Query template) qs
163171--
164172-- Throws 'FormatError' if the query string could not be formatted
165173-- correctly.
166−formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
174+formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
167175formatMany _ q [] = fmtError "no rows supplied" q []
168176formatMany conn q@(Query template) qs = do
169− case match re template [] of
170− Just [_,before,qbits,after] -> do
171− bs <- mapM (buildQuery conn q qbits . renderParams) qs
172− return . toByteString . mconcat $ fromByteString before :
173− intersperse (fromChar ',') bs ++
174− [fromByteString after]
175− _ -> error "foo"
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
176203 where
177− re = compile "^([^?]+\\bvalues\\s*)\
178− \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
179− \([^?]*)$"
180− [caseless]
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
181279
182−escapeStringConn conn s = withConnection conn $ \c -> do
183− PQ.escapeStringConn c s
184280
185281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
186−buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
187− where quote = inQuotes . fromByteString . maybe undefined id
188− sub (Plain b) = pure b
189− sub (Escape s) = quote <$> escapeStringConn conn s
190− sub (Many ys) = mconcat <$> mapM sub ys
191− split s = fromByteString h : if B.null t then [] else split (B.tail t)
192− where (h,t) = B.break (=='?') s
193− zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
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
194293 zipParams [t] [] = t
195− zipParams _ _ = fmtError (show (B.count '?' template) ++
196− " '?' characters, but " ++
294+ zipParams _ _ = fmtError (show countSingleQs ++
295+ " single '?' characters, but " ++
197296 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
198306
199307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
200308-- expected to return results.
201309--
202310-- Returns the number of rows affected.
203311--
204−-- Throws 'FormatError' if the query could not be formatted correctly.
205−execute :: (QueryParams q) => Connection -> Query -> q -> IO Int64
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
206315execute conn template qs = do
207316 result <- exec conn =<< formatQuery conn template qs
208317 finishExecute conn template result
209318
210−-- | A version of 'execute' that does not perform query substitution.
211−execute_ :: Connection -> Query -> IO Int64
212−execute_ conn q@(Query stmt) = do
213− result <- exec conn stmt
214− finishExecute conn q result
215−
216319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
217320-- expected to return results.
218321--
219−-- Returns the number of rows affected.
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.
220325--
221−-- Throws 'FormatError' if the query could not be formatted correctly.
222−executeMany :: (QueryParams q) => Connection -> Query -> [q] -> IO Int64
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:
339+--
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
223350executeMany _ _ [] = return 0
224351executeMany conn q qs = do
225352 result <- exec conn =<< formatMany conn q qs
226353 finishExecute conn q result
227354
228−finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
229−finishExecute conn q result = do
230− status <- PQ.resultStatus result
231− case status of
232− PQ.CommandOk -> do
233− ncols <- PQ.nfields result
234− if ncols /= 0
235− then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
236− "-column result") q
237− else do
238− nstr <- PQ.cmdTuples result
239− return $ case nstr of
240− Nothing -> 0 -- is this appropriate?
241− Just str -> toInteger str
242− PQ.TuplesOk -> do
243− ncols <- PQ.nfields result
244− throwIO $ QueryError ("execute resulted in " ++ show ncols ++
245− "-column result") q
246− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
247− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
248− _ -> do
249− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
250− statusmsg <- PQ.resStatus status
251− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
252− throwIO $ SqlError { sqlState = state
253− , sqlNativeError = fromEnum status
254− , sqlErrorMsg = B.concat [ "execute: ", statusmsg
255− , ": ", errormsg ]}
256− where
257− toInteger str = B.foldl' delta 0 str
258− where
259− delta acc c =
260− if '0' <= c && c <= '9'
261− then 10 * acc + fromIntegral (ord c - ord '0')
262− else error ("finishExecute: not an int: " ++ B.unpack str)
263−
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
264369
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
265376
266377-- | Perform a @SELECT@ or other SQL query that is expected to return
267378-- results. All results are retrieved and converted before this
@@ -278,33 +389,44 @@ finishExecute conn q result = do
278389-- using 'execute' instead of 'query').
279390--
280391-- * 'ResultError': result conversion failed.
281−query :: (QueryParams q, QueryResults r)
282− => Connection -> Query -> q -> IO [r]
283−query conn template qs = do
284− result <- exec conn =<< formatQuery conn template qs
285− finishQuery conn template result
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
286397
287398-- | A version of 'query' that does not perform query substitution.
288−query_ :: (QueryResults r) => Connection -> Query -> IO [r]
289−query_ conn q@(Query que) = do
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
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
290411 result <- exec conn que
291− finishQuery conn q result
412+ finishQueryWith parser conn q result
292413
293414-- | Perform a @SELECT@ or other SQL query that is expected to return
294415-- results. Results are streamed incrementally from the server, and
295416-- consumed via a left fold.
296417--
297−-- The result consumer must be carefully written to execute
298−-- quickly. If the consumer is slow, server resources will be tied up,
299−-- and other clients may not be able to update the tables from which
300−-- the results are being streamed.
301−--
302418-- When dealing with small results, it may be simpler (and perhaps
303419-- faster) to use 'query' instead.
304420--
305421-- This fold is /not/ strict. The stream consumer is responsible for
306422-- forcing the evaluation of its result to avoid space leaks.
307423--
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+--
308430-- Exceptions that may be thrown:
309431--
310432-- * 'FormatError': the query string could not be formatted correctly.
@@ -313,191 +435,202 @@ query_ conn q@(Query que) = do
313435-- using 'execute' instead of 'query').
314436--
315437-- * 'ResultError': result conversion failed.
316−fold :: (QueryParams q, QueryResults r) =>
317− Connection
318− -> Query -- ^ Query template.
319− -> q -- ^ Query parameters.
320− -> a -- ^ Initial state for result consumer.
321− -> (a -> r -> IO a) -- ^ Result consumer.
322− -> IO a
323−fold conn template qs z f = withConnection conn $ \c -> do
324− success <- PQ.sendQuery c =<< formatQuery conn template qs
325− if success
326− then finishFold conn c template z f
327− else do
328− msg <- maybe "fold error" id <$> PQ.errorMessage c
329− throwIO $ SqlError { sqlNativeError = -1
330− , sqlErrorMsg = msg
331− , sqlState = "" }
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 )
442+ => Connection
443+ -> Query
444+ -> params
445+ -> a
446+ -> (a -> row -> IO a)
447+ -> IO a
448+fold = foldWithOptions defaultFoldOptions
449+
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.
464+data FetchQuantity
465+ = Automatic
466+ | Fixed !Int
467+
468+data FoldOptions
469+ = FoldOptions {
470+ fetchQuantity :: !FetchQuantity,
471+ transactionMode :: !TransactionMode
472+ }
473+
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 )
488+ => FoldOptions
489+ -> Connection
490+ -> Query
491+ -> params
492+ -> a
493+ -> (a -> row -> IO a)
494+ -> 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
508+ q <- formatQuery conn template qs
509+ doFold opts parser conn template (Query q) a f
332510
333511-- | A version of 'fold' that does not perform query substitution.
334−fold_ :: (QueryResults r) =>
512+fold_ :: (FromRow r) =>
335513 Connection
336514 -> Query -- ^ Query.
337515 -> a -- ^ Initial state for result consumer.
338516 -> (a -> r -> IO a) -- ^ Result consumer.
339517 -> IO a
340−fold_ conn q@(Query que) z f = withConnection conn $ \c -> do
341− success <- PQ.sendQuery c que
342− if success
343− then finishFold conn c q z f
344− else do
345− msg <- maybe "fold_ error" id <$> PQ.errorMessage c
346− throwIO $ SqlError { sqlNativeError = -1
347− , sqlErrorMsg = msg
348− , sqlState = "" }
518+fold_ = foldWithOptions_ defaultFoldOptions
519+
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
528+
529+foldWithOptions_ :: (FromRow r) =>
530+ FoldOptions
531+ -> Connection
532+ -> Query -- ^ Query.
533+ -> a -- ^ Initial state for result consumer.
534+ -> (a -> r -> IO a) -- ^ Result consumer.
535+ -> 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
550+ -> Connection
551+ -> Query
552+ -> Query
553+ -> a
554+ -> (a -> row -> IO a)
555+ -> IO a
556+doFold FoldOptions{..} parser conn _template q a0 f = do
557+ stat <- withConnection conn PQ.transactionStatus
558+ case stat of
559+ PQ.TransIdle -> withTransactionMode transactionMode conn go
560+ PQ.TransInTrans -> go
561+ PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
562+ -- This _shouldn't_ occur in the current incarnation of
563+ -- the library, as we aren't using libpq asynchronously.
564+ -- However, it could occur in future incarnations of
565+ -- this library or if client code uses the Internal module
566+ -- to use raw libpq commands on postgresql-simple connections.
567+ PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
568+ -- This should be turned into a better error message.
569+ -- It is probably a bad idea to automatically roll
570+ -- back the transaction and start another.
571+ PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572+ -- Not sure what this means.
573+ 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
585+
586+-- FIXME: choose the Automatic chunkSize more intelligently
587+-- One possibility is to use the type of the results, although this
588+-- still isn't a perfect solution, given that common types (e.g. text)
589+-- are of highly variable size.
590+-- A refinement of this technique is to pick this number adaptively
591+-- as results are read in from the database.
592+ chunkSize = case fetchQuantity of
593+ Automatic -> 256
594+ Fixed n -> n
349595
350596-- | A version of 'fold' that does not transform a state value.
351−forEach :: (QueryParams q, QueryResults r) =>
597+forEach :: (ToRow q, FromRow r) =>
352598 Connection
353599 -> Query -- ^ Query template.
354600 -> q -- ^ Query parameters.
355601 -> (r -> IO ()) -- ^ Result consumer.
356602 -> IO ()
357−forEach conn template qs = fold conn template qs () . const
603+forEach = forEachWith fromRow
358604{-# INLINE forEach #-}
359605
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+
360617-- | A version of 'forEach' that does not perform query substitution.
361−forEach_ :: (QueryResults r) =>
618+forEach_ :: (FromRow r) =>
362619 Connection
363620 -> Query -- ^ Query template.
364621 -> (r -> IO ()) -- ^ Result consumer.
365622 -> IO ()
366−forEach_ conn template = fold_ conn template () . const
623+forEach_ = forEachWith_ fromRow
367624{-# INLINE forEach_ #-}
368625
369−forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
370−forM' lo hi m = loop hi []
371− where
372− loop !n !as
373− | n < lo = return as
374− | otherwise = do
375− a <- m n
376− loop (n-1) (a:as)
377−
378−finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
379−finishQuery conn q result = do
380− status <- PQ.resultStatus result
381− case status of
382− PQ.CommandOk -> do
383− throwIO $ QueryError "query resulted in a command response" q
384− PQ.TuplesOk -> do
385− ncols <- PQ.nfields result
386− fields <- forM' 0 (ncols-1) $ \column -> do
387− type_oid <- PQ.ftype result column
388− typename <- getTypename conn type_oid
389− return Field{..}
390− nrows <- PQ.ntuples result
391− forM' 0 (nrows-1) $ \row -> do
392− values <- forM' 0 (ncols-1) (\col -> PQ.getvalue result row col)
393− case convertResults fields values of
394− Left err -> throwIO err
395− Right a -> return a
396− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
397− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
398− _ -> do
399− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
400− statusmsg <- PQ.resStatus status
401− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
402− throwIO $ SqlError { sqlState = state
403− , sqlNativeError = fromEnum status
404− , sqlErrorMsg = B.concat [ "query: ", statusmsg
405− , ": ", errormsg ]}
406−
407−
408−finishFold :: (QueryResults r) =>
409− Connection
410− -> PQ.Connection
411− -> Query -- ^ Query.
412− -> a -- ^ Initial state for result consumer.
413− -> (a -> r -> IO a) -- ^ Result consumer.
414− -> IO a
415−finishFold conn c q a_ f = loop a_
416− where
417− loop a = do
418− mres <- PQ.getResult c
419− case mres of
420− Nothing -> return a
421− Just result -> do
422− stat <- PQ.resultStatus result
423− case stat of
424− PQ.TuplesOk -> do
425− ncols <- PQ.nfields result
426− fields <- forM' 0 (ncols-1) $ \column -> do
427− type_oid <- PQ.ftype result column
428− typename <- getTypename conn type_oid
429− return Field{..}
430− nrows <- PQ.ntuples result
431− a' <- foldM (\a row -> do
432− values <- forM' 0 (ncols-1) (PQ.getvalue result row)
433− case convertResults fields values of
434− Left err -> clear c >> throwIO err
435− Right r -> f a r)
436− a [0..nrows-1]
437− loop a'
438− _ -> do
439− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
440− statusmsg <- PQ.resStatus stat
441− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
442− clear c
443− throwIO $ SqlError {
444− sqlState = state,
445− sqlNativeError = fromEnum stat,
446− sqlErrorMsg = B.concat [ "fold: ", statusmsg
447− , ": ", errormsg ]}
448− clear c = do
449− mres <- PQ.getResult c
450− case mres of
451− Nothing -> return ()
452− Just _ -> clear c
453−
454−-- | Execute an action inside a SQL transaction.
455−--
456−-- This function initiates a transaction with a \"@begin
457−-- transaction@\" statement, then executes the supplied action. If
458−-- the action succeeds, the transaction will be completed with
459−-- 'Base.commit' before this function returns.
460−--
461−-- If the action throws /any/ kind of exception (not just a
462−-- PostgreSQL-related exception), the transaction will be rolled back using
463−-- 'rollback', then the exception will be rethrown.
464−withTransaction :: Connection -> IO a -> IO a
465−withTransaction conn act = do
466− _ <- begin conn
467− r <- act `onException` rollback conn
468− commit conn
469− return r
470−
471−-- | Rollback a transaction.
472−-- rollback :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
473−rollback :: Connection -> IO ()
474−rollback conn = do
475− _ <- execute_ conn "ABORT"
476− return ()
477−
478−-- | Commit a transaction.
479−-- commit :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
480−commit :: Connection -> IO ()
481−commit conn = do
482− _ <- execute_ conn "COMMIT"
483− return ()
484−
485−-- | Begin a transaction.
486−-- begin :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
487−begin :: Connection -> IO ()
488−begin conn = do
489− _ <- execute_ conn "BEGIN"
490− return ()
491−
492−fmtError :: String -> Query -> [Action] -> a
493−fmtError msg q xs = throw FormatError {
494− fmtMessage = msg
495− , fmtQuery = q
496− , fmtParams = map twiddle xs
497− }
498− where twiddle (Plain b) = toByteString b
499− twiddle (Escape s) = s
500− twiddle (Many ys) = B.concat (map twiddle ys)
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+
501634
502635-- $use
503636--
@@ -525,9 +658,11 @@ fmtError msg q xs = throw FormatError {
525658-- >
526659-- > import Database.PostgreSQL.Simple
527660-- >
661+-- > hello :: IO Int
528662-- > hello = do
529−-- > conn <- connect defaultConnectInfo
530−-- > query conn "select 2 + 2"
663+-- > conn <- connectPostgreSQL ""
664+-- > [Only i] <- query_ conn "select 2 + 2"
665+-- > return i
531666--
532667-- A 'Query' value does not represent the actual query that will be
533668-- executed, but is a template for constructing the final query.
@@ -574,7 +709,7 @@ fmtError msg q xs = throw FormatError {
574709-- Automated type inference means that you will often be able to avoid
575710-- supplying explicit type signatures for the elements of a tuple.
576711-- However, sometimes the compiler will not be able to infer your
577−-- types. Consider a care where you write a numeric literal in a
712+-- types. Consider a case where you write a numeric literal in a
578713-- parameter tuple:
579714--
580715-- > query conn "select ? + ?" (40,2)
@@ -588,15 +723,30 @@ fmtError msg q xs = throw FormatError {
588723-- The same kind of problem can arise with string literals if you have
589724-- the @OverloadedStrings@ language extension enabled. Again, just
590725-- 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])
591740
592741-- $only_param
593742--
594743-- Haskell lacks a single-element tuple type, so if you have just one
595−-- value you want substituted into a query, what should you do?
744+-- value you want substituted into a query or a single-column result,
745+-- what should you do?
596746--
597747-- The obvious approach would appear to be something like this:
598748--
599−-- > instance (Param a) => QueryParam a where
749+-- > instance (ToField a) => ToRow a where
600750-- > ...
601751--
602752-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -607,6 +757,9 @@ fmtError msg q xs = throw FormatError {
607757--
608758-- > execute conn "insert into users (first_name) values (?)"
609759-- > ["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.
610763
611764-- $in
612765--
@@ -624,7 +777,7 @@ fmtError msg q xs = throw FormatError {
624777-- Here's an example:
625778--
626779-- > query conn "select * from users where first_name in ?" $
627−-- > In ["Anna", "Boris", "Carla"]
780+-- > Only $ In ["Anna", "Boris", "Carla"]
628781--
629782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
630783-- substituted instead, to ensure that your clause remains
@@ -652,7 +805,7 @@ fmtError msg q xs = throw FormatError {
652805-- * There must be no other \"@?@\" characters anywhere in your
653806-- template.
654807--
655−-- * There must one or more \"@?@\" in the parentheses.
808+-- * There must be one or more \"@?@\" in the parentheses.
656809--
657810-- * Extra white space is fine.
658811--
@@ -673,10 +826,26 @@ fmtError msg q xs = throw FormatError {
673826-- > insert into users (first_name,last_name) values
674827-- > ('Boris','Karloff'),('Ed','Wood')
675828
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+
676845-- $result
677846--
678847-- The 'query' and 'query_' functions return a list of values in the
679−-- 'QueryResults' typeclass. This class performs automatic extraction
848+-- 'FromRow' typeclass. This class performs automatic extraction
680849-- and type conversion of rows from a query result.
681850--
682851-- Here is a simple example of how to extract results:
@@ -707,7 +876,7 @@ fmtError msg q xs = throw FormatError {
707876--
708877-- Although SQL can accommodate @NULL@ as a value for any of these
709878-- types, Haskell cannot. If your result contains columns that may be
710−-- @NULL@, be sure that you use 'Maybe' in those positions of of your
879+-- @NULL@, be sure that you use 'Maybe' in those positions of your
711880-- tuple.
712881--
713882-- > (Text, Maybe Int, Int)
@@ -733,7 +902,7 @@ fmtError msg q xs = throw FormatError {
733902-- all values of the given PostgreSQL type is considered \"compatible\".
734903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
735904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
736−-- represent a @SMALLINT@, so it is considered compatble with those types.
905+-- represent a @SMALLINT@, so it is considered compatible with those types.
737906--
738907-- * A numeric compatibility check is based only on the type of a
739908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -747,25 +916,3 @@ fmtError msg q xs = throw FormatError {
747916-- UTF-8. If you use some other encoding, decoding may fail or give
748917-- wrong results. In such cases, write a @newtype@ wrapper and a
749918-- custom 'Result' instance to handle your encoding.
750−
751−getTypename :: Connection -> PQ.Oid -> IO ByteString
752−getTypename conn@Connection{..} oid =
753− case oid2builtin oid of
754− Just builtin -> return $! builtin2typname builtin
755− Nothing -> modifyMVar connectionObjects $ \oidmap -> do
756− case IntMap.lookup (oid2int oid) oidmap of
757− Just name -> return (oidmap, name)
758− Nothing -> do
759− names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
760− (Only oid)
761− name <- case names of
762− [] -> return $ throw SqlError {
763− sqlNativeError = -1,
764− sqlErrorMsg = "invalid type oid",
765− sqlState = ""
766− }
767− [Only x] -> return x
768− _ -> fail "typename query returned more than one result"
769− -- oid is a primary key, so the query should
770− -- never return more than one result
771− return (IntMap.insert (oid2int oid) name oidmap, name)