@@ -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,26 +55,35 @@ 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
7288 , FoldOptions(..)
7389 , FetchQuantity(..)
@@ -78,6 +94,15 @@ module Database.PostgreSQL.Simple
7894 , foldWithOptions_
7995 , forEach
8096 , 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
81106 -- * Statements that do not return results
82107 , execute
83108 , execute_
@@ -85,13 +110,9 @@ module Database.PostgreSQL.Simple
85110-- , Base.insertID
86111 -- * Transaction handling
87112 , withTransaction
88− , TransactionMode(..)
89− , IsolationLevel(..)
90− , ReadWriteMode(..)
91− , withTransactionMode
113+ , withSavepoint
92114-- , Base.autocommit
93115 , begin
94− , beginMode
95116 , commit
96117 , rollback
97118 -- * Helper functions
@@ -99,50 +120,27 @@ module Database.PostgreSQL.Simple
99120 , formatQuery
100121 ) where
101122
102−import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
103−import Blaze.ByteString.Builder.Char8 (fromChar)
104−import Control.Applicative ((<$>), pure)
105−import Control.Concurrent.MVar
106−import Control.Exception (Exception, bracket, onException, throw, throwIO, finally)
107−import Control.Monad (foldM)
108−import Control.Monad.Fix (fix)
109−import Data.ByteString (ByteString)
110−import Data.Char(ord)
111−import Data.Int (Int64)
112−import qualified Data.IntMap as IntMap
113−import Data.List (intersperse)
114−import Data.Monoid (mappend, mconcat)
115−import Data.Typeable (Typeable)
116−import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
117−import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
118−import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
119−import Database.PostgreSQL.Simple.Result (ResultError(..))
120−import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
121−import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
122−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
123141import qualified Database.PostgreSQL.LibPQ as PQ
124−import Text.Regex.PCRE.Light (compile, caseless, match)
125142import qualified Data.ByteString.Char8 as B
126143
127−-- | Exception thrown if a 'Query' could not be formatted correctly.
128−-- This may occur if the number of \'@?@\' characters in the query
129−-- string does not match the number of parameters provided.
130−data FormatError = FormatError {
131− fmtMessage :: String
132− , fmtQuery :: Query
133− , fmtParams :: [ByteString]
134− } deriving (Eq, Show, Typeable)
135−
136−instance Exception FormatError
137−
138−-- | Exception thrown if 'query' is used to perform an @INSERT@-like
139−-- operation, or 'execute' is used to perform a @SELECT@-like operation.
140−data QueryError = QueryError {
141− qeMessage :: String
142− , qeQuery :: Query
143− } deriving (Eq, Show, Typeable)
144−
145−instance Exception QueryError
146144
147145-- | Format a query string.
148146--
@@ -154,11 +152,11 @@ instance Exception QueryError
154152--
155153-- Throws 'FormatError' if the query string could not be formatted
156154-- correctly.
157−formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
155+formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
158156formatQuery conn q@(Query template) qs
159157 | null xs && '?' `B.notElem` template = return template
160158 | otherwise = toByteString <$> buildQuery conn q template xs
161− where xs = renderParams qs
159+ where xs = toRow qs
162160
163161-- | Format a query string with a variable number of rows.
164162--
@@ -173,105 +171,208 @@ formatQuery conn q@(Query template) qs
173171--
174172-- Throws 'FormatError' if the query string could not be formatted
175173-- correctly.
176−formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
174+formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
177175formatMany _ q [] = fmtError "no rows supplied" q []
178176formatMany conn q@(Query template) qs = do
179− case match re template [] of
180− Just [_,before,qbits,after] -> do
181− bs <- mapM (buildQuery conn q qbits . renderParams) qs
182− return . toByteString . mconcat $ fromByteString before :
183− intersperse (fromChar ',') bs ++
184− [fromByteString after]
185− _ -> 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
186203 where
187− re = compile "^([^?]+\\bvalues\\s*)\
188− \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
189− \([^?]*)$"
190− [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
191279
192−escapeStringConn conn s = withConnection conn $ \c -> do
193− PQ.escapeStringConn c s
194280
195281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
196−buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
197− where quote = inQuotes . fromByteString . maybe undefined id
198− sub (Plain b) = pure b
199− sub (Escape s) = quote <$> escapeStringConn conn s
200− sub (Many ys) = mconcat <$> mapM sub ys
201− split s = fromByteString h : if B.null t then [] else split (B.tail t)
202− where (h,t) = B.break (=='?') s
203− 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
204293 zipParams [t] [] = t
205− zipParams _ _ = fmtError (show (B.count '?' template) ++
206− " '?' characters, but " ++
294+ zipParams _ _ = fmtError (show countSingleQs ++
295+ " single '?' characters, but " ++
207296 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
208306
209307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
210308-- expected to return results.
211309--
212310-- Returns the number of rows affected.
213311--
214−-- Throws 'FormatError' if the query could not be formatted correctly.
215−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
216315execute conn template qs = do
217316 result <- exec conn =<< formatQuery conn template qs
218317 finishExecute conn template result
219318
220−-- | A version of 'execute' that does not perform query substitution.
221−execute_ :: Connection -> Query -> IO Int64
222−execute_ conn q@(Query stmt) = do
223− result <- exec conn stmt
224− finishExecute conn q result
225−
226319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
227320-- expected to return results.
228321--
229−-- 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.
230325--
231−-- Throws 'FormatError' if the query could not be formatted correctly.
232−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
233350executeMany _ _ [] = return 0
234351executeMany conn q qs = do
235352 result <- exec conn =<< formatMany conn q qs
236353 finishExecute conn q result
237354
238−finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
239−finishExecute conn q result = do
240− status <- PQ.resultStatus result
241− case status of
242− PQ.CommandOk -> do
243− ncols <- PQ.nfields result
244− if ncols /= 0
245− then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
246− "-column result") q
247− else do
248− nstr <- PQ.cmdTuples result
249− return $ case nstr of
250− Nothing -> 0 -- is this appropriate?
251− Just str -> toInteger str
252− PQ.TuplesOk -> do
253− ncols <- PQ.nfields result
254− throwIO $ QueryError ("execute resulted in " ++ show ncols ++
255− "-column result") q
256− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
257− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
258− _ -> do
259− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
260− statusmsg <- PQ.resStatus status
261− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
262− throwIO $ SqlError { sqlState = state
263− , sqlNativeError = fromEnum status
264− , sqlErrorMsg = B.concat [ "execute: ", statusmsg
265− , ": ", errormsg ]}
266− where
267− toInteger str = B.foldl' delta 0 str
268− where
269− delta acc c =
270− if '0' <= c && c <= '9'
271− then 10 * acc + fromIntegral (ord c - ord '0')
272− else error ("finishExecute: not an int: " ++ B.unpack str)
273−
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
274369
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
275376
276377-- | Perform a @SELECT@ or other SQL query that is expected to return
277378-- results. All results are retrieved and converted before this
@@ -288,17 +389,27 @@ finishExecute conn q result = do
288389-- using 'execute' instead of 'query').
289390--
290391-- * 'ResultError': result conversion failed.
291−query :: (QueryParams q, QueryResults r)
292− => Connection -> Query -> q -> IO [r]
293−query conn template qs = do
294− result <- exec conn =<< formatQuery conn template qs
295− 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
296397
297398-- | A version of 'query' that does not perform query substitution.
298−query_ :: (QueryResults r) => Connection -> Query -> IO [r]
299−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
300411 result <- exec conn que
301− finishQuery conn q result
412+ finishQueryWith parser conn q result
302413
303414-- | Perform a @SELECT@ or other SQL query that is expected to return
304415-- results. Results are streamed incrementally from the server, and
@@ -310,6 +421,12 @@ query_ conn q@(Query que) = do
310421-- This fold is /not/ strict. The stream consumer is responsible for
311422-- forcing the evaluation of its result to avoid space leaks.
312423--
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+--
313430-- Exceptions that may be thrown:
314431--
315432-- * 'FormatError': the query string could not be formatted correctly.
@@ -318,8 +435,10 @@ query_ conn q@(Query que) = do
318435-- using 'execute' instead of 'query').
319436--
320437-- * 'ResultError': result conversion failed.
321−
322−fold :: ( QueryResults row, QueryParams params )
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 )
323442 => Connection
324443 -> Query
325444 -> params
@@ -328,6 +447,20 @@ fold :: ( QueryResults row, QueryParams params )
328447 -> IO a
329448fold = foldWithOptions defaultFoldOptions
330449
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.
331464data FetchQuantity
332465 = Automatic
333466 | Fixed !Int
@@ -338,12 +471,20 @@ data FoldOptions
338471 transactionMode :: !TransactionMode
339472 }
340473
341−defaultFoldOptions = FoldOptions {
474+-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475+defaultFoldOptions :: FoldOptions
476+defaultFoldOptions = FoldOptions {
342477 fetchQuantity = Automatic,
343478 transactionMode = TransactionMode ReadCommitted ReadOnly
344479 }
345480
346−foldWithOptions :: ( QueryResults row, QueryParams params )
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 )
347488 => FoldOptions
348489 -> Connection
349490 -> Query
@@ -351,12 +492,24 @@ foldWithOptions :: ( QueryResults row, QueryParams params )
351492 -> a
352493 -> (a -> row -> IO a)
353494 -> IO a
354−foldWithOptions opts conn template qs a f = do
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
355508 q <- formatQuery conn template qs
356− doFold opts conn template (Query q) a f
509+ doFold opts parser conn template (Query q) a f
357510
358511-- | A version of 'fold' that does not perform query substitution.
359−fold_ :: (QueryResults r) =>
512+fold_ :: (FromRow r) =>
360513 Connection
361514 -> Query -- ^ Query.
362515 -> a -- ^ Initial state for result consumer.
@@ -364,26 +517,43 @@ fold_ :: (QueryResults r) =>
364517 -> IO a
365518fold_ = foldWithOptions_ defaultFoldOptions
366519
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
367528
368−foldWithOptions_ :: (QueryResults r) =>
529+foldWithOptions_ :: (FromRow r) =>
369530 FoldOptions
370531 -> Connection
371532 -> Query -- ^ Query.
372533 -> a -- ^ Initial state for result consumer.
373534 -> (a -> r -> IO a) -- ^ Result consumer.
374535 -> IO a
375−foldWithOptions_ opts conn query a f = doFold opts conn query query a f
376−
377−
378−doFold :: ( QueryResults row )
379− => FoldOptions
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
380550 -> Connection
381551 -> Query
382552 -> Query
383553 -> a
384554 -> (a -> row -> IO a)
385555 -> IO a
386−doFold FoldOptions{..} conn _template q a f = do
556+doFold FoldOptions{..} parser conn _template q a0 f = do
387557 stat <- withConnection conn PQ.transactionStatus
388558 case stat of
389559 PQ.TransIdle -> withTransactionMode transactionMode conn go
@@ -401,11 +571,17 @@ doFold FoldOptions{..} conn _template q a f = do
401571 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
402572 -- Not sure what this means.
403573 where
404− go = do
405− -- FIXME: what about name clashes with already-declared cursors?
406− _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
407− `mappend` q)
408− loop a `finally` execute_ conn "CLOSE fold"
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
409585
410586-- FIXME: choose the Automatic chunkSize more intelligently
411587-- One possibility is to use the type of the results, although this
@@ -416,151 +592,45 @@ doFold FoldOptions{..} conn _template q a f = do
416592 chunkSize = case fetchQuantity of
417593 Automatic -> 256
418594 Fixed n -> n
419− loop a = do
420− rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
421− if null rs then return a else foldM f a rs >>= loop
422595
423596-- | A version of 'fold' that does not transform a state value.
424−forEach :: (QueryParams q, QueryResults r) =>
597+forEach :: (ToRow q, FromRow r) =>
425598 Connection
426599 -> Query -- ^ Query template.
427600 -> q -- ^ Query parameters.
428601 -> (r -> IO ()) -- ^ Result consumer.
429602 -> IO ()
430−forEach conn template qs = fold conn template qs () . const
603+forEach = forEachWith fromRow
431604{-# INLINE forEach #-}
432605
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+
433617-- | A version of 'forEach' that does not perform query substitution.
434−forEach_ :: (QueryResults r) =>
618+forEach_ :: (FromRow r) =>
435619 Connection
436620 -> Query -- ^ Query template.
437621 -> (r -> IO ()) -- ^ Result consumer.
438622 -> IO ()
439−forEach_ conn template = fold_ conn template () . const
623+forEach_ = forEachWith_ fromRow
440624{-# INLINE forEach_ #-}
441625
442−forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
443−forM' lo hi m = loop hi []
444− where
445− loop !n !as
446− | n < lo = return as
447− | otherwise = do
448− a <- m n
449− loop (n-1) (a:as)
450−
451−finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
452−finishQuery conn q result = do
453− status <- PQ.resultStatus result
454− case status of
455− PQ.CommandOk -> do
456− throwIO $ QueryError "query resulted in a command response" q
457− PQ.TuplesOk -> do
458− ncols <- PQ.nfields result
459− fields <- forM' 0 (ncols-1) $ \column -> do
460− type_oid <- PQ.ftype result column
461− typename <- getTypename conn type_oid
462− return Field{..}
463− nrows <- PQ.ntuples result
464− forM' 0 (nrows-1) $ \row -> do
465− values <- forM' 0 (ncols-1) (\col -> PQ.getvalue result row col)
466− case convertResults fields values of
467− Left err -> throwIO err
468− Right a -> return a
469− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
470− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
471− _ -> do
472− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
473− statusmsg <- PQ.resStatus status
474− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
475− throwIO $ SqlError { sqlState = state
476− , sqlNativeError = fromEnum status
477− , sqlErrorMsg = B.concat [ "query: ", statusmsg
478− , ": ", errormsg ]}
479−
480−-- | Of the four isolation levels defined by the SQL standard,
481−-- these are the three levels distinguished by PostgreSQL as of version 9.0.
482−-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
483−-- for more information.
484−
485−data IsolationLevel
486− = ReadCommitted
487− | RepeatableRead
488− | Serializable
489− deriving (Show, Eq, Ord, Enum, Bounded)
490−
491−data ReadWriteMode
492− = ReadWrite
493− | ReadOnly
494− deriving (Show, Eq, Ord, Enum, Bounded)
495−
496−data TransactionMode = TransactionMode {
497− isolationLevel :: !IsolationLevel,
498− readWriteMode :: !ReadWriteMode
499− } deriving (Show, Eq, Ord)
500−
501−defaultTransactionMode :: TransactionMode
502−defaultTransactionMode = TransactionMode ReadCommitted ReadWrite
503−
504−-- | Execute an action inside a SQL transaction.
505−--
506−-- This function initiates a transaction with a \"@begin
507−-- transaction@\" statement, then executes the supplied action. If
508−-- the action succeeds, the transaction will be completed with
509−-- 'Base.commit' before this function returns.
510−--
511−-- If the action throws /any/ kind of exception (not just a
512−-- PostgreSQL-related exception), the transaction will be rolled back using
513−-- 'rollback', then the exception will be rethrown.
514−withTransaction :: Connection -> IO a -> IO a
515−withTransaction = withTransactionMode defaultTransactionMode
516−
517−-- | Execute an action inside a SQL transaction with a given isolation level.
518−withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
519−withTransactionMode mode conn act = do
520− beginMode mode conn
521− r <- act `onException` rollback conn
522− commit conn
523− return r
524−
525−-- | Rollback a transaction.
526−rollback :: Connection -> IO ()
527−rollback conn = execute_ conn "ABORT" >> return ()
528−
529−-- | Commit a transaction.
530−commit :: Connection -> IO ()
531−commit conn = execute_ conn "COMMIT" >> return ()
532−
533−-- | Begin a transaction.
534−begin :: Connection -> IO ()
535−begin = beginMode defaultTransactionMode
536−
537−-- | Begin a transaction with a given isolation level
538−beginMode :: TransactionMode -> Connection -> IO ()
539−beginMode mode conn = do
540− execute_ conn $! case mode of
541− TransactionMode ReadCommitted ReadWrite ->
542− "BEGIN"
543− TransactionMode ReadCommitted ReadOnly ->
544− "BEGIN READ ONLY"
545− TransactionMode RepeatableRead ReadWrite ->
546− "BEGIN ISOLATION LEVEL REPEATABLE READ"
547− TransactionMode RepeatableRead ReadOnly ->
548− "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"
549− TransactionMode Serializable ReadWrite ->
550− "BEGIN ISOLATION LEVEL SERIALIZABLE"
551− TransactionMode Serializable ReadOnly ->
552− "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"
553− return ()
554−
555−fmtError :: String -> Query -> [Action] -> a
556−fmtError msg q xs = throw FormatError {
557− fmtMessage = msg
558− , fmtQuery = q
559− , fmtParams = map twiddle xs
560− }
561− where twiddle (Plain b) = toByteString b
562− twiddle (Escape s) = s
563− 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+
564634
565635-- $use
566636--
@@ -588,9 +658,11 @@ fmtError msg q xs = throw FormatError {
588658-- >
589659-- > import Database.PostgreSQL.Simple
590660-- >
661+-- > hello :: IO Int
591662-- > hello = do
592−-- > conn <- connect defaultConnectInfo
593−-- > query conn "select 2 + 2"
663+-- > conn <- connectPostgreSQL ""
664+-- > [Only i] <- query_ conn "select 2 + 2"
665+-- > return i
594666--
595667-- A 'Query' value does not represent the actual query that will be
596668-- executed, but is a template for constructing the final query.
@@ -637,7 +709,7 @@ fmtError msg q xs = throw FormatError {
637709-- Automated type inference means that you will often be able to avoid
638710-- supplying explicit type signatures for the elements of a tuple.
639711-- However, sometimes the compiler will not be able to infer your
640−-- 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
641713-- parameter tuple:
642714--
643715-- > query conn "select ? + ?" (40,2)
@@ -651,15 +723,30 @@ fmtError msg q xs = throw FormatError {
651723-- The same kind of problem can arise with string literals if you have
652724-- the @OverloadedStrings@ language extension enabled. Again, just
653725-- 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])
654740
655741-- $only_param
656742--
657743-- Haskell lacks a single-element tuple type, so if you have just one
658−-- 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?
659746--
660747-- The obvious approach would appear to be something like this:
661748--
662−-- > instance (Param a) => QueryParam a where
749+-- > instance (ToField a) => ToRow a where
663750-- > ...
664751--
665752-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -670,6 +757,9 @@ fmtError msg q xs = throw FormatError {
670757--
671758-- > execute conn "insert into users (first_name) values (?)"
672759-- > ["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.
673763
674764-- $in
675765--
@@ -687,7 +777,7 @@ fmtError msg q xs = throw FormatError {
687777-- Here's an example:
688778--
689779-- > query conn "select * from users where first_name in ?" $
690−-- > In ["Anna", "Boris", "Carla"]
780+-- > Only $ In ["Anna", "Boris", "Carla"]
691781--
692782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
693783-- substituted instead, to ensure that your clause remains
@@ -715,7 +805,7 @@ fmtError msg q xs = throw FormatError {
715805-- * There must be no other \"@?@\" characters anywhere in your
716806-- template.
717807--
718−-- * There must one or more \"@?@\" in the parentheses.
808+-- * There must be one or more \"@?@\" in the parentheses.
719809--
720810-- * Extra white space is fine.
721811--
@@ -736,10 +826,26 @@ fmtError msg q xs = throw FormatError {
736826-- > insert into users (first_name,last_name) values
737827-- > ('Boris','Karloff'),('Ed','Wood')
738828
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+
739845-- $result
740846--
741847-- The 'query' and 'query_' functions return a list of values in the
742−-- 'QueryResults' typeclass. This class performs automatic extraction
848+-- 'FromRow' typeclass. This class performs automatic extraction
743849-- and type conversion of rows from a query result.
744850--
745851-- Here is a simple example of how to extract results:
@@ -770,7 +876,7 @@ fmtError msg q xs = throw FormatError {
770876--
771877-- Although SQL can accommodate @NULL@ as a value for any of these
772878-- types, Haskell cannot. If your result contains columns that may be
773−-- @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
774880-- tuple.
775881--
776882-- > (Text, Maybe Int, Int)
@@ -796,7 +902,7 @@ fmtError msg q xs = throw FormatError {
796902-- all values of the given PostgreSQL type is considered \"compatible\".
797903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
798904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
799−-- represent a @SMALLINT@, so it is considered compatble with those types.
905+-- represent a @SMALLINT@, so it is considered compatible with those types.
800906--
801907-- * A numeric compatibility check is based only on the type of a
802908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -810,25 +916,3 @@ fmtError msg q xs = throw FormatError {
810916-- UTF-8. If you use some other encoding, decoding may fail or give
811917-- wrong results. In such cases, write a @newtype@ wrapper and a
812918-- custom 'Result' instance to handle your encoding.
813−
814−getTypename :: Connection -> PQ.Oid -> IO ByteString
815−getTypename conn@Connection{..} oid =
816− case oid2builtin oid of
817− Just builtin -> return $! builtin2typname builtin
818− Nothing -> modifyMVar connectionObjects $ \oidmap -> do
819− case IntMap.lookup (oid2int oid) oidmap of
820− Just name -> return (oidmap, name)
821− Nothing -> do
822− names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
823− (Only oid)
824− name <- case names of
825− [] -> return $ throw SqlError {
826− sqlNativeError = -1,
827− sqlErrorMsg = "invalid type oid",
828− sqlState = ""
829− }
830− [Only x] -> return x
831− _ -> fail "typename query returned more than one result"
832− -- oid is a primary key, so the query should
833− -- never return more than one result
834− return (IntMap.insert (oid2int oid) name oidmap, name)