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