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