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
106 -- * Helper functions
111import Blaze.ByteString.Builder
112 ( Builder, fromByteString, toByteString )
113import Blaze.ByteString.Builder.Char8 (fromChar)
114import Control.Applicative ((<$>), pure)
115import Control.Exception
116 ( Exception, throw, throwIO, finally )
117import Control.Monad (foldM)
118import Data.ByteString (ByteString)
119import Data.Int (Int64)
120import Data.List (intersperse)
121import Data.Monoid (mconcat)
122import Data.Typeable (Typeable)
123import Database.PostgreSQL.Simple.Compat ( (<>) )
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 Database.PostgreSQL.Simple.Transaction
133import Database.PostgreSQL.Simple.TypeInfo
134import qualified Database.PostgreSQL.LibPQ as PQ
135import qualified Data.ByteString.Char8 as B
136import qualified Data.Text as T
137import qualified Data.Text.Encoding as TE
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 parseTemplate 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]
190 Nothing -> fmtError "syntax error in multi-row template" q []
192-- Split the input string into three pieces, @before@, @qbits@, and @after@,
193-- following this grammar:
195-- start: ^ before qbits after $
196-- before: ([^?]* [^?\w])? 'VALUES' \s*
197-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
201-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
203-- This would be much more concise with some sort of regex engine.
204-- 'formatMany' used to use pcre-light instead of this hand-written parser,
205-- but pcre is a hassle to install on Windows.
206parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
207parseTemplate template =
208 -- Convert input string to uppercase, to facilitate searching.
209 search $ B.map toUpper_ascii template
211 -- Search for the next occurrence of "VALUES"
213 case B.breakSubstring "VALUES" bs of
215 -- If "VALUES" is not present in the string, or any '?' characters
216 -- were encountered prior to it, fail.
217 | B.null y || ('?' `B.elem` x)
220 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
221 -- try the next occurrence.
222 | not (B.null x) && isIdent (B.last x)
223 -> search $ B.drop 6 y
225 -- Otherwise, we have a legitimate "VALUES" token.
227 -> parseQueryBits $ skipSpace $ B.drop 6 y
229 -- Parse '(' \s* '?' \s* . If this doesn't match
230 -- (and we don't consume a '?'), look for another "VALUES".
232 -- qb points to the open paren (if present), meaning it points to the
233 -- beginning of the "qbits" production described above. This is why we
234 -- pass it down to finishQueryBits.
236 | Just ('(', skipSpace -> bs1) <- B.uncons qb
237 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
238 = finishQueryBits qb bs2
242 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
244 -- Since we've already consumed at least one '?', there's no turning back.
245 -- The parse has to succeed here, or the whole thing fails
246 -- (because we don't allow '?' to appear outside of the VALUES list).
247 finishQueryBits qb bs0
248 | Just (')', bs1) <- B.uncons bs0
249 = if '?' `B.elem` bs1
251 else Just $ slice3 template qb bs1
252 | Just (',', skipSpace -> bs1) <- B.uncons bs0
253 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
254 = finishQueryBits qb bs2
258 -- Slice a string into three pieces, given the start offset of the second
259 -- and third pieces. Each "offset" is actually a tail of the uppercase
260 -- version of the template string. Its length is used to infer the offset.
262 -- It is important to note that we only slice the original template.
263 -- We don't want our all-caps trick messing up the actual query string.
264 slice3 source p1 p2 =
267 (s1, source') = B.splitAt (B.length source - B.length p1) source
268 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
270 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
273 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
274 -- in the PostgreSQL source. No need to check [a-z], since we converted
275 -- the whole string to uppercase.
276 isIdent c = (c >= '0' && c <= '9')
277 || (c >= 'A' && c <= 'Z')
278 || (c >= '\x80' && c <= '\xFF')
282 -- Based on {space} in scan.l
283 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
285 skipSpace = B.dropWhile isSpace_ascii
287escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
288escapeStringConn conn s =
289 withConnection conn $ \c ->
290 PQ.escapeStringConn c s >>= checkError c
292escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
293escapeByteaConn conn s =
294 withConnection conn $ \c ->
295 PQ.escapeByteaConn c s >>= checkError c
297checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
298checkError _ (Just x) = return $ Right x
299checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
301buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
302buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
303 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
304 (inQuotes . fromByteString)
305 utf8ToString = T.unpack . TE.decodeUtf8
306 sub (Plain b) = pure b
307 sub (Escape s) = quote <$> escapeStringConn conn s
308 sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
309 sub (Many ys) = mconcat <$> mapM sub ys
310 split s = fromByteString h : if B.null t then [] else split (B.tail t)
311 where (h,t) = B.break (=='?') s
312 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
314 zipParams _ _ = fmtError (show (B.count '?' template) ++
315 " '?' characters, but " ++
316 show (length xs) ++ " parameters") q xs
318-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
319-- expected to return results.
321-- Returns the number of rows affected.
323-- Throws 'FormatError' if the query could not be formatted correctly.
324execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
325execute conn template qs = do
326 result <- exec conn =<< formatQuery conn template qs
327 finishExecute conn template result
329-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
330-- expected to return results.
332-- Returns the number of rows affected.
334-- Throws 'FormatError' if the query could not be formatted correctly.
335executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
336executeMany _ _ [] = return 0
337executeMany conn q qs = do
338 result <- exec conn =<< formatMany conn q qs
339 finishExecute conn q result
341-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
342-- query that accepts multi-row input and is expected to return results.
343-- Note that it is possible to write
344-- @'query' conn "INSERT ... RETURNING ..." ...@
345-- in cases where you are only inserting a single row, and do not need
346-- functionality analogous to 'executeMany'.
348-- Throws 'FormatError' if the query could not be formatted correctly.
349returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
350returning _ _ [] = return []
351returning conn q qs = do
352 result <- exec conn =<< formatMany conn q qs
353 finishQuery conn q result
355-- | Perform a @SELECT@ or other SQL query that is expected to return
356-- results. All results are retrieved and converted before this
359-- When processing large results, this function will consume a lot of
360-- client-side memory. Consider using 'fold' instead.
362-- Exceptions that may be thrown:
364-- * 'FormatError': the query string could not be formatted correctly.
366-- * 'QueryError': the result contains no columns (i.e. you should be
367-- using 'execute' instead of 'query').
369-- * 'ResultError': result conversion failed.
370query :: (ToRow q, FromRow r)
371 => Connection -> Query -> q -> IO [r]
372query conn template qs = do
373 result <- exec conn =<< formatQuery conn template qs
374 finishQuery conn template result
376-- | A version of 'query' that does not perform query substitution.
377query_ :: (FromRow r) => Connection -> Query -> IO [r]
378query_ conn q@(Query que) = do
379 result <- exec conn que
380 finishQuery conn q result
382-- | Perform a @SELECT@ or other SQL query that is expected to return
383-- results. Results are streamed incrementally from the server, and
384-- consumed via a left fold.
386-- When dealing with small results, it may be simpler (and perhaps
387-- faster) to use 'query' instead.
389-- This fold is /not/ strict. The stream consumer is responsible for
390-- forcing the evaluation of its result to avoid space leaks.
392-- Exceptions that may be thrown:
394-- * 'FormatError': the query string could not be formatted correctly.
396-- * 'QueryError': the result contains no columns (i.e. you should be
397-- using 'execute' instead of 'query').
399-- * 'ResultError': result conversion failed.
401fold :: ( FromRow row, ToRow params )
406 -> (a -> row -> IO a)
408fold = foldWithOptions defaultFoldOptions
416 fetchQuantity :: !FetchQuantity,
417 transactionMode :: !TransactionMode
420defaultFoldOptions :: FoldOptions
421defaultFoldOptions = FoldOptions {
422 fetchQuantity = Automatic,
423 transactionMode = TransactionMode ReadCommitted ReadOnly
426foldWithOptions :: ( FromRow row, ToRow params )
432 -> (a -> row -> IO a)
434foldWithOptions opts conn template qs a f = do
435 q <- formatQuery conn template qs
436 doFold opts conn template (Query q) a f
438-- | A version of 'fold' that does not perform query substitution.
439fold_ :: (FromRow r) =>
442 -> a -- ^ Initial state for result consumer.
443 -> (a -> r -> IO a) -- ^ Result consumer.
445fold_ = foldWithOptions_ defaultFoldOptions
448foldWithOptions_ :: (FromRow r) =>
452 -> a -- ^ Initial state for result consumer.
453 -> (a -> r -> IO a) -- ^ Result consumer.
455foldWithOptions_ opts conn query a f = doFold opts conn query query a f
458doFold :: ( FromRow row )
464 -> (a -> row -> IO a)
466doFold FoldOptions{..} conn _template q a f = do
467 stat <- withConnection conn PQ.transactionStatus
469 PQ.TransIdle -> withTransactionMode transactionMode conn go
470 PQ.TransInTrans -> go
471 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
472 -- This _shouldn't_ occur in the current incarnation of
473 -- the library, as we aren't using libpq asynchronously.
474 -- However, it could occur in future incarnations of
475 -- this library or if client code uses the Internal module
476 -- to use raw libpq commands on postgresql-simple connections.
477 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
478 -- This should be turned into a better error message.
479 -- It is probably a bad idea to automatically roll
480 -- back the transaction and start another.
481 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
482 -- Not sure what this means.
485 -- FIXME: what about name clashes with already-declared cursors?
486 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR " <> q)
487 loop a `finally` execute_ conn "CLOSE fold"
489-- FIXME: choose the Automatic chunkSize more intelligently
490-- One possibility is to use the type of the results, although this
491-- still isn't a perfect solution, given that common types (e.g. text)
492-- are of highly variable size.
493-- A refinement of this technique is to pick this number adaptively
494-- as results are read in from the database.
495 chunkSize = case fetchQuantity of
499 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
500 if null rs then return a else foldM f a rs >>= loop
502-- | A version of 'fold' that does not transform a state value.
503forEach :: (ToRow q, FromRow r) =>
505 -> Query -- ^ Query template.
506 -> q -- ^ Query parameters.
507 -> (r -> IO ()) -- ^ Result consumer.
509forEach conn template qs = fold conn template qs () . const
510{-# INLINE forEach #-}
512-- | A version of 'forEach' that does not perform query substitution.
513forEach_ :: (FromRow r) =>
515 -> Query -- ^ Query template.
516 -> (r -> IO ()) -- ^ Result consumer.
518forEach_ conn template = fold_ conn template () . const
519{-# INLINE forEach_ #-}
521forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
522forM' lo hi m = loop hi []
530finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
531finishQuery conn q result = do
532 status <- PQ.resultStatus result
535 throwIO $ QueryError "query: Empty query" q
537 throwIO $ QueryError "query resulted in a command response" q
539 let unCol (PQ.Col x) = fromIntegral x :: Int
540 nrows <- PQ.ntuples result
541 ncols <- PQ.nfields result
542 forM' 0 (nrows-1) $ \row -> do
543 let rw = Row row result
544 okvc <- runConversion (runStateT (runReaderT (unRP fromRow) rw) 0) conn
546 Ok (val,col) | col == ncols -> return val
548 vals <- forM' 0 (ncols-1) $ \c -> do
549 tinfo <- getTypeInfo conn =<< PQ.ftype result c
550 v <- PQ.getvalue result row c
553 throw (ConversionFailed
554 (show (unCol ncols) ++ " values: " ++ show vals)
557 (show (unCol col) ++ " slots in target type")
558 "mismatch between number of columns to \
559 \convert and number in target type")
560 Errors [] -> throwIO $ ConversionFailed "" Nothing "" "" "unknown error"
561 Errors [x] -> throwIO x
562 Errors xs -> throwIO $ ManyErrors xs
564 throwIO $ QueryError "query: COPY TO is not supported" q
566 throwIO $ QueryError "query: COPY FROM is not supported" q
567 PQ.BadResponse -> throwResultError "query" result status
568 PQ.NonfatalError -> throwResultError "query" result status
569 PQ.FatalError -> throwResultError "query" result status
571ellipsis :: ByteString -> ByteString
573 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
576fmtError :: String -> Query -> [Action] -> a
577fmtError msg q xs = throw FormatError {
580 , fmtParams = map twiddle xs
582 where twiddle (Plain b) = toByteString b
583 twiddle (Escape s) = s
584 twiddle (EscapeByteA s) = s
585 twiddle (Many ys) = B.concat (map twiddle ys)
589-- SQL-based applications are somewhat notorious for their
590-- susceptibility to attacks through the injection of maliciously
591-- crafted data. The primary reason for widespread vulnerability to
592-- SQL injections is that many applications are sloppy in handling
593-- user data when constructing SQL queries.
595-- This library provides a 'Query' type and a parameter substitution
596-- facility to address both ease of use and security.
600-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
601-- exposes a tiny API that is not compatible with the 'ByteString'
602-- API; this makes it difficult to construct queries from fragments of
603-- strings. The 'query' and 'execute' functions require queries to be
606-- To most easily construct a query, enable GHC's @OverloadedStrings@
607-- language extension and write your query as a normal literal string.
609-- > {-# LANGUAGE OverloadedStrings #-}
611-- > import Database.PostgreSQL.Simple
614-- > conn <- connect defaultConnectInfo
615-- > query conn "select 2 + 2"
617-- A 'Query' value does not represent the actual query that will be
618-- executed, but is a template for constructing the final query.
622-- Since applications need to be able to construct queries with
623-- parameters that change, this library provides a query substitution
626-- The 'Query' template accepted by 'query' and 'execute' can contain
627-- any number of \"@?@\" characters. Both 'query' and 'execute'
628-- accept a third argument, typically a tuple. When constructing the
629-- real query to execute, these functions replace the first \"@?@\" in
630-- the template with the first element of the tuple, the second
631-- \"@?@\" with the second element, and so on. If necessary, each
632-- tuple element will be quoted and escaped prior to substitution;
633-- this defeats the single most common injection vector for malicious
636-- For example, given the following 'Query' template:
638-- > select * from user where first_name = ? and age > ?
640-- And a tuple of this form:
642-- > ("Boris" :: String, 37 :: Int)
644-- The query to be executed will look like this after substitution:
646-- > select * from user where first_name = 'Boris' and age > 37
648-- If there is a mismatch between the number of \"@?@\" characters in
649-- your template and the number of elements in your tuple, a
650-- 'FormatError' will be thrown.
652-- Note that the substitution functions do not attempt to parse or
653-- validate your query. It's up to you to write syntactically valid
654-- SQL, and to ensure that each \"@?@\" in your query template is
655-- matched with the right tuple element.
659-- Automated type inference means that you will often be able to avoid
660-- supplying explicit type signatures for the elements of a tuple.
661-- However, sometimes the compiler will not be able to infer your
662-- types. Consider a case where you write a numeric literal in a
665-- > query conn "select ? + ?" (40,2)
667-- The above query will be rejected by the compiler, because it does
668-- not know the specific numeric types of the literals @40@ and @2@.
669-- This is easily fixed:
671-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
673-- The same kind of problem can arise with string literals if you have
674-- the @OverloadedStrings@ language extension enabled. Again, just
675-- use an explicit type signature if this happens.
679-- Haskell lacks a single-element tuple type, so if you have just one
680-- value you want substituted into a query, what should you do?
682-- The obvious approach would appear to be something like this:
684-- > instance (Param a) => QueryParam a where
687-- Unfortunately, this wreaks havoc with type inference, so we take a
688-- different tack. To represent a single value @val@ as a parameter, write
689-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
691-- Here's an example using a singleton list:
693-- > execute conn "insert into users (first_name) values (?)"
698-- Suppose you want to write a query using an @IN@ clause:
700-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
702-- In such cases, it's common for both the elements and length of the
703-- list after the @IN@ keyword to vary from query to query.
705-- To address this case, use the 'In' type wrapper, and use a single
706-- \"@?@\" character to represent the list. Omit the parentheses
707-- around the list; these will be added for you.
711-- > query conn "select * from users where first_name in ?" $
712-- > In ["Anna", "Boris", "Carla"]
714-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
715-- substituted instead, to ensure that your clause remains
716-- syntactically valid.
720-- If you know that you have many rows of data to insert into a table,
721-- it is much more efficient to perform all the insertions in a single
722-- multi-row @INSERT@ statement than individually.
724-- The 'executeMany' function is intended specifically for helping
725-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
726-- query substitution are different than those for 'execute'.
728-- What 'executeMany' searches for in your 'Query' template is a
729-- single substring of the form:
733-- The rules are as follows:
735-- * The keyword @VALUES@ is matched case insensitively.
737-- * There must be no other \"@?@\" characters anywhere in your
740-- * There must be one or more \"@?@\" in the parentheses.
742-- * Extra white space is fine.
744-- The last argument to 'executeMany' is a list of parameter
745-- tuples. These will be substituted into the query where the @(?,?)@
746-- string appears, in a form suitable for use in a multi-row @INSERT@
749-- Here is an example:
752-- > "insert into users (first_name,last_name) values (?,?)"
753-- > [("Boris","Karloff"),("Ed","Wood")]
755-- The query that will be executed here will look like this
756-- (reformatted for tidiness):
758-- > insert into users (first_name,last_name) values
759-- > ('Boris','Karloff'),('Ed','Wood')
763-- The 'returning' function is similar to 'executeMany' but is
764-- intended for use with multi-tuple @INSERT@ or @UPDATE@ statements
765-- that make use of @RETURNING@.
767-- For example, were there an auto-incrementing @id@ column and
768-- timestamp column @t@ that defaulted to the present time for the
769-- @sales@ table, then the following query would insert two new
770-- sales records and also return their new @id@s and timestamps.
772-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
773-- > xs :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
777-- The 'query' and 'query_' functions return a list of values in the
778-- 'FromRow' typeclass. This class performs automatic extraction
779-- and type conversion of rows from a query result.
781-- Here is a simple example of how to extract results:
783-- > import qualified Data.Text as Text
785-- > xs <- query_ conn "select name,age from users"
786-- > forM_ xs $ \(name,age) ->
787-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
789-- Notice two important details about this code:
791-- * The number of columns we ask for in the query template must
792-- exactly match the number of elements we specify in a row of the
793-- result tuple. If they do not match, a 'ResultError' exception
796-- * Sometimes, the compiler needs our help in specifying types. It
797-- can infer that @name@ must be a 'Text', due to our use of the
798-- @unpack@ function. However, we have to tell it the type of @age@,
799-- as it has no other information to determine the exact type.
803-- The type of a result tuple will look something like this:
807-- Although SQL can accommodate @NULL@ as a value for any of these
808-- types, Haskell cannot. If your result contains columns that may be
809-- @NULL@, be sure that you use 'Maybe' in those positions of your
812-- > (Text, Maybe Int, Int)
814-- If 'query' encounters a @NULL@ in a row where the corresponding
815-- Haskell type is not 'Maybe', it will throw a 'ResultError'
820-- To specify that a query returns a single-column result, use the
823-- > xs <- query_ conn "select id from users"
824-- > forM_ xs $ \(Only dbid) -> {- ... -}
828-- Conversion of SQL values to Haskell values is somewhat
829-- permissive. Here are the rules.
831-- * For numeric types, any Haskell type that can accurately represent
832-- all values of the given PostgreSQL type is considered \"compatible\".
833-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
834-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
835-- represent a @SMALLINT@, so it is considered compatble with those types.
837-- * A numeric compatibility check is based only on the type of a
838-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
839-- @BIGINT@ column will be considered incompatible with a Haskell
840-- 'Int16', even if it contains the value @1@.
842-- * If a numeric incompatibility is found, 'query' will throw a
845-- * The 'String' and 'Text' types are assumed to be encoded as
846-- UTF-8. If you use some other encoding, decoding may fail or give
847-- wrong results. In such cases, write a @newtype@ wrapper and a
848-- 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