git.iko.soy/typeable/postgresql-simple
on e20ffa2 help sign in
751 lines 27 kB history raw
1{-# LANGUAGE BangPatterns, DeriveDataTypeable, OverloadedStrings #-}
2{-# LANGUAGE DoAndIfThenElse, 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 , FormatError(fmtMessage, fmtQuery, fmtParams)
59 , QueryError(qeMessage, qeQuery)
60 , ResultError(errSQLType, errHaskellType, errMessage)
61 -- * Connection management
62 , Base.connect
63 , Base.connectPostgreSQL
64 , Base.postgreSQLConnectionString
65 , Base.defaultConnectInfo
66 , Base.close
67 -- * Queries that return results
68 , query
69 , query_
70{--
71 -- * Queries that stream results
72 , fold
73 , fold_
74 , forEach
75 , forEach_
76--}
77 -- * Statements that do not return results
78 , execute
79 , execute_
80 , executeMany
81-- , Base.insertID
82 -- * Transaction handling
83 , withTransaction
84-- , Base.autocommit
85 , begin
86 , commit
87 , rollback
88 -- * Helper functions
89 , formatMany
90 , formatQuery
91 ) where
93import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
94import Blaze.ByteString.Builder.Char8 (fromChar)
95import Control.Applicative ((<$>), pure)
96import Control.Concurrent.MVar
97import Control.Exception (Exception, bracket, onException, throw, throwIO)
98import Control.Monad (forM)
99import Control.Monad.Fix (fix)
100import Data.ByteString (ByteString)
101-- import qualified Data.ByteString as B (unpack)
102import Data.Char(ord)
103import Data.Int (Int64)
104import qualified Data.IntMap as IntMap
105import Data.List (intersperse)
106import Data.Monoid (mappend, mconcat)
107import Data.Typeable (Typeable)
108--import Database.MySQL.Base (Connection, Result)
109--import Database.MySQL.Base.Types (Field)
110import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
111import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
112import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
113import Database.PostgreSQL.Simple.Result (ResultError(..))
114import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
115-- import Database.PostgreSQL.Simple.Result (ResultError(..))
116import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
117import Database.PostgreSQL.Simple.Internal as Base
118import qualified Database.PostgreSQL.LibPQ as PQ
119import Text.Regex.PCRE.Light (compile, caseless, match)
120import qualified Data.ByteString.Char8 as B
121--import qualified Database.MySQL.Base as Base
123-- | Exception thrown if a 'Query' could not be formatted correctly.
124-- This may occur if the number of \'@?@\' characters in the query
125-- string does not match the number of parameters provided.
126data FormatError = FormatError {
127 fmtMessage :: String
128 , fmtQuery :: Query
129 , fmtParams :: [ByteString]
130 } deriving (Eq, Show, Typeable)
132instance Exception FormatError
134-- | Exception thrown if 'query' is used to perform an @INSERT@-like
135-- operation, or 'execute' is used to perform a @SELECT@-like operation.
136data QueryError = QueryError {
137 qeMessage :: String
138 , qeQuery :: Query
139 } deriving (Eq, Show, Typeable)
141instance Exception QueryError
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 :: QueryParams 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 = renderParams 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 :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
173formatMany _ q [] = fmtError "no rows supplied" q []
174formatMany conn q@(Query template) qs = do
175 case match re template [] of
176 Just [_,before,qbits,after] -> do
177 bs <- mapM (buildQuery conn q qbits . renderParams) qs
178 return . toByteString . mconcat $ fromByteString before :
179 intersperse (fromChar ',') bs ++
180 [fromByteString after]
181 _ -> error "foo"
182 where
183 re = compile "^([^?]+\\bvalues\\s*)\
184 \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
185 \([^?]*)$"
186 [caseless]
188escapeStringConn conn s = withConnection conn $ \c -> do
189 PQ.escapeStringConn c s
191buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
192buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
193 where quote = inQuotes . fromByteString . maybe undefined id
194 sub (Plain b) = pure b
195 sub (Escape s) = quote <$> escapeStringConn conn s
196 sub (Many ys) = mconcat <$> mapM sub ys
197 split s = fromByteString h : if B.null t then [] else split (B.tail t)
198 where (h,t) = B.break (=='?') s
199 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
200 zipParams [t] [] = t
201 zipParams _ _ = fmtError (show (B.count '?' template) ++
202 " '?' characters, but " ++
203 show (length xs) ++ " parameters") q xs
205-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
206-- expected to return results.
207--
208-- Returns the number of rows affected.
209--
210-- Throws 'FormatError' if the query could not be formatted correctly.
211execute :: (QueryParams q) => Connection -> Query -> q -> IO Int64
212execute conn template qs = do
213 result <- exec conn =<< formatQuery conn template qs
214 finishExecute conn template result
216-- | A version of 'execute' that does not perform query substitution.
217execute_ :: Connection -> Query -> IO Int64
218execute_ conn q@(Query stmt) = do
219 result <- exec conn stmt
220 finishExecute conn q result
222-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
223-- expected to return results.
224--
225-- Returns the number of rows affected.
226--
227-- Throws 'FormatError' if the query could not be formatted correctly.
228executeMany :: (QueryParams q) => Connection -> Query -> [q] -> IO Int64
229executeMany _ _ [] = return 0
230executeMany conn q qs = do
231 result <- exec conn =<< formatMany conn q qs
232 finishExecute conn q result
234finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
235finishExecute conn q result = do
236 status <- PQ.resultStatus result
237 case status of
238 PQ.EmptyQuery -> fail "empty query" -- FIXME: error message
239 PQ.CommandOk -> do
240 ncols <- PQ.nfields result
241 if ncols /= 0
242 then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
243 "-column result") q
244 else do
245 nstr <- PQ.cmdTuples result
246 return $ case nstr of
247 Nothing -> 0 -- is this appropriate?
248 Just str -> toInteger str
249 PQ.TuplesOk -> do
250 ncols <- PQ.nfields result
251 throwIO $ QueryError ("execute resulted in " ++ show ncols ++
252 "-column result") q
253 PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
254 PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
255 _ -> do
256 errormsg <- maybe "" id <$> PQ.resultErrorMessage result
257 statusmsg <- PQ.resStatus status
258 state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
259 throw $ SqlError { sqlState = state
260 , sqlNativeError = 0 -- FIXME
261 , sqlErrorMsg = B.concat [ "execute: ", statusmsg
262 , ": ", errormsg ]}
263 where
264 toInteger str = B.foldl' delta 0 str
265 where
266 delta acc c =
267 if '0' <= c && c <= '9'
268 then 10 * acc + fromIntegral (ord c - ord '0')
269 else error ("finishExecute: not an int: " ++ B.unpack str)
273-- | Perform a @SELECT@ or other SQL query that is expected to return
274-- results. All results are retrieved and converted before this
275-- function returns.
276--
277-- When processing large results, this function will consume a lot of
278-- client-side memory. Consider using 'fold' instead.
279--
280-- Exceptions that may be thrown:
281--
282-- * 'FormatError': the query string could not be formatted correctly.
283--
284-- * 'QueryError': the result contains no columns (i.e. you should be
285-- using 'execute' instead of 'query').
286--
287-- * 'ResultError': result conversion failed.
288query :: (QueryParams q, QueryResults r)
289 => Connection -> Query -> q -> IO [r]
290query conn template qs = do
291 result <- exec conn =<< formatQuery conn template qs
292 finishQuery conn template result
294-- | A version of 'query' that does not perform query substitution.
295query_ :: (QueryResults r) => Connection -> Query -> IO [r]
296query_ conn q@(Query que) = do
297 result <- exec conn que
298 finishQuery conn q result
299{--
300-- | Perform a @SELECT@ or other SQL query that is expected to return
301-- results. Results are streamed incrementally from the server, and
302-- consumed via a left fold.
303--
304-- The result consumer must be carefully written to execute
305-- quickly. If the consumer is slow, server resources will be tied up,
306-- and other clients may not be able to update the tables from which
307-- the results are being streamed.
308--
309-- When dealing with small results, it may be simpler (and perhaps
310-- faster) to use 'query' instead.
311--
312-- This fold is /not/ strict. The stream consumer is responsible for
313-- forcing the evaluation of its result to avoid space leaks.
314--
315-- Exceptions that may be thrown:
316--
317-- * 'FormatError': the query string could not be formatted correctly.
318--
319-- * 'QueryError': the result contains no columns (i.e. you should be
320-- using 'execute' instead of 'query').
321--
322-- * 'ResultError': result conversion failed.
323fold :: (QueryParams q, QueryResults r) =>
324 Connection
325 -> Query -- ^ Query template.
326 -> q -- ^ Query parameters.
327 -> a -- ^ Initial state for result consumer.
328 -> (a -> r -> IO a) -- ^ Result consumer.
329 -> IO a
330fold conn template qs z f = do
331 Base.query conn =<< formatQuery conn template qs
332 finishFold conn template z f
333--}
334{--
335-- | A version of 'fold' that does not perform query substitution.
336fold_ :: (QueryResults r) =>
337 Connection
338 -> Query -- ^ Query.
339 -> a -- ^ Initial state for result consumer.
340 -> (a -> r -> IO a) -- ^ Result consumer.
341 -> IO a
342fold_ conn q@(Query que) z f = do
343 Base.query conn que
344 finishFold conn q z f
345--}
346{--
347-- | A version of 'fold' that does not transform a state value.
348forEach :: (QueryParams q, QueryResults r) =>
349 Connection
350 -> Query -- ^ Query template.
351 -> q -- ^ Query parameters.
352 -> (r -> IO ()) -- ^ Result consumer.
353 -> IO ()
354forEach conn template qs = fold conn template qs () . const
355{-# INLINE forEach #-}
357-- | A version of 'forEach' that does not perform query substitution.
358forEach_ :: (QueryResults r) =>
359 Connection
360 -> Query -- ^ Query template.
361 -> (r -> IO ()) -- ^ Result consumer.
362 -> IO ()
363forEach_ conn template = fold_ conn template () . const
364{-# INLINE forEach_ #-}
365--}
367forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
368forM' lo hi m = loop hi []
369 where
370 loop !n !as
371 | n < lo = return as
372 | otherwise = do
373 a <- m n
374 loop (n-1) (a:as)
376finishQuery :: (QueryResults r) => Connection -> Query -> PQ.Result -> IO [r]
377finishQuery conn q result = do
378 status <- PQ.resultStatus result
379 case status of
380 PQ.EmptyQuery -> fail "empty query" -- FIXME: error message
381 PQ.CommandOk -> do
382 throwIO $ QueryError "query resulted in a command response" q
383 PQ.TuplesOk -> do
384 ncols <- PQ.nfields result
385 fields <- forM' 0 (ncols-1) $ \column -> do
386 type_oid <- PQ.ftype result column
387 typename <- getTypename conn type_oid
388 return Field{..}
389 nrows <- PQ.ntuples result
390 forM' 0 (nrows-1) $ \row -> do
391 values <- forM' 0 (ncols-1) (\col -> PQ.getvalue' result row col)
392 case convertResults fields values of
393 Left err -> throwIO err
394 Right a -> return a
395 PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
396 PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
397 _ -> do
398 errormsg <- maybe "" id <$> PQ.resultErrorMessage result
399 statusmsg <- PQ.resStatus status
400 state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
401 throw $ SqlError { sqlState = state
402 , sqlNativeError = 0 -- FIXME
403 , sqlErrorMsg = B.concat [ "execute: ", statusmsg
404 , ": ", errormsg ]}
406{--
407withResult (Base.storeResult conn) q $ \r fs -> do
408 status <-
409/ flip fix [] $ \loop acc -> do
410 row <- Base.fetchRow r
411 case row of
412 [] -> return (reverse acc)
413 _ -> let !c = convertResults fs row
414 in loop (c:acc)
415--}
416{--
417finishFold :: (QueryResults r) =>
418 Connection -> Query -> a -> (a -> r -> IO a) -> IO a
419finishFold conn q z0 f = withResult (Base.useResult conn) q $ \r fs ->
420 flip fix z0 $ \loop z -> do
421 row <- Base.fetchRow r
422 case row of
423 [] -> return z
424 _ -> (f z $! convertResults fs row) >>= loop
425--}
426{--
427withResult :: (IO Result) -> Query -> (Result -> [Field] -> IO a) -> IO a
428withResult fetchResult q act = bracket fetchResult Base.freeResult $ \r -> do
429 ncols <- Base.fieldCount (Right r)
430 if ncols == 0
431 then throwIO $ QueryError "query resulted in zero-column result" q
432 else act r =<< Base.fetchFields r
433--}
434-- | Execute an action inside a SQL transaction.
435--
436-- This function initiates a transaction with a \"@begin
437-- transaction@\" statement, then executes the supplied action. If
438-- the action succeeds, the transaction will be completed with
439-- 'Base.commit' before this function returns.
440--
441-- If the action throws /any/ kind of exception (not just a
442-- PostgreSQL-related exception), the transaction will be rolled back using
443-- 'rollback', then the exception will be rethrown.
444withTransaction :: Connection -> IO a -> IO a
445withTransaction conn act = do
446 _ <- begin conn
447 r <- act `onException` rollback conn
448 commit conn
449 return r
451-- | Rollback a transaction.
452-- rollback :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
453rollback :: Connection -> IO ()
454rollback conn = do
455 _ <- execute_ conn "ABORT"
456 return ()
458-- | Commit a transaction.
459-- commit :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
460commit :: Connection -> IO ()
461commit conn = do
462 _ <- execute_ conn "COMMIT"
463 return ()
465-- | Begin a transaction.
466-- begin :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
467begin :: Connection -> IO ()
468begin conn = do
469 _ <- execute_ conn "BEGIN"
470 return ()
472fmtError :: String -> Query -> [Action] -> a
473fmtError msg q xs = throw FormatError {
474 fmtMessage = msg
475 , fmtQuery = q
476 , fmtParams = map twiddle xs
477 }
478 where twiddle (Plain b) = toByteString b
479 twiddle (Escape s) = s
480 twiddle (Many ys) = B.concat (map twiddle ys)
482-- $use
483--
484-- SQL-based applications are somewhat notorious for their
485-- susceptibility to attacks through the injection of maliciously
486-- crafted data. The primary reason for widespread vulnerability to
487-- SQL injections is that many applications are sloppy in handling
488-- user data when constructing SQL queries.
489--
490-- This library provides a 'Query' type and a parameter substitution
491-- facility to address both ease of use and security.
493-- $querytype
494--
495-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
496-- exposes a tiny API that is not compatible with the 'ByteString'
497-- API; this makes it difficult to construct queries from fragments of
498-- strings. The 'query' and 'execute' functions require queries to be
499-- of type 'Query'.
500--
501-- To most easily construct a query, enable GHC's @OverloadedStrings@
502-- language extension and write your query as a normal literal string.
503--
504-- > {-# LANGUAGE OverloadedStrings #-}
505-- >
506-- > import Database.PostgreSQL.Simple
507-- >
508-- > hello = do
509-- > conn <- connect defaultConnectInfo
510-- > query conn "select 2 + 2"
511--
512-- A 'Query' value does not represent the actual query that will be
513-- executed, but is a template for constructing the final query.
515-- $subst
516--
517-- Since applications need to be able to construct queries with
518-- parameters that change, this library provides a query substitution
519-- capability.
520--
521-- The 'Query' template accepted by 'query' and 'execute' can contain
522-- any number of \"@?@\" characters. Both 'query' and 'execute'
523-- accept a third argument, typically a tuple. When constructing the
524-- real query to execute, these functions replace the first \"@?@\" in
525-- the template with the first element of the tuple, the second
526-- \"@?@\" with the second element, and so on. If necessary, each
527-- tuple element will be quoted and escaped prior to substitution;
528-- this defeats the single most common injection vector for malicious
529-- data.
530--
531-- For example, given the following 'Query' template:
532--
533-- > select * from user where first_name = ? and age > ?
534--
535-- And a tuple of this form:
536--
537-- > ("Boris" :: String, 37 :: Int)
538--
539-- The query to be executed will look like this after substitution:
540--
541-- > select * from user where first_name = 'Boris' and age > 37
542--
543-- If there is a mismatch between the number of \"@?@\" characters in
544-- your template and the number of elements in your tuple, a
545-- 'FormatError' will be thrown.
546--
547-- Note that the substitution functions do not attempt to parse or
548-- validate your query. It's up to you to write syntactically valid
549-- SQL, and to ensure that each \"@?@\" in your query template is
550-- matched with the right tuple element.
552-- $inference
553--
554-- Automated type inference means that you will often be able to avoid
555-- supplying explicit type signatures for the elements of a tuple.
556-- However, sometimes the compiler will not be able to infer your
557-- types. Consider a care where you write a numeric literal in a
558-- parameter tuple:
559--
560-- > query conn "select ? + ?" (40,2)
561--
562-- The above query will be rejected by the compiler, because it does
563-- not know the specific numeric types of the literals @40@ and @2@.
564-- This is easily fixed:
565--
566-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
567--
568-- The same kind of problem can arise with string literals if you have
569-- the @OverloadedStrings@ language extension enabled. Again, just
570-- use an explicit type signature if this happens.
572-- $only_param
573--
574-- Haskell lacks a single-element tuple type, so if you have just one
575-- value you want substituted into a query, what should you do?
576--
577-- The obvious approach would appear to be something like this:
578--
579-- > instance (Param a) => QueryParam a where
580-- > ...
581--
582-- Unfortunately, this wreaks havoc with type inference, so we take a
583-- different tack. To represent a single value @val@ as a parameter, write
584-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
585--
586-- Here's an example using a singleton list:
587--
588-- > execute conn "insert into users (first_name) values (?)"
589-- > ["Nuala"]
591-- $in
592--
593-- Suppose you want to write a query using an @IN@ clause:
594--
595-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
596--
597-- In such cases, it's common for both the elements and length of the
598-- list after the @IN@ keyword to vary from query to query.
599--
600-- To address this case, use the 'In' type wrapper, and use a single
601-- \"@?@\" character to represent the list. Omit the parentheses
602-- around the list; these will be added for you.
603--
604-- Here's an example:
605--
606-- > query conn "select * from users where first_name in ?" $
607-- > In ["Anna", "Boris", "Carla"]
608--
609-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
610-- substituted instead, to ensure that your clause remains
611-- syntactically valid.
613-- $many
614--
615-- If you know that you have many rows of data to insert into a table,
616-- it is much more efficient to perform all the insertions in a single
617-- multi-row @INSERT@ statement than individually.
618--
619-- The 'executeMany' function is intended specifically for helping
620-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
621-- query substitution are different than those for 'execute'.
622--
623-- What 'executeMany' searches for in your 'Query' template is a
624-- single substring of the form:
625--
626-- > values (?,?,?)
627--
628-- The rules are as follows:
629--
630-- * The keyword @VALUES@ is matched case insensitively.
631--
632-- * There must be no other \"@?@\" characters anywhere in your
633-- template.
634--
635-- * There must one or more \"@?@\" in the parentheses.
636--
637-- * Extra white space is fine.
638--
639-- The last argument to 'executeMany' is a list of parameter
640-- tuples. These will be substituted into the query where the @(?,?)@
641-- string appears, in a form suitable for use in a multi-row @INSERT@
642-- or @UPDATE@.
643--
644-- Here is an example:
645--
646-- > executeMany conn
647-- > "insert into users (first_name,last_name) values (?,?)"
648-- > [("Boris","Karloff"),("Ed","Wood")]
649--
650-- The query that will be executed here will look like this
651-- (reformatted for tidiness):
652--
653-- > insert into users (first_name,last_name) values
654-- > ('Boris','Karloff'),('Ed','Wood')
656-- $result
657--
658-- The 'query' and 'query_' functions return a list of values in the
659-- 'QueryResults' typeclass. This class performs automatic extraction
660-- and type conversion of rows from a query result.
661--
662-- Here is a simple example of how to extract results:
663--
664-- > import qualified Data.Text as Text
665-- >
666-- > xs <- query_ conn "select name,age from users"
667-- > forM_ xs $ \(name,age) ->
668-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
669--
670-- Notice two important details about this code:
671--
672-- * The number of columns we ask for in the query template must
673-- exactly match the number of elements we specify in a row of the
674-- result tuple. If they do not match, a 'ResultError' exception
675-- will be thrown.
676--
677-- * Sometimes, the compiler needs our help in specifying types. It
678-- can infer that @name@ must be a 'Text', due to our use of the
679-- @unpack@ function. However, we have to tell it the type of @age@,
680-- as it has no other information to determine the exact type.
682-- $null
683--
684-- The type of a result tuple will look something like this:
685--
686-- > (Text, Int, Int)
687--
688-- Although SQL can accommodate @NULL@ as a value for any of these
689-- types, Haskell cannot. If your result contains columns that may be
690-- @NULL@, be sure that you use 'Maybe' in those positions of of your
691-- tuple.
692--
693-- > (Text, Maybe Int, Int)
694--
695-- If 'query' encounters a @NULL@ in a row where the corresponding
696-- Haskell type is not 'Maybe', it will throw a 'ResultError'
697-- exception.
699-- $only_result
700--
701-- To specify that a query returns a single-column result, use the
702-- 'Only' type.
703--
704-- > xs <- query_ conn "select id from users"
705-- > forM_ xs $ \(Only dbid) -> {- ... -}
707-- $types
708--
709-- Conversion of SQL values to Haskell values is somewhat
710-- permissive. Here are the rules.
711--
712-- * For numeric types, any Haskell type that can accurately represent
713-- all values of the given PostgreSQL type is considered \"compatible\".
714-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
715-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
716-- represent a @SMALLINT@, so it is considered compatble with those types.
717--
718-- * A numeric compatibility check is based only on the type of a
719-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
720-- @BIGINT@ column will be considered incompatible with a Haskell
721-- 'Int16', even if it contains the value @1@.
722--
723-- * If a numeric incompatibility is found, 'query' will throw a
724-- 'ResultError'.
725--
726-- * The 'String' and 'Text' types are assumed to be encoded as
727-- UTF-8. If you use some other encoding, decoding may fail or give
728-- wrong results. In such cases, write a @newtype@ wrapper and a
729-- custom 'Result' instance to handle your encoding.
731getTypename :: Connection -> PQ.Oid -> IO ByteString
732getTypename conn@Connection{..} oid =
733 case oid2builtin oid of
734 Just builtin -> return $! builtin2typname builtin
735 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
736 case IntMap.lookup (oid2int oid) oidmap of
737 Just name -> return (oidmap, name)
738 Nothing -> do
739 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
740 (Only oid)
741 name <- case names of
742 [] -> return $ throw SqlError {
743 sqlNativeError = -1,
744 sqlErrorMsg = "invalid type oid",
745 sqlState = ""
746 }
747 [Only x] -> return x
748 _ -> fail "typename query returned more than one result"
749 -- oid is a primary key, so the query should
750 -- never return more than one result
751 return (IntMap.insert (oid2int oid) name oidmap, name)