git.iko.soy/typeable/postgresql-simple
on 0ffbbce help sign in
955 lines 36 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2{-# LANGUAGE NamedFieldPuns #-}
3{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE PatternGuards #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE ViewPatterns #-}
8------------------------------------------------------------------------------
9-- |
10-- Module: Database.PostgreSQL.Simple
11-- Copyright: (c) 2011 MailRank, Inc.
12-- (c) 2011-2012 Leon P Smith
13-- License: BSD3
14-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Stability: experimental
16-- Portability: portable
17--
18-- A mid-level client library for the PostgreSQL database, aimed at ease of
19-- use and high performance.
20--
21------------------------------------------------------------------------------
23module Database.PostgreSQL.Simple
24 (
25 -- * Writing queries
26 -- $use
28 -- ** The Query type
29 -- $querytype
31 -- ** Parameter substitution
32 -- $subst
34 -- *** Type inference
35 -- $inference
37 -- ** Substituting a single parameter
38 -- $only_param
40 -- ** Representing a list of values
41 -- $in
43 -- ** Modifying multiple rows at once
44 -- $many
46 -- * Extracting results
47 -- $result
49 -- ** Handling null values
50 -- $null
52 -- ** Type conversions
53 -- $types
55 -- * Types
56 Base.ConnectInfo(..)
57 , Connection
58 , Query
59 , ToRow
60 , FromRow
61 , In(..)
62 , Binary(..)
63 , Only(..)
64 , (:.)(..)
65 -- ** Exceptions
66 , SqlError(..)
67 , FormatError(fmtMessage, fmtQuery, fmtParams)
68 , QueryError(qeMessage, qeQuery)
69 , ResultError(errSQLType, errHaskellType, errMessage)
70 -- * Connection management
71 , Base.connect
72 , Base.connectPostgreSQL
73 , Base.postgreSQLConnectionString
74 , Base.defaultConnectInfo
75 , Base.close
76 -- * Queries that return results
77 , query
78 , query_
79 -- * Queries that stream results
80 , FoldOptions(..)
81 , FetchQuantity(..)
82 , defaultFoldOptions
83 , fold
84 , foldWithOptions
85 , fold_
86 , foldWithOptions_
87 , forEach
88 , forEach_
89 -- * Statements that do not return results
90 , execute
91 , execute_
92 , executeMany
93-- , Base.insertID
94 -- * Transaction handling
95 , withTransaction
96 , TransactionMode(..)
97 , IsolationLevel(..)
98 , ReadWriteMode(..)
99 , defaultTransactionMode
100 , defaultIsolationLevel
101 , defaultReadWriteMode
102 , withTransactionLevel
103 , withTransactionMode
104-- , Base.autocommit
105 , begin
106 , beginLevel
107 , beginMode
108 , commit
109 , rollback
110 -- * Helper functions
111 , formatMany
112 , formatQuery
113 ) where
115import Blaze.ByteString.Builder
116 ( Builder, fromByteString, toByteString )
117import Blaze.ByteString.Builder.Char8 (fromChar)
118import Control.Applicative ((<$>), pure)
119import Control.Concurrent.MVar
120import Control.Exception
121 ( Exception, onException, throw, throwIO, finally )
122import Control.Monad (foldM)
123import Data.ByteString (ByteString)
124import Data.Int (Int64)
125import qualified Data.IntMap as IntMap
126import Data.List (intersperse)
127import Data.Monoid (mappend, mconcat)
128import Data.Typeable (Typeable)
129import Database.PostgreSQL.Simple.BuiltinTypes
130 ( oid2builtin, builtin2typname )
131import Database.PostgreSQL.Simple.Compat ( mask )
132import Database.PostgreSQL.Simple.FromField (ResultError(..))
133import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134import Database.PostgreSQL.Simple.Ok
135import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
136import Database.PostgreSQL.Simple.ToRow (ToRow(..))
137import Database.PostgreSQL.Simple.Types
138 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
139import Database.PostgreSQL.Simple.Internal as Base
140import qualified Database.PostgreSQL.LibPQ as PQ
141import qualified Data.ByteString.Char8 as B
142import qualified Data.Text as T
143import qualified Data.Text.Encoding as TE
144import qualified Data.Vector as V
145import Control.Monad.Trans.Reader
146import Control.Monad.Trans.State.Strict
148-- | Exception thrown if a 'Query' could not be formatted correctly.
149-- This may occur if the number of \'@?@\' characters in the query
150-- string does not match the number of parameters provided.
151data FormatError = FormatError {
152 fmtMessage :: String
153 , fmtQuery :: Query
154 , fmtParams :: [ByteString]
155 } deriving (Eq, Show, Typeable)
157instance Exception FormatError
159-- | Format a query string.
160--
161-- This function is exposed to help with debugging and logging. Do not
162-- use it to prepare queries for execution.
163--
164-- String parameters are escaped according to the character set in use
165-- on the 'Connection'.
166--
167-- Throws 'FormatError' if the query string could not be formatted
168-- correctly.
169formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
170formatQuery conn q@(Query template) qs
171 | null xs && '?' `B.notElem` template = return template
172 | otherwise = toByteString <$> buildQuery conn q template xs
173 where xs = toRow qs
175-- | Format a query string with a variable number of rows.
176--
177-- This function is exposed to help with debugging and logging. Do not
178-- use it to prepare queries for execution.
179--
180-- The query string must contain exactly one substitution group,
181-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
182-- followed by an \"@(@\" character, a series of one or more \"@?@\"
183-- characters separated by commas, and a \"@)@\" character. White
184-- space in a substitution group is permitted.
185--
186-- Throws 'FormatError' if the query string could not be formatted
187-- correctly.
188formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
189formatMany _ q [] = fmtError "no rows supplied" q []
190formatMany conn q@(Query template) qs = do
191 case parseTemplate template of
192 Just (before, qbits, after) -> do
193 bs <- mapM (buildQuery conn q qbits . toRow) qs
194 return . toByteString . mconcat $ fromByteString before :
195 intersperse (fromChar ',') bs ++
196 [fromByteString after]
197 Nothing -> fmtError "syntax error in query template for executeMany" q []
199-- Split the input string into three pieces, @before@, @qbits@, and @after@,
200-- following this grammar:
201--
202-- start: ^ before qbits after $
203-- before: ([^?]* [^?\w])? 'VALUES' \s*
204-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
205-- after: [^?]*
206--
207-- \s: [ \t\n\r\f]
208-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
209--
210-- This would be much more concise with some sort of regex engine.
211-- 'formatMany' used to use pcre-light instead of this hand-written parser,
212-- but pcre is a hassle to install on Windows.
213parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
214parseTemplate template =
215 -- Convert input string to uppercase, to facilitate searching.
216 search $ B.map toUpper_ascii template
217 where
218 -- Search for the next occurrence of "VALUES"
219 search bs =
220 case B.breakSubstring "VALUES" bs of
221 (x, y)
222 -- If "VALUES" is not present in the string, or any '?' characters
223 -- were encountered prior to it, fail.
224 | B.null y || ('?' `B.elem` x)
225 -> Nothing
227 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
228 -- try the next occurrence.
229 | not (B.null x) && isIdent (B.last x)
230 -> search $ B.drop 6 y
232 -- Otherwise, we have a legitimate "VALUES" token.
233 | otherwise
234 -> parseQueryBits $ skipSpace $ B.drop 6 y
236 -- Parse '(' \s* '?' \s* . If this doesn't match
237 -- (and we don't consume a '?'), look for another "VALUES".
238 --
239 -- qb points to the open paren (if present), meaning it points to the
240 -- beginning of the "qbits" production described above. This is why we
241 -- pass it down to finishQueryBits.
242 parseQueryBits qb
243 | Just ('(', skipSpace -> bs1) <- B.uncons qb
244 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
245 = finishQueryBits qb bs2
246 | otherwise
247 = search qb
249 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
250 --
251 -- Since we've already consumed at least one '?', there's no turning back.
252 -- The parse has to succeed here, or the whole thing fails
253 -- (because we don't allow '?' to appear outside of the VALUES list).
254 finishQueryBits qb bs0
255 | Just (')', bs1) <- B.uncons bs0
256 = if '?' `B.elem` bs1
257 then Nothing
258 else Just $ slice3 template qb bs1
259 | Just (',', skipSpace -> bs1) <- B.uncons bs0
260 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
261 = finishQueryBits qb bs2
262 | otherwise
263 = Nothing
265 -- Slice a string into three pieces, given the start offset of the second
266 -- and third pieces. Each "offset" is actually a tail of the uppercase
267 -- version of the template string. Its length is used to infer the offset.
268 --
269 -- It is important to note that we only slice the original template.
270 -- We don't want our all-caps trick messing up the actual query string.
271 slice3 source p1 p2 =
272 (s1, s2, source'')
273 where
274 (s1, source') = B.splitAt (B.length source - B.length p1) source
275 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
277 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
278 | otherwise = c
280 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
281 -- in the PostgreSQL source. No need to check [a-z], since we converted
282 -- the whole string to uppercase.
283 isIdent c = (c >= '0' && c <= '9')
284 || (c >= 'A' && c <= 'Z')
285 || (c >= '\x80' && c <= '\xFF')
286 || c == '_'
287 || c == '$'
289 -- Based on {space} in scan.l
290 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
292 skipSpace = B.dropWhile isSpace_ascii
294escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
295escapeStringConn conn s =
296 withConnection conn $ \c ->
297 PQ.escapeStringConn c s >>= checkError c
299escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
300escapeByteaConn conn s =
301 withConnection conn $ \c ->
302 PQ.escapeByteaConn c s >>= checkError c
304checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
305checkError _ (Just x) = return $ Right x
306checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
308buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
309buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
310 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
311 (inQuotes . fromByteString)
312 utf8ToString = T.unpack . TE.decodeUtf8
313 sub (Plain b) = pure b
314 sub (Escape s) = quote <$> escapeStringConn conn s
315 sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
316 sub (Many ys) = mconcat <$> mapM sub ys
317 split s = fromByteString h : if B.null t then [] else split (B.tail t)
318 where (h,t) = B.break (=='?') s
319 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
320 zipParams [t] [] = t
321 zipParams _ _ = fmtError (show (B.count '?' template) ++
322 " '?' characters, but " ++
323 show (length xs) ++ " parameters") q xs
325-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
326-- expected to return results.
327--
328-- Returns the number of rows affected.
329--
330-- Throws 'FormatError' if the query could not be formatted correctly.
331execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
332execute conn template qs = do
333 result <- exec conn =<< formatQuery conn template qs
334 finishExecute conn template result
336-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
337-- expected to return results.
338--
339-- Returns the number of rows affected.
340--
341-- Throws 'FormatError' if the query could not be formatted correctly.
342executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
343executeMany _ _ [] = return 0
344executeMany conn q qs = do
345 result <- exec conn =<< formatMany conn q qs
346 finishExecute conn q result
348-- | Perform a @SELECT@ or other SQL query that is expected to return
349-- results. All results are retrieved and converted before this
350-- function returns.
351--
352-- When processing large results, this function will consume a lot of
353-- client-side memory. Consider using 'fold' instead.
354--
355-- Exceptions that may be thrown:
356--
357-- * 'FormatError': the query string could not be formatted correctly.
358--
359-- * 'QueryError': the result contains no columns (i.e. you should be
360-- using 'execute' instead of 'query').
361--
362-- * 'ResultError': result conversion failed.
363query :: (ToRow q, FromRow r)
364 => Connection -> Query -> q -> IO [r]
365query conn template qs = do
366 result <- exec conn =<< formatQuery conn template qs
367 finishQuery conn template result
369-- | A version of 'query' that does not perform query substitution.
370query_ :: (FromRow r) => Connection -> Query -> IO [r]
371query_ conn q@(Query que) = do
372 result <- exec conn que
373 finishQuery conn q result
375-- | Perform a @SELECT@ or other SQL query that is expected to return
376-- results. Results are streamed incrementally from the server, and
377-- consumed via a left fold.
378--
379-- When dealing with small results, it may be simpler (and perhaps
380-- faster) to use 'query' instead.
381--
382-- This fold is /not/ strict. The stream consumer is responsible for
383-- forcing the evaluation of its result to avoid space leaks.
384--
385-- Exceptions that may be thrown:
386--
387-- * 'FormatError': the query string could not be formatted correctly.
388--
389-- * 'QueryError': the result contains no columns (i.e. you should be
390-- using 'execute' instead of 'query').
391--
392-- * 'ResultError': result conversion failed.
394fold :: ( FromRow row, ToRow params )
395 => Connection
396 -> Query
397 -> params
398 -> a
399 -> (a -> row -> IO a)
400 -> IO a
401fold = foldWithOptions defaultFoldOptions
403data FetchQuantity
404 = Automatic
405 | Fixed !Int
407data FoldOptions
408 = FoldOptions {
409 fetchQuantity :: !FetchQuantity,
410 transactionMode :: !TransactionMode
411 }
413defaultFoldOptions :: FoldOptions
414defaultFoldOptions = FoldOptions {
415 fetchQuantity = Automatic,
416 transactionMode = TransactionMode ReadCommitted ReadOnly
417 }
419foldWithOptions :: ( FromRow row, ToRow params )
420 => FoldOptions
421 -> Connection
422 -> Query
423 -> params
424 -> a
425 -> (a -> row -> IO a)
426 -> IO a
427foldWithOptions opts conn template qs a f = do
428 q <- formatQuery conn template qs
429 doFold opts conn template (Query q) a f
431-- | A version of 'fold' that does not perform query substitution.
432fold_ :: (FromRow r) =>
433 Connection
434 -> Query -- ^ Query.
435 -> a -- ^ Initial state for result consumer.
436 -> (a -> r -> IO a) -- ^ Result consumer.
437 -> IO a
438fold_ = foldWithOptions_ defaultFoldOptions
441foldWithOptions_ :: (FromRow r) =>
442 FoldOptions
443 -> Connection
444 -> Query -- ^ Query.
445 -> a -- ^ Initial state for result consumer.
446 -> (a -> r -> IO a) -- ^ Result consumer.
447 -> IO a
448foldWithOptions_ opts conn query a f = doFold opts conn query query a f
451doFold :: ( FromRow row )
452 => FoldOptions
453 -> Connection
454 -> Query
455 -> Query
456 -> a
457 -> (a -> row -> IO a)
458 -> IO a
459doFold FoldOptions{..} conn _template q a f = do
460 stat <- withConnection conn PQ.transactionStatus
461 case stat of
462 PQ.TransIdle -> withTransactionMode transactionMode conn go
463 PQ.TransInTrans -> go
464 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
465 -- This _shouldn't_ occur in the current incarnation of
466 -- the library, as we aren't using libpq asynchronously.
467 -- However, it could occur in future incarnations of
468 -- this library or if client code uses the Internal module
469 -- to use raw libpq commands on postgresql-simple connections.
470 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
471 -- This should be turned into a better error message.
472 -- It is probably a bad idea to automatically roll
473 -- back the transaction and start another.
474 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
475 -- Not sure what this means.
476 where
477 go = do
478 -- FIXME: what about name clashes with already-declared cursors?
479 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
480 `mappend` q)
481 loop a `finally` execute_ conn "CLOSE fold"
483-- FIXME: choose the Automatic chunkSize more intelligently
484-- One possibility is to use the type of the results, although this
485-- still isn't a perfect solution, given that common types (e.g. text)
486-- are of highly variable size.
487-- A refinement of this technique is to pick this number adaptively
488-- as results are read in from the database.
489 chunkSize = case fetchQuantity of
490 Automatic -> 256
491 Fixed n -> n
492 loop a = do
493 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
494 if null rs then return a else foldM f a rs >>= loop
496-- | A version of 'fold' that does not transform a state value.
497forEach :: (ToRow q, FromRow r) =>
498 Connection
499 -> Query -- ^ Query template.
500 -> q -- ^ Query parameters.
501 -> (r -> IO ()) -- ^ Result consumer.
502 -> IO ()
503forEach conn template qs = fold conn template qs () . const
504{-# INLINE forEach #-}
506-- | A version of 'forEach' that does not perform query substitution.
507forEach_ :: (FromRow r) =>
508 Connection
509 -> Query -- ^ Query template.
510 -> (r -> IO ()) -- ^ Result consumer.
511 -> IO ()
512forEach_ conn template = fold_ conn template () . const
513{-# INLINE forEach_ #-}
515forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
516forM' lo hi m = loop hi []
517 where
518 loop !n !as
519 | n < lo = return as
520 | otherwise = do
521 a <- m n
522 loop (n-1) (a:as)
524finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
525finishQuery conn q result = do
526 status <- PQ.resultStatus result
527 case status of
528 PQ.EmptyQuery ->
529 throwIO $ QueryError "query: Empty query" q
530 PQ.CommandOk -> do
531 throwIO $ QueryError "query resulted in a command response" q
532 PQ.TuplesOk -> do
533 ncols <- PQ.nfields result
534 let unCol (PQ.Col x) = fromIntegral x :: Int
535 typenames <- V.generateM (unCol ncols)
536 (\(PQ.Col . fromIntegral -> col) -> do
537 getTypename conn =<< PQ.ftype result col)
538 nrows <- PQ.ntuples result
539 ncols <- PQ.nfields result
540 forM' 0 (nrows-1) $ \row -> do
541 let rw = Row row typenames result
542 case runStateT (runReaderT (unRP fromRow) rw) 0 of
543 Ok (val,col) | col == ncols -> return val
544 | otherwise -> do
545 vals <- forM' 0 (ncols-1) $ \c -> do
546 v <- PQ.getvalue result row c
547 return ( typenames V.! unCol c
548 , fmap ellipsis v )
549 throw (ConversionFailed
550 (show (unCol ncols) ++ " values: " ++ show vals)
551 (show (unCol col) ++ " slots in target type")
552 "mismatch between number of columns to \
553 \convert and number in target type")
554 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
555 Errors [x] -> throwIO x
556 Errors xs -> throwIO $ ManyErrors xs
557 PQ.CopyOut ->
558 throwIO $ QueryError "query: COPY TO is not supported" q
559 PQ.CopyIn ->
560 throwIO $ QueryError "query: COPY FROM is not supported" q
561 PQ.BadResponse -> throwResultError "query" result status
562 PQ.NonfatalError -> throwResultError "query" result status
563 PQ.FatalError -> throwResultError "query" result status
565ellipsis :: ByteString -> ByteString
566ellipsis bs
567 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
568 | otherwise = bs
571-- | Of the four isolation levels defined by the SQL standard,
572-- these are the three levels distinguished by PostgreSQL as of version 9.0.
573-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
574-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
575-- was equivalent to 'Serializable'.
577data IsolationLevel
578 = DefaultIsolationLevel -- ^ the isolation level will be taken from
579 -- PostgreSQL's per-connection
580 -- @default_transaction_isolation@ variable,
581 -- which is initialized according to the
582 -- server's config. The default configuration
583 -- is 'ReadCommitted'.
584 | ReadCommitted
585 | RepeatableRead
586 | Serializable
587 deriving (Show, Eq, Ord, Enum, Bounded)
589data ReadWriteMode
590 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
591 -- PostgreSQL's per-connection
592 -- @default_transaction_read_only@ variable,
593 -- which is initialized according to the
594 -- server's config. The default configuration
595 -- is 'ReadWrite'.
596 | ReadWrite
597 | ReadOnly
598 deriving (Show, Eq, Ord, Enum, Bounded)
600data TransactionMode = TransactionMode {
601 isolationLevel :: !IsolationLevel,
602 readWriteMode :: !ReadWriteMode
603 } deriving (Show, Eq)
605defaultTransactionMode :: TransactionMode
606defaultTransactionMode = TransactionMode
607 defaultIsolationLevel
608 defaultReadWriteMode
610defaultIsolationLevel :: IsolationLevel
611defaultIsolationLevel = DefaultIsolationLevel
613defaultReadWriteMode :: ReadWriteMode
614defaultReadWriteMode = DefaultReadWriteMode
616-- | Execute an action inside a SQL transaction.
617--
618-- This function initiates a transaction with a \"@begin
619-- transaction@\" statement, then executes the supplied action. If
620-- the action succeeds, the transaction will be completed with
621-- 'Base.commit' before this function returns.
622--
623-- If the action throws /any/ kind of exception (not just a
624-- PostgreSQL-related exception), the transaction will be rolled back using
625-- 'rollback', then the exception will be rethrown.
626withTransaction :: Connection -> IO a -> IO a
627withTransaction = withTransactionMode defaultTransactionMode
629-- | Execute an action inside a SQL transaction with a given isolation level.
630withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
631withTransactionLevel lvl
632 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
634-- | Execute an action inside a SQL transaction with a given transaction mode.
635withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
636withTransactionMode mode conn act =
637 mask $ \restore -> do
638 beginMode mode conn
639 r <- restore act `onException` rollback conn
640 commit conn
641 return r
643-- | Rollback a transaction.
644rollback :: Connection -> IO ()
645rollback conn = execute_ conn "ABORT" >> return ()
647-- | Commit a transaction.
648commit :: Connection -> IO ()
649commit conn = execute_ conn "COMMIT" >> return ()
651-- | Begin a transaction.
652begin :: Connection -> IO ()
653begin = beginMode defaultTransactionMode
655-- | Begin a transaction with a given isolation level
656beginLevel :: IsolationLevel -> Connection -> IO ()
657beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
659-- | Begin a transaction with a given transaction mode
660beginMode :: TransactionMode -> Connection -> IO ()
661beginMode mode conn = do
662 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
663 return ()
664 where
665 isolevel = case isolationLevel mode of
666 DefaultIsolationLevel -> ""
667 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
668 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
669 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
670 readmode = case readWriteMode mode of
671 DefaultReadWriteMode -> ""
672 ReadWrite -> " READ WRITE"
673 ReadOnly -> " READ ONLY"
675fmtError :: String -> Query -> [Action] -> a
676fmtError msg q xs = throw FormatError {
677 fmtMessage = msg
678 , fmtQuery = q
679 , fmtParams = map twiddle xs
680 }
681 where twiddle (Plain b) = toByteString b
682 twiddle (Escape s) = s
683 twiddle (EscapeByteA s) = s
684 twiddle (Many ys) = B.concat (map twiddle ys)
686-- $use
687--
688-- SQL-based applications are somewhat notorious for their
689-- susceptibility to attacks through the injection of maliciously
690-- crafted data. The primary reason for widespread vulnerability to
691-- SQL injections is that many applications are sloppy in handling
692-- user data when constructing SQL queries.
693--
694-- This library provides a 'Query' type and a parameter substitution
695-- facility to address both ease of use and security.
697-- $querytype
698--
699-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
700-- exposes a tiny API that is not compatible with the 'ByteString'
701-- API; this makes it difficult to construct queries from fragments of
702-- strings. The 'query' and 'execute' functions require queries to be
703-- of type 'Query'.
704--
705-- To most easily construct a query, enable GHC's @OverloadedStrings@
706-- language extension and write your query as a normal literal string.
707--
708-- > {-# LANGUAGE OverloadedStrings #-}
709-- >
710-- > import Database.PostgreSQL.Simple
711-- >
712-- > hello = do
713-- > conn <- connect defaultConnectInfo
714-- > query conn "select 2 + 2"
715--
716-- A 'Query' value does not represent the actual query that will be
717-- executed, but is a template for constructing the final query.
719-- $subst
720--
721-- Since applications need to be able to construct queries with
722-- parameters that change, this library provides a query substitution
723-- capability.
724--
725-- The 'Query' template accepted by 'query' and 'execute' can contain
726-- any number of \"@?@\" characters. Both 'query' and 'execute'
727-- accept a third argument, typically a tuple. When constructing the
728-- real query to execute, these functions replace the first \"@?@\" in
729-- the template with the first element of the tuple, the second
730-- \"@?@\" with the second element, and so on. If necessary, each
731-- tuple element will be quoted and escaped prior to substitution;
732-- this defeats the single most common injection vector for malicious
733-- data.
734--
735-- For example, given the following 'Query' template:
736--
737-- > select * from user where first_name = ? and age > ?
738--
739-- And a tuple of this form:
740--
741-- > ("Boris" :: String, 37 :: Int)
742--
743-- The query to be executed will look like this after substitution:
744--
745-- > select * from user where first_name = 'Boris' and age > 37
746--
747-- If there is a mismatch between the number of \"@?@\" characters in
748-- your template and the number of elements in your tuple, a
749-- 'FormatError' will be thrown.
750--
751-- Note that the substitution functions do not attempt to parse or
752-- validate your query. It's up to you to write syntactically valid
753-- SQL, and to ensure that each \"@?@\" in your query template is
754-- matched with the right tuple element.
756-- $inference
757--
758-- Automated type inference means that you will often be able to avoid
759-- supplying explicit type signatures for the elements of a tuple.
760-- However, sometimes the compiler will not be able to infer your
761-- types. Consider a case where you write a numeric literal in a
762-- parameter tuple:
763--
764-- > query conn "select ? + ?" (40,2)
765--
766-- The above query will be rejected by the compiler, because it does
767-- not know the specific numeric types of the literals @40@ and @2@.
768-- This is easily fixed:
769--
770-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
771--
772-- The same kind of problem can arise with string literals if you have
773-- the @OverloadedStrings@ language extension enabled. Again, just
774-- use an explicit type signature if this happens.
776-- $only_param
777--
778-- Haskell lacks a single-element tuple type, so if you have just one
779-- value you want substituted into a query, what should you do?
780--
781-- The obvious approach would appear to be something like this:
782--
783-- > instance (Param a) => QueryParam a where
784-- > ...
785--
786-- Unfortunately, this wreaks havoc with type inference, so we take a
787-- different tack. To represent a single value @val@ as a parameter, write
788-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
789--
790-- Here's an example using a singleton list:
791--
792-- > execute conn "insert into users (first_name) values (?)"
793-- > ["Nuala"]
795-- $in
796--
797-- Suppose you want to write a query using an @IN@ clause:
798--
799-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
800--
801-- In such cases, it's common for both the elements and length of the
802-- list after the @IN@ keyword to vary from query to query.
803--
804-- To address this case, use the 'In' type wrapper, and use a single
805-- \"@?@\" character to represent the list. Omit the parentheses
806-- around the list; these will be added for you.
807--
808-- Here's an example:
809--
810-- > query conn "select * from users where first_name in ?" $
811-- > In ["Anna", "Boris", "Carla"]
812--
813-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
814-- substituted instead, to ensure that your clause remains
815-- syntactically valid.
817-- $many
818--
819-- If you know that you have many rows of data to insert into a table,
820-- it is much more efficient to perform all the insertions in a single
821-- multi-row @INSERT@ statement than individually.
822--
823-- The 'executeMany' function is intended specifically for helping
824-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
825-- query substitution are different than those for 'execute'.
826--
827-- What 'executeMany' searches for in your 'Query' template is a
828-- single substring of the form:
829--
830-- > values (?,?,?)
831--
832-- The rules are as follows:
833--
834-- * The keyword @VALUES@ is matched case insensitively.
835--
836-- * There must be no other \"@?@\" characters anywhere in your
837-- template.
838--
839-- * There must one or more \"@?@\" in the parentheses.
840--
841-- * Extra white space is fine.
842--
843-- The last argument to 'executeMany' is a list of parameter
844-- tuples. These will be substituted into the query where the @(?,?)@
845-- string appears, in a form suitable for use in a multi-row @INSERT@
846-- or @UPDATE@.
847--
848-- Here is an example:
849--
850-- > executeMany conn
851-- > "insert into users (first_name,last_name) values (?,?)"
852-- > [("Boris","Karloff"),("Ed","Wood")]
853--
854-- The query that will be executed here will look like this
855-- (reformatted for tidiness):
856--
857-- > insert into users (first_name,last_name) values
858-- > ('Boris','Karloff'),('Ed','Wood')
860-- $result
861--
862-- The 'query' and 'query_' functions return a list of values in the
863-- 'FromRow' typeclass. This class performs automatic extraction
864-- and type conversion of rows from a query result.
865--
866-- Here is a simple example of how to extract results:
867--
868-- > import qualified Data.Text as Text
869-- >
870-- > xs <- query_ conn "select name,age from users"
871-- > forM_ xs $ \(name,age) ->
872-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
873--
874-- Notice two important details about this code:
875--
876-- * The number of columns we ask for in the query template must
877-- exactly match the number of elements we specify in a row of the
878-- result tuple. If they do not match, a 'ResultError' exception
879-- will be thrown.
880--
881-- * Sometimes, the compiler needs our help in specifying types. It
882-- can infer that @name@ must be a 'Text', due to our use of the
883-- @unpack@ function. However, we have to tell it the type of @age@,
884-- as it has no other information to determine the exact type.
886-- $null
887--
888-- The type of a result tuple will look something like this:
889--
890-- > (Text, Int, Int)
891--
892-- Although SQL can accommodate @NULL@ as a value for any of these
893-- types, Haskell cannot. If your result contains columns that may be
894-- @NULL@, be sure that you use 'Maybe' in those positions of of your
895-- tuple.
896--
897-- > (Text, Maybe Int, Int)
898--
899-- If 'query' encounters a @NULL@ in a row where the corresponding
900-- Haskell type is not 'Maybe', it will throw a 'ResultError'
901-- exception.
903-- $only_result
904--
905-- To specify that a query returns a single-column result, use the
906-- 'Only' type.
907--
908-- > xs <- query_ conn "select id from users"
909-- > forM_ xs $ \(Only dbid) -> {- ... -}
911-- $types
912--
913-- Conversion of SQL values to Haskell values is somewhat
914-- permissive. Here are the rules.
915--
916-- * For numeric types, any Haskell type that can accurately represent
917-- all values of the given PostgreSQL type is considered \"compatible\".
918-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
919-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
920-- represent a @SMALLINT@, so it is considered compatble with those types.
921--
922-- * A numeric compatibility check is based only on the type of a
923-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
924-- @BIGINT@ column will be considered incompatible with a Haskell
925-- 'Int16', even if it contains the value @1@.
926--
927-- * If a numeric incompatibility is found, 'query' will throw a
928-- 'ResultError'.
929--
930-- * The 'String' and 'Text' types are assumed to be encoded as
931-- UTF-8. If you use some other encoding, decoding may fail or give
932-- wrong results. In such cases, write a @newtype@ wrapper and a
933-- custom 'Result' instance to handle your encoding.
935getTypename :: Connection -> PQ.Oid -> IO ByteString
936getTypename conn@Connection{..} oid =
937 case oid2builtin oid of
938 Just builtin -> return $! builtin2typname builtin
939 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
940 case IntMap.lookup (oid2int oid) oidmap of
941 Just name -> return (oidmap, name)
942 Nothing -> do
943 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
944 (Only oid)
945 name <- case names of
946 [] -> return $ throw SqlError {
947 sqlNativeError = -1,
948 sqlErrorMsg = "invalid type oid",
949 sqlState = ""
950 }
951 [Only x] -> return x
952 _ -> fail "typename query returned more than one result"
953 -- oid is a primary key, so the query should
954 -- never return more than one result
955 return (IntMap.insert (oid2int oid) name oidmap, name)