1{-# LANGUAGE DeriveDataTypeable #-}
2{-# LANGUAGE NamedFieldPuns #-}
3{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE PatternGuards #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE ViewPatterns #-}
8------------------------------------------------------------------------------
10-- Module: Database.PostgreSQL.Simple
11-- Copyright: (c) 2011 MailRank, Inc.
12-- (c) 2011-2012 Leon P Smith
14-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Stability: experimental
16-- Portability: portable
18-- A mid-level client library for the PostgreSQL database, aimed at ease of
19-- use and high performance.
21------------------------------------------------------------------------------
23module Database.PostgreSQL.Simple
31 -- ** Parameter substitution
37 -- ** Substituting a single parameter
40 -- ** Representing a list of values
43 -- ** Modifying multiple rows at once
46 -- ** @RETURNING@: modifications that returns results
49 -- * Extracting results
52 -- ** Handling null values
55 -- ** Type conversions
71 , FormatError(fmtMessage, fmtQuery, fmtParams)
72 , QueryError(qeMessage, qeQuery)
73 , ResultError(errSQLType, errHaskellType, errMessage)
74 -- * Connection management
76 , Base.connectPostgreSQL
77 , Base.postgreSQLConnectionString
78 , Base.defaultConnectInfo
80 -- * Queries that return results
83 -- * Queries that stream results
94 -- * Statements that do not return results
99 -- * Transaction handling
101 , withTransactionSerializable
102 , TransactionMode(..)
105 , defaultTransactionMode
106 , defaultIsolationLevel
107 , defaultReadWriteMode
108 , withTransactionLevel
109 , withTransactionMode
110 , withTransactionModeRetry
117 -- * Helper functions
122import Blaze.ByteString.Builder
123 ( Builder, fromByteString, toByteString )
124import Blaze.ByteString.Builder.Char8 (fromChar)
125import Control.Applicative ((<$>), pure)
126import Control.Exception
127 ( Exception, throw, throwIO, finally )
128import Control.Monad (foldM)
129import Data.ByteString (ByteString)
130import Data.Int (Int64)
131import Data.List (intersperse)
132import Data.Monoid (mconcat)
133import Data.Typeable (Typeable)
134import Database.PostgreSQL.Simple.Compat ( (<>) )
135import Database.PostgreSQL.Simple.FromField (ResultError(..))
136import Database.PostgreSQL.Simple.FromRow (FromRow(..))
137import Database.PostgreSQL.Simple.Ok
138import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
139import Database.PostgreSQL.Simple.ToRow (ToRow(..))
140import Database.PostgreSQL.Simple.Types
141 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
142import Database.PostgreSQL.Simple.Internal as Base
143import Database.PostgreSQL.Simple.Transaction
144import Database.PostgreSQL.Simple.TypeInfo
145import qualified Database.PostgreSQL.LibPQ as PQ
146import qualified Data.ByteString.Char8 as B
147import qualified Data.Text as T
148import qualified Data.Text.Encoding as TE
149import qualified Data.Vector as V
150import Control.Monad.Trans.Reader
151import Control.Monad.Trans.State.Strict
153-- | Exception thrown if a 'Query' could not be formatted correctly.
154-- This may occur if the number of \'@?@\' characters in the query
155-- string does not match the number of parameters provided.
156data FormatError = FormatError {
159 , fmtParams :: [ByteString]
160 } deriving (Eq, Show, Typeable)
162instance Exception FormatError
164-- | Format a query string.
166-- This function is exposed to help with debugging and logging. Do not
167-- use it to prepare queries for execution.
169-- String parameters are escaped according to the character set in use
170-- on the 'Connection'.
172-- Throws 'FormatError' if the query string could not be formatted
174formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
175formatQuery conn q@(Query template) qs
176 | null xs && '?' `B.notElem` template = return template
177 | otherwise = toByteString <$> buildQuery conn q template xs
180-- | Format a query string with a variable number of rows.
182-- This function is exposed to help with debugging and logging. Do not
183-- use it to prepare queries for execution.
185-- The query string must contain exactly one substitution group,
186-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
187-- followed by an \"@(@\" character, a series of one or more \"@?@\"
188-- characters separated by commas, and a \"@)@\" character. White
189-- space in a substitution group is permitted.
191-- Throws 'FormatError' if the query string could not be formatted
193formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
194formatMany _ q [] = fmtError "no rows supplied" q []
195formatMany conn q@(Query template) qs = do
196 case parseTemplate template of
197 Just (before, qbits, after) -> do
198 bs <- mapM (buildQuery conn q qbits . toRow) qs
199 return . toByteString . mconcat $ fromByteString before :
200 intersperse (fromChar ',') bs ++
201 [fromByteString after]
202 Nothing -> fmtError "syntax error in multi-row template" q []
204-- Split the input string into three pieces, @before@, @qbits@, and @after@,
205-- following this grammar:
207-- start: ^ before qbits after $
208-- before: ([^?]* [^?\w])? 'VALUES' \s*
209-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
213-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
215-- This would be much more concise with some sort of regex engine.
216-- 'formatMany' used to use pcre-light instead of this hand-written parser,
217-- but pcre is a hassle to install on Windows.
218parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
219parseTemplate template =
220 -- Convert input string to uppercase, to facilitate searching.
221 search $ B.map toUpper_ascii template
223 -- Search for the next occurrence of "VALUES"
225 case B.breakSubstring "VALUES" bs of
227 -- If "VALUES" is not present in the string, or any '?' characters
228 -- were encountered prior to it, fail.
229 | B.null y || ('?' `B.elem` x)
232 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
233 -- try the next occurrence.
234 | not (B.null x) && isIdent (B.last x)
235 -> search $ B.drop 6 y
237 -- Otherwise, we have a legitimate "VALUES" token.
239 -> parseQueryBits $ skipSpace $ B.drop 6 y
241 -- Parse '(' \s* '?' \s* . If this doesn't match
242 -- (and we don't consume a '?'), look for another "VALUES".
244 -- qb points to the open paren (if present), meaning it points to the
245 -- beginning of the "qbits" production described above. This is why we
246 -- pass it down to finishQueryBits.
248 | Just ('(', skipSpace -> bs1) <- B.uncons qb
249 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
250 = finishQueryBits qb bs2
254 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
256 -- Since we've already consumed at least one '?', there's no turning back.
257 -- The parse has to succeed here, or the whole thing fails
258 -- (because we don't allow '?' to appear outside of the VALUES list).
259 finishQueryBits qb bs0
260 | Just (')', bs1) <- B.uncons bs0
261 = if '?' `B.elem` bs1
263 else Just $ slice3 template qb bs1
264 | Just (',', skipSpace -> bs1) <- B.uncons bs0
265 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
266 = finishQueryBits qb bs2
270 -- Slice a string into three pieces, given the start offset of the second
271 -- and third pieces. Each "offset" is actually a tail of the uppercase
272 -- version of the template string. Its length is used to infer the offset.
274 -- It is important to note that we only slice the original template.
275 -- We don't want our all-caps trick messing up the actual query string.
276 slice3 source p1 p2 =
279 (s1, source') = B.splitAt (B.length source - B.length p1) source
280 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
282 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
285 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
286 -- in the PostgreSQL source. No need to check [a-z], since we converted
287 -- the whole string to uppercase.
288 isIdent c = (c >= '0' && c <= '9')
289 || (c >= 'A' && c <= 'Z')
290 || (c >= '\x80' && c <= '\xFF')
294 -- Based on {space} in scan.l
295 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
297 skipSpace = B.dropWhile isSpace_ascii
299escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
300escapeStringConn conn s =
301 withConnection conn $ \c ->
302 PQ.escapeStringConn c s >>= checkError c
304escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
305escapeByteaConn conn s =
306 withConnection conn $ \c ->
307 PQ.escapeByteaConn c s >>= checkError c
309checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
310checkError _ (Just x) = return $ Right x
311checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
313buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
314buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
315 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
316 (inQuotes . fromByteString)
317 utf8ToString = T.unpack . TE.decodeUtf8
318 sub (Plain b) = pure b
319 sub (Escape s) = quote <$> escapeStringConn conn s
320 sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
321 sub (Many ys) = mconcat <$> mapM sub ys
322 split s = fromByteString h : if B.null t then [] else split (B.tail t)
323 where (h,t) = B.break (=='?') s
324 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
326 zipParams _ _ = fmtError (show (B.count '?' template) ++
327 " '?' characters, but " ++
328 show (length xs) ++ " parameters") q xs
330-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
331-- expected to return results.
333-- Returns the number of rows affected.
335-- Throws 'FormatError' if the query could not be formatted correctly.
336execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
337execute conn template qs = do
338 result <- exec conn =<< formatQuery conn template qs
339 finishExecute conn template result
341-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
342-- expected to return results.
344-- Returns the number of rows affected.
346-- Throws 'FormatError' if the query could not be formatted correctly.
347executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
348executeMany _ _ [] = return 0
349executeMany conn q qs = do
350 result <- exec conn =<< formatMany conn q qs
351 finishExecute conn q result
353-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
354-- query that accepts multi-row input and is expected to return results.
355-- Note that it is possible to write
356-- @'query' conn "INSERT ... RETURNING ..." ...@
357-- in cases where you are only inserting a single row, and do not need
358-- functionality analogous to 'executeMany'.
360-- Throws 'FormatError' if the query could not be formatted correctly.
361returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
362returning _ _ [] = return []
363returning conn q qs = do
364 result <- exec conn =<< formatMany conn q qs
365 finishQuery conn q result
367-- | Perform a @SELECT@ or other SQL query that is expected to return
368-- results. All results are retrieved and converted before this
371-- When processing large results, this function will consume a lot of
372-- client-side memory. Consider using 'fold' instead.
374-- Exceptions that may be thrown:
376-- * 'FormatError': the query string could not be formatted correctly.
378-- * 'QueryError': the result contains no columns (i.e. you should be
379-- using 'execute' instead of 'query').
381-- * 'ResultError': result conversion failed.
382query :: (ToRow q, FromRow r)
383 => Connection -> Query -> q -> IO [r]
384query conn template qs = do
385 result <- exec conn =<< formatQuery conn template qs
386 finishQuery conn template result
388-- | A version of 'query' that does not perform query substitution.
389query_ :: (FromRow r) => Connection -> Query -> IO [r]
390query_ conn q@(Query que) = do
391 result <- exec conn que
392 finishQuery conn q result
394-- | Perform a @SELECT@ or other SQL query that is expected to return
395-- results. Results are streamed incrementally from the server, and
396-- consumed via a left fold.
398-- When dealing with small results, it may be simpler (and perhaps
399-- faster) to use 'query' instead.
401-- This fold is /not/ strict. The stream consumer is responsible for
402-- forcing the evaluation of its result to avoid space leaks.
404-- Exceptions that may be thrown:
406-- * 'FormatError': the query string could not be formatted correctly.
408-- * 'QueryError': the result contains no columns (i.e. you should be
409-- using 'execute' instead of 'query').
411-- * 'ResultError': result conversion failed.
413fold :: ( FromRow row, ToRow params )
418 -> (a -> row -> IO a)
420fold = foldWithOptions defaultFoldOptions
428 fetchQuantity :: !FetchQuantity,
429 transactionMode :: !TransactionMode
432defaultFoldOptions :: FoldOptions
433defaultFoldOptions = FoldOptions {
434 fetchQuantity = Automatic,
435 transactionMode = TransactionMode ReadCommitted ReadOnly
438foldWithOptions :: ( FromRow row, ToRow params )
444 -> (a -> row -> IO a)
446foldWithOptions opts conn template qs a f = do
447 q <- formatQuery conn template qs
448 doFold opts conn template (Query q) a f
450-- | A version of 'fold' that does not perform query substitution.
451fold_ :: (FromRow r) =>
454 -> a -- ^ Initial state for result consumer.
455 -> (a -> r -> IO a) -- ^ Result consumer.
457fold_ = foldWithOptions_ defaultFoldOptions
460foldWithOptions_ :: (FromRow r) =>
464 -> a -- ^ Initial state for result consumer.
465 -> (a -> r -> IO a) -- ^ Result consumer.
467foldWithOptions_ opts conn query a f = doFold opts conn query query a f
470doFold :: ( FromRow row )
476 -> (a -> row -> IO a)
478doFold FoldOptions{..} conn _template q a f = do
479 stat <- withConnection conn PQ.transactionStatus
481 PQ.TransIdle -> withTransactionMode transactionMode conn go
482 PQ.TransInTrans -> go
483 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
484 -- This _shouldn't_ occur in the current incarnation of
485 -- the library, as we aren't using libpq asynchronously.
486 -- However, it could occur in future incarnations of
487 -- this library or if client code uses the Internal module
488 -- to use raw libpq commands on postgresql-simple connections.
489 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
490 -- This should be turned into a better error message.
491 -- It is probably a bad idea to automatically roll
492 -- back the transaction and start another.
493 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
494 -- Not sure what this means.
497 -- FIXME: what about name clashes with already-declared cursors?
498 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR " <> q)
499 loop a `finally` execute_ conn "CLOSE fold"
501-- FIXME: choose the Automatic chunkSize more intelligently
502-- One possibility is to use the type of the results, although this
503-- still isn't a perfect solution, given that common types (e.g. text)
504-- are of highly variable size.
505-- A refinement of this technique is to pick this number adaptively
506-- as results are read in from the database.
507 chunkSize = case fetchQuantity of
511 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
512 if null rs then return a else foldM f a rs >>= loop
514-- | A version of 'fold' that does not transform a state value.
515forEach :: (ToRow q, FromRow r) =>
517 -> Query -- ^ Query template.
518 -> q -- ^ Query parameters.
519 -> (r -> IO ()) -- ^ Result consumer.
521forEach conn template qs = fold conn template qs () . const
522{-# INLINE forEach #-}
524-- | A version of 'forEach' that does not perform query substitution.
525forEach_ :: (FromRow r) =>
527 -> Query -- ^ Query template.
528 -> (r -> IO ()) -- ^ Result consumer.
530forEach_ conn template = fold_ conn template () . const
531{-# INLINE forEach_ #-}
533forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
534forM' lo hi m = loop hi []
542finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
543finishQuery conn q result = do
544 status <- PQ.resultStatus result
547 throwIO $ QueryError "query: Empty query" q
549 throwIO $ QueryError "query resulted in a command response" q
551 ncols <- PQ.nfields result
552 let unCol (PQ.Col x) = fromIntegral x :: Int
553 typeinfos <- V.generateM (unCol ncols)
554 (\(PQ.Col . fromIntegral -> col) -> do
555 getTypeInfo conn =<< PQ.ftype result col)
556 nrows <- PQ.ntuples result
557 ncols <- PQ.nfields result
558 forM' 0 (nrows-1) $ \row -> do
559 let rw = Row row typeinfos result
560 case runStateT (runReaderT (unRP fromRow) rw) 0 of
561 Ok (val,col) | col == ncols -> return val
563 vals <- forM' 0 (ncols-1) $ \c -> do
564 v <- PQ.getvalue result row c
565 return ( typeinfos V.! unCol c
567 throw (ConversionFailed
568 (show (unCol ncols) ++ " values: " ++ show vals)
571 (show (unCol col) ++ " slots in target type")
572 "mismatch between number of columns to \
573 \convert and number in target type")
574 Errors [] -> throwIO $ ConversionFailed "" Nothing "" "" "unknown error"
575 Errors [x] -> throwIO x
576 Errors xs -> throwIO $ ManyErrors xs
578 throwIO $ QueryError "query: COPY TO is not supported" q
580 throwIO $ QueryError "query: COPY FROM is not supported" q
581 PQ.BadResponse -> throwResultError "query" result status
582 PQ.NonfatalError -> throwResultError "query" result status
583 PQ.FatalError -> throwResultError "query" result status
585ellipsis :: ByteString -> ByteString
587 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
590fmtError :: String -> Query -> [Action] -> a
591fmtError msg q xs = throw FormatError {
594 , fmtParams = map twiddle xs
596 where twiddle (Plain b) = toByteString b
597 twiddle (Escape s) = s
598 twiddle (EscapeByteA s) = s
599 twiddle (Many ys) = B.concat (map twiddle ys)
603-- SQL-based applications are somewhat notorious for their
604-- susceptibility to attacks through the injection of maliciously
605-- crafted data. The primary reason for widespread vulnerability to
606-- SQL injections is that many applications are sloppy in handling
607-- user data when constructing SQL queries.
609-- This library provides a 'Query' type and a parameter substitution
610-- facility to address both ease of use and security.
614-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
615-- exposes a tiny API that is not compatible with the 'ByteString'
616-- API; this makes it difficult to construct queries from fragments of
617-- strings. The 'query' and 'execute' functions require queries to be
620-- To most easily construct a query, enable GHC's @OverloadedStrings@
621-- language extension and write your query as a normal literal string.
623-- > {-# LANGUAGE OverloadedStrings #-}
625-- > import Database.PostgreSQL.Simple
628-- > conn <- connect defaultConnectInfo
629-- > query conn "select 2 + 2"
631-- A 'Query' value does not represent the actual query that will be
632-- executed, but is a template for constructing the final query.
636-- Since applications need to be able to construct queries with
637-- parameters that change, this library provides a query substitution
640-- The 'Query' template accepted by 'query' and 'execute' can contain
641-- any number of \"@?@\" characters. Both 'query' and 'execute'
642-- accept a third argument, typically a tuple. When constructing the
643-- real query to execute, these functions replace the first \"@?@\" in
644-- the template with the first element of the tuple, the second
645-- \"@?@\" with the second element, and so on. If necessary, each
646-- tuple element will be quoted and escaped prior to substitution;
647-- this defeats the single most common injection vector for malicious
650-- For example, given the following 'Query' template:
652-- > select * from user where first_name = ? and age > ?
654-- And a tuple of this form:
656-- > ("Boris" :: String, 37 :: Int)
658-- The query to be executed will look like this after substitution:
660-- > select * from user where first_name = 'Boris' and age > 37
662-- If there is a mismatch between the number of \"@?@\" characters in
663-- your template and the number of elements in your tuple, a
664-- 'FormatError' will be thrown.
666-- Note that the substitution functions do not attempt to parse or
667-- validate your query. It's up to you to write syntactically valid
668-- SQL, and to ensure that each \"@?@\" in your query template is
669-- matched with the right tuple element.
673-- Automated type inference means that you will often be able to avoid
674-- supplying explicit type signatures for the elements of a tuple.
675-- However, sometimes the compiler will not be able to infer your
676-- types. Consider a case where you write a numeric literal in a
679-- > query conn "select ? + ?" (40,2)
681-- The above query will be rejected by the compiler, because it does
682-- not know the specific numeric types of the literals @40@ and @2@.
683-- This is easily fixed:
685-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
687-- The same kind of problem can arise with string literals if you have
688-- the @OverloadedStrings@ language extension enabled. Again, just
689-- use an explicit type signature if this happens.
693-- Haskell lacks a single-element tuple type, so if you have just one
694-- value you want substituted into a query, what should you do?
696-- The obvious approach would appear to be something like this:
698-- > instance (Param a) => QueryParam a where
701-- Unfortunately, this wreaks havoc with type inference, so we take a
702-- different tack. To represent a single value @val@ as a parameter, write
703-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
705-- Here's an example using a singleton list:
707-- > execute conn "insert into users (first_name) values (?)"
712-- Suppose you want to write a query using an @IN@ clause:
714-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
716-- In such cases, it's common for both the elements and length of the
717-- list after the @IN@ keyword to vary from query to query.
719-- To address this case, use the 'In' type wrapper, and use a single
720-- \"@?@\" character to represent the list. Omit the parentheses
721-- around the list; these will be added for you.
725-- > query conn "select * from users where first_name in ?" $
726-- > In ["Anna", "Boris", "Carla"]
728-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
729-- substituted instead, to ensure that your clause remains
730-- syntactically valid.
734-- If you know that you have many rows of data to insert into a table,
735-- it is much more efficient to perform all the insertions in a single
736-- multi-row @INSERT@ statement than individually.
738-- The 'executeMany' function is intended specifically for helping
739-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
740-- query substitution are different than those for 'execute'.
742-- What 'executeMany' searches for in your 'Query' template is a
743-- single substring of the form:
747-- The rules are as follows:
749-- * The keyword @VALUES@ is matched case insensitively.
751-- * There must be no other \"@?@\" characters anywhere in your
754-- * There must one or more \"@?@\" in the parentheses.
756-- * Extra white space is fine.
758-- The last argument to 'executeMany' is a list of parameter
759-- tuples. These will be substituted into the query where the @(?,?)@
760-- string appears, in a form suitable for use in a multi-row @INSERT@
763-- Here is an example:
766-- > "insert into users (first_name,last_name) values (?,?)"
767-- > [("Boris","Karloff"),("Ed","Wood")]
769-- The query that will be executed here will look like this
770-- (reformatted for tidiness):
772-- > insert into users (first_name,last_name) values
773-- > ('Boris','Karloff'),('Ed','Wood')
777-- The 'returning' function is similar to 'executeMany' but is
778-- intended for use with multi-tuple @INSERT@ or @UPDATE@ statements
779-- that make use of @RETURNING@.
781-- For example, were there an auto-incrementing @id@ column and
782-- timestamp column @t@ that defaulted to the present time for the
783-- @sales@ table, then the following query would insert two new
784-- sales records and also return their new @id@s and timestamps.
786-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
787-- > xs :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
791-- The 'query' and 'query_' functions return a list of values in the
792-- 'FromRow' typeclass. This class performs automatic extraction
793-- and type conversion of rows from a query result.
795-- Here is a simple example of how to extract results:
797-- > import qualified Data.Text as Text
799-- > xs <- query_ conn "select name,age from users"
800-- > forM_ xs $ \(name,age) ->
801-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
803-- Notice two important details about this code:
805-- * The number of columns we ask for in the query template must
806-- exactly match the number of elements we specify in a row of the
807-- result tuple. If they do not match, a 'ResultError' exception
810-- * Sometimes, the compiler needs our help in specifying types. It
811-- can infer that @name@ must be a 'Text', due to our use of the
812-- @unpack@ function. However, we have to tell it the type of @age@,
813-- as it has no other information to determine the exact type.
817-- The type of a result tuple will look something like this:
821-- Although SQL can accommodate @NULL@ as a value for any of these
822-- types, Haskell cannot. If your result contains columns that may be
823-- @NULL@, be sure that you use 'Maybe' in those positions of of your
826-- > (Text, Maybe Int, Int)
828-- If 'query' encounters a @NULL@ in a row where the corresponding
829-- Haskell type is not 'Maybe', it will throw a 'ResultError'
834-- To specify that a query returns a single-column result, use the
837-- > xs <- query_ conn "select id from users"
838-- > forM_ xs $ \(Only dbid) -> {- ... -}
842-- Conversion of SQL values to Haskell values is somewhat
843-- permissive. Here are the rules.
845-- * For numeric types, any Haskell type that can accurately represent
846-- all values of the given PostgreSQL type is considered \"compatible\".
847-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
848-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
849-- represent a @SMALLINT@, so it is considered compatble with those types.
851-- * A numeric compatibility check is based only on the type of a
852-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
853-- @BIGINT@ column will be considered incompatible with a Haskell
854-- 'Int16', even if it contains the value @1@.
856-- * If a numeric incompatibility is found, 'query' will throw a
859-- * The 'String' and 'Text' types are assumed to be encoded as
860-- UTF-8. If you use some other encoding, decoding may fail or give
861-- wrong results. In such cases, write a @newtype@ wrapper and a
862-- custom 'Result' instance to handle your encoding.
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