git.iko.soy/typeable/postgresql-simple
on cd784ea help sign in
908 lines 34 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--
17-- A mid-level client library for the PostgreSQL database, aimed at ease of
18-- use and high performance.
19--
20------------------------------------------------------------------------------
22module Database.PostgreSQL.Simple
23 (
24 -- * Writing queries
25 -- $use
27 -- ** The Query type
28 -- $querytype
30 -- ** Parameter substitution
31 -- $subst
33 -- *** Type inference
34 -- $inference
36 -- ** Substituting a single parameter
37 -- $only_param
39 -- ** Representing a list of values
40 -- $in
42 -- ** Modifying multiple rows at once
43 -- $many
45 -- ** @RETURNING@: modifications that return results
46 -- $returning
48 -- * Extracting results
49 -- $result
51 -- ** Handling null values
52 -- $null
54 -- ** Type conversions
55 -- $types
57 -- * Types
58 Connection
59 , Query
60 , ToRow
61 , FromRow
62 , In(..)
63 , Binary(..)
64 , Only(..)
65 , (:.)(..)
66 -- ** Exceptions
67 , SqlError(..)
68 , PQ.ExecStatus(..)
69 , FormatError(..)
70 , QueryError(..)
71 , ResultError(..)
72 -- * Connection management
73 , Base.connectPostgreSQL
74 , Base.close
75 , Base.connect
76 , Base.ConnectInfo(..)
77 , Base.defaultConnectInfo
78 , Base.postgreSQLConnectionString
79 -- * Queries that return results
80 , query
81 , query_
82 -- ** Queries taking parser as argument
83 , queryWith
84 , queryWith_
85 -- * Queries that stream results
86 , FoldOptions(..)
87 , FetchQuantity(..)
88 , defaultFoldOptions
89 , fold
90 , foldWithOptions
91 , fold_
92 , foldWithOptions_
93 , forEach
94 , forEach_
95 , returning
96 -- * Statements that do not return results
97 , execute
98 , execute_
99 , executeMany
100-- , Base.insertID
101 -- * Transaction handling
102 , withTransaction
103 , withSavepoint
104-- , Base.autocommit
105 , begin
106 , commit
107 , rollback
108 -- * Helper functions
109 , formatMany
110 , formatQuery
111 ) where
113import Data.ByteString.Builder
114 ( Builder, byteString, char8, intDec )
115import Control.Applicative ((<$>))
116import Control.Exception as E
117import Control.Monad (foldM)
118import Data.ByteString (ByteString)
119import Data.Int (Int64)
120import Data.List (intersperse)
121import Data.Monoid (mconcat)
122import Database.PostgreSQL.Simple.Compat ( (<>), toByteString )
123import Database.PostgreSQL.Simple.FromField (ResultError(..))
124import Database.PostgreSQL.Simple.FromRow (FromRow(..))
125import Database.PostgreSQL.Simple.Ok
126import Database.PostgreSQL.Simple.ToField (Action(..))
127import Database.PostgreSQL.Simple.ToRow (ToRow(..))
128import Database.PostgreSQL.Simple.Types
129 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
130import Database.PostgreSQL.Simple.Internal as Base
131import Database.PostgreSQL.Simple.Transaction
132import Database.PostgreSQL.Simple.TypeInfo
133import qualified Database.PostgreSQL.LibPQ as PQ
134import qualified Data.ByteString.Char8 as B
135import Control.Monad.Trans.Reader
136import Control.Monad.Trans.State.Strict
139-- | Format a query string.
140--
141-- This function is exposed to help with debugging and logging. Do not
142-- use it to prepare queries for execution.
143--
144-- String parameters are escaped according to the character set in use
145-- on the 'Connection'.
146--
147-- Throws 'FormatError' if the query string could not be formatted
148-- correctly.
149formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
150formatQuery conn q@(Query template) qs
151 | null xs && '?' `B.notElem` template = return template
152 | otherwise = toByteString <$> buildQuery conn q template xs
153 where xs = toRow qs
155-- | Format a query string with a variable number of rows.
156--
157-- This function is exposed to help with debugging and logging. Do not
158-- use it to prepare queries for execution.
159--
160-- The query string must contain exactly one substitution group,
161-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
162-- followed by an \"@(@\" character, a series of one or more \"@?@\"
163-- characters separated by commas, and a \"@)@\" character. White
164-- space in a substitution group is permitted.
165--
166-- Throws 'FormatError' if the query string could not be formatted
167-- correctly.
168formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
169formatMany _ q [] = fmtError "no rows supplied" q []
170formatMany conn q@(Query template) qs = do
171 case parseTemplate template of
172 Just (before, qbits, after) -> do
173 bs <- mapM (buildQuery conn q qbits . toRow) qs
174 return . toByteString . mconcat $ byteString before :
175 intersperse (char8 ',') bs ++
176 [byteString after]
177 Nothing -> fmtError "syntax error in multi-row template" q []
179-- Split the input string into three pieces, @before@, @qbits@, and @after@,
180-- following this grammar:
181--
182-- start: ^ before qbits after $
183-- before: ([^?]* [^?\w])? 'VALUES' \s*
184-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
185-- after: [^?]*
186--
187-- \s: [ \t\n\r\f]
188-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
189--
190-- This would be much more concise with some sort of regex engine.
191-- 'formatMany' used to use pcre-light instead of this hand-written parser,
192-- but pcre is a hassle to install on Windows.
193parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
194parseTemplate template =
195 -- Convert input string to uppercase, to facilitate searching.
196 search $ B.map toUpper_ascii template
197 where
198 -- Search for the next occurrence of "VALUES"
199 search bs =
200 case B.breakSubstring "VALUES" bs of
201 (x, y)
202 -- If "VALUES" is not present in the string, or any '?' characters
203 -- were encountered prior to it, fail.
204 | B.null y || ('?' `B.elem` x)
205 -> Nothing
207 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
208 -- try the next occurrence.
209 | not (B.null x) && isIdent (B.last x)
210 -> search $ B.drop 6 y
212 -- Otherwise, we have a legitimate "VALUES" token.
213 | otherwise
214 -> parseQueryBits $ skipSpace $ B.drop 6 y
216 -- Parse '(' \s* '?' \s* . If this doesn't match
217 -- (and we don't consume a '?'), look for another "VALUES".
218 --
219 -- qb points to the open paren (if present), meaning it points to the
220 -- beginning of the "qbits" production described above. This is why we
221 -- pass it down to finishQueryBits.
222 parseQueryBits qb
223 | Just ('(', skipSpace -> bs1) <- B.uncons qb
224 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
225 = finishQueryBits qb bs2
226 | otherwise
227 = search qb
229 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
230 --
231 -- Since we've already consumed at least one '?', there's no turning back.
232 -- The parse has to succeed here, or the whole thing fails
233 -- (because we don't allow '?' to appear outside of the VALUES list).
234 finishQueryBits qb bs0
235 | Just (')', bs1) <- B.uncons bs0
236 = if '?' `B.elem` bs1
237 then Nothing
238 else Just $ slice3 template qb bs1
239 | Just (',', skipSpace -> bs1) <- B.uncons bs0
240 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
241 = finishQueryBits qb bs2
242 | otherwise
243 = Nothing
245 -- Slice a string into three pieces, given the start offset of the second
246 -- and third pieces. Each "offset" is actually a tail of the uppercase
247 -- version of the template string. Its length is used to infer the offset.
248 --
249 -- It is important to note that we only slice the original template.
250 -- We don't want our all-caps trick messing up the actual query string.
251 slice3 source p1 p2 =
252 (s1, s2, source'')
253 where
254 (s1, source') = B.splitAt (B.length source - B.length p1) source
255 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
257 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
258 | otherwise = c
260 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
261 -- in the PostgreSQL source. No need to check [a-z], since we converted
262 -- the whole string to uppercase.
263 isIdent c = (c >= '0' && c <= '9')
264 || (c >= 'A' && c <= 'Z')
265 || (c >= '\x80' && c <= '\xFF')
266 || c == '_'
267 || c == '$'
269 -- Based on {space} in scan.l
270 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
272 skipSpace = B.dropWhile isSpace_ascii
276buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
277buildQuery conn q template xs =
278 zipParams (split template) <$> mapM (buildAction conn q xs) xs
279 where split s =
280 let (h,t) = B.break (=='?') s
281 in byteString h
282 : if B.null t
283 then []
284 else split (B.tail t)
285 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
286 zipParams [t] [] = t
287 zipParams _ _ = fmtError (show (B.count '?' template) ++
288 " '?' characters, but " ++
289 show (length xs) ++ " parameters") q xs
291-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
292-- expected to return results.
293--
294-- Returns the number of rows affected.
295--
296-- Throws 'FormatError' if the query could not be formatted correctly, or
297-- a 'SqlError' exception if the backend returns an error.
298execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
299execute conn template qs = do
300 result <- exec conn =<< formatQuery conn template qs
301 finishExecute conn template result
303-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
304-- expected to return results.
305--
306-- Returns the number of rows affected. If the list of parameters is empty,
307-- this function will simply return 0 without issuing the query to the backend.
308-- If this is not desired, consider using the 'Values' constructor instead.
309--
310-- Throws 'FormatError' if the query could not be formatted correctly, or
311-- a 'SqlError' exception if the backend returns an error.
312--
313-- For example, here's a command that inserts two rows into a table
314-- with two columns:
315--
316-- @
317-- executeMany c [sql|
318-- INSERT INTO sometable VALUES (?,?)
319-- |] [(1, \"hello\"),(2, \"world\")]
320-- @
321--
322-- Here's an canonical example of a multi-row update command:
323--
324-- @
325-- executeMany c [sql|
326-- UPDATE sometable
327-- SET sometable.y = upd.y
328-- FROM (VALUES (?,?)) as upd(x,y)
329-- WHERE sometable.x = upd.x
330-- |] [(1, \"hello\"),(2, \"world\")
331-- @
333executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
334executeMany _ _ [] = return 0
335executeMany conn q qs = do
336 result <- exec conn =<< formatMany conn q qs
337 finishExecute conn q result
339-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
340-- query that accepts multi-row input and is expected to return results.
341-- Note that it is possible to write
342-- @'query' conn "INSERT ... RETURNING ..." ...@
343-- in cases where you are only inserting a single row, and do not need
344-- functionality analogous to 'executeMany'.
345--
346-- If the list of parameters is empty, this function will simply return @[]@
347-- without issuing the query to the backend. If this is not desired,
348-- consider using the 'Values' constructor instead.
349--
350-- Throws 'FormatError' if the query could not be formatted correctly.
351returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
352returning _ _ [] = return []
353returning conn q qs = do
354 result <- exec conn =<< formatMany conn q qs
355 finishQuery conn q result
357-- | Perform a @SELECT@ or other SQL query that is expected to return
358-- results. All results are retrieved and converted before this
359-- function returns.
360--
361-- When processing large results, this function will consume a lot of
362-- client-side memory. Consider using 'fold' instead.
363--
364-- Exceptions that may be thrown:
365--
366-- * 'FormatError': the query string could not be formatted correctly.
367--
368-- * 'QueryError': the result contains no columns (i.e. you should be
369-- using 'execute' instead of 'query').
370--
371-- * 'ResultError': result conversion failed.
372--
373-- * 'SqlError': the postgresql backend returned an error, e.g.
374-- a syntax or type error, or an incorrect table or column name.
375query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r]
376query = queryWith fromRow
378-- | A version of 'query' that does not perform query substitution.
379query_ :: (FromRow r) => Connection -> Query -> IO [r]
380query_ = queryWith_ fromRow
382-- | A version of 'query' taking parser as argument
383queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
384queryWith parser conn template qs = do
385 result <- exec conn =<< formatQuery conn template qs
386 finishQueryWith parser conn template result
388-- | A version of 'query_' taking parser as argument
389queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
390queryWith_ parser conn q@(Query que) = do
391 result <- exec conn que
392 finishQueryWith parser conn q result
394-- | Perform a @SELECT@ or other SQL query that is expected to return
395-- results. Results are streamed incrementally from the server, and
396-- consumed via a left fold.
397--
398-- When dealing with small results, it may be simpler (and perhaps
399-- faster) to use 'query' instead.
400--
401-- This fold is /not/ strict. The stream consumer is responsible for
402-- forcing the evaluation of its result to avoid space leaks.
403--
404-- This is implemented using a database cursor. As such, this requires
405-- a transaction. This function will detect whether or not there is a
406-- transaction in progress, and will create a 'ReadCommitted' 'ReadOnly'
407-- transaction if needed. The cursor is given a unique temporary name,
408-- so the consumer may itself call fold.
409--
410-- Exceptions that may be thrown:
411--
412-- * 'FormatError': the query string could not be formatted correctly.
413--
414-- * 'QueryError': the result contains no columns (i.e. you should be
415-- using 'execute' instead of 'query').
416--
417-- * 'ResultError': result conversion failed.
418--
419-- * 'SqlError': the postgresql backend returned an error, e.g.
420-- a syntax or type error, or an incorrect table or column name.
421fold :: ( FromRow row, ToRow params )
422 => Connection
423 -> Query
424 -> params
425 -> a
426 -> (a -> row -> IO a)
427 -> IO a
428fold = foldWithOptions defaultFoldOptions
430-- | Number of rows to fetch at a time. 'Automatic' currently defaults
431-- to 256 rows, although it might be nice to make this more intelligent
432-- based on e.g. the average size of the rows.
433data FetchQuantity
434 = Automatic
435 | Fixed !Int
437data FoldOptions
438 = FoldOptions {
439 fetchQuantity :: !FetchQuantity,
440 transactionMode :: !TransactionMode
441 }
443-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
444defaultFoldOptions :: FoldOptions
445defaultFoldOptions = FoldOptions {
446 fetchQuantity = Automatic,
447 transactionMode = TransactionMode ReadCommitted ReadOnly
448 }
450-- | The same as 'fold', but this provides a bit more control over
451-- lower-level details. Currently, the number of rows fetched per
452-- round-trip to the server and the transaction mode may be adjusted
453-- accordingly. If the connection is already in a transaction,
454-- then the existing transaction is used and thus the 'transactionMode'
455-- option is ignored.
456foldWithOptions :: ( FromRow row, ToRow params )
457 => FoldOptions
458 -> Connection
459 -> Query
460 -> params
461 -> a
462 -> (a -> row -> IO a)
463 -> IO a
464foldWithOptions opts conn template qs a f = do
465 q <- formatQuery conn template qs
466 doFold opts conn template (Query q) a f
468-- | A version of 'fold' that does not perform query substitution.
469fold_ :: (FromRow r) =>
470 Connection
471 -> Query -- ^ Query.
472 -> a -- ^ Initial state for result consumer.
473 -> (a -> r -> IO a) -- ^ Result consumer.
474 -> IO a
475fold_ = foldWithOptions_ defaultFoldOptions
478foldWithOptions_ :: (FromRow r) =>
479 FoldOptions
480 -> Connection
481 -> Query -- ^ Query.
482 -> a -- ^ Initial state for result consumer.
483 -> (a -> r -> IO a) -- ^ Result consumer.
484 -> IO a
485foldWithOptions_ opts conn query a f = doFold opts conn query query a f
488doFold :: ( FromRow row )
489 => FoldOptions
490 -> Connection
491 -> Query
492 -> Query
493 -> a
494 -> (a -> row -> IO a)
495 -> IO a
496doFold FoldOptions{..} conn _template q a0 f = do
497 stat <- withConnection conn PQ.transactionStatus
498 case stat of
499 PQ.TransIdle -> withTransactionMode transactionMode conn go
500 PQ.TransInTrans -> go
501 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
502 -- This _shouldn't_ occur in the current incarnation of
503 -- the library, as we aren't using libpq asynchronously.
504 -- However, it could occur in future incarnations of
505 -- this library or if client code uses the Internal module
506 -- to use raw libpq commands on postgresql-simple connections.
507 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
508 -- This should be turned into a better error message.
509 -- It is probably a bad idea to automatically roll
510 -- back the transaction and start another.
511 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
512 -- Not sure what this means.
513 where
514 declare = do
515 name <- newTempName conn
516 _ <- execute_ conn $ mconcat
517 [ "DECLARE ", name, " NO SCROLL CURSOR FOR ", q ]
518 return name
519 fetch (Query name) = query_ conn $
520 Query (toByteString (byteString "FETCH FORWARD "
521 <> intDec chunkSize
522 <> byteString " FROM "
523 <> byteString name
524 ))
525 close name =
526 (execute_ conn ("CLOSE " <> name) >> return ()) `E.catch` \ex ->
527 -- Don't throw exception if CLOSE failed because the transaction is
528 -- aborted. Otherwise, it will throw away the original error.
529 if isFailedTransactionError ex then return () else throwIO ex
531 go = bracket declare close $ \name ->
532 let loop a = do
533 rs <- fetch name
534 if null rs then return a else foldM f a rs >>= loop
535 in loop a0
537-- FIXME: choose the Automatic chunkSize more intelligently
538-- One possibility is to use the type of the results, although this
539-- still isn't a perfect solution, given that common types (e.g. text)
540-- are of highly variable size.
541-- A refinement of this technique is to pick this number adaptively
542-- as results are read in from the database.
543 chunkSize = case fetchQuantity of
544 Automatic -> 256
545 Fixed n -> n
547-- | A version of 'fold' that does not transform a state value.
548forEach :: (ToRow q, FromRow r) =>
549 Connection
550 -> Query -- ^ Query template.
551 -> q -- ^ Query parameters.
552 -> (r -> IO ()) -- ^ Result consumer.
553 -> IO ()
554forEach conn template qs = fold conn template qs () . const
555{-# INLINE forEach #-}
557-- | A version of 'forEach' that does not perform query substitution.
558forEach_ :: (FromRow r) =>
559 Connection
560 -> Query -- ^ Query template.
561 -> (r -> IO ()) -- ^ Result consumer.
562 -> IO ()
563forEach_ conn template = fold_ conn template () . const
564{-# INLINE forEach_ #-}
566forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
567forM' lo hi m = loop hi []
568 where
569 loop !n !as
570 | n < lo = return as
571 | otherwise = do
572 a <- m n
573 loop (n-1) (a:as)
575finishQuery :: FromRow r => Connection -> Query -> PQ.Result -> IO [r]
576finishQuery = finishQueryWith fromRow
578finishQueryWith :: RowParser r -> Connection -> Query -> PQ.Result -> IO [r]
579finishQueryWith parser conn q result = do
580 status <- PQ.resultStatus result
581 case status of
582 PQ.EmptyQuery ->
583 throwIO $ QueryError "query: Empty query" q
584 PQ.CommandOk -> do
585 throwIO $ QueryError "query resulted in a command response" q
586 PQ.TuplesOk -> do
587 let unCol (PQ.Col x) = fromIntegral x :: Int
588 nrows <- PQ.ntuples result
589 ncols <- PQ.nfields result
590 forM' 0 (nrows-1) $ \row -> do
591 let rw = Row row result
592 okvc <- runConversion (runStateT (runReaderT (unRP parser) rw) 0) conn
593 case okvc of
594 Ok (val,col) | col == ncols -> return val
595 | otherwise -> do
596 vals <- forM' 0 (ncols-1) $ \c -> do
597 tinfo <- getTypeInfo conn =<< PQ.ftype result c
598 v <- PQ.getvalue result row c
599 return ( tinfo
600 , fmap ellipsis v )
601 throw (ConversionFailed
602 (show (unCol ncols) ++ " values: " ++ show vals)
603 Nothing
604 ""
605 (show (unCol col) ++ " slots in target type")
606 "mismatch between number of columns to \
607 \convert and number in target type")
608 Errors [] -> throwIO $ ConversionFailed "" Nothing "" "" "unknown error"
609 Errors [x] -> throwIO x
610 Errors xs -> throwIO $ ManyErrors xs
611 PQ.CopyOut ->
612 throwIO $ QueryError "query: COPY TO is not supported" q
613 PQ.CopyIn ->
614 throwIO $ QueryError "query: COPY FROM is not supported" q
615 PQ.BadResponse -> throwResultError "query" result status
616 PQ.NonfatalError -> throwResultError "query" result status
617 PQ.FatalError -> throwResultError "query" result status
619ellipsis :: ByteString -> ByteString
620ellipsis bs
621 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
622 | otherwise = bs
625-- $use
626--
627-- SQL-based applications are somewhat notorious for their
628-- susceptibility to attacks through the injection of maliciously
629-- crafted data. The primary reason for widespread vulnerability to
630-- SQL injections is that many applications are sloppy in handling
631-- user data when constructing SQL queries.
632--
633-- This library provides a 'Query' type and a parameter substitution
634-- facility to address both ease of use and security.
636-- $querytype
637--
638-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
639-- exposes a tiny API that is not compatible with the 'ByteString'
640-- API; this makes it difficult to construct queries from fragments of
641-- strings. The 'query' and 'execute' functions require queries to be
642-- of type 'Query'.
643--
644-- To most easily construct a query, enable GHC's @OverloadedStrings@
645-- language extension and write your query as a normal literal string.
646--
647-- > {-# LANGUAGE OverloadedStrings #-}
648-- >
649-- > import Database.PostgreSQL.Simple
650-- >
651-- > hello :: IO Int
652-- > hello = do
653-- > conn <- connectPostgreSQL ""
654-- > [Only i] <- query_ conn "select 2 + 2"
655-- > return i
656--
657-- A 'Query' value does not represent the actual query that will be
658-- executed, but is a template for constructing the final query.
660-- $subst
661--
662-- Since applications need to be able to construct queries with
663-- parameters that change, this library provides a query substitution
664-- capability.
665--
666-- The 'Query' template accepted by 'query' and 'execute' can contain
667-- any number of \"@?@\" characters. Both 'query' and 'execute'
668-- accept a third argument, typically a tuple. When constructing the
669-- real query to execute, these functions replace the first \"@?@\" in
670-- the template with the first element of the tuple, the second
671-- \"@?@\" with the second element, and so on. If necessary, each
672-- tuple element will be quoted and escaped prior to substitution;
673-- this defeats the single most common injection vector for malicious
674-- data.
675--
676-- For example, given the following 'Query' template:
677--
678-- > select * from user where first_name = ? and age > ?
679--
680-- And a tuple of this form:
681--
682-- > ("Boris" :: String, 37 :: Int)
683--
684-- The query to be executed will look like this after substitution:
685--
686-- > select * from user where first_name = 'Boris' and age > 37
687--
688-- If there is a mismatch between the number of \"@?@\" characters in
689-- your template and the number of elements in your tuple, a
690-- 'FormatError' will be thrown.
691--
692-- Note that the substitution functions do not attempt to parse or
693-- validate your query. It's up to you to write syntactically valid
694-- SQL, and to ensure that each \"@?@\" in your query template is
695-- matched with the right tuple element.
697-- $inference
698--
699-- Automated type inference means that you will often be able to avoid
700-- supplying explicit type signatures for the elements of a tuple.
701-- However, sometimes the compiler will not be able to infer your
702-- types. Consider a case where you write a numeric literal in a
703-- parameter tuple:
704--
705-- > query conn "select ? + ?" (40,2)
706--
707-- The above query will be rejected by the compiler, because it does
708-- not know the specific numeric types of the literals @40@ and @2@.
709-- This is easily fixed:
710--
711-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
712--
713-- The same kind of problem can arise with string literals if you have
714-- the @OverloadedStrings@ language extension enabled. Again, just
715-- use an explicit type signature if this happens.
716--
717-- Finally, remember that the compiler must be able to infer the type
718-- of a query's /results/ as well as its parameters. We might like
719-- the following example to work:
720--
721-- > print =<< query_ conn "select 2 + 2"
722--
723-- Unfortunately, while a quick glance tells us that the result type
724-- should be a single row containing a single numeric column, the
725-- compiler has no way to infer what the types are. We can easily fix
726-- this by providing an explicit type annotation:
727--
728-- > xs <- query_ conn "select 2 + 2"
729-- > print (xs :: [Only Int])
731-- $only_param
732--
733-- Haskell lacks a single-element tuple type, so if you have just one
734-- value you want substituted into a query or a single-column result,
735-- what should you do?
736--
737-- The obvious approach would appear to be something like this:
738--
739-- > instance (ToField a) => ToRow a where
740-- > ...
741--
742-- Unfortunately, this wreaks havoc with type inference, so we take a
743-- different tack. To represent a single value @val@ as a parameter, write
744-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
745--
746-- Here's an example using a singleton list:
747--
748-- > execute conn "insert into users (first_name) values (?)"
749-- > ["Nuala"]
750--
751-- A row of /n/ query results is represented using an /n/-tuple, so
752-- you should use 'Only' to represent a single-column result.
754-- $in
755--
756-- Suppose you want to write a query using an @IN@ clause:
757--
758-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
759--
760-- In such cases, it's common for both the elements and length of the
761-- list after the @IN@ keyword to vary from query to query.
762--
763-- To address this case, use the 'In' type wrapper, and use a single
764-- \"@?@\" character to represent the list. Omit the parentheses
765-- around the list; these will be added for you.
766--
767-- Here's an example:
768--
769-- > query conn "select * from users where first_name in ?" $
770-- > Only $ In ["Anna", "Boris", "Carla"]
771--
772-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
773-- substituted instead, to ensure that your clause remains
774-- syntactically valid.
776-- $many
777--
778-- If you know that you have many rows of data to insert into a table,
779-- it is much more efficient to perform all the insertions in a single
780-- multi-row @INSERT@ statement than individually.
781--
782-- The 'executeMany' function is intended specifically for helping
783-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
784-- query substitution are different than those for 'execute'.
785--
786-- What 'executeMany' searches for in your 'Query' template is a
787-- single substring of the form:
788--
789-- > values (?,?,?)
790--
791-- The rules are as follows:
792--
793-- * The keyword @VALUES@ is matched case insensitively.
794--
795-- * There must be no other \"@?@\" characters anywhere in your
796-- template.
797--
798-- * There must be one or more \"@?@\" in the parentheses.
799--
800-- * Extra white space is fine.
801--
802-- The last argument to 'executeMany' is a list of parameter
803-- tuples. These will be substituted into the query where the @(?,?)@
804-- string appears, in a form suitable for use in a multi-row @INSERT@
805-- or @UPDATE@.
806--
807-- Here is an example:
808--
809-- > executeMany conn
810-- > "insert into users (first_name,last_name) values (?,?)"
811-- > [("Boris","Karloff"),("Ed","Wood")]
812--
813-- The query that will be executed here will look like this
814-- (reformatted for tidiness):
815--
816-- > insert into users (first_name,last_name) values
817-- > ('Boris','Karloff'),('Ed','Wood')
819-- $returning
820--
821-- PostgreSQL supports returning values from data manipulation statements
822-- such as @INSERT@ and @UPDATE@. You can use these statements by
823-- using 'query' instead of 'execute'. For multi-tuple inserts,
824-- use 'returning' instead of 'executeMany'.
825--
826-- For example, were there an auto-incrementing @id@ column and
827-- timestamp column @t@ that defaulted to the present time for the
828-- @sales@ table, then the following query would insert two new
829-- sales records and also return their new @id@s and timestamps.
830--
831-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
832-- > xs :: [(Int, UTCTime)] <- query conn q (15,"Sawdust")
833-- > ys :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
835-- $result
836--
837-- The 'query' and 'query_' functions return a list of values in the
838-- 'FromRow' typeclass. This class performs automatic extraction
839-- and type conversion of rows from a query result.
840--
841-- Here is a simple example of how to extract results:
842--
843-- > import qualified Data.Text as Text
844-- >
845-- > xs <- query_ conn "select name,age from users"
846-- > forM_ xs $ \(name,age) ->
847-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
848--
849-- Notice two important details about this code:
850--
851-- * The number of columns we ask for in the query template must
852-- exactly match the number of elements we specify in a row of the
853-- result tuple. If they do not match, a 'ResultError' exception
854-- will be thrown.
855--
856-- * Sometimes, the compiler needs our help in specifying types. It
857-- can infer that @name@ must be a 'Text', due to our use of the
858-- @unpack@ function. However, we have to tell it the type of @age@,
859-- as it has no other information to determine the exact type.
861-- $null
862--
863-- The type of a result tuple will look something like this:
864--
865-- > (Text, Int, Int)
866--
867-- Although SQL can accommodate @NULL@ as a value for any of these
868-- types, Haskell cannot. If your result contains columns that may be
869-- @NULL@, be sure that you use 'Maybe' in those positions of your
870-- tuple.
871--
872-- > (Text, Maybe Int, Int)
873--
874-- If 'query' encounters a @NULL@ in a row where the corresponding
875-- Haskell type is not 'Maybe', it will throw a 'ResultError'
876-- exception.
878-- $only_result
879--
880-- To specify that a query returns a single-column result, use the
881-- 'Only' type.
882--
883-- > xs <- query_ conn "select id from users"
884-- > forM_ xs $ \(Only dbid) -> {- ... -}
886-- $types
887--
888-- Conversion of SQL values to Haskell values is somewhat
889-- permissive. Here are the rules.
890--
891-- * For numeric types, any Haskell type that can accurately represent
892-- all values of the given PostgreSQL type is considered \"compatible\".
893-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
894-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
895-- represent a @SMALLINT@, so it is considered compatble with those types.
896--
897-- * A numeric compatibility check is based only on the type of a
898-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
899-- @BIGINT@ column will be considered incompatible with a Haskell
900-- 'Int16', even if it contains the value @1@.
901--
902-- * If a numeric incompatibility is found, 'query' will throw a
903-- 'ResultError'.
904--
905-- * The 'String' and 'Text' types are assumed to be encoded as
906-- UTF-8. If you use some other encoding, decoding may fail or give
907-- wrong results. In such cases, write a @newtype@ wrapper and a
908-- custom 'Result' instance to handle your encoding.