@@ -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,18 +110,9 @@ module Database.PostgreSQL.Simple
85110-- , Base.insertID
86111 -- * Transaction handling
87112 , withTransaction
88− , TransactionMode(..)
89− , IsolationLevel(..)
90− , ReadWriteMode(..)
91− , defaultTransactionMode
92− , defaultIsolationLevel
93− , defaultReadWriteMode
94− , withTransactionLevel
95− , withTransactionMode
113+ , withSavepoint
96114-- , Base.autocommit
97115 , begin
98− , beginLevel
99− , beginMode
100116 , commit
101117 , rollback
102118 -- * Helper functions
@@ -104,51 +120,27 @@ module Database.PostgreSQL.Simple
104120 , formatQuery
105121 ) where
106122
107−import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
108−import Blaze.ByteString.Builder.Char8 (fromChar)
109−import Control.Applicative ((<$>), pure)
110−import Control.Concurrent.MVar
111−import Control.Exception (Exception, onException, throw, throwIO, finally)
112−import Control.Monad (foldM)
113−import Control.Monad.Fix (fix)
114−import Data.ByteString (ByteString)
115−import Data.Char(ord)
116−import Data.Int (Int64)
117−import qualified Data.IntMap as IntMap
118−import Data.List (intersperse)
119−import Data.Monoid (mappend, mconcat)
120−import Data.Typeable (Typeable)
121−import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
122−import Database.PostgreSQL.Simple.Compat (mask)
123−import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
124−import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
125−import Database.PostgreSQL.Simple.Result (ResultError(..))
126−import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
127−import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
128−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
129141import qualified Database.PostgreSQL.LibPQ as PQ
130−import Text.Regex.PCRE.Light (compile, caseless, match)
131142import qualified Data.ByteString.Char8 as B
132143
133−-- | Exception thrown if a 'Query' could not be formatted correctly.
134−-- This may occur if the number of \'@?@\' characters in the query
135−-- string does not match the number of parameters provided.
136−data FormatError = FormatError {
137− fmtMessage :: String
138− , fmtQuery :: Query
139− , fmtParams :: [ByteString]
140− } deriving (Eq, Show, Typeable)
141−
142−instance Exception FormatError
143−
144−-- | Exception thrown if 'query' is used to perform an @INSERT@-like
145−-- operation, or 'execute' is used to perform a @SELECT@-like operation.
146−data QueryError = QueryError {
147− qeMessage :: String
148− , qeQuery :: Query
149− } deriving (Eq, Show, Typeable)
150−
151−instance Exception QueryError
152144
153145-- | Format a query string.
154146--
@@ -160,11 +152,11 @@ instance Exception QueryError
160152--
161153-- Throws 'FormatError' if the query string could not be formatted
162154-- correctly.
163−formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
155+formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
164156formatQuery conn q@(Query template) qs
165157 | null xs && '?' `B.notElem` template = return template
166158 | otherwise = toByteString <$> buildQuery conn q template xs
167− where xs = renderParams qs
159+ where xs = toRow qs
168160
169161-- | Format a query string with a variable number of rows.
170162--
@@ -179,105 +171,208 @@ formatQuery conn q@(Query template) qs
179171--
180172-- Throws 'FormatError' if the query string could not be formatted
181173-- correctly.
182−formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
174+formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
183175formatMany _ q [] = fmtError "no rows supplied" q []
184176formatMany conn q@(Query template) qs = do
185− case match re template [] of
186− Just [_,before,qbits,after] -> do
187− bs <- mapM (buildQuery conn q qbits . renderParams) qs
188− return . toByteString . mconcat $ fromByteString before :
189− intersperse (fromChar ',') bs ++
190− [fromByteString after]
191− _ -> 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
192203 where
193− re = compile "^([^?]+\\bvalues\\s*)\
194− \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
195− \([^?]*)$"
196− [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
197279
198−escapeStringConn conn s = withConnection conn $ \c -> do
199− PQ.escapeStringConn c s
200280
201281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
202−buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
203− where quote = inQuotes . fromByteString . maybe undefined id
204− sub (Plain b) = pure b
205− sub (Escape s) = quote <$> escapeStringConn conn s
206− sub (Many ys) = mconcat <$> mapM sub ys
207− split s = fromByteString h : if B.null t then [] else split (B.tail t)
208− where (h,t) = B.break (=='?') s
209− 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
210293 zipParams [t] [] = t
211− zipParams _ _ = fmtError (show (B.count '?' template) ++
212− " '?' characters, but " ++
294+ zipParams _ _ = fmtError (show countSingleQs ++
295+ " single '?' characters, but " ++
213296 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
214306
215307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
216308-- expected to return results.
217309--
218310-- Returns the number of rows affected.
219311--
220−-- Throws 'FormatError' if the query could not be formatted correctly.
221−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
222315execute conn template qs = do
223316 result <- exec conn =<< formatQuery conn template qs
224317 finishExecute conn template result
225318
226−-- | A version of 'execute' that does not perform query substitution.
227−execute_ :: Connection -> Query -> IO Int64
228−execute_ conn q@(Query stmt) = do
229− result <- exec conn stmt
230− finishExecute conn q result
231−
232319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
233320-- expected to return results.
234321--
235−-- 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.
236325--
237−-- Throws 'FormatError' if the query could not be formatted correctly.
238−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
239350executeMany _ _ [] = return 0
240351executeMany conn q qs = do
241352 result <- exec conn =<< formatMany conn q qs
242353 finishExecute conn q result
243354
244−finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
245−finishExecute conn q result = do
246− status <- PQ.resultStatus result
247− case status of
248− PQ.CommandOk -> do
249− ncols <- PQ.nfields result
250− if ncols /= 0
251− then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
252− "-column result") q
253− else do
254− nstr <- PQ.cmdTuples result
255− return $ case nstr of
256− Nothing -> 0 -- is this appropriate?
257− Just str -> toInteger str
258− PQ.TuplesOk -> do
259− ncols <- PQ.nfields result
260− throwIO $ QueryError ("execute resulted in " ++ show ncols ++
261− "-column result") q
262− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
263− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
264− _ -> do
265− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
266− statusmsg <- PQ.resStatus status
267− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
268− throwIO $ SqlError { sqlState = state
269− , sqlNativeError = fromEnum status
270− , sqlErrorMsg = B.concat [ "execute: ", statusmsg
271− , ": ", errormsg ]}
272− where
273− toInteger str = B.foldl' delta 0 str
274− where
275− delta acc c =
276− if '0' <= c && c <= '9'
277− then 10 * acc + fromIntegral (ord c - ord '0')
278− else error ("finishExecute: not an int: " ++ B.unpack str)
279−
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
280369
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
281376
282377-- | Perform a @SELECT@ or other SQL query that is expected to return
283378-- results. All results are retrieved and converted before this
@@ -294,17 +389,27 @@ finishExecute conn q result = do
294389-- using 'execute' instead of 'query').
295390--
296391-- * 'ResultError': result conversion failed.
297−query :: (QueryParams q, QueryResults r)
298− => Connection -> Query -> q -> IO [r]
299−query conn template qs = do
300− result <- exec conn =<< formatQuery conn template qs
301− 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
302397
303398-- | A version of 'query' that does not perform query substitution.
304−query_ :: (QueryResults r) => Connection -> Query -> IO [r]
305−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
306411 result <- exec conn que
307− finishQuery conn q result
412+ finishQueryWith parser conn q result
308413
309414-- | Perform a @SELECT@ or other SQL query that is expected to return
310415-- results. Results are streamed incrementally from the server, and
@@ -316,6 +421,12 @@ query_ conn q@(Query que) = do
316421-- This fold is /not/ strict. The stream consumer is responsible for
317422-- forcing the evaluation of its result to avoid space leaks.
318423--
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+--
319430-- Exceptions that may be thrown:
320431--
321432-- * 'FormatError': the query string could not be formatted correctly.
@@ -324,8 +435,10 @@ query_ conn q@(Query que) = do
324435-- using 'execute' instead of 'query').
325436--
326437-- * 'ResultError': result conversion failed.
327−
328−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 )
329442 => Connection
330443 -> Query
331444 -> params
@@ -334,6 +447,20 @@ fold :: ( QueryResults row, QueryParams params )
334447 -> IO a
335448fold = foldWithOptions defaultFoldOptions
336449
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.
337464data FetchQuantity
338465 = Automatic
339466 | Fixed !Int
@@ -344,12 +471,20 @@ data FoldOptions
344471 transactionMode :: !TransactionMode
345472 }
346473
474+-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475+defaultFoldOptions :: FoldOptions
347476defaultFoldOptions = FoldOptions {
348477 fetchQuantity = Automatic,
349478 transactionMode = TransactionMode ReadCommitted ReadOnly
350479 }
351480
352−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 )
353488 => FoldOptions
354489 -> Connection
355490 -> Query
@@ -357,12 +492,24 @@ foldWithOptions :: ( QueryResults row, QueryParams params )
357492 -> a
358493 -> (a -> row -> IO a)
359494 -> IO a
360−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
361508 q <- formatQuery conn template qs
362− doFold opts conn template (Query q) a f
509+ doFold opts parser conn template (Query q) a f
363510
364511-- | A version of 'fold' that does not perform query substitution.
365−fold_ :: (QueryResults r) =>
512+fold_ :: (FromRow r) =>
366513 Connection
367514 -> Query -- ^ Query.
368515 -> a -- ^ Initial state for result consumer.
@@ -370,26 +517,43 @@ fold_ :: (QueryResults r) =>
370517 -> IO a
371518fold_ = foldWithOptions_ defaultFoldOptions
372519
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
373528
374−foldWithOptions_ :: (QueryResults r) =>
529+foldWithOptions_ :: (FromRow r) =>
375530 FoldOptions
376531 -> Connection
377532 -> Query -- ^ Query.
378533 -> a -- ^ Initial state for result consumer.
379534 -> (a -> r -> IO a) -- ^ Result consumer.
380535 -> IO a
381−foldWithOptions_ opts conn query a f = doFold opts conn query query a f
382−
383−
384−doFold :: ( QueryResults row )
385− => 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
386550 -> Connection
387551 -> Query
388552 -> Query
389553 -> a
390554 -> (a -> row -> IO a)
391555 -> IO a
392−doFold FoldOptions{..} conn _template q a f = do
556+doFold FoldOptions{..} parser conn _template q a0 f = do
393557 stat <- withConnection conn PQ.transactionStatus
394558 case stat of
395559 PQ.TransIdle -> withTransactionMode transactionMode conn go
@@ -407,11 +571,17 @@ doFold FoldOptions{..} conn _template q a f = do
407571 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
408572 -- Not sure what this means.
409573 where
410− go = do
411− -- FIXME: what about name clashes with already-declared cursors?
412− _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
413− `mappend` q)
414− 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
415585
416586-- FIXME: choose the Automatic chunkSize more intelligently
417587-- One possibility is to use the type of the results, although this
@@ -422,167 +592,45 @@ doFold FoldOptions{..} conn _template q a f = do
422592 chunkSize = case fetchQuantity of
423593 Automatic -> 256
424594 Fixed n -> n
425− loop a = do
426− rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
427− if null rs then return a else foldM f a rs >>= loop
428595
429596-- | A version of 'fold' that does not transform a state value.
430−forEach :: (QueryParams q, QueryResults r) =>
597+forEach :: (ToRow q, FromRow r) =>
431598 Connection
432599 -> Query -- ^ Query template.
433600 -> q -- ^ Query parameters.
434601 -> (r -> IO ()) -- ^ Result consumer.
435602 -> IO ()
436−forEach conn template qs = fold conn template qs () . const
603+forEach = forEachWith fromRow
437604{-# INLINE forEach #-}
438605
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+
439617-- | A version of 'forEach' that does not perform query substitution.
440−forEach_ :: (QueryResults r) =>
618+forEach_ :: (FromRow r) =>
441619 Connection
442620 -> Query -- ^ Query template.
443621 -> (r -> IO ()) -- ^ Result consumer.
444622 -> IO ()
445−forEach_ conn template = fold_ conn template () . const
623+forEach_ = forEachWith_ fromRow
446624{-# INLINE forEach_ #-}
447625
448−forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
449−forM' lo hi m = loop hi []
450− where
451− loop !n !as
452− | n < lo = return as
453− | otherwise = do
454− a <- m n
455− loop (n-1) (a:as)
456−
457−finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
458−finishQuery conn q result = do
459− status <- PQ.resultStatus result
460− case status of
461− PQ.CommandOk -> do
462− throwIO $ QueryError "query resulted in a command response" q
463− PQ.TuplesOk -> do
464− ncols <- PQ.nfields result
465− fields <- forM' 0 (ncols-1) $ \column -> do
466− type_oid <- PQ.ftype result column
467− typename <- getTypename conn type_oid
468− return Field{..}
469− nrows <- PQ.ntuples result
470− forM' 0 (nrows-1) $ \row -> do
471− values <- forM' 0 (ncols-1) (\col -> PQ.getvalue result row col)
472− case convertResults fields values of
473− Left err -> throwIO err
474− Right a -> return a
475− PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
476− PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
477− _ -> do
478− errormsg <- maybe "" id <$> PQ.resultErrorMessage result
479− statusmsg <- PQ.resStatus status
480− state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
481− throwIO $ SqlError { sqlState = state
482− , sqlNativeError = fromEnum status
483− , sqlErrorMsg = B.concat [ "query: ", statusmsg
484− , ": ", errormsg ]}
485−
486−-- | Of the four isolation levels defined by the SQL standard,
487−-- these are the three levels distinguished by PostgreSQL as of version 9.0.
488−-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
489−-- for more information.
490−
491−data IsolationLevel
492− = ReadCommitted
493− | RepeatableRead
494− | Serializable
495− deriving (Show, Eq, Ord, Enum, Bounded)
496−
497−data ReadWriteMode
498− = ReadWrite
499− | ReadOnly
500− deriving (Show, Eq, Ord, Enum, Bounded)
501−
502−data TransactionMode = TransactionMode {
503− isolationLevel :: !IsolationLevel,
504− readWriteMode :: !ReadWriteMode
505− } deriving (Show, Eq)
506−
507−defaultTransactionMode :: TransactionMode
508−defaultTransactionMode = TransactionMode ReadCommitted ReadWrite
509−
510−defaultIsolationLevel :: IsolationLevel
511−defaultIsolationLevel = ReadCommitted
512−
513−defaultReadWriteMode :: ReadWriteMode
514−defaultReadWriteMode = ReadWrite
515−
516−-- | Execute an action inside a SQL transaction.
517−--
518−-- This function initiates a transaction with a \"@begin
519−-- transaction@\" statement, then executes the supplied action. If
520−-- the action succeeds, the transaction will be completed with
521−-- 'Base.commit' before this function returns.
522−--
523−-- If the action throws /any/ kind of exception (not just a
524−-- PostgreSQL-related exception), the transaction will be rolled back using
525−-- 'rollback', then the exception will be rethrown.
526−withTransaction :: Connection -> IO a -> IO a
527−withTransaction = withTransactionMode defaultTransactionMode
528−
529−-- | Execute an action inside a SQL transaction with a given isolation level.
530−withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
531−withTransactionLevel lvl
532− = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
533−
534−-- | Execute an action inside a SQL transaction with a given transaction mode.
535−withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
536−withTransactionMode mode conn act =
537− mask $ \restore -> do
538− beginMode mode conn
539− r <- restore act `onException` rollback conn
540− commit conn
541− return r
542−
543−-- | Rollback a transaction.
544−rollback :: Connection -> IO ()
545−rollback conn = execute_ conn "ABORT" >> return ()
546−
547−-- | Commit a transaction.
548−commit :: Connection -> IO ()
549−commit conn = execute_ conn "COMMIT" >> return ()
550−
551−-- | Begin a transaction.
552−begin :: Connection -> IO ()
553−begin = beginMode defaultTransactionMode
554−
555−-- | Begin a transaction with a given isolation level
556−beginLevel :: IsolationLevel -> Connection -> IO ()
557−beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
558−
559−-- | Begin a transaction with a given transaction mode
560−beginMode :: TransactionMode -> Connection -> IO ()
561−beginMode mode conn = do
562− execute_ conn $! case mode of
563− TransactionMode ReadCommitted ReadWrite ->
564− "BEGIN"
565− TransactionMode ReadCommitted ReadOnly ->
566− "BEGIN READ ONLY"
567− TransactionMode RepeatableRead ReadWrite ->
568− "BEGIN ISOLATION LEVEL REPEATABLE READ"
569− TransactionMode RepeatableRead ReadOnly ->
570− "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"
571− TransactionMode Serializable ReadWrite ->
572− "BEGIN ISOLATION LEVEL SERIALIZABLE"
573− TransactionMode Serializable ReadOnly ->
574− "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"
575− return ()
576−
577−fmtError :: String -> Query -> [Action] -> a
578−fmtError msg q xs = throw FormatError {
579− fmtMessage = msg
580− , fmtQuery = q
581− , fmtParams = map twiddle xs
582− }
583− where twiddle (Plain b) = toByteString b
584− twiddle (Escape s) = s
585− 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+
586634
587635-- $use
588636--
@@ -610,9 +658,11 @@ fmtError msg q xs = throw FormatError {
610658-- >
611659-- > import Database.PostgreSQL.Simple
612660-- >
661+-- > hello :: IO Int
613662-- > hello = do
614−-- > conn <- connect defaultConnectInfo
615−-- > query conn "select 2 + 2"
663+-- > conn <- connectPostgreSQL ""
664+-- > [Only i] <- query_ conn "select 2 + 2"
665+-- > return i
616666--
617667-- A 'Query' value does not represent the actual query that will be
618668-- executed, but is a template for constructing the final query.
@@ -659,7 +709,7 @@ fmtError msg q xs = throw FormatError {
659709-- Automated type inference means that you will often be able to avoid
660710-- supplying explicit type signatures for the elements of a tuple.
661711-- However, sometimes the compiler will not be able to infer your
662−-- 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
663713-- parameter tuple:
664714--
665715-- > query conn "select ? + ?" (40,2)
@@ -673,15 +723,30 @@ fmtError msg q xs = throw FormatError {
673723-- The same kind of problem can arise with string literals if you have
674724-- the @OverloadedStrings@ language extension enabled. Again, just
675725-- 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])
676740
677741-- $only_param
678742--
679743-- Haskell lacks a single-element tuple type, so if you have just one
680−-- 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?
681746--
682747-- The obvious approach would appear to be something like this:
683748--
684−-- > instance (Param a) => QueryParam a where
749+-- > instance (ToField a) => ToRow a where
685750-- > ...
686751--
687752-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -692,6 +757,9 @@ fmtError msg q xs = throw FormatError {
692757--
693758-- > execute conn "insert into users (first_name) values (?)"
694759-- > ["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.
695763
696764-- $in
697765--
@@ -709,7 +777,7 @@ fmtError msg q xs = throw FormatError {
709777-- Here's an example:
710778--
711779-- > query conn "select * from users where first_name in ?" $
712−-- > In ["Anna", "Boris", "Carla"]
780+-- > Only $ In ["Anna", "Boris", "Carla"]
713781--
714782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
715783-- substituted instead, to ensure that your clause remains
@@ -737,7 +805,7 @@ fmtError msg q xs = throw FormatError {
737805-- * There must be no other \"@?@\" characters anywhere in your
738806-- template.
739807--
740−-- * There must one or more \"@?@\" in the parentheses.
808+-- * There must be one or more \"@?@\" in the parentheses.
741809--
742810-- * Extra white space is fine.
743811--
@@ -758,10 +826,26 @@ fmtError msg q xs = throw FormatError {
758826-- > insert into users (first_name,last_name) values
759827-- > ('Boris','Karloff'),('Ed','Wood')
760828
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+
761845-- $result
762846--
763847-- The 'query' and 'query_' functions return a list of values in the
764−-- 'QueryResults' typeclass. This class performs automatic extraction
848+-- 'FromRow' typeclass. This class performs automatic extraction
765849-- and type conversion of rows from a query result.
766850--
767851-- Here is a simple example of how to extract results:
@@ -792,7 +876,7 @@ fmtError msg q xs = throw FormatError {
792876--
793877-- Although SQL can accommodate @NULL@ as a value for any of these
794878-- types, Haskell cannot. If your result contains columns that may be
795−-- @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
796880-- tuple.
797881--
798882-- > (Text, Maybe Int, Int)
@@ -818,7 +902,7 @@ fmtError msg q xs = throw FormatError {
818902-- all values of the given PostgreSQL type is considered \"compatible\".
819903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
820904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
821−-- represent a @SMALLINT@, so it is considered compatble with those types.
905+-- represent a @SMALLINT@, so it is considered compatible with those types.
822906--
823907-- * A numeric compatibility check is based only on the type of a
824908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -832,25 +916,3 @@ fmtError msg q xs = throw FormatError {
832916-- UTF-8. If you use some other encoding, decoding may fail or give
833917-- wrong results. In such cases, write a @newtype@ wrapper and a
834918-- custom 'Result' instance to handle your encoding.
835−
836−getTypename :: Connection -> PQ.Oid -> IO ByteString
837−getTypename conn@Connection{..} oid =
838− case oid2builtin oid of
839− Just builtin -> return $! builtin2typname builtin
840− Nothing -> modifyMVar connectionObjects $ \oidmap -> do
841− case IntMap.lookup (oid2int oid) oidmap of
842− Just name -> return (oidmap, name)
843− Nothing -> do
844− names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
845− (Only oid)
846− name <- case names of
847− [] -> return $ throw SqlError {
848− sqlNativeError = -1,
849− sqlErrorMsg = "invalid type oid",
850− sqlState = ""
851− }
852− [Only x] -> return x
853− _ -> fail "typename query returned more than one result"
854− -- oid is a primary key, so the query should
855− -- never return more than one result
856− return (IntMap.insert (oid2int oid) name oidmap, name)