@@ -1,18 +1,14 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
1+{-# LANGUAGE BangPatterns, DeriveDataTypeable, OverloadedStrings #-}
2−{-# LANGUAGE NamedFieldPuns #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE PatternGuards #-}
5−{-# LANGUAGE RecordWildCards #-}
2+{-# LANGUAGE DoAndIfThenElse, RecordWildCards, NamedFieldPuns #-}
6−{-# LANGUAGE ViewPatterns #-}
8------------------------------------------------------------------------------
3------------------------------------------------------------------------------
10-- Module: Database.PostgreSQL.Simple
5-- Module: Database.PostgreSQL.Simple
11-- Copyright: (c) 2011 MailRank, Inc.
6-- Copyright: (c) 2011 MailRank, Inc.
12−-- (c) 2011-2012 Leon P Smith
7+-- (c) 2011 Leon P Smith
13-- License: BSD3
8-- License: BSD3
14-- Maintainer: Leon P Smith <leon@melding-monads.com>
9-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Stability: experimental
10-- Stability: experimental
11+-- Portability: portable
17-- A mid-level client library for the PostgreSQL database, aimed at ease of
13-- A mid-level client library for the PostgreSQL database, aimed at ease of
18-- use and high performance.
14-- use and high performance.
@@ -42,9 +38,6 @@ module Database.PostgreSQL.Simple
42 -- ** Modifying multiple rows at once
38 -- ** Modifying multiple rows at once
45− -- ** @RETURNING@: modifications that return results
48 -- * Extracting results
41 -- * Extracting results
49 -- $result
42 -- $result
@@ -55,35 +48,26 @@ module Database.PostgreSQL.Simple
57 -- * Types
50 -- * Types
58− Connection
52+ , Connection
63 , Binary(..)
55 , Binary(..)
64 , Only(..)
56 , Only(..)
66 -- ** Exceptions
57 -- ** Exceptions
67− , SomePostgreSqlException(..)
68 , SqlError(..)
58 , SqlError(..)
70− , FormatError(..)
59+ , FormatError(fmtMessage, fmtQuery, fmtParams)
71− , QueryError(..)
60+ , QueryError(qeMessage, qeQuery)
72− , ResultError(..)
61+ , ResultError(errSQLType, errHaskellType, errMessage)
73 -- * Connection management
62 -- * Connection management
74− , Base.connectPostgreSQL
76 , Base.connect
63 , Base.connect
77− , Base.withConnect
64+ , Base.connectPostgreSQL
78− , Base.ConnectInfo(..)
79− , Base.defaultConnectInfo
80 , Base.postgreSQLConnectionString
65 , Base.postgreSQLConnectionString
66+ , Base.defaultConnectInfo
81 -- * Queries that return results
68 -- * Queries that return results
84− -- ** Queries taking parser as argument
87 -- * Queries that stream results
71 -- * Queries that stream results
88 , FoldOptions(..)
72 , FoldOptions(..)
89 , FetchQuantity(..)
73 , FetchQuantity(..)
@@ -94,15 +78,6 @@ module Database.PostgreSQL.Simple
94 , foldWithOptions_
78 , foldWithOptions_
96 , forEach_
80 , forEach_
98− -- ** Queries that stream results taking a parser as an argument
100− , foldWithOptionsAndParser
102− , foldWithOptionsAndParser_
106 -- * Statements that do not return results
81 -- * Statements that do not return results
107 , execute
82 , execute
108 , execute_
83 , execute_
@@ -110,9 +85,18 @@ module Database.PostgreSQL.Simple
110-- , Base.insertID
85-- , Base.insertID
111 -- * Transaction handling
86 -- * Transaction handling
112 , withTransaction
87 , withTransaction
113− , withSavepoint
88+ , TransactionMode(..)
91+ , defaultTransactionMode
92+ , defaultIsolationLevel
93+ , defaultReadWriteMode
94+ , withTransactionLevel
95+ , withTransactionMode
114-- , Base.autocommit
96-- , Base.autocommit
117 , rollback
101 , rollback
118 -- * Helper functions
102 -- * Helper functions
@@ -120,27 +104,50 @@ module Database.PostgreSQL.Simple
120 , formatQuery
104 , formatQuery
123−import Data.ByteString.Builder (Builder, byteString, char8)
107+import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
108+import Blaze.ByteString.Builder.Char8 (fromChar)
124−import Control.Applicative ((<$>))
109+import Control.Applicative ((<$>), pure)
125−import Control.Exception as E
110+import Control.Concurrent.MVar
111+import Control.Exception (Exception, bracket, onException, throw, throwIO, finally)
112+import Control.Monad (foldM)
113+import Control.Monad.Fix (fix)
126−import Data.ByteString (ByteString)
114+import Data.ByteString (ByteString)
115+import Data.Char(ord)
127−import Data.Int (Int64)
116+import Data.Int (Int64)
117+import qualified Data.IntMap as IntMap
128−import Data.List (intersperse)
118+import Data.List (intersperse)
129−import Data.Monoid (mconcat)
119+import Data.Monoid (mappend, mconcat)
130−import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
120+import Data.Typeable (Typeable)
131−import Database.PostgreSQL.Simple.Cursor
132−import Database.PostgreSQL.Simple.FromField (ResultError(..))
121+import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
133−import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134−import Database.PostgreSQL.Simple.ToField (Action(..))
122+import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
135−import Database.PostgreSQL.Simple.ToRow (ToRow(..))
123+import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
124+import Database.PostgreSQL.Simple.Result (ResultError(..))
125+import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
136−import Database.PostgreSQL.Simple.Types
126+import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
137− ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
138−import Database.PostgreSQL.Simple.Internal as Base
127+import Database.PostgreSQL.Simple.Internal as Base
139−import Database.PostgreSQL.Simple.Internal.PQResultUtils
140−import Database.PostgreSQL.Simple.Transaction
141import qualified Database.PostgreSQL.LibPQ as PQ
128import qualified Database.PostgreSQL.LibPQ as PQ
129+import Text.Regex.PCRE.Light (compile, caseless, match)
142import qualified Data.ByteString.Char8 as B
130import qualified Data.ByteString.Char8 as B
132+-- | Exception thrown if a 'Query' could not be formatted correctly.
133+-- This may occur if the number of \'@?@\' characters in the query
134+-- string does not match the number of parameters provided.
135+data FormatError = FormatError {
136+ fmtMessage :: String
138+ , fmtParams :: [ByteString]
139+ } deriving (Eq, Show, Typeable)
141+instance Exception FormatError
143+-- | Exception thrown if 'query' is used to perform an @INSERT@-like
144+-- operation, or 'execute' is used to perform a @SELECT@-like operation.
145+data QueryError = QueryError {
148+ } deriving (Eq, Show, Typeable)
150+instance Exception QueryError
145-- | Format a query string.
152-- | Format a query string.
@@ -152,11 +159,11 @@ import qualified Data.ByteString.Char8 as B
153-- Throws 'FormatError' if the query string could not be formatted
160-- Throws 'FormatError' if the query string could not be formatted
154-- correctly.
161-- correctly.
155−formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
162+formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
156formatQuery conn q@(Query template) qs
163formatQuery conn q@(Query template) qs
157 | null xs && '?' `B.notElem` template = return template
164 | null xs && '?' `B.notElem` template = return template
158 | otherwise = toByteString <$> buildQuery conn q template xs
165 | otherwise = toByteString <$> buildQuery conn q template xs
159− where xs = toRow qs
166+ where xs = renderParams qs
161-- | Format a query string with a variable number of rows.
168-- | Format a query string with a variable number of rows.
@@ -171,208 +178,105 @@ formatQuery conn q@(Query template) qs
172-- Throws 'FormatError' if the query string could not be formatted
179-- Throws 'FormatError' if the query string could not be formatted
173-- correctly.
180-- correctly.
174−formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
181+formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
175formatMany _ q [] = fmtError "no rows supplied" q []
182formatMany _ q [] = fmtError "no rows supplied" q []
176formatMany conn q@(Query template) qs = do
183formatMany conn q@(Query template) qs = do
177− case parseTemplate template of
184+ case match re template [] of
178− Just (before, qbits, after) -> do
185+ Just [_,before,qbits,after] -> do
179− bs <- mapM (buildQuery conn q qbits . toRow) qs
186+ bs <- mapM (buildQuery conn q qbits . renderParams) qs
180− return . toByteString . mconcat $ byteString before :
187+ return . toByteString . mconcat $ fromByteString before :
181− intersperse (char8 ',') bs ++
188+ intersperse (fromChar ',') bs ++
182− [byteString after]
189+ [fromByteString after]
183− Nothing -> fmtError "syntax error in multi-row template" q []
190+ _ -> error "foo"
185−-- Split the input string into three pieces, @before@, @qbits@, and @after@,
186−-- following this grammar:
188−-- start: ^ before qbits after $
189−-- before: ([^?]* [^?\w])? 'VALUES' \s*
190−-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
194−-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
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
204− -- Search for the next occurrence of "VALUES"
192+ re = compile "^([^?]+\\bvalues\\s*)\
205− search bs =
193+ \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
206− case B.breakSubstring "VALUES" bs of
194+ \([^?]*)$"
207− (x, y)
195+ [caseless]
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)
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
218− -- Otherwise, we have a legitimate "VALUES" token.
220− -> parseQueryBits $ skipSpace $ B.drop 6 y
222− -- Parse '(' \s* '?' \s* . If this doesn't match
223− -- (and we don't consume a '?'), look for another "VALUES".
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.
229− | Just ('(', skipSpace -> bs1) <- B.uncons qb
230− , Just ('?', skipSpace -> bs2) <- B.uncons bs1
231− = finishQueryBits qb bs2
235− -- Parse (',' \s* '?' \s*)* ')' [^?]* .
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
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
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.
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 =
260− (s1, source') = B.splitAt (B.length source - B.length p1) source
261− (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
263− toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
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')
275− -- Based on {space} in scan.l
276− isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
278− skipSpace = B.dropWhile isSpace_ascii
197+escapeStringConn conn s = withConnection conn $ \c -> do
198+ PQ.escapeStringConn c s
281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
200buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
282−buildQuery conn q template xs =
201+buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
283− zipParams (split template) <$> mapM (buildAction conn q xs) xs
202+ where quote = inQuotes . fromByteString . maybe undefined id
284− where split s =
203+ sub (Plain b) = pure b
285− -- This part escapes double '??'s to make literal '?'s possible
204+ sub (Escape s) = quote <$> escapeStringConn conn s
286− -- in PostgreSQL queries using the JSON operators: @?@, @?|@ and @?&@
205+ sub (Many ys) = mconcat <$> mapM sub ys
287− let (h,t) = breakOnSingleQuestionMark s
291− else split (B.tail t)
206+ split s = fromByteString h : if B.null t then [] else split (B.tail t)
207+ where (h,t) = B.break (=='?') s
292− zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
208+ zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
293 zipParams [t] [] = t
209 zipParams [t] [] = t
294− zipParams _ _ = fmtError (show countSingleQs ++
210+ zipParams _ _ = fmtError (show (B.count '?' template) ++
295− " single '?' characters, but " ++
211+ " '?' characters, but " ++
296 show (length xs) ++ " parameters") q xs
212 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
303− where qms = B.splitAt 1 qmBS
304− (qmBS,nextQMBS) = B.splitAt 2 qmBS'
305− qmBS' = B.dropWhile (/= '?') bs
307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
214-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
308-- expected to return results.
215-- expected to return results.
310-- Returns the number of rows affected.
217-- Returns the number of rows affected.
312−-- Throws 'FormatError' if the query could not be formatted correctly, or
219+-- Throws 'FormatError' if the query could not be formatted correctly.
313−-- a 'SqlError' exception if the backend returns an error.
314−execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
220+execute :: (QueryParams q) => Connection -> Query -> q -> IO Int64
315execute conn template qs = do
221execute conn template qs = do
316 result <- exec conn =<< formatQuery conn template qs
222 result <- exec conn =<< formatQuery conn template qs
317 finishExecute conn template result
223 finishExecute conn template result
225+-- | A version of 'execute' that does not perform query substitution.
226+execute_ :: Connection -> Query -> IO Int64
227+execute_ conn q@(Query stmt) = do
228+ result <- exec conn stmt
229+ finishExecute conn q result
319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
231-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
320-- expected to return results.
232-- expected to return results.
322−-- Returns the number of rows affected. If the list of parameters is empty,
234+-- Returns the number of rows affected.
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.
326−-- Throws 'FormatError' if the query could not be formatted correctly, or
327−-- a 'SqlError' exception if the backend returns an error.
329−-- For example, here's a command that inserts two rows into a table
333−-- executeMany c [sql|
334−-- INSERT INTO sometable VALUES (?,?)
335−-- |] [(1, \"hello\"),(2, \"world\")]
338−-- Here's an canonical example of a multi-row update command:
340−-- @
236+-- Throws 'FormatError' if the query could not be formatted correctly.
341−-- executeMany c [sql|
344−-- FROM (VALUES (?,?)) as upd(x,y)
345−-- WHERE sometable.x = upd.x
346−-- |] [(1, \"hello\"),(2, \"world\")]
349−executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
237+executeMany :: (QueryParams q) => Connection -> Query -> [q] -> IO Int64
350executeMany _ _ [] = return 0
238executeMany _ _ [] = return 0
351executeMany conn q qs = do
239executeMany conn q qs = do
352 result <- exec conn =<< formatMany conn q qs
240 result <- exec conn =<< formatMany conn q qs
353 finishExecute conn q result
241 finishExecute conn q result
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'.
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.
366−-- Throws 'FormatError' if the query could not be formatted correctly.
367−returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
243+finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
368−returning = returningWith fromRow
244+finishExecute conn q result = do
245+ status <- PQ.resultStatus result
248+ ncols <- PQ.nfields result
250+ then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
253+ nstr <- PQ.cmdTuples result
254+ return $ case nstr of
255+ Nothing -> 0 -- is this appropriate?
256+ Just str -> toInteger str
258+ ncols <- PQ.nfields result
259+ throwIO $ QueryError ("execute resulted in " ++ show ncols ++
261+ PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
262+ PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
264+ errormsg <- maybe "" id <$> PQ.resultErrorMessage result
265+ statusmsg <- PQ.resStatus status
266+ state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
267+ throwIO $ SqlError { sqlState = state
268+ , sqlNativeError = fromEnum status
269+ , sqlErrorMsg = B.concat [ "execute: ", statusmsg
272+ toInteger str = B.foldl' delta 0 str
275+ if '0' <= c && c <= '9'
276+ then 10 * acc + fromIntegral (ord c - ord '0')
277+ else error ("finishExecute: not an int: " ++ B.unpack str)
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
377-- | Perform a @SELECT@ or other SQL query that is expected to return
281-- | Perform a @SELECT@ or other SQL query that is expected to return
378-- results. All results are retrieved and converted before this
282-- results. All results are retrieved and converted before this
@@ -389,27 +293,17 @@ returningWith parser conn q qs = do
389-- using 'execute' instead of 'query').
293-- using 'execute' instead of 'query').
391-- * 'ResultError': result conversion failed.
295-- * 'ResultError': result conversion failed.
392−--
296+query :: (QueryParams q, QueryResults r)
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
398−-- | A version of 'query' that does not perform query substitution.
399−query_ :: (FromRow r) => Connection -> Query -> IO [r]
400−query_ = queryWith_ fromRow
402−-- | A version of 'query' taking parser as argument
403−queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
297+ => Connection -> Query -> q -> IO [r]
404−queryWith parser conn template qs = do
298+query conn template qs = do
405 result <- exec conn =<< formatQuery conn template qs
299 result <- exec conn =<< formatQuery conn template qs
406− finishQueryWith parser conn template result
300+ finishQuery conn template result
408−-- | A version of 'query_' taking parser as argument
302+-- | A version of 'query' that does not perform query substitution.
409−queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
303+query_ :: (QueryResults r) => Connection -> Query -> IO [r]
410−queryWith_ parser conn q@(Query que) = do
304+query_ conn q@(Query que) = do
411 result <- exec conn que
305 result <- exec conn que
412− finishQueryWith parser conn q result
306+ finishQuery conn q result
414-- | Perform a @SELECT@ or other SQL query that is expected to return
308-- | Perform a @SELECT@ or other SQL query that is expected to return
415-- results. Results are streamed incrementally from the server, and
309-- results. Results are streamed incrementally from the server, and
@@ -421,12 +315,6 @@ queryWith_ parser conn q@(Query que) = do
421-- This fold is /not/ strict. The stream consumer is responsible for
315-- This fold is /not/ strict. The stream consumer is responsible for
422-- forcing the evaluation of its result to avoid space leaks.
316-- forcing the evaluation of its result to avoid space leaks.
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.
430-- Exceptions that may be thrown:
318-- Exceptions that may be thrown:
432-- * 'FormatError': the query string could not be formatted correctly.
320-- * 'FormatError': the query string could not be formatted correctly.
@@ -435,10 +323,8 @@ queryWith_ parser conn q@(Query que) = do
435-- using 'execute' instead of 'query').
323-- using 'execute' instead of 'query').
437-- * 'ResultError': result conversion failed.
325-- * 'ResultError': result conversion failed.
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 )
327+fold :: ( QueryResults row, QueryParams params )
442 => Connection
328 => Connection
444 -> params
330 -> params
@@ -447,20 +333,6 @@ fold :: ( FromRow row, ToRow params )
448fold = foldWithOptions defaultFoldOptions
334fold = foldWithOptions defaultFoldOptions
450−-- | A version of 'fold' taking a parser as an argument
451−foldWith :: ( ToRow params )
457− -> (a -> row -> IO a)
459−foldWith = foldWithOptionsAndParser defaultFoldOptions
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.
464data FetchQuantity
336data FetchQuantity
465 = Automatic
337 = Automatic
466 | Fixed !Int
338 | Fixed !Int
@@ -471,20 +343,12 @@ data FoldOptions
471 transactionMode :: !TransactionMode
343 transactionMode :: !TransactionMode
474−-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475−defaultFoldOptions :: FoldOptions
476defaultFoldOptions = FoldOptions {
346defaultFoldOptions = FoldOptions {
477 fetchQuantity = Automatic,
347 fetchQuantity = Automatic,
478 transactionMode = TransactionMode ReadCommitted ReadOnly
348 transactionMode = TransactionMode ReadCommitted ReadOnly
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 )
351+foldWithOptions :: ( QueryResults row, QueryParams params )
488 => FoldOptions
352 => FoldOptions
489 -> Connection
353 -> Connection
@@ -492,24 +356,12 @@ foldWithOptions :: ( FromRow row, ToRow params )
493 -> (a -> row -> IO a)
357 -> (a -> row -> IO a)
495−foldWithOptions opts = foldWithOptionsAndParser opts fromRow
359+foldWithOptions opts conn template qs a f = do
497−-- | A version of 'foldWithOptions' taking a parser as an argument
498−foldWithOptionsAndParser :: (ToRow params)
505− -> (a -> row -> IO a)
507−foldWithOptionsAndParser opts parser conn template qs a f = do
508 q <- formatQuery conn template qs
360 q <- formatQuery conn template qs
509− doFold opts parser conn template (Query q) a f
361+ doFold opts conn template (Query q) a f
511-- | A version of 'fold' that does not perform query substitution.
363-- | A version of 'fold' that does not perform query substitution.
512−fold_ :: (FromRow r) =>
364+fold_ :: (QueryResults r) =>
513 Connection
365 Connection
514 -> Query -- ^ Query.
366 -> Query -- ^ Query.
515 -> a -- ^ Initial state for result consumer.
367 -> a -- ^ Initial state for result consumer.
@@ -517,43 +369,26 @@ fold_ :: (FromRow r) =>
518fold_ = foldWithOptions_ defaultFoldOptions
370fold_ = foldWithOptions_ defaultFoldOptions
520−-- | A version of 'fold_' taking a parser as an argument
521−foldWith_ :: RowParser r
527−foldWith_ = foldWithOptionsAndParser_ defaultFoldOptions
529−foldWithOptions_ :: (FromRow r) =>
373+foldWithOptions_ :: (QueryResults r) =>
530 FoldOptions
374 FoldOptions
531 -> Connection
375 -> Connection
532 -> Query -- ^ Query.
376 -> Query -- ^ Query.
533 -> a -- ^ Initial state for result consumer.
377 -> a -- ^ Initial state for result consumer.
534 -> (a -> r -> IO a) -- ^ Result consumer.
378 -> (a -> r -> IO a) -- ^ Result consumer.
536−foldWithOptions_ opts conn query' a f = doFold opts fromRow conn query' query' a f
380+foldWithOptions_ opts conn query a f = doFold opts conn query query a f
538−-- | A version of 'foldWithOptions_' taking a parser as an argument
382+
539−foldWithOptionsAndParser_ :: FoldOptions
383+doFold :: ( QueryResults row )
540− -> RowParser r
384+ => FoldOptions
542− -> Query -- ^ Query.
543− -> a -- ^ Initial state for result consumer.
544− -> (a -> r -> IO a) -- ^ Result consumer.
546−foldWithOptionsAndParser_ opts parser conn query' a f = doFold opts parser conn query' query' a f
548−doFold :: FoldOptions
550 -> Connection
385 -> Connection
554 -> (a -> row -> IO a)
389 -> (a -> row -> IO a)
556−doFold FoldOptions{..} parser conn _template q a0 f = do
391+doFold FoldOptions{..} conn _template q a f = do
557 stat <- withConnection conn PQ.transactionStatus
392 stat <- withConnection conn PQ.transactionStatus
558 case stat of
393 case stat of
559 PQ.TransIdle -> withTransactionMode transactionMode conn go
394 PQ.TransIdle -> withTransactionMode transactionMode conn go
@@ -571,17 +406,11 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
571 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
406 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572 -- Not sure what this means.
407 -- Not sure what this means.
574− declare =
409+ go = do
575− declareCursor conn q
410+ -- FIXME: what about name clashes with already-declared cursors?
576− fetch cursor a =
411+ _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
577− foldForwardWithParser cursor parser chunkSize f a
412+ `mappend` q)
578−
413+ loop a `finally` execute_ conn "CLOSE fold"
579− go = bracket declare closeCursor $ \cursor ->
580− let loop a = fetch cursor a >>=
586-- FIXME: choose the Automatic chunkSize more intelligently
415-- FIXME: choose the Automatic chunkSize more intelligently
587-- One possibility is to use the type of the results, although this
416-- One possibility is to use the type of the results, although this
@@ -592,45 +421,166 @@ doFold FoldOptions{..} parser conn _template q a0 f = do
592 chunkSize = case fetchQuantity of
421 chunkSize = case fetchQuantity of
593 Automatic -> 256
422 Automatic -> 256
594 Fixed n -> n
423 Fixed n -> n
425+ rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
426+ if null rs then return a else foldM f a rs >>= loop
596-- | A version of 'fold' that does not transform a state value.
428-- | A version of 'fold' that does not transform a state value.
597−forEach :: (ToRow q, FromRow r) =>
429+forEach :: (QueryParams q, QueryResults r) =>
598 Connection
430 Connection
599 -> Query -- ^ Query template.
431 -> Query -- ^ Query template.
600 -> q -- ^ Query parameters.
432 -> q -- ^ Query parameters.
601 -> (r -> IO ()) -- ^ Result consumer.
433 -> (r -> IO ()) -- ^ Result consumer.
603−forEach = forEachWith fromRow
435+forEach conn template qs = fold conn template qs () . const
604{-# INLINE forEach #-}
436{-# INLINE forEach #-}
606−-- | A version of 'forEach' taking a parser as an argument
607−forEachWith :: ( ToRow q )
614−forEachWith parser conn template qs = foldWith parser conn template qs () . const
615−{-# INLINE forEachWith #-}
617-- | A version of 'forEach' that does not perform query substitution.
438-- | A version of 'forEach' that does not perform query substitution.
618−forEach_ :: (FromRow r) =>
439+forEach_ :: (QueryResults r) =>
619 Connection
440 Connection
620 -> Query -- ^ Query template.
441 -> Query -- ^ Query template.
621 -> (r -> IO ()) -- ^ Result consumer.
442 -> (r -> IO ()) -- ^ Result consumer.
623−forEach_ = forEachWith_ fromRow
444+forEach_ conn template = fold_ conn template () . const
624{-# INLINE forEach_ #-}
445{-# INLINE forEach_ #-}
626−forEachWith_ :: RowParser r
447+forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
627− -> Connection
448+forM' lo hi m = loop hi []
629− -> (r -> IO ())
450+ loop !n !as
630− -> IO ()
451+ | n < lo = return as
631−forEachWith_ parser conn template = foldWith_ parser conn template () . const
452+ | otherwise = do
632−{-# INLINE forEachWith_ #-}
453+ a <- m n
633−
454+ loop (n-1) (a:as)
456+finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
457+finishQuery conn q result = do
458+ status <- PQ.resultStatus result
461+ throwIO $ QueryError "query resulted in a command response" q
463+ ncols <- PQ.nfields result
464+ fields <- forM' 0 (ncols-1) $ \column -> do
465+ type_oid <- PQ.ftype result column
466+ typename <- getTypename conn type_oid
468+ nrows <- PQ.ntuples result
469+ forM' 0 (nrows-1) $ \row -> do
470+ values <- forM' 0 (ncols-1) (\col -> PQ.getvalue result row col)
471+ case convertResults fields values of
472+ Left err -> throwIO err
474+ PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
475+ PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
477+ errormsg <- maybe "" id <$> PQ.resultErrorMessage result
478+ statusmsg <- PQ.resStatus status
479+ state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
480+ throwIO $ SqlError { sqlState = state
481+ , sqlNativeError = fromEnum status
482+ , sqlErrorMsg = B.concat [ "query: ", statusmsg
485+-- | Of the four isolation levels defined by the SQL standard,
486+-- these are the three levels distinguished by PostgreSQL as of version 9.0.
487+-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
488+-- for more information.
494+ deriving (Show, Eq, Ord, Enum, Bounded)
499+ deriving (Show, Eq, Ord, Enum, Bounded)
501+data TransactionMode = TransactionMode {
502+ isolationLevel :: !IsolationLevel,
503+ readWriteMode :: !ReadWriteMode
504+ } deriving (Show, Eq)
506+defaultTransactionMode :: TransactionMode
507+defaultTransactionMode = TransactionMode ReadCommitted ReadWrite
509+defaultIsolationLevel :: IsolationLevel
510+defaultIsolationLevel = ReadCommitted
512+defaultReadWriteMode :: ReadWriteMode
513+defaultReadWriteMode = ReadWrite
515+-- | Execute an action inside a SQL transaction.
517+-- This function initiates a transaction with a \"@begin
518+-- transaction@\" statement, then executes the supplied action. If
519+-- the action succeeds, the transaction will be completed with
520+-- 'Base.commit' before this function returns.
522+-- If the action throws /any/ kind of exception (not just a
523+-- PostgreSQL-related exception), the transaction will be rolled back using
524+-- 'rollback', then the exception will be rethrown.
525+withTransaction :: Connection -> IO a -> IO a
526+withTransaction = withTransactionMode defaultTransactionMode
528+-- | Execute an action inside a SQL transaction with a given isolation level.
529+withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
530+withTransactionLevel lvl
531+ = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
533+-- | Execute an action inside a SQL transaction with a given transaction mode.
534+withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
535+withTransactionMode mode conn act = do
537+ r <- act `onException` rollback conn
541+-- | Rollback a transaction.
542+rollback :: Connection -> IO ()
543+rollback conn = execute_ conn "ABORT" >> return ()
545+-- | Commit a transaction.
546+commit :: Connection -> IO ()
547+commit conn = execute_ conn "COMMIT" >> return ()
549+-- | Begin a transaction.
550+begin :: Connection -> IO ()
551+begin = beginMode defaultTransactionMode
553+-- | Begin a transaction with a given isolation level
554+beginLevel :: IsolationLevel -> Connection -> IO ()
555+beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
557+-- | Begin a transaction with a given transaction mode
558+beginMode :: TransactionMode -> Connection -> IO ()
559+beginMode mode conn = do
560+ execute_ conn $! case mode of
561+ TransactionMode ReadCommitted ReadWrite ->
563+ TransactionMode ReadCommitted ReadOnly ->
565+ TransactionMode RepeatableRead ReadWrite ->
566+ "BEGIN ISOLATION LEVEL REPEATABLE READ"
567+ TransactionMode RepeatableRead ReadOnly ->
568+ "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"
569+ TransactionMode Serializable ReadWrite ->
570+ "BEGIN ISOLATION LEVEL SERIALIZABLE"
571+ TransactionMode Serializable ReadOnly ->
572+ "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"
575+fmtError :: String -> Query -> [Action] -> a
576+fmtError msg q xs = throw FormatError {
579+ , fmtParams = map twiddle xs
581+ where twiddle (Plain b) = toByteString b
582+ twiddle (Escape s) = s
583+ twiddle (Many ys) = B.concat (map twiddle ys)
@@ -658,11 +608,9 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
659-- > import Database.PostgreSQL.Simple
609-- > import Database.PostgreSQL.Simple
662-- > hello = do
611-- > hello = do
663−-- > conn <- connectPostgreSQL ""
612+-- > conn <- connect defaultConnectInfo
664−-- > [Only i] <- query_ conn "select 2 + 2"
613+-- > query conn "select 2 + 2"
667-- A 'Query' value does not represent the actual query that will be
615-- A 'Query' value does not represent the actual query that will be
668-- executed, but is a template for constructing the final query.
616-- executed, but is a template for constructing the final query.
@@ -709,7 +657,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
709-- Automated type inference means that you will often be able to avoid
657-- Automated type inference means that you will often be able to avoid
710-- supplying explicit type signatures for the elements of a tuple.
658-- supplying explicit type signatures for the elements of a tuple.
711-- However, sometimes the compiler will not be able to infer your
659-- However, sometimes the compiler will not be able to infer your
712−-- types. Consider a case where you write a numeric literal in a
660+-- types. Consider a care where you write a numeric literal in a
713-- parameter tuple:
661-- parameter tuple:
715-- > query conn "select ? + ?" (40,2)
663-- > query conn "select ? + ?" (40,2)
@@ -723,30 +671,15 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
723-- The same kind of problem can arise with string literals if you have
671-- The same kind of problem can arise with string literals if you have
724-- the @OverloadedStrings@ language extension enabled. Again, just
672-- the @OverloadedStrings@ language extension enabled. Again, just
725-- use an explicit type signature if this happens.
673-- use an explicit type signature if this happens.
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:
731−-- > print =<< query_ conn "select 2 + 2"
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:
738−-- > xs <- query_ conn "select 2 + 2"
739−-- > print (xs :: [Only Int])
741-- $only_param
675-- $only_param
743-- Haskell lacks a single-element tuple type, so if you have just one
677-- Haskell lacks a single-element tuple type, so if you have just one
744−-- value you want substituted into a query or a single-column result,
678+-- value you want substituted into a query, what should you do?
745−-- what should you do?
747-- The obvious approach would appear to be something like this:
680-- The obvious approach would appear to be something like this:
749−-- > instance (ToField a) => ToRow a where
682+-- > instance (Param a) => QueryParam a where
752-- Unfortunately, this wreaks havoc with type inference, so we take a
685-- Unfortunately, this wreaks havoc with type inference, so we take a
@@ -757,9 +690,6 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
758-- > execute conn "insert into users (first_name) values (?)"
691-- > execute conn "insert into users (first_name) values (?)"
759-- > ["Nuala"]
692-- > ["Nuala"]
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.
@@ -777,7 +707,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
777-- Here's an example:
707-- Here's an example:
779-- > query conn "select * from users where first_name in ?" $
709-- > query conn "select * from users where first_name in ?" $
780−-- > Only $ In ["Anna", "Boris", "Carla"]
710+-- > In ["Anna", "Boris", "Carla"]
782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
712-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
783-- substituted instead, to ensure that your clause remains
713-- substituted instead, to ensure that your clause remains
@@ -805,7 +735,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
805-- * There must be no other \"@?@\" characters anywhere in your
735-- * There must be no other \"@?@\" characters anywhere in your
806-- template.
736-- template.
808−-- * There must be one or more \"@?@\" in the parentheses.
738+-- * There must one or more \"@?@\" in the parentheses.
810-- * Extra white space is fine.
740-- * Extra white space is fine.
@@ -826,26 +756,10 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
826-- > insert into users (first_name,last_name) values
756-- > insert into users (first_name,last_name) values
827-- > ('Boris','Karloff'),('Ed','Wood')
757-- > ('Boris','Karloff'),('Ed','Wood')
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'.
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.
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")]
845-- $result
759-- $result
847-- The 'query' and 'query_' functions return a list of values in the
761-- The 'query' and 'query_' functions return a list of values in the
848−-- 'FromRow' typeclass. This class performs automatic extraction
762+-- 'QueryResults' typeclass. This class performs automatic extraction
849-- and type conversion of rows from a query result.
763-- and type conversion of rows from a query result.
851-- Here is a simple example of how to extract results:
765-- Here is a simple example of how to extract results:
@@ -876,7 +790,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
877-- Although SQL can accommodate @NULL@ as a value for any of these
791-- Although SQL can accommodate @NULL@ as a value for any of these
878-- types, Haskell cannot. If your result contains columns that may be
792-- types, Haskell cannot. If your result contains columns that may be
879−-- @NULL@, be sure that you use 'Maybe' in those positions of your
793+-- @NULL@, be sure that you use 'Maybe' in those positions of of your
882-- > (Text, Maybe Int, Int)
796-- > (Text, Maybe Int, Int)
@@ -902,7 +816,7 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
902-- all values of the given PostgreSQL type is considered \"compatible\".
816-- all values of the given PostgreSQL type is considered \"compatible\".
903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
817-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
818-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
905−-- represent a @SMALLINT@, so it is considered compatible with those types.
819+-- represent a @SMALLINT@, so it is considered compatble with those types.
907-- * A numeric compatibility check is based only on the type of a
821-- * A numeric compatibility check is based only on the type of a
908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
822-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
@@ -916,3 +830,25 @@ forEachWith_ parser conn template = foldWith_ parser conn template () . const
916-- UTF-8. If you use some other encoding, decoding may fail or give
830-- UTF-8. If you use some other encoding, decoding may fail or give
917-- wrong results. In such cases, write a @newtype@ wrapper and a
831-- wrong results. In such cases, write a @newtype@ wrapper and a
918-- custom 'Result' instance to handle your encoding.
832-- custom 'Result' instance to handle your encoding.
834+getTypename :: Connection -> PQ.Oid -> IO ByteString
835+getTypename conn@Connection{..} oid =
836+ case oid2builtin oid of
837+ Just builtin -> return $! builtin2typname builtin
838+ Nothing -> modifyMVar connectionObjects $ \oidmap -> do
839+ case IntMap.lookup (oid2int oid) oidmap of
840+ Just name -> return (oidmap, name)
842+ names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
844+ name <- case names of
845+ [] -> return $ throw SqlError {
846+ sqlNativeError = -1,
847+ sqlErrorMsg = "invalid type oid",
850+ [Only x] -> return x
851+ _ -> fail "typename query returned more than one result"
852+ -- oid is a primary key, so the query should
853+ -- never return more than one result
854+ return (IntMap.insert (oid2int oid) name oidmap, name)