1{-# LANGUAGE DeriveDataTypeable, RecordWildCards, NamedFieldPuns #-}
3------------------------------------------------------------------------------
5-- Module: Database.PostgreSQL.Simple
6-- Copyright: (c) 2011 MailRank, Inc.
7-- (c) 2011 Leon P Smith
9-- Maintainer: Leon P Smith <leon@melding-monads.com>
10-- Stability: experimental
11-- Portability: portable
13-- A mid-level client library for the PostgreSQL database, aimed at ease of
14-- use and high performance.
16------------------------------------------------------------------------------
18module Database.PostgreSQL.Simple
26 -- ** Parameter substitution
32 -- ** Substituting a single parameter
35 -- ** Representing a list of values
38 -- ** Modifying multiple rows at once
41 -- * Extracting results
44 -- ** Handling null values
47 -- ** Type conversions
60 , FormatError(fmtMessage, fmtQuery, fmtParams)
61 , QueryError(qeMessage, qeQuery)
62 , ResultError(errSQLType, errHaskellType, errMessage)
63 -- * Connection management
65 , Base.connectPostgreSQL
66 , Base.postgreSQLConnectionString
67 , Base.defaultConnectInfo
69 -- * Queries that return results
72 -- * Queries that stream results
82 -- * Statements that do not return results
87 -- * Transaction handling
92 , defaultTransactionMode
93 , defaultIsolationLevel
94 , defaultReadWriteMode
95 , withTransactionLevel
103 -- * Helper functions
108import Blaze.ByteString.Builder
109 ( Builder, fromByteString, toByteString )
110import Blaze.ByteString.Builder.Char8 (fromChar)
111import Control.Applicative ((<$>), pure)
112import Control.Concurrent.MVar
113import Control.Exception
114 ( Exception, onException, throw, throwIO, finally )
115import Control.Monad (foldM)
116import Data.ByteString (ByteString)
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.ToField (Action(..), inQuotes)
129import Database.PostgreSQL.Simple.ToRow (ToRow(..))
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.Text as T
137import qualified Data.Text.Encoding as TE
138import qualified Data.Vector as V
139import Control.Monad.Trans.Reader
140import Control.Monad.Trans.State.Strict
142-- | Exception thrown if a 'Query' could not be formatted correctly.
143-- This may occur if the number of \'@?@\' characters in the query
144-- string does not match the number of parameters provided.
145data FormatError = FormatError {
148 , fmtParams :: [ByteString]
149 } deriving (Eq, Show, Typeable)
151instance Exception FormatError
153-- | Format a query string.
155-- This function is exposed to help with debugging and logging. Do not
156-- use it to prepare queries for execution.
158-- String parameters are escaped according to the character set in use
159-- on the 'Connection'.
161-- Throws 'FormatError' if the query string could not be formatted
163formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
164formatQuery conn q@(Query template) qs
165 | null xs && '?' `B.notElem` template = return template
166 | otherwise = toByteString <$> buildQuery conn q template xs
169-- | Format a query string with a variable number of rows.
171-- This function is exposed to help with debugging and logging. Do not
172-- use it to prepare queries for execution.
174-- The query string must contain exactly one substitution group,
175-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
176-- followed by an \"@(@\" character, a series of one or more \"@?@\"
177-- characters separated by commas, and a \"@)@\" character. White
178-- space in a substitution group is permitted.
180-- Throws 'FormatError' if the query string could not be formatted
182formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
183formatMany _ q [] = fmtError "no rows supplied" q []
184formatMany conn q@(Query template) qs = do
185 case match re template [] of
186 Just [_,before,qbits,after] -> do
187 bs <- mapM (buildQuery conn q qbits . toRow) qs
188 return . toByteString . mconcat $ fromByteString before :
189 intersperse (fromChar ',') bs ++
190 [fromByteString after]
193 re = compile "^([^?]+\\bvalues\\s*)\
194 \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
198escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
199escapeStringConn conn s =
200 withConnection conn $ \c ->
201 PQ.escapeStringConn c s >>= checkError c
203escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
204escapeByteaConn conn s =
205 withConnection conn $ \c ->
206 PQ.escapeByteaConn c s >>= checkError c
208checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
209checkError _ (Just x) = return $ Right x
210checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
212buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
213buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
214 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
215 (inQuotes . fromByteString)
216 utf8ToString = T.unpack . TE.decodeUtf8
217 sub (Plain b) = pure b
218 sub (Escape s) = quote <$> escapeStringConn conn s
219 sub (EscapeBytea s) = quote <$> escapeByteaConn conn s
220 sub (Many ys) = mconcat <$> mapM sub ys
221 split s = fromByteString h : if B.null t then [] else split (B.tail t)
222 where (h,t) = B.break (=='?') s
223 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
225 zipParams _ _ = fmtError (show (B.count '?' template) ++
226 " '?' characters, but " ++
227 show (length xs) ++ " parameters") q xs
229-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
230-- expected to return results.
232-- Returns the number of rows affected.
234-- Throws 'FormatError' if the query could not be formatted correctly.
235execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
236execute conn template qs = do
237 result <- exec conn =<< formatQuery conn template qs
238 finishExecute conn template result
240-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
241-- expected to return results.
243-- Returns the number of rows affected.
245-- Throws 'FormatError' if the query could not be formatted correctly.
246executeMany :: (ToRow 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
252-- | Perform a @SELECT@ or other SQL query that is expected to return
253-- results. All results are retrieved and converted before this
256-- When processing large results, this function will consume a lot of
257-- client-side memory. Consider using 'fold' instead.
259-- Exceptions that may be thrown:
261-- * 'FormatError': the query string could not be formatted correctly.
263-- * 'QueryError': the result contains no columns (i.e. you should be
264-- using 'execute' instead of 'query').
266-- * 'ResultError': result conversion failed.
267query :: (ToRow q, FromRow r)
268 => Connection -> Query -> q -> IO [r]
269query conn template qs = do
270 result <- exec conn =<< formatQuery conn template qs
271 finishQuery conn template result
273-- | A version of 'query' that does not perform query substitution.
274query_ :: (FromRow r) => Connection -> Query -> IO [r]
275query_ conn q@(Query que) = do
276 result <- exec conn que
277 finishQuery conn q result
279-- | Perform a @SELECT@ or other SQL query that is expected to return
280-- results. Results are streamed incrementally from the server, and
281-- consumed via a left fold.
283-- When dealing with small results, it may be simpler (and perhaps
284-- faster) to use 'query' instead.
286-- This fold is /not/ strict. The stream consumer is responsible for
287-- forcing the evaluation of its result to avoid space leaks.
289-- Exceptions that may be thrown:
291-- * 'FormatError': the query string could not be formatted correctly.
293-- * 'QueryError': the result contains no columns (i.e. you should be
294-- using 'execute' instead of 'query').
296-- * 'ResultError': result conversion failed.
298fold :: ( FromRow row, ToRow params )
303 -> (a -> row -> IO a)
305fold = foldWithOptions defaultFoldOptions
313 fetchQuantity :: !FetchQuantity,
314 transactionMode :: !TransactionMode
317defaultFoldOptions :: FoldOptions
318defaultFoldOptions = FoldOptions {
319 fetchQuantity = Automatic,
320 transactionMode = TransactionMode ReadCommitted ReadOnly
323foldWithOptions :: ( FromRow row, ToRow params )
329 -> (a -> row -> IO a)
331foldWithOptions opts conn template qs a f = do
332 q <- formatQuery conn template qs
333 doFold opts conn template (Query q) a f
335-- | A version of 'fold' that does not perform query substitution.
336fold_ :: (FromRow r) =>
339 -> a -- ^ Initial state for result consumer.
340 -> (a -> r -> IO a) -- ^ Result consumer.
342fold_ = foldWithOptions_ defaultFoldOptions
345foldWithOptions_ :: (FromRow r) =>
349 -> a -- ^ Initial state for result consumer.
350 -> (a -> r -> IO a) -- ^ Result consumer.
352foldWithOptions_ opts conn query a f = doFold opts conn query query a f
355doFold :: ( FromRow row )
361 -> (a -> row -> IO a)
363doFold FoldOptions{..} conn _template q a f = do
364 stat <- withConnection conn PQ.transactionStatus
366 PQ.TransIdle -> withTransactionMode transactionMode conn go
367 PQ.TransInTrans -> go
368 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
369 -- This _shouldn't_ occur in the current incarnation of
370 -- the library, as we aren't using libpq asynchronously.
371 -- However, it could occur in future incarnations of
372 -- this library or if client code uses the Internal module
373 -- to use raw libpq commands on postgresql-simple connections.
374 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
375 -- This should be turned into a better error message.
376 -- It is probably a bad idea to automatically roll
377 -- back the transaction and start another.
378 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
379 -- Not sure what this means.
382 -- FIXME: what about name clashes with already-declared cursors?
383 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
385 loop a `finally` execute_ conn "CLOSE fold"
387-- FIXME: choose the Automatic chunkSize more intelligently
388-- One possibility is to use the type of the results, although this
389-- still isn't a perfect solution, given that common types (e.g. text)
390-- are of highly variable size.
391-- A refinement of this technique is to pick this number adaptively
392-- as results are read in from the database.
393 chunkSize = case fetchQuantity of
397 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
398 if null rs then return a else foldM f a rs >>= loop
400-- | A version of 'fold' that does not transform a state value.
401forEach :: (ToRow q, FromRow r) =>
403 -> Query -- ^ Query template.
404 -> q -- ^ Query parameters.
405 -> (r -> IO ()) -- ^ Result consumer.
407forEach conn template qs = fold conn template qs () . const
408{-# INLINE forEach #-}
410-- | A version of 'forEach' that does not perform query substitution.
411forEach_ :: (FromRow r) =>
413 -> Query -- ^ Query template.
414 -> (r -> IO ()) -- ^ Result consumer.
416forEach_ conn template = fold_ conn template () . const
417{-# INLINE forEach_ #-}
419forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
420forM' lo hi m = loop hi []
428finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
429finishQuery conn q result = do
430 status <- PQ.resultStatus result
433 throwIO $ QueryError "query: Empty query" q
435 throwIO $ QueryError "query resulted in a command response" q
437 ncols <- PQ.nfields result
438 let unCol (PQ.Col x) = fromIntegral x :: Int
439 typenames <- V.generateM (unCol ncols)
440 (\(PQ.Col . fromIntegral -> col) -> do
441 getTypename conn =<< PQ.ftype result col)
442 nrows <- PQ.ntuples result
443 ncols <- PQ.nfields result
444 forM' 0 (nrows-1) $ \row -> do
445 let rw = Row row typenames result
446 case runStateT (runReaderT (unRP fromRow) rw) 0 of
447 Ok (val,col) | col == ncols -> return val
449 vals <- forM' 0 (ncols-1) $ \c -> do
450 v <- PQ.getvalue result row c
451 return ( typenames V.! unCol c
453 throw (ConversionFailed
454 (show (unCol ncols) ++ " values: " ++ show vals)
455 (show (unCol col) ++ " slots in target type")
456 "mismatch between number of columns to \
457 \convert and number in target type")
458 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
459 Errors [x] -> throwIO x
460 Errors xs -> throwIO $ ManyErrors xs
462 throwIO $ QueryError "query: COPY TO is not supported" q
464 throwIO $ QueryError "query: COPY FROM is not supported" q
465 PQ.BadResponse -> throwResultError "query" result status
466 PQ.NonfatalError -> throwResultError "query" result status
467 PQ.FatalError -> throwResultError "query" result status
469ellipsis :: ByteString -> ByteString
471 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
475-- | Of the four isolation levels defined by the SQL standard,
476-- these are the three levels distinguished by PostgreSQL as of version 9.0.
477-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
478-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
479-- was equivalent to 'Serializable'.
482 = DefaultIsolationLevel -- ^ the isolation level will be taken from
483 -- PostgreSQL's per-connection
484 -- @default_transaction_isolation@ variable,
485 -- which is initialized according to the
486 -- server's config. The default configuration
487 -- is 'ReadCommitted'.
491 deriving (Show, Eq, Ord, Enum, Bounded)
494 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
495 -- PostgreSQL's per-connection
496 -- @default_transaction_read_only@ variable,
497 -- which is initialized according to the
498 -- server's config. The default configuration
502 deriving (Show, Eq, Ord, Enum, Bounded)
504data TransactionMode = TransactionMode {
505 isolationLevel :: !IsolationLevel,
506 readWriteMode :: !ReadWriteMode
507 } deriving (Show, Eq)
509defaultTransactionMode :: TransactionMode
510defaultTransactionMode = TransactionMode
511 defaultIsolationLevel
514defaultIsolationLevel :: IsolationLevel
515defaultIsolationLevel = DefaultIsolationLevel
517defaultReadWriteMode :: ReadWriteMode
518defaultReadWriteMode = DefaultReadWriteMode
520-- | Execute an action inside a SQL transaction.
522-- This function initiates a transaction with a \"@begin
523-- transaction@\" statement, then executes the supplied action. If
524-- the action succeeds, the transaction will be completed with
525-- 'Base.commit' before this function returns.
527-- If the action throws /any/ kind of exception (not just a
528-- PostgreSQL-related exception), the transaction will be rolled back using
529-- 'rollback', then the exception will be rethrown.
530withTransaction :: Connection -> IO a -> IO a
531withTransaction = withTransactionMode defaultTransactionMode
533-- | Execute an action inside a SQL transaction with a given isolation level.
534withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
535withTransactionLevel lvl
536 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
538-- | Execute an action inside a SQL transaction with a given transaction mode.
539withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
540withTransactionMode mode conn act =
541 mask $ \restore -> do
543 r <- restore act `onException` rollback conn
547-- | Rollback a transaction.
548rollback :: Connection -> IO ()
549rollback conn = execute_ conn "ABORT" >> return ()
551-- | Commit a transaction.
552commit :: Connection -> IO ()
553commit conn = execute_ conn "COMMIT" >> return ()
555-- | Begin a transaction.
556begin :: Connection -> IO ()
557begin = beginMode defaultTransactionMode
559-- | Begin a transaction with a given isolation level
560beginLevel :: IsolationLevel -> Connection -> IO ()
561beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
563-- | Begin a transaction with a given transaction mode
564beginMode :: TransactionMode -> Connection -> IO ()
565beginMode mode conn = do
566 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
569 isolevel = case isolationLevel mode of
570 DefaultIsolationLevel -> ""
571 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
572 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
573 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
574 readmode = case readWriteMode mode of
575 DefaultReadWriteMode -> ""
576 ReadWrite -> " READ WRITE"
577 ReadOnly -> " READ ONLY"
579fmtError :: String -> Query -> [Action] -> a
580fmtError msg q xs = throw FormatError {
583 , fmtParams = map twiddle xs
585 where twiddle (Plain b) = toByteString b
586 twiddle (Escape s) = s
587 twiddle (EscapeBytea s) = s
588 twiddle (Many ys) = B.concat (map twiddle ys)
592-- SQL-based applications are somewhat notorious for their
593-- susceptibility to attacks through the injection of maliciously
594-- crafted data. The primary reason for widespread vulnerability to
595-- SQL injections is that many applications are sloppy in handling
596-- user data when constructing SQL queries.
598-- This library provides a 'Query' type and a parameter substitution
599-- facility to address both ease of use and security.
603-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
604-- exposes a tiny API that is not compatible with the 'ByteString'
605-- API; this makes it difficult to construct queries from fragments of
606-- strings. The 'query' and 'execute' functions require queries to be
609-- To most easily construct a query, enable GHC's @OverloadedStrings@
610-- language extension and write your query as a normal literal string.
612-- > {-# LANGUAGE OverloadedStrings #-}
614-- > import Database.PostgreSQL.Simple
617-- > conn <- connect defaultConnectInfo
618-- > query conn "select 2 + 2"
620-- A 'Query' value does not represent the actual query that will be
621-- executed, but is a template for constructing the final query.
625-- Since applications need to be able to construct queries with
626-- parameters that change, this library provides a query substitution
629-- The 'Query' template accepted by 'query' and 'execute' can contain
630-- any number of \"@?@\" characters. Both 'query' and 'execute'
631-- accept a third argument, typically a tuple. When constructing the
632-- real query to execute, these functions replace the first \"@?@\" in
633-- the template with the first element of the tuple, the second
634-- \"@?@\" with the second element, and so on. If necessary, each
635-- tuple element will be quoted and escaped prior to substitution;
636-- this defeats the single most common injection vector for malicious
639-- For example, given the following 'Query' template:
641-- > select * from user where first_name = ? and age > ?
643-- And a tuple of this form:
645-- > ("Boris" :: String, 37 :: Int)
647-- The query to be executed will look like this after substitution:
649-- > select * from user where first_name = 'Boris' and age > 37
651-- If there is a mismatch between the number of \"@?@\" characters in
652-- your template and the number of elements in your tuple, a
653-- 'FormatError' will be thrown.
655-- Note that the substitution functions do not attempt to parse or
656-- validate your query. It's up to you to write syntactically valid
657-- SQL, and to ensure that each \"@?@\" in your query template is
658-- matched with the right tuple element.
662-- Automated type inference means that you will often be able to avoid
663-- supplying explicit type signatures for the elements of a tuple.
664-- However, sometimes the compiler will not be able to infer your
665-- types. Consider a case where you write a numeric literal in a
668-- > query conn "select ? + ?" (40,2)
670-- The above query will be rejected by the compiler, because it does
671-- not know the specific numeric types of the literals @40@ and @2@.
672-- This is easily fixed:
674-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
676-- The same kind of problem can arise with string literals if you have
677-- the @OverloadedStrings@ language extension enabled. Again, just
678-- use an explicit type signature if this happens.
682-- Haskell lacks a single-element tuple type, so if you have just one
683-- value you want substituted into a query, what should you do?
685-- The obvious approach would appear to be something like this:
687-- > instance (Param a) => QueryParam a where
690-- Unfortunately, this wreaks havoc with type inference, so we take a
691-- different tack. To represent a single value @val@ as a parameter, write
692-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
694-- Here's an example using a singleton list:
696-- > execute conn "insert into users (first_name) values (?)"
701-- Suppose you want to write a query using an @IN@ clause:
703-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
705-- In such cases, it's common for both the elements and length of the
706-- list after the @IN@ keyword to vary from query to query.
708-- To address this case, use the 'In' type wrapper, and use a single
709-- \"@?@\" character to represent the list. Omit the parentheses
710-- around the list; these will be added for you.
714-- > query conn "select * from users where first_name in ?" $
715-- > In ["Anna", "Boris", "Carla"]
717-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
718-- substituted instead, to ensure that your clause remains
719-- syntactically valid.
723-- If you know that you have many rows of data to insert into a table,
724-- it is much more efficient to perform all the insertions in a single
725-- multi-row @INSERT@ statement than individually.
727-- The 'executeMany' function is intended specifically for helping
728-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
729-- query substitution are different than those for 'execute'.
731-- What 'executeMany' searches for in your 'Query' template is a
732-- single substring of the form:
736-- The rules are as follows:
738-- * The keyword @VALUES@ is matched case insensitively.
740-- * There must be no other \"@?@\" characters anywhere in your
743-- * There must one or more \"@?@\" in the parentheses.
745-- * Extra white space is fine.
747-- The last argument to 'executeMany' is a list of parameter
748-- tuples. These will be substituted into the query where the @(?,?)@
749-- string appears, in a form suitable for use in a multi-row @INSERT@
752-- Here is an example:
755-- > "insert into users (first_name,last_name) values (?,?)"
756-- > [("Boris","Karloff"),("Ed","Wood")]
758-- The query that will be executed here will look like this
759-- (reformatted for tidiness):
761-- > insert into users (first_name,last_name) values
762-- > ('Boris','Karloff'),('Ed','Wood')
766-- The 'query' and 'query_' functions return a list of values in the
767-- 'FromRow' typeclass. This class performs automatic extraction
768-- and type conversion of rows from a query result.
770-- Here is a simple example of how to extract results:
772-- > import qualified Data.Text as Text
774-- > xs <- query_ conn "select name,age from users"
775-- > forM_ xs $ \(name,age) ->
776-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
778-- Notice two important details about this code:
780-- * The number of columns we ask for in the query template must
781-- exactly match the number of elements we specify in a row of the
782-- result tuple. If they do not match, a 'ResultError' exception
785-- * Sometimes, the compiler needs our help in specifying types. It
786-- can infer that @name@ must be a 'Text', due to our use of the
787-- @unpack@ function. However, we have to tell it the type of @age@,
788-- as it has no other information to determine the exact type.
792-- The type of a result tuple will look something like this:
796-- Although SQL can accommodate @NULL@ as a value for any of these
797-- types, Haskell cannot. If your result contains columns that may be
798-- @NULL@, be sure that you use 'Maybe' in those positions of of your
801-- > (Text, Maybe Int, Int)
803-- If 'query' encounters a @NULL@ in a row where the corresponding
804-- Haskell type is not 'Maybe', it will throw a 'ResultError'
809-- To specify that a query returns a single-column result, use the
812-- > xs <- query_ conn "select id from users"
813-- > forM_ xs $ \(Only dbid) -> {- ... -}
817-- Conversion of SQL values to Haskell values is somewhat
818-- permissive. Here are the rules.
820-- * For numeric types, any Haskell type that can accurately represent
821-- all values of the given PostgreSQL type is considered \"compatible\".
822-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
823-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
824-- represent a @SMALLINT@, so it is considered compatble with those types.
826-- * A numeric compatibility check is based only on the type of a
827-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
828-- @BIGINT@ column will be considered incompatible with a Haskell
829-- 'Int16', even if it contains the value @1@.
831-- * If a numeric incompatibility is found, 'query' will throw a
834-- * The 'String' and 'Text' types are assumed to be encoded as
835-- UTF-8. If you use some other encoding, decoding may fail or give
836-- wrong results. In such cases, write a @newtype@ wrapper and a
837-- custom 'Result' instance to handle your encoding.
839getTypename :: Connection -> PQ.Oid -> IO ByteString
840getTypename conn@Connection{..} oid =
841 case oid2builtin oid of
842 Just builtin -> return $! builtin2typname builtin
843 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
844 case IntMap.lookup (oid2int oid) oidmap of
845 Just name -> return (oidmap, name)
847 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
849 name <- case names of
850 [] -> return $ throw SqlError {
852 sqlErrorMsg = "invalid type oid",
856 _ -> fail "typename query returned more than one result"
857 -- oid is a primary key, so the query should
858 -- never return more than one result
859 return (IntMap.insert (oid2int oid) name oidmap, name)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list