git.iko.soy/typeable/postgresql-simple
on 4e912e3 help sign in
750 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 , 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{--
72 -- * Queries that stream results
73 , fold
74 , fold_
75 , forEach
76 , forEach_
77--}
78 -- * Statements that do not return results
79 , execute
80 , execute_
81 , executeMany
82-- , Base.insertID
83 -- * Transaction handling
84 , withTransaction
85-- , Base.autocommit
86 , begin
87 , commit
88 , rollback
89 -- * Helper functions
90 , formatMany
91 , formatQuery
92 ) where
94import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
95import Blaze.ByteString.Builder.Char8 (fromChar)
96import Control.Applicative ((<$>), pure)
97import Control.Concurrent.MVar
98import Control.Exception (Exception, bracket, onException, throw, throwIO)
99import Control.Monad (forM)
100import Control.Monad.Fix (fix)
101import Data.ByteString (ByteString)
102-- import qualified Data.ByteString as B (unpack)
103import Data.Char(ord)
104import Data.Int (Int64)
105import qualified Data.IntMap as IntMap
106import Data.List (intersperse)
107import Data.Monoid (mappend, mconcat)
108import Data.Typeable (Typeable)
109--import Database.MySQL.Base (Connection, Result)
110--import Database.MySQL.Base.Types (Field)
111import Database.PostgreSQL.Simple.BuiltinTypes (oid2builtin, builtin2typname)
112import Database.PostgreSQL.Simple.Param (Action(..), inQuotes)
113import Database.PostgreSQL.Simple.QueryParams (QueryParams(..))
114import Database.PostgreSQL.Simple.Result (ResultError(..))
115import Database.PostgreSQL.Simple.QueryResults (QueryResults(..))
116-- import Database.PostgreSQL.Simple.Result (ResultError(..))
117import Database.PostgreSQL.Simple.Types (Binary(..), In(..), Only(..), Query(..))
118import Database.PostgreSQL.Simple.Internal as Base
119import qualified Database.PostgreSQL.LibPQ as PQ
120import Text.Regex.PCRE.Light (compile, caseless, match)
121import qualified Data.ByteString.Char8 as B
122--import qualified Database.MySQL.Base as Base
124-- | Exception thrown if a 'Query' could not be formatted correctly.
125-- This may occur if the number of \'@?@\' characters in the query
126-- string does not match the number of parameters provided.
127data FormatError = FormatError {
128 fmtMessage :: String
129 , fmtQuery :: Query
130 , fmtParams :: [ByteString]
131 } deriving (Eq, Show, Typeable)
133instance Exception FormatError
135-- | Exception thrown if 'query' is used to perform an @INSERT@-like
136-- operation, or 'execute' is used to perform a @SELECT@-like operation.
137data QueryError = QueryError {
138 qeMessage :: String
139 , qeQuery :: Query
140 } deriving (Eq, Show, Typeable)
142instance Exception QueryError
144-- | Format a query string.
145--
146-- This function is exposed to help with debugging and logging. Do not
147-- use it to prepare queries for execution.
148--
149-- String parameters are escaped according to the character set in use
150-- on the 'Connection'.
151--
152-- Throws 'FormatError' if the query string could not be formatted
153-- correctly.
154formatQuery :: QueryParams q => Connection -> Query -> q -> IO ByteString
155formatQuery conn q@(Query template) qs
156 | null xs && '?' `B.notElem` template = return template
157 | otherwise = toByteString <$> buildQuery conn q template xs
158 where xs = renderParams qs
160-- | Format a query string with a variable number of rows.
161--
162-- This function is exposed to help with debugging and logging. Do not
163-- use it to prepare queries for execution.
164--
165-- The query string must contain exactly one substitution group,
166-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
167-- followed by an \"@(@\" character, a series of one or more \"@?@\"
168-- characters separated by commas, and a \"@)@\" character. White
169-- space in a substitution group is permitted.
170--
171-- Throws 'FormatError' if the query string could not be formatted
172-- correctly.
173formatMany :: (QueryParams q) => Connection -> Query -> [q] -> IO ByteString
174formatMany _ q [] = fmtError "no rows supplied" q []
175formatMany conn q@(Query template) qs = do
176 case match re template [] of
177 Just [_,before,qbits,after] -> do
178 bs <- mapM (buildQuery conn q qbits . renderParams) qs
179 return . toByteString . mconcat $ fromByteString before :
180 intersperse (fromChar ',') bs ++
181 [fromByteString after]
182 _ -> error "foo"
183 where
184 re = compile "^([^?]+\\bvalues\\s*)\
185 \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
186 \([^?]*)$"
187 [caseless]
189escapeStringConn conn s = withConnection conn $ \c -> do
190 PQ.escapeStringConn c s
192buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
193buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
194 where quote = inQuotes . fromByteString . maybe undefined id
195 sub (Plain b) = pure b
196 sub (Escape s) = quote <$> escapeStringConn conn s
197 sub (Many ys) = mconcat <$> mapM sub ys
198 split s = fromByteString h : if B.null t then [] else split (B.tail t)
199 where (h,t) = B.break (=='?') s
200 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
201 zipParams [t] [] = t
202 zipParams _ _ = fmtError (show (B.count '?' template) ++
203 " '?' characters, but " ++
204 show (length xs) ++ " parameters") q xs
206-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
207-- expected to return results.
208--
209-- Returns the number of rows affected.
210--
211-- Throws 'FormatError' if the query could not be formatted correctly.
212execute :: (QueryParams q) => Connection -> Query -> q -> IO Int64
213execute conn template qs = do
214 result <- exec conn =<< formatQuery conn template qs
215 finishExecute conn template result
217-- | A version of 'execute' that does not perform query substitution.
218execute_ :: Connection -> Query -> IO Int64
219execute_ conn q@(Query stmt) = do
220 result <- exec conn stmt
221 finishExecute conn q result
223-- | Execute a multi-row @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.
229executeMany :: (QueryParams q) => Connection -> Query -> [q] -> IO Int64
230executeMany _ _ [] = return 0
231executeMany conn q qs = do
232 result <- exec conn =<< formatMany conn q qs
233 finishExecute conn q result
235finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
236finishExecute conn q result = do
237 status <- PQ.resultStatus result
238 case status of
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 throwIO $ SqlError { sqlState = state
260 , sqlNativeError = fromEnum status
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.CommandOk -> do
381 throwIO $ QueryError "query resulted in a command response" q
382 PQ.TuplesOk -> do
383 ncols <- PQ.nfields result
384 fields <- forM' 0 (ncols-1) $ \column -> do
385 type_oid <- PQ.ftype result column
386 typename <- getTypename conn type_oid
387 return Field{..}
388 nrows <- PQ.ntuples result
389 forM' 0 (nrows-1) $ \row -> do
390 values <- forM' 0 (ncols-1) (\col -> PQ.getvalue' result row col)
391 case convertResults fields values of
392 Left err -> throwIO err
393 Right a -> return a
394 PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
395 PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
396 _ -> do
397 errormsg <- maybe "" id <$> PQ.resultErrorMessage result
398 statusmsg <- PQ.resStatus status
399 state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
400 throwIO $ SqlError { sqlState = state
401 , sqlNativeError = fromEnum status
402 , sqlErrorMsg = B.concat [ "query: ", statusmsg
403 , ": ", errormsg ]}
405{--
406withResult (Base.storeResult conn) q $ \r fs -> do
407 status <-
408/ flip fix [] $ \loop acc -> do
409 row <- Base.fetchRow r
410 case row of
411 [] -> return (reverse acc)
412 _ -> let !c = convertResults fs row
413 in loop (c:acc)
414--}
415{--
416finishFold :: (QueryResults r) =>
417 Connection -> Query -> a -> (a -> r -> IO a) -> IO a
418finishFold conn q z0 f = withResult (Base.useResult conn) q $ \r fs ->
419 flip fix z0 $ \loop z -> do
420 row <- Base.fetchRow r
421 case row of
422 [] -> return z
423 _ -> (f z $! convertResults fs row) >>= loop
424--}
425{--
426withResult :: (IO Result) -> Query -> (Result -> [Field] -> IO a) -> IO a
427withResult fetchResult q act = bracket fetchResult Base.freeResult $ \r -> do
428 ncols <- Base.fieldCount (Right r)
429 if ncols == 0
430 then throwIO $ QueryError "query resulted in zero-column result" q
431 else act r =<< Base.fetchFields r
432--}
433-- | Execute an action inside a SQL transaction.
434--
435-- This function initiates a transaction with a \"@begin
436-- transaction@\" statement, then executes the supplied action. If
437-- the action succeeds, the transaction will be completed with
438-- 'Base.commit' before this function returns.
439--
440-- If the action throws /any/ kind of exception (not just a
441-- PostgreSQL-related exception), the transaction will be rolled back using
442-- 'rollback', then the exception will be rethrown.
443withTransaction :: Connection -> IO a -> IO a
444withTransaction conn act = do
445 _ <- begin conn
446 r <- act `onException` rollback conn
447 commit conn
448 return r
450-- | Rollback a transaction.
451-- rollback :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
452rollback :: Connection -> IO ()
453rollback conn = do
454 _ <- execute_ conn "ABORT"
455 return ()
457-- | Commit a transaction.
458-- commit :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
459commit :: Connection -> IO ()
460commit conn = do
461 _ <- execute_ conn "COMMIT"
462 return ()
464-- | Begin a transaction.
465-- begin :: (MonadCatchIO m,MonadIO m) => Connection -> m ()
466begin :: Connection -> IO ()
467begin conn = do
468 _ <- execute_ conn "BEGIN"
469 return ()
471fmtError :: String -> Query -> [Action] -> a
472fmtError msg q xs = throw FormatError {
473 fmtMessage = msg
474 , fmtQuery = q
475 , fmtParams = map twiddle xs
476 }
477 where twiddle (Plain b) = toByteString b
478 twiddle (Escape s) = s
479 twiddle (Many ys) = B.concat (map twiddle ys)
481-- $use
482--
483-- SQL-based applications are somewhat notorious for their
484-- susceptibility to attacks through the injection of maliciously
485-- crafted data. The primary reason for widespread vulnerability to
486-- SQL injections is that many applications are sloppy in handling
487-- user data when constructing SQL queries.
488--
489-- This library provides a 'Query' type and a parameter substitution
490-- facility to address both ease of use and security.
492-- $querytype
493--
494-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
495-- exposes a tiny API that is not compatible with the 'ByteString'
496-- API; this makes it difficult to construct queries from fragments of
497-- strings. The 'query' and 'execute' functions require queries to be
498-- of type 'Query'.
499--
500-- To most easily construct a query, enable GHC's @OverloadedStrings@
501-- language extension and write your query as a normal literal string.
502--
503-- > {-# LANGUAGE OverloadedStrings #-}
504-- >
505-- > import Database.PostgreSQL.Simple
506-- >
507-- > hello = do
508-- > conn <- connect defaultConnectInfo
509-- > query conn "select 2 + 2"
510--
511-- A 'Query' value does not represent the actual query that will be
512-- executed, but is a template for constructing the final query.
514-- $subst
515--
516-- Since applications need to be able to construct queries with
517-- parameters that change, this library provides a query substitution
518-- capability.
519--
520-- The 'Query' template accepted by 'query' and 'execute' can contain
521-- any number of \"@?@\" characters. Both 'query' and 'execute'
522-- accept a third argument, typically a tuple. When constructing the
523-- real query to execute, these functions replace the first \"@?@\" in
524-- the template with the first element of the tuple, the second
525-- \"@?@\" with the second element, and so on. If necessary, each
526-- tuple element will be quoted and escaped prior to substitution;
527-- this defeats the single most common injection vector for malicious
528-- data.
529--
530-- For example, given the following 'Query' template:
531--
532-- > select * from user where first_name = ? and age > ?
533--
534-- And a tuple of this form:
535--
536-- > ("Boris" :: String, 37 :: Int)
537--
538-- The query to be executed will look like this after substitution:
539--
540-- > select * from user where first_name = 'Boris' and age > 37
541--
542-- If there is a mismatch between the number of \"@?@\" characters in
543-- your template and the number of elements in your tuple, a
544-- 'FormatError' will be thrown.
545--
546-- Note that the substitution functions do not attempt to parse or
547-- validate your query. It's up to you to write syntactically valid
548-- SQL, and to ensure that each \"@?@\" in your query template is
549-- matched with the right tuple element.
551-- $inference
552--
553-- Automated type inference means that you will often be able to avoid
554-- supplying explicit type signatures for the elements of a tuple.
555-- However, sometimes the compiler will not be able to infer your
556-- types. Consider a care where you write a numeric literal in a
557-- parameter tuple:
558--
559-- > query conn "select ? + ?" (40,2)
560--
561-- The above query will be rejected by the compiler, because it does
562-- not know the specific numeric types of the literals @40@ and @2@.
563-- This is easily fixed:
564--
565-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
566--
567-- The same kind of problem can arise with string literals if you have
568-- the @OverloadedStrings@ language extension enabled. Again, just
569-- use an explicit type signature if this happens.
571-- $only_param
572--
573-- Haskell lacks a single-element tuple type, so if you have just one
574-- value you want substituted into a query, what should you do?
575--
576-- The obvious approach would appear to be something like this:
577--
578-- > instance (Param a) => QueryParam a where
579-- > ...
580--
581-- Unfortunately, this wreaks havoc with type inference, so we take a
582-- different tack. To represent a single value @val@ as a parameter, write
583-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
584--
585-- Here's an example using a singleton list:
586--
587-- > execute conn "insert into users (first_name) values (?)"
588-- > ["Nuala"]
590-- $in
591--
592-- Suppose you want to write a query using an @IN@ clause:
593--
594-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
595--
596-- In such cases, it's common for both the elements and length of the
597-- list after the @IN@ keyword to vary from query to query.
598--
599-- To address this case, use the 'In' type wrapper, and use a single
600-- \"@?@\" character to represent the list. Omit the parentheses
601-- around the list; these will be added for you.
602--
603-- Here's an example:
604--
605-- > query conn "select * from users where first_name in ?" $
606-- > In ["Anna", "Boris", "Carla"]
607--
608-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
609-- substituted instead, to ensure that your clause remains
610-- syntactically valid.
612-- $many
613--
614-- If you know that you have many rows of data to insert into a table,
615-- it is much more efficient to perform all the insertions in a single
616-- multi-row @INSERT@ statement than individually.
617--
618-- The 'executeMany' function is intended specifically for helping
619-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
620-- query substitution are different than those for 'execute'.
621--
622-- What 'executeMany' searches for in your 'Query' template is a
623-- single substring of the form:
624--
625-- > values (?,?,?)
626--
627-- The rules are as follows:
628--
629-- * The keyword @VALUES@ is matched case insensitively.
630--
631-- * There must be no other \"@?@\" characters anywhere in your
632-- template.
633--
634-- * There must one or more \"@?@\" in the parentheses.
635--
636-- * Extra white space is fine.
637--
638-- The last argument to 'executeMany' is a list of parameter
639-- tuples. These will be substituted into the query where the @(?,?)@
640-- string appears, in a form suitable for use in a multi-row @INSERT@
641-- or @UPDATE@.
642--
643-- Here is an example:
644--
645-- > executeMany conn
646-- > "insert into users (first_name,last_name) values (?,?)"
647-- > [("Boris","Karloff"),("Ed","Wood")]
648--
649-- The query that will be executed here will look like this
650-- (reformatted for tidiness):
651--
652-- > insert into users (first_name,last_name) values
653-- > ('Boris','Karloff'),('Ed','Wood')
655-- $result
656--
657-- The 'query' and 'query_' functions return a list of values in the
658-- 'QueryResults' typeclass. This class performs automatic extraction
659-- and type conversion of rows from a query result.
660--
661-- Here is a simple example of how to extract results:
662--
663-- > import qualified Data.Text as Text
664-- >
665-- > xs <- query_ conn "select name,age from users"
666-- > forM_ xs $ \(name,age) ->
667-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
668--
669-- Notice two important details about this code:
670--
671-- * The number of columns we ask for in the query template must
672-- exactly match the number of elements we specify in a row of the
673-- result tuple. If they do not match, a 'ResultError' exception
674-- will be thrown.
675--
676-- * Sometimes, the compiler needs our help in specifying types. It
677-- can infer that @name@ must be a 'Text', due to our use of the
678-- @unpack@ function. However, we have to tell it the type of @age@,
679-- as it has no other information to determine the exact type.
681-- $null
682--
683-- The type of a result tuple will look something like this:
684--
685-- > (Text, Int, Int)
686--
687-- Although SQL can accommodate @NULL@ as a value for any of these
688-- types, Haskell cannot. If your result contains columns that may be
689-- @NULL@, be sure that you use 'Maybe' in those positions of of your
690-- tuple.
691--
692-- > (Text, Maybe Int, Int)
693--
694-- If 'query' encounters a @NULL@ in a row where the corresponding
695-- Haskell type is not 'Maybe', it will throw a 'ResultError'
696-- exception.
698-- $only_result
699--
700-- To specify that a query returns a single-column result, use the
701-- 'Only' type.
702--
703-- > xs <- query_ conn "select id from users"
704-- > forM_ xs $ \(Only dbid) -> {- ... -}
706-- $types
707--
708-- Conversion of SQL values to Haskell values is somewhat
709-- permissive. Here are the rules.
710--
711-- * For numeric types, any Haskell type that can accurately represent
712-- all values of the given PostgreSQL type is considered \"compatible\".
713-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
714-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
715-- represent a @SMALLINT@, so it is considered compatble with those types.
716--
717-- * A numeric compatibility check is based only on the type of a
718-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
719-- @BIGINT@ column will be considered incompatible with a Haskell
720-- 'Int16', even if it contains the value @1@.
721--
722-- * If a numeric incompatibility is found, 'query' will throw a
723-- 'ResultError'.
724--
725-- * The 'String' and 'Text' types are assumed to be encoded as
726-- UTF-8. If you use some other encoding, decoding may fail or give
727-- wrong results. In such cases, write a @newtype@ wrapper and a
728-- custom 'Result' instance to handle your encoding.
730getTypename :: Connection -> PQ.Oid -> IO ByteString
731getTypename conn@Connection{..} oid =
732 case oid2builtin oid of
733 Just builtin -> return $! builtin2typname builtin
734 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
735 case IntMap.lookup (oid2int oid) oidmap of
736 Just name -> return (oidmap, name)
737 Nothing -> do
738 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
739 (Only oid)
740 name <- case names of
741 [] -> return $ throw SqlError {
742 sqlNativeError = -1,
743 sqlErrorMsg = "invalid type oid",
744 sqlState = ""
745 }
746 [Only x] -> return x
747 _ -> fail "typename query returned more than one result"
748 -- oid is a primary key, so the query should
749 -- never return more than one result
750 return (IntMap.insert (oid2int oid) name oidmap, name)