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