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
59 , FormatError(fmtMessage, fmtQuery, fmtParams)
60 , QueryError(qeMessage, qeQuery)
61 , ResultError(errSQLType, errHaskellType, errMessage)
62 -- * Connection management
64 , Base.connectPostgreSQL
65 , Base.postgreSQLConnectionString
66 , Base.defaultConnectInfo
68 -- * Queries that return results
71 -- * Queries that stream results
81 -- * Statements that do not return results
86 -- * Transaction handling
91 , defaultTransactionMode
92 , defaultIsolationLevel
93 , defaultReadWriteMode
94 , withTransactionLevel
102 -- * Helper functions
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.Int (Int64)
117import qualified Data.IntMap as IntMap
118import Data.List (intersperse)
119import Data.Monoid (mappend, mconcat)
120import Data.Typeable (Typeable)
121import Database.PostgreSQL.Simple.BuiltinTypes
122 ( oid2builtin, builtin2typname )
123import Database.PostgreSQL.Simple.Compat ( mask )
124import Database.PostgreSQL.Simple.FromField (ResultError(..))
125import Database.PostgreSQL.Simple.FromRow (FromRow(..))
126import Database.PostgreSQL.Simple.Ok
127import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
128import Database.PostgreSQL.Simple.ToRow (ToRow(..))
129import Database.PostgreSQL.Simple.Types
130 ( Binary(..), In(..), Only(..), Query(..) )
131import Database.PostgreSQL.Simple.Internal as Base
132import qualified Database.PostgreSQL.LibPQ as PQ
133import Text.Regex.PCRE.Light (compile, caseless, match)
134import qualified Data.ByteString.Char8 as B
135import qualified Data.Text as T
136import qualified Data.Text.Encoding as TE
137import qualified Data.Vector as V
138import Control.Monad.Trans.Reader
139import Control.Monad.Trans.State.Strict
141-- | Exception thrown if a 'Query' could not be formatted correctly.
142-- This may occur if the number of \'@?@\' characters in the query
143-- string does not match the number of parameters provided.
144data FormatError = FormatError {
147 , fmtParams :: [ByteString]
148 } deriving (Eq, Show, Typeable)
150instance Exception FormatError
152-- | Format a query string.
154-- This function is exposed to help with debugging and logging. Do not
155-- use it to prepare queries for execution.
157-- String parameters are escaped according to the character set in use
158-- on the 'Connection'.
160-- Throws 'FormatError' if the query string could not be formatted
162formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
163formatQuery conn q@(Query template) qs
164 | null xs && '?' `B.notElem` template = return template
165 | otherwise = toByteString <$> buildQuery conn q template xs
168-- | Format a query string with a variable number of rows.
170-- This function is exposed to help with debugging and logging. Do not
171-- use it to prepare queries for execution.
173-- The query string must contain exactly one substitution group,
174-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
175-- followed by an \"@(@\" character, a series of one or more \"@?@\"
176-- characters separated by commas, and a \"@)@\" character. White
177-- space in a substitution group is permitted.
179-- Throws 'FormatError' if the query string could not be formatted
181formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
182formatMany _ q [] = fmtError "no rows supplied" q []
183formatMany conn q@(Query template) qs = do
184 case match re template [] of
185 Just [_,before,qbits,after] -> do
186 bs <- mapM (buildQuery conn q qbits . toRow) qs
187 return . toByteString . mconcat $ fromByteString before :
188 intersperse (fromChar ',') bs ++
189 [fromByteString after]
192 re = compile "^([^?]+\\bvalues\\s*)\
193 \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
197escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
198escapeStringConn conn s =
199 withConnection conn $ \c ->
200 PQ.escapeStringConn c s >>= checkError c
202escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
203escapeByteaConn conn s =
204 withConnection conn $ \c ->
205 PQ.escapeByteaConn c s >>= checkError c
207checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
208checkError c (Just x) = return $ Right x
209checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
211buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
212buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
213 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
214 (inQuotes . fromByteString)
215 utf8ToString = T.unpack . TE.decodeUtf8
216 sub (Plain b) = pure b
217 sub (Escape s) = quote <$> escapeStringConn conn s
218 sub (EscapeBytea s) = quote <$> escapeByteaConn conn s
219 sub (Many ys) = mconcat <$> mapM sub ys
220 split s = fromByteString h : if B.null t then [] else split (B.tail t)
221 where (h,t) = B.break (=='?') s
222 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
224 zipParams _ _ = fmtError (show (B.count '?' template) ++
225 " '?' characters, but " ++
226 show (length xs) ++ " parameters") q xs
228-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
229-- expected to return results.
231-- Returns the number of rows affected.
233-- Throws 'FormatError' if the query could not be formatted correctly.
234execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
235execute conn template qs = do
236 result <- exec conn =<< formatQuery conn template qs
237 finishExecute conn template result
239-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
240-- expected to return results.
242-- Returns the number of rows affected.
244-- Throws 'FormatError' if the query could not be formatted correctly.
245executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
246executeMany _ _ [] = return 0
247executeMany conn q qs = do
248 result <- exec conn =<< formatMany conn q qs
249 finishExecute conn q result
251-- | Perform a @SELECT@ or other SQL query that is expected to return
252-- results. All results are retrieved and converted before this
255-- When processing large results, this function will consume a lot of
256-- client-side memory. Consider using 'fold' instead.
258-- Exceptions that may be thrown:
260-- * 'FormatError': the query string could not be formatted correctly.
262-- * 'QueryError': the result contains no columns (i.e. you should be
263-- using 'execute' instead of 'query').
265-- * 'ResultError': result conversion failed.
266query :: (ToRow q, FromRow r)
267 => Connection -> Query -> q -> IO [r]
268query conn template qs = do
269 result <- exec conn =<< formatQuery conn template qs
270 finishQuery conn template result
272-- | A version of 'query' that does not perform query substitution.
273query_ :: (FromRow r) => Connection -> Query -> IO [r]
274query_ conn q@(Query que) = do
275 result <- exec conn que
276 finishQuery conn q result
278-- | Perform a @SELECT@ or other SQL query that is expected to return
279-- results. Results are streamed incrementally from the server, and
280-- consumed via a left fold.
282-- When dealing with small results, it may be simpler (and perhaps
283-- faster) to use 'query' instead.
285-- This fold is /not/ strict. The stream consumer is responsible for
286-- forcing the evaluation of its result to avoid space leaks.
288-- Exceptions that may be thrown:
290-- * 'FormatError': the query string could not be formatted correctly.
292-- * 'QueryError': the result contains no columns (i.e. you should be
293-- using 'execute' instead of 'query').
295-- * 'ResultError': result conversion failed.
297fold :: ( FromRow row, ToRow params )
302 -> (a -> row -> IO a)
304fold = foldWithOptions defaultFoldOptions
312 fetchQuantity :: !FetchQuantity,
313 transactionMode :: !TransactionMode
316defaultFoldOptions :: FoldOptions
317defaultFoldOptions = FoldOptions {
318 fetchQuantity = Automatic,
319 transactionMode = TransactionMode ReadCommitted ReadOnly
322foldWithOptions :: ( FromRow row, ToRow params )
328 -> (a -> row -> IO a)
330foldWithOptions opts conn template qs a f = do
331 q <- formatQuery conn template qs
332 doFold opts conn template (Query q) a f
334-- | A version of 'fold' that does not perform query substitution.
335fold_ :: (FromRow r) =>
338 -> a -- ^ Initial state for result consumer.
339 -> (a -> r -> IO a) -- ^ Result consumer.
341fold_ = foldWithOptions_ defaultFoldOptions
344foldWithOptions_ :: (FromRow r) =>
348 -> a -- ^ Initial state for result consumer.
349 -> (a -> r -> IO a) -- ^ Result consumer.
351foldWithOptions_ opts conn query a f = doFold opts conn query query a f
354doFold :: ( FromRow row )
360 -> (a -> row -> IO a)
362doFold FoldOptions{..} conn _template q a f = do
363 stat <- withConnection conn PQ.transactionStatus
365 PQ.TransIdle -> withTransactionMode transactionMode conn go
366 PQ.TransInTrans -> go
367 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
368 -- This _shouldn't_ occur in the current incarnation of
369 -- the library, as we aren't using libpq asynchronously.
370 -- However, it could occur in future incarnations of
371 -- this library or if client code uses the Internal module
372 -- to use raw libpq commands on postgresql-simple connections.
373 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
374 -- This should be turned into a better error message.
375 -- It is probably a bad idea to automatically roll
376 -- back the transaction and start another.
377 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
378 -- Not sure what this means.
381 -- FIXME: what about name clashes with already-declared cursors?
382 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
384 loop a `finally` execute_ conn "CLOSE fold"
386-- FIXME: choose the Automatic chunkSize more intelligently
387-- One possibility is to use the type of the results, although this
388-- still isn't a perfect solution, given that common types (e.g. text)
389-- are of highly variable size.
390-- A refinement of this technique is to pick this number adaptively
391-- as results are read in from the database.
392 chunkSize = case fetchQuantity of
396 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
397 if null rs then return a else foldM f a rs >>= loop
399-- | A version of 'fold' that does not transform a state value.
400forEach :: (ToRow q, FromRow r) =>
402 -> Query -- ^ Query template.
403 -> q -- ^ Query parameters.
404 -> (r -> IO ()) -- ^ Result consumer.
406forEach conn template qs = fold conn template qs () . const
407{-# INLINE forEach #-}
409-- | A version of 'forEach' that does not perform query substitution.
410forEach_ :: (FromRow r) =>
412 -> Query -- ^ Query template.
413 -> (r -> IO ()) -- ^ Result consumer.
415forEach_ conn template = fold_ conn template () . const
416{-# INLINE forEach_ #-}
418forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
419forM' lo hi m = loop hi []
427finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
428finishQuery conn q result = do
429 status <- PQ.resultStatus result
432 throwIO $ QueryError "query: Empty query" q
434 throwIO $ QueryError "query resulted in a command response" q
436 ncols <- PQ.nfields result
437 let unCol (PQ.Col x) = fromIntegral x :: Int
438 typenames <- V.generateM (unCol ncols)
439 (\(PQ.Col . fromIntegral -> col) -> do
440 getTypename conn =<< PQ.ftype result col)
441 nrows <- PQ.ntuples result
442 ncols <- PQ.nfields result
443 forM' 0 (nrows-1) $ \row -> do
444 let rw = Row row typenames result
445 case runStateT (runReaderT (unRP fromRow) rw) 0 of
446 Ok (val,col) | col == ncols -> return val
448 vals <- forM' 0 (ncols-1) $ \c -> do
449 v <- PQ.getvalue result row c
450 return ( typenames V.! unCol c
452 throw (ConversionFailed
453 (show (unCol ncols) ++ " values: " ++ show vals)
454 (show (unCol col) ++ " slots in target type")
455 "mismatch between number of columns to \
456 \convert and number in target type")
457 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
458 Errors [x] -> throwIO x
459 Errors xs -> throwIO $ ManyErrors xs
461 throwIO $ QueryError "query: COPY TO is not supported" q
463 throwIO $ QueryError "query: COPY FROM is not supported" q
464 PQ.BadResponse -> throwResultError "query" result status
465 PQ.NonfatalError -> throwResultError "query" result status
466 PQ.FatalError -> throwResultError "query" result status
468ellipsis :: ByteString -> ByteString
470 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
474-- | Of the four isolation levels defined by the SQL standard,
475-- these are the three levels distinguished by PostgreSQL as of version 9.0.
476-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
477-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
478-- was equivalent to 'Serializable'.
481 = DefaultIsolationLevel -- ^ the isolation level will be taken from
482 -- PostgreSQL's per-connection
483 -- @default_transaction_isolation@ variable,
484 -- which is initialized according to the
485 -- server's config. The default configuration
486 -- is 'ReadCommitted'.
490 deriving (Show, Eq, Ord, Enum, Bounded)
493 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
494 -- PostgreSQL's per-connection
495 -- @default_transaction_read_only@ variable,
496 -- which is initialized according to the
497 -- server's config. The default configuration
501 deriving (Show, Eq, Ord, Enum, Bounded)
503data TransactionMode = TransactionMode {
504 isolationLevel :: !IsolationLevel,
505 readWriteMode :: !ReadWriteMode
506 } deriving (Show, Eq)
508defaultTransactionMode :: TransactionMode
509defaultTransactionMode = TransactionMode
510 defaultIsolationLevel
513defaultIsolationLevel :: IsolationLevel
514defaultIsolationLevel = DefaultIsolationLevel
516defaultReadWriteMode :: ReadWriteMode
517defaultReadWriteMode = DefaultReadWriteMode
519-- | Execute an action inside a SQL transaction.
521-- This function initiates a transaction with a \"@begin
522-- transaction@\" statement, then executes the supplied action. If
523-- the action succeeds, the transaction will be completed with
524-- 'Base.commit' before this function returns.
526-- If the action throws /any/ kind of exception (not just a
527-- PostgreSQL-related exception), the transaction will be rolled back using
528-- 'rollback', then the exception will be rethrown.
529withTransaction :: Connection -> IO a -> IO a
530withTransaction = withTransactionMode defaultTransactionMode
532-- | Execute an action inside a SQL transaction with a given isolation level.
533withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
534withTransactionLevel lvl
535 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
537-- | Execute an action inside a SQL transaction with a given transaction mode.
538withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
539withTransactionMode mode conn act =
540 mask $ \restore -> do
542 r <- restore act `onException` rollback conn
546-- | Rollback a transaction.
547rollback :: Connection -> IO ()
548rollback conn = execute_ conn "ABORT" >> return ()
550-- | Commit a transaction.
551commit :: Connection -> IO ()
552commit conn = execute_ conn "COMMIT" >> return ()
554-- | Begin a transaction.
555begin :: Connection -> IO ()
556begin = beginMode defaultTransactionMode
558-- | Begin a transaction with a given isolation level
559beginLevel :: IsolationLevel -> Connection -> IO ()
560beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
562-- | Begin a transaction with a given transaction mode
563beginMode :: TransactionMode -> Connection -> IO ()
564beginMode mode conn = do
565 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
568 isolevel = case isolationLevel mode of
569 DefaultIsolationLevel -> ""
570 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
571 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
572 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
573 readmode = case readWriteMode mode of
574 DefaultReadWriteMode -> ""
575 ReadWrite -> " READ WRITE"
576 ReadOnly -> " READ ONLY"
578fmtError :: String -> Query -> [Action] -> a
579fmtError msg q xs = throw FormatError {
582 , fmtParams = map twiddle xs
584 where twiddle (Plain b) = toByteString b
585 twiddle (Escape s) = s
586 twiddle (EscapeBytea s) = s
587 twiddle (Many ys) = B.concat (map twiddle ys)
591-- SQL-based applications are somewhat notorious for their
592-- susceptibility to attacks through the injection of maliciously
593-- crafted data. The primary reason for widespread vulnerability to
594-- SQL injections is that many applications are sloppy in handling
595-- user data when constructing SQL queries.
597-- This library provides a 'Query' type and a parameter substitution
598-- facility to address both ease of use and security.
602-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
603-- exposes a tiny API that is not compatible with the 'ByteString'
604-- API; this makes it difficult to construct queries from fragments of
605-- strings. The 'query' and 'execute' functions require queries to be
608-- To most easily construct a query, enable GHC's @OverloadedStrings@
609-- language extension and write your query as a normal literal string.
611-- > {-# LANGUAGE OverloadedStrings #-}
613-- > import Database.PostgreSQL.Simple
616-- > conn <- connect defaultConnectInfo
617-- > query conn "select 2 + 2"
619-- A 'Query' value does not represent the actual query that will be
620-- executed, but is a template for constructing the final query.
624-- Since applications need to be able to construct queries with
625-- parameters that change, this library provides a query substitution
628-- The 'Query' template accepted by 'query' and 'execute' can contain
629-- any number of \"@?@\" characters. Both 'query' and 'execute'
630-- accept a third argument, typically a tuple. When constructing the
631-- real query to execute, these functions replace the first \"@?@\" in
632-- the template with the first element of the tuple, the second
633-- \"@?@\" with the second element, and so on. If necessary, each
634-- tuple element will be quoted and escaped prior to substitution;
635-- this defeats the single most common injection vector for malicious
638-- For example, given the following 'Query' template:
640-- > select * from user where first_name = ? and age > ?
642-- And a tuple of this form:
644-- > ("Boris" :: String, 37 :: Int)
646-- The query to be executed will look like this after substitution:
648-- > select * from user where first_name = 'Boris' and age > 37
650-- If there is a mismatch between the number of \"@?@\" characters in
651-- your template and the number of elements in your tuple, a
652-- 'FormatError' will be thrown.
654-- Note that the substitution functions do not attempt to parse or
655-- validate your query. It's up to you to write syntactically valid
656-- SQL, and to ensure that each \"@?@\" in your query template is
657-- matched with the right tuple element.
661-- Automated type inference means that you will often be able to avoid
662-- supplying explicit type signatures for the elements of a tuple.
663-- However, sometimes the compiler will not be able to infer your
664-- types. Consider a care where you write a numeric literal in a
667-- > query conn "select ? + ?" (40,2)
669-- The above query will be rejected by the compiler, because it does
670-- not know the specific numeric types of the literals @40@ and @2@.
671-- This is easily fixed:
673-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
675-- The same kind of problem can arise with string literals if you have
676-- the @OverloadedStrings@ language extension enabled. Again, just
677-- use an explicit type signature if this happens.
681-- Haskell lacks a single-element tuple type, so if you have just one
682-- value you want substituted into a query, what should you do?
684-- The obvious approach would appear to be something like this:
686-- > instance (Param a) => QueryParam a where
689-- Unfortunately, this wreaks havoc with type inference, so we take a
690-- different tack. To represent a single value @val@ as a parameter, write
691-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
693-- Here's an example using a singleton list:
695-- > execute conn "insert into users (first_name) values (?)"
700-- Suppose you want to write a query using an @IN@ clause:
702-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
704-- In such cases, it's common for both the elements and length of the
705-- list after the @IN@ keyword to vary from query to query.
707-- To address this case, use the 'In' type wrapper, and use a single
708-- \"@?@\" character to represent the list. Omit the parentheses
709-- around the list; these will be added for you.
713-- > query conn "select * from users where first_name in ?" $
714-- > In ["Anna", "Boris", "Carla"]
716-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
717-- substituted instead, to ensure that your clause remains
718-- syntactically valid.
722-- If you know that you have many rows of data to insert into a table,
723-- it is much more efficient to perform all the insertions in a single
724-- multi-row @INSERT@ statement than individually.
726-- The 'executeMany' function is intended specifically for helping
727-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
728-- query substitution are different than those for 'execute'.
730-- What 'executeMany' searches for in your 'Query' template is a
731-- single substring of the form:
735-- The rules are as follows:
737-- * The keyword @VALUES@ is matched case insensitively.
739-- * There must be no other \"@?@\" characters anywhere in your
742-- * There must one or more \"@?@\" in the parentheses.
744-- * Extra white space is fine.
746-- The last argument to 'executeMany' is a list of parameter
747-- tuples. These will be substituted into the query where the @(?,?)@
748-- string appears, in a form suitable for use in a multi-row @INSERT@
751-- Here is an example:
754-- > "insert into users (first_name,last_name) values (?,?)"
755-- > [("Boris","Karloff"),("Ed","Wood")]
757-- The query that will be executed here will look like this
758-- (reformatted for tidiness):
760-- > insert into users (first_name,last_name) values
761-- > ('Boris','Karloff'),('Ed','Wood')
765-- The 'query' and 'query_' functions return a list of values in the
766-- 'FromRow' typeclass. This class performs automatic extraction
767-- and type conversion of rows from a query result.
769-- Here is a simple example of how to extract results:
771-- > import qualified Data.Text as Text
773-- > xs <- query_ conn "select name,age from users"
774-- > forM_ xs $ \(name,age) ->
775-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
777-- Notice two important details about this code:
779-- * The number of columns we ask for in the query template must
780-- exactly match the number of elements we specify in a row of the
781-- result tuple. If they do not match, a 'ResultError' exception
784-- * Sometimes, the compiler needs our help in specifying types. It
785-- can infer that @name@ must be a 'Text', due to our use of the
786-- @unpack@ function. However, we have to tell it the type of @age@,
787-- as it has no other information to determine the exact type.
791-- The type of a result tuple will look something like this:
795-- Although SQL can accommodate @NULL@ as a value for any of these
796-- types, Haskell cannot. If your result contains columns that may be
797-- @NULL@, be sure that you use 'Maybe' in those positions of of your
800-- > (Text, Maybe Int, Int)
802-- If 'query' encounters a @NULL@ in a row where the corresponding
803-- Haskell type is not 'Maybe', it will throw a 'ResultError'
808-- To specify that a query returns a single-column result, use the
811-- > xs <- query_ conn "select id from users"
812-- > forM_ xs $ \(Only dbid) -> {- ... -}
816-- Conversion of SQL values to Haskell values is somewhat
817-- permissive. Here are the rules.
819-- * For numeric types, any Haskell type that can accurately represent
820-- all values of the given PostgreSQL type is considered \"compatible\".
821-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
822-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
823-- represent a @SMALLINT@, so it is considered compatble with those types.
825-- * A numeric compatibility check is based only on the type of a
826-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
827-- @BIGINT@ column will be considered incompatible with a Haskell
828-- 'Int16', even if it contains the value @1@.
830-- * If a numeric incompatibility is found, 'query' will throw a
833-- * The 'String' and 'Text' types are assumed to be encoded as
834-- UTF-8. If you use some other encoding, decoding may fail or give
835-- wrong results. In such cases, write a @newtype@ wrapper and a
836-- custom 'Result' instance to handle your encoding.
838getTypename :: Connection -> PQ.Oid -> IO ByteString
839getTypename conn@Connection{..} oid =
840 case oid2builtin oid of
841 Just builtin -> return $! builtin2typname builtin
842 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
843 case IntMap.lookup (oid2int oid) oidmap of
844 Just name -> return (oidmap, name)
846 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
848 name <- case names of
849 [] -> return $ throw SqlError {
851 sqlErrorMsg = "invalid type oid",
855 _ -> fail "typename query returned more than one result"
856 -- oid is a primary key, so the query should
857 -- never return more than one result
858 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