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)
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-- | Exception thrown if 'query' is used to perform an @INSERT@-like
154-- operation, or 'execute' is used to perform a @SELECT@-like operation.
155data QueryError = QueryError {
158 } deriving (Eq, Show, Typeable)
160instance Exception QueryError
162-- | Format a query string.
164-- This function is exposed to help with debugging and logging. Do not
165-- use it to prepare queries for execution.
167-- String parameters are escaped according to the character set in use
168-- on the 'Connection'.
170-- Throws 'FormatError' if the query string could not be formatted
172formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
173formatQuery conn q@(Query template) qs
174 | null xs && '?' `B.notElem` template = return template
175 | otherwise = toByteString <$> buildQuery conn q template xs
178-- | Format a query string with a variable number of rows.
180-- This function is exposed to help with debugging and logging. Do not
181-- use it to prepare queries for execution.
183-- The query string must contain exactly one substitution group,
184-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
185-- followed by an \"@(@\" character, a series of one or more \"@?@\"
186-- characters separated by commas, and a \"@)@\" character. White
187-- space in a substitution group is permitted.
189-- Throws 'FormatError' if the query string could not be formatted
191formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
192formatMany _ q [] = fmtError "no rows supplied" q []
193formatMany conn q@(Query template) qs = do
194 case match re template [] of
195 Just [_,before,qbits,after] -> do
196 bs <- mapM (buildQuery conn q qbits . toRow) qs
197 return . toByteString . mconcat $ fromByteString before :
198 intersperse (fromChar ',') bs ++
199 [fromByteString after]
202 re = compile "^([^?]+\\bvalues\\s*)\
203 \(\\(\\s*[?](?:\\s*,\\s*[?])*\\s*\\))\
207escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
208escapeStringConn conn s =
209 withConnection conn $ \c ->
210 PQ.escapeStringConn c s >>= checkError c
212escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
213escapeByteaConn conn s =
214 withConnection conn $ \c ->
215 PQ.escapeByteaConn c s >>= checkError c
217checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
218checkError c (Just x) = return $ Right x
219checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
221buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
222buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
223 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
224 (inQuotes . fromByteString)
225 utf8ToString = T.unpack . TE.decodeUtf8
226 sub (Plain b) = pure b
227 sub (Escape s) = quote <$> escapeStringConn conn s
228 sub (EscapeBytea s) = quote <$> escapeByteaConn conn s
229 sub (Many ys) = mconcat <$> mapM sub ys
230 split s = fromByteString h : if B.null t then [] else split (B.tail t)
231 where (h,t) = B.break (=='?') s
232 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
234 zipParams _ _ = fmtError (show (B.count '?' template) ++
235 " '?' characters, but " ++
236 show (length xs) ++ " parameters") q xs
238-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
239-- expected to return results.
241-- Returns the number of rows affected.
243-- Throws 'FormatError' if the query could not be formatted correctly.
244execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
245execute conn template qs = do
246 result <- exec conn =<< formatQuery conn template qs
247 finishExecute conn template result
249-- | A version of 'execute' that does not perform query substitution.
250execute_ :: Connection -> Query -> IO Int64
251execute_ conn q@(Query stmt) = do
252 result <- exec conn stmt
253 finishExecute conn q result
255-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
256-- expected to return results.
258-- Returns the number of rows affected.
260-- Throws 'FormatError' if the query could not be formatted correctly.
261executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
262executeMany _ _ [] = return 0
263executeMany conn q qs = do
264 result <- exec conn =<< formatMany conn q qs
265 finishExecute conn q result
267finishExecute :: Connection -> Query -> PQ.Result -> IO Int64
268finishExecute _conn q result = do
269 status <- PQ.resultStatus result
272 ncols <- PQ.nfields result
274 then throwIO $ QueryError ("execute resulted in " ++ show ncols ++
277 nstr <- PQ.cmdTuples result
278 return $ case nstr of
279 Nothing -> 0 -- is this appropriate?
280 Just str -> toInteger str
282 ncols <- PQ.nfields result
283 throwIO $ QueryError ("execute resulted in " ++ show ncols ++
285 PQ.CopyIn -> fail "FIXME: postgresql-simple does not currently support COPY IN"
286 PQ.CopyOut -> fail "FIXME: postgresql-simple does not currently support COPY OUT"
288 errormsg <- maybe "" id <$> PQ.resultErrorMessage result
289 statusmsg <- PQ.resStatus status
290 state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate
291 throwIO $ SqlError { sqlState = state
292 , sqlNativeError = fromEnum status
293 , sqlErrorMsg = B.concat [ "execute: ", statusmsg
296 toInteger str = B.foldl' delta 0 str
299 if '0' <= c && c <= '9'
300 then 10 * acc + fromIntegral (ord c - ord '0')
301 else error ("finishExecute: not an int: " ++ B.unpack str)
305-- | Perform a @SELECT@ or other SQL query that is expected to return
306-- results. All results are retrieved and converted before this
309-- When processing large results, this function will consume a lot of
310-- client-side memory. Consider using 'fold' instead.
312-- Exceptions that may be thrown:
314-- * 'FormatError': the query string could not be formatted correctly.
316-- * 'QueryError': the result contains no columns (i.e. you should be
317-- using 'execute' instead of 'query').
319-- * 'ResultError': result conversion failed.
320query :: (ToRow q, FromRow r)
321 => Connection -> Query -> q -> IO [r]
322query conn template qs = do
323 result <- exec conn =<< formatQuery conn template qs
324 finishQuery conn template result
326-- | A version of 'query' that does not perform query substitution.
327query_ :: (FromRow r) => Connection -> Query -> IO [r]
328query_ conn q@(Query que) = do
329 result <- exec conn que
330 finishQuery conn q result
332-- | Perform a @SELECT@ or other SQL query that is expected to return
333-- results. Results are streamed incrementally from the server, and
334-- consumed via a left fold.
336-- When dealing with small results, it may be simpler (and perhaps
337-- faster) to use 'query' instead.
339-- This fold is /not/ strict. The stream consumer is responsible for
340-- forcing the evaluation of its result to avoid space leaks.
342-- Exceptions that may be thrown:
344-- * 'FormatError': the query string could not be formatted correctly.
346-- * 'QueryError': the result contains no columns (i.e. you should be
347-- using 'execute' instead of 'query').
349-- * 'ResultError': result conversion failed.
351fold :: ( FromRow row, ToRow params )
356 -> (a -> row -> IO a)
358fold = foldWithOptions defaultFoldOptions
366 fetchQuantity :: !FetchQuantity,
367 transactionMode :: !TransactionMode
370defaultFoldOptions :: FoldOptions
371defaultFoldOptions = FoldOptions {
372 fetchQuantity = Automatic,
373 transactionMode = TransactionMode ReadCommitted ReadOnly
376foldWithOptions :: ( FromRow row, ToRow params )
382 -> (a -> row -> IO a)
384foldWithOptions opts conn template qs a f = do
385 q <- formatQuery conn template qs
386 doFold opts conn template (Query q) a f
388-- | A version of 'fold' that does not perform query substitution.
389fold_ :: (FromRow r) =>
392 -> a -- ^ Initial state for result consumer.
393 -> (a -> r -> IO a) -- ^ Result consumer.
395fold_ = foldWithOptions_ defaultFoldOptions
398foldWithOptions_ :: (FromRow r) =>
402 -> a -- ^ Initial state for result consumer.
403 -> (a -> r -> IO a) -- ^ Result consumer.
405foldWithOptions_ opts conn query a f = doFold opts conn query query a f
408doFold :: ( FromRow row )
414 -> (a -> row -> IO a)
416doFold FoldOptions{..} conn _template q a f = do
417 stat <- withConnection conn PQ.transactionStatus
419 PQ.TransIdle -> withTransactionMode transactionMode conn go
420 PQ.TransInTrans -> go
421 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
422 -- This _shouldn't_ occur in the current incarnation of
423 -- the library, as we aren't using libpq asynchronously.
424 -- However, it could occur in future incarnations of
425 -- this library or if client code uses the Internal module
426 -- to use raw libpq commands on postgresql-simple connections.
427 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
428 -- This should be turned into a better error message.
429 -- It is probably a bad idea to automatically roll
430 -- back the transaction and start another.
431 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
432 -- Not sure what this means.
435 -- FIXME: what about name clashes with already-declared cursors?
436 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
438 loop a `finally` execute_ conn "CLOSE fold"
440-- FIXME: choose the Automatic chunkSize more intelligently
441-- One possibility is to use the type of the results, although this
442-- still isn't a perfect solution, given that common types (e.g. text)
443-- are of highly variable size.
444-- A refinement of this technique is to pick this number adaptively
445-- as results are read in from the database.
446 chunkSize = case fetchQuantity of
450 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
451 if null rs then return a else foldM f a rs >>= loop
453-- | A version of 'fold' that does not transform a state value.
454forEach :: (ToRow q, FromRow r) =>
456 -> Query -- ^ Query template.
457 -> q -- ^ Query parameters.
458 -> (r -> IO ()) -- ^ Result consumer.
460forEach conn template qs = fold conn template qs () . const
461{-# INLINE forEach #-}
463-- | A version of 'forEach' that does not perform query substitution.
464forEach_ :: (FromRow r) =>
466 -> Query -- ^ Query template.
467 -> (r -> IO ()) -- ^ Result consumer.
469forEach_ conn template = fold_ conn template () . const
470{-# INLINE forEach_ #-}
472forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
473forM' lo hi m = loop hi []
481finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
482finishQuery conn q result = do
483 status <- PQ.resultStatus result
486 throwIO $ QueryError "query resulted in a command response" q
488 ncols <- PQ.nfields result
489 let unCol (PQ.Col x) = fromIntegral x :: Int
490 typenames <- V.generateM (unCol ncols)
491 (\(PQ.Col . fromIntegral -> col) -> do
492 getTypename conn =<< PQ.ftype result col)
493 nrows <- PQ.ntuples result
494 ncols <- PQ.nfields result
495 forM' 0 (nrows-1) $ \row -> do
496 let rw = Row row typenames result
497 case runStateT (runReaderT (unRP fromRow) rw) 0 of
498 Ok (val,col) | col == ncols -> return val
500 vals <- forM' 0 (ncols-1) $ \c -> do
501 v <- PQ.getvalue result row c
502 return ( typenames V.! unCol c
504 throw (ConversionFailed
505 (show (unCol ncols) ++ " values: " ++ show vals)
506 (show (unCol col) ++ " slots in target type")
507 "mismatch between number of columns to \
508 \convert and number in target type")
509 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
510 Errors [x] -> throwIO x
511 Errors xs -> throwIO $ ManyErrors xs
513ellipsis :: ByteString -> ByteString
515 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
519-- | Of the four isolation levels defined by the SQL standard,
520-- these are the three levels distinguished by PostgreSQL as of version 9.0.
521-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
522-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
523-- was equivalent to 'Serializable'.
526 = DefaultIsolationLevel -- ^ the isolation level will be taken from
527 -- PostgreSQL's per-connection
528 -- @default_transaction_isolation@ variable,
529 -- which is initialized according to the
530 -- server's config. The default configuration
531 -- is 'ReadCommitted'.
535 deriving (Show, Eq, Ord, Enum, Bounded)
538 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
539 -- PostgreSQL's per-connection
540 -- @default_transaction_read_only@ variable,
541 -- which is initialized according to the
542 -- server's config. The default configuration
546 deriving (Show, Eq, Ord, Enum, Bounded)
548data TransactionMode = TransactionMode {
549 isolationLevel :: !IsolationLevel,
550 readWriteMode :: !ReadWriteMode
551 } deriving (Show, Eq)
553defaultTransactionMode :: TransactionMode
554defaultTransactionMode = TransactionMode
555 defaultIsolationLevel
558defaultIsolationLevel :: IsolationLevel
559defaultIsolationLevel = DefaultIsolationLevel
561defaultReadWriteMode :: ReadWriteMode
562defaultReadWriteMode = DefaultReadWriteMode
564-- | Execute an action inside a SQL transaction.
566-- This function initiates a transaction with a \"@begin
567-- transaction@\" statement, then executes the supplied action. If
568-- the action succeeds, the transaction will be completed with
569-- 'Base.commit' before this function returns.
571-- If the action throws /any/ kind of exception (not just a
572-- PostgreSQL-related exception), the transaction will be rolled back using
573-- 'rollback', then the exception will be rethrown.
574withTransaction :: Connection -> IO a -> IO a
575withTransaction = withTransactionMode defaultTransactionMode
577-- | Execute an action inside a SQL transaction with a given isolation level.
578withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
579withTransactionLevel lvl
580 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
582-- | Execute an action inside a SQL transaction with a given transaction mode.
583withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
584withTransactionMode mode conn act =
585 mask $ \restore -> do
587 r <- restore act `onException` rollback conn
591-- | Rollback a transaction.
592rollback :: Connection -> IO ()
593rollback conn = execute_ conn "ABORT" >> return ()
595-- | Commit a transaction.
596commit :: Connection -> IO ()
597commit conn = execute_ conn "COMMIT" >> return ()
599-- | Begin a transaction.
600begin :: Connection -> IO ()
601begin = beginMode defaultTransactionMode
603-- | Begin a transaction with a given isolation level
604beginLevel :: IsolationLevel -> Connection -> IO ()
605beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
607-- | Begin a transaction with a given transaction mode
608beginMode :: TransactionMode -> Connection -> IO ()
609beginMode mode conn = do
610 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
613 isolevel = case isolationLevel mode of
614 DefaultIsolationLevel -> ""
615 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
616 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
617 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
618 readmode = case readWriteMode mode of
619 DefaultReadWriteMode -> ""
620 ReadWrite -> " READ WRITE"
621 ReadOnly -> " READ ONLY"
623fmtError :: String -> Query -> [Action] -> a
624fmtError msg q xs = throw FormatError {
627 , fmtParams = map twiddle xs
629 where twiddle (Plain b) = toByteString b
630 twiddle (Escape s) = s
631 twiddle (EscapeBytea s) = s
632 twiddle (Many ys) = B.concat (map twiddle ys)
636-- SQL-based applications are somewhat notorious for their
637-- susceptibility to attacks through the injection of maliciously
638-- crafted data. The primary reason for widespread vulnerability to
639-- SQL injections is that many applications are sloppy in handling
640-- user data when constructing SQL queries.
642-- This library provides a 'Query' type and a parameter substitution
643-- facility to address both ease of use and security.
647-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
648-- exposes a tiny API that is not compatible with the 'ByteString'
649-- API; this makes it difficult to construct queries from fragments of
650-- strings. The 'query' and 'execute' functions require queries to be
653-- To most easily construct a query, enable GHC's @OverloadedStrings@
654-- language extension and write your query as a normal literal string.
656-- > {-# LANGUAGE OverloadedStrings #-}
658-- > import Database.PostgreSQL.Simple
661-- > conn <- connect defaultConnectInfo
662-- > query conn "select 2 + 2"
664-- A 'Query' value does not represent the actual query that will be
665-- executed, but is a template for constructing the final query.
669-- Since applications need to be able to construct queries with
670-- parameters that change, this library provides a query substitution
673-- The 'Query' template accepted by 'query' and 'execute' can contain
674-- any number of \"@?@\" characters. Both 'query' and 'execute'
675-- accept a third argument, typically a tuple. When constructing the
676-- real query to execute, these functions replace the first \"@?@\" in
677-- the template with the first element of the tuple, the second
678-- \"@?@\" with the second element, and so on. If necessary, each
679-- tuple element will be quoted and escaped prior to substitution;
680-- this defeats the single most common injection vector for malicious
683-- For example, given the following 'Query' template:
685-- > select * from user where first_name = ? and age > ?
687-- And a tuple of this form:
689-- > ("Boris" :: String, 37 :: Int)
691-- The query to be executed will look like this after substitution:
693-- > select * from user where first_name = 'Boris' and age > 37
695-- If there is a mismatch between the number of \"@?@\" characters in
696-- your template and the number of elements in your tuple, a
697-- 'FormatError' will be thrown.
699-- Note that the substitution functions do not attempt to parse or
700-- validate your query. It's up to you to write syntactically valid
701-- SQL, and to ensure that each \"@?@\" in your query template is
702-- matched with the right tuple element.
706-- Automated type inference means that you will often be able to avoid
707-- supplying explicit type signatures for the elements of a tuple.
708-- However, sometimes the compiler will not be able to infer your
709-- types. Consider a care where you write a numeric literal in a
712-- > query conn "select ? + ?" (40,2)
714-- The above query will be rejected by the compiler, because it does
715-- not know the specific numeric types of the literals @40@ and @2@.
716-- This is easily fixed:
718-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
720-- The same kind of problem can arise with string literals if you have
721-- the @OverloadedStrings@ language extension enabled. Again, just
722-- use an explicit type signature if this happens.
726-- Haskell lacks a single-element tuple type, so if you have just one
727-- value you want substituted into a query, what should you do?
729-- The obvious approach would appear to be something like this:
731-- > instance (Param a) => QueryParam a where
734-- Unfortunately, this wreaks havoc with type inference, so we take a
735-- different tack. To represent a single value @val@ as a parameter, write
736-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
738-- Here's an example using a singleton list:
740-- > execute conn "insert into users (first_name) values (?)"
745-- Suppose you want to write a query using an @IN@ clause:
747-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
749-- In such cases, it's common for both the elements and length of the
750-- list after the @IN@ keyword to vary from query to query.
752-- To address this case, use the 'In' type wrapper, and use a single
753-- \"@?@\" character to represent the list. Omit the parentheses
754-- around the list; these will be added for you.
758-- > query conn "select * from users where first_name in ?" $
759-- > In ["Anna", "Boris", "Carla"]
761-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
762-- substituted instead, to ensure that your clause remains
763-- syntactically valid.
767-- If you know that you have many rows of data to insert into a table,
768-- it is much more efficient to perform all the insertions in a single
769-- multi-row @INSERT@ statement than individually.
771-- The 'executeMany' function is intended specifically for helping
772-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
773-- query substitution are different than those for 'execute'.
775-- What 'executeMany' searches for in your 'Query' template is a
776-- single substring of the form:
780-- The rules are as follows:
782-- * The keyword @VALUES@ is matched case insensitively.
784-- * There must be no other \"@?@\" characters anywhere in your
787-- * There must one or more \"@?@\" in the parentheses.
789-- * Extra white space is fine.
791-- The last argument to 'executeMany' is a list of parameter
792-- tuples. These will be substituted into the query where the @(?,?)@
793-- string appears, in a form suitable for use in a multi-row @INSERT@
796-- Here is an example:
799-- > "insert into users (first_name,last_name) values (?,?)"
800-- > [("Boris","Karloff"),("Ed","Wood")]
802-- The query that will be executed here will look like this
803-- (reformatted for tidiness):
805-- > insert into users (first_name,last_name) values
806-- > ('Boris','Karloff'),('Ed','Wood')
810-- The 'query' and 'query_' functions return a list of values in the
811-- 'FromRow' typeclass. This class performs automatic extraction
812-- and type conversion of rows from a query result.
814-- Here is a simple example of how to extract results:
816-- > import qualified Data.Text as Text
818-- > xs <- query_ conn "select name,age from users"
819-- > forM_ xs $ \(name,age) ->
820-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
822-- Notice two important details about this code:
824-- * The number of columns we ask for in the query template must
825-- exactly match the number of elements we specify in a row of the
826-- result tuple. If they do not match, a 'ResultError' exception
829-- * Sometimes, the compiler needs our help in specifying types. It
830-- can infer that @name@ must be a 'Text', due to our use of the
831-- @unpack@ function. However, we have to tell it the type of @age@,
832-- as it has no other information to determine the exact type.
836-- The type of a result tuple will look something like this:
840-- Although SQL can accommodate @NULL@ as a value for any of these
841-- types, Haskell cannot. If your result contains columns that may be
842-- @NULL@, be sure that you use 'Maybe' in those positions of of your
845-- > (Text, Maybe Int, Int)
847-- If 'query' encounters a @NULL@ in a row where the corresponding
848-- Haskell type is not 'Maybe', it will throw a 'ResultError'
853-- To specify that a query returns a single-column result, use the
856-- > xs <- query_ conn "select id from users"
857-- > forM_ xs $ \(Only dbid) -> {- ... -}
861-- Conversion of SQL values to Haskell values is somewhat
862-- permissive. Here are the rules.
864-- * For numeric types, any Haskell type that can accurately represent
865-- all values of the given PostgreSQL type is considered \"compatible\".
866-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
867-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
868-- represent a @SMALLINT@, so it is considered compatble with those types.
870-- * A numeric compatibility check is based only on the type of a
871-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
872-- @BIGINT@ column will be considered incompatible with a Haskell
873-- 'Int16', even if it contains the value @1@.
875-- * If a numeric incompatibility is found, 'query' will throw a
878-- * The 'String' and 'Text' types are assumed to be encoded as
879-- UTF-8. If you use some other encoding, decoding may fail or give
880-- wrong results. In such cases, write a @newtype@ wrapper and a
881-- custom 'Result' instance to handle your encoding.
883getTypename :: Connection -> PQ.Oid -> IO ByteString
884getTypename conn@Connection{..} oid =
885 case oid2builtin oid of
886 Just builtin -> return $! builtin2typname builtin
887 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
888 case IntMap.lookup (oid2int oid) oidmap of
889 Just name -> return (oidmap, name)
891 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
893 name <- case names of
894 [] -> return $ throw SqlError {
896 sqlErrorMsg = "invalid type oid",
900 _ -> fail "typename query returned more than one result"
901 -- oid is a primary key, so the query should
902 -- never return more than one result
903 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