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
17-- A mid-level client library for the PostgreSQL database, aimed at ease of
18-- use and high performance.
20------------------------------------------------------------------------------
22module Database.PostgreSQL.Simple
30 -- ** Parameter substitution
36 -- ** Substituting a single parameter
39 -- ** Representing a list of values
42 -- ** Modifying multiple rows at once
45 -- ** @RETURNING@: modifications that return results
48 -- * Extracting results
51 -- ** Handling null values
54 -- ** Type conversions
72 -- * Connection management
73 , Base.connectPostgreSQL
76 , Base.ConnectInfo(..)
77 , Base.defaultConnectInfo
78 , Base.postgreSQLConnectionString
79 -- * Queries that return results
82 -- ** Queries taking parser as argument
85 -- * Queries that stream results
96 -- ** Queries that stream results taking a parser as an argument
98 , foldWithOptionsAndParser
100 , foldWithOptionsAndParser_
104 -- * Statements that do not return results
109 -- * Transaction handling
116 -- * Helper functions
121import Data.ByteString.Builder (Builder, byteString, char8)
122import Control.Applicative ((<$>))
123import Control.Exception as E
124import Data.ByteString (ByteString)
125import Data.Int (Int64)
126import Data.List (intersperse)
127import Data.Monoid (mconcat)
128import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
129import Database.PostgreSQL.Simple.Cursor
130import Database.PostgreSQL.Simple.FromField (ResultError(..))
131import Database.PostgreSQL.Simple.FromRow (FromRow(..))
132import Database.PostgreSQL.Simple.ToField (Action(..))
133import Database.PostgreSQL.Simple.ToRow (ToRow(..))
134import Database.PostgreSQL.Simple.Types
135 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
136import Database.PostgreSQL.Simple.Internal as Base
137import Database.PostgreSQL.Simple.Internal.PQResultUtils
138import Database.PostgreSQL.Simple.Transaction
139import qualified Database.PostgreSQL.LibPQ as PQ
140import qualified Data.ByteString.Char8 as B
143-- | Format a query string.
145-- This function is exposed to help with debugging and logging. Do not
146-- use it to prepare queries for execution.
148-- String parameters are escaped according to the character set in use
149-- on the 'Connection'.
151-- Throws 'FormatError' if the query string could not be formatted
153formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
154formatQuery conn q@(Query template) qs
155 | null xs && '?' `B.notElem` template = return template
156 | otherwise = toByteString <$> buildQuery conn q template xs
159-- | Format a query string with a variable number of rows.
161-- This function is exposed to help with debugging and logging. Do not
162-- use it to prepare queries for execution.
164-- The query string must contain exactly one substitution group,
165-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
166-- followed by an \"@(@\" character, a series of one or more \"@?@\"
167-- characters separated by commas, and a \"@)@\" character. White
168-- space in a substitution group is permitted.
170-- Throws 'FormatError' if the query string could not be formatted
172formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
173formatMany _ q [] = fmtError "no rows supplied" q []
174formatMany conn q@(Query template) qs = do
175 case parseTemplate template of
176 Just (before, qbits, after) -> do
177 bs <- mapM (buildQuery conn q qbits . toRow) qs
178 return . toByteString . mconcat $ byteString before :
179 intersperse (char8 ',') bs ++
181 Nothing -> fmtError "syntax error in multi-row template" q []
183-- Split the input string into three pieces, @before@, @qbits@, and @after@,
184-- following this grammar:
186-- start: ^ before qbits after $
187-- before: ([^?]* [^?\w])? 'VALUES' \s*
188-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
192-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
194-- This would be much more concise with some sort of regex engine.
195-- 'formatMany' used to use pcre-light instead of this hand-written parser,
196-- but pcre is a hassle to install on Windows.
197parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
198parseTemplate template =
199 -- Convert input string to uppercase, to facilitate searching.
200 search $ B.map toUpper_ascii template
202 -- Search for the next occurrence of "VALUES"
204 case B.breakSubstring "VALUES" bs of
206 -- If "VALUES" is not present in the string, or any '?' characters
207 -- were encountered prior to it, fail.
208 | B.null y || ('?' `B.elem` x)
211 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
212 -- try the next occurrence.
213 | not (B.null x) && isIdent (B.last x)
214 -> search $ B.drop 6 y
216 -- Otherwise, we have a legitimate "VALUES" token.
218 -> parseQueryBits $ skipSpace $ B.drop 6 y
220 -- Parse '(' \s* '?' \s* . If this doesn't match
221 -- (and we don't consume a '?'), look for another "VALUES".
223 -- qb points to the open paren (if present), meaning it points to the
224 -- beginning of the "qbits" production described above. This is why we
225 -- pass it down to finishQueryBits.
227 | Just ('(', skipSpace -> bs1) <- B.uncons qb
228 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
229 = finishQueryBits qb bs2
233 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
235 -- Since we've already consumed at least one '?', there's no turning back.
236 -- The parse has to succeed here, or the whole thing fails
237 -- (because we don't allow '?' to appear outside of the VALUES list).
238 finishQueryBits qb bs0
239 | Just (')', bs1) <- B.uncons bs0
240 = if '?' `B.elem` bs1
242 else Just $ slice3 template qb bs1
243 | Just (',', skipSpace -> bs1) <- B.uncons bs0
244 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
245 = finishQueryBits qb bs2
249 -- Slice a string into three pieces, given the start offset of the second
250 -- and third pieces. Each "offset" is actually a tail of the uppercase
251 -- version of the template string. Its length is used to infer the offset.
253 -- It is important to note that we only slice the original template.
254 -- We don't want our all-caps trick messing up the actual query string.
255 slice3 source p1 p2 =
258 (s1, source') = B.splitAt (B.length source - B.length p1) source
259 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
261 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
264 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
265 -- in the PostgreSQL source. No need to check [a-z], since we converted
266 -- the whole string to uppercase.
267 isIdent c = (c >= '0' && c <= '9')
268 || (c >= 'A' && c <= 'Z')
269 || (c >= '\x80' && c <= '\xFF')
273 -- Based on {space} in scan.l
274 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
276 skipSpace = B.dropWhile isSpace_ascii
279buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
280buildQuery conn q template xs =
281 zipParams (split template) <$> mapM (buildAction conn q xs) xs
283 -- This part escapes double '??'s to make literal '?'s possible
284 -- in PostgreSQL queries using the JSON operators: @?@, @?|@ and @?&@
285 let (h,t) = breakOnSingleQuestionMark s
289 else split (B.tail t)
290 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
292 zipParams _ _ = fmtError (show countSingleQs ++
293 " single '?' characters, but " ++
294 show (length xs) ++ " parameters") q xs
295 countSingleQs = go 0 template
296 where go i "" = (i :: Int)
297 go i bs = case qms of
298 ("?","?") -> go i nextQMBS
299 ("?",_) -> go (i+1) nextQMBS
301 where qms = B.splitAt 1 qmBS
302 (qmBS,nextQMBS) = B.splitAt 2 qmBS'
303 qmBS' = B.dropWhile (/= '?') bs
305-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
306-- expected to return results.
308-- Returns the number of rows affected.
310-- Throws 'FormatError' if the query could not be formatted correctly, or
311-- a 'SqlError' exception if the backend returns an error.
312execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
313execute conn template qs = do
314 result <- exec conn =<< formatQuery conn template qs
315 finishExecute conn template result
317-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
318-- expected to return results.
320-- Returns the number of rows affected. If the list of parameters is empty,
321-- this function will simply return 0 without issuing the query to the backend.
322-- If this is not desired, consider using the 'Values' constructor instead.
324-- Throws 'FormatError' if the query could not be formatted correctly, or
325-- a 'SqlError' exception if the backend returns an error.
327-- For example, here's a command that inserts two rows into a table
331-- executeMany c [sql|
332-- INSERT INTO sometable VALUES (?,?)
333-- |] [(1, \"hello\"),(2, \"world\")]
336-- Here's an canonical example of a multi-row update command:
339-- executeMany c [sql|
342-- FROM (VALUES (?,?)) as upd(x,y)
343-- WHERE sometable.x = upd.x
344-- |] [(1, \"hello\"),(2, \"world\")]
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-- If the list of parameters is empty, this function will simply return @[]@
361-- without issuing the query to the backend. If this is not desired,
362-- consider using the 'Values' constructor instead.
364-- Throws 'FormatError' if the query could not be formatted correctly.
365returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
366returning = returningWith fromRow
368-- | A version of 'returning' taking parser as argument
369returningWith :: (ToRow q) => RowParser r -> Connection -> Query -> [q] -> IO [r]
370returningWith _ _ _ [] = return []
371returningWith parser conn q qs = do
372 result <- exec conn =<< formatMany conn q qs
373 finishQueryWith parser conn q result
375-- | Perform a @SELECT@ or other SQL query that is expected to return
376-- results. All results are retrieved and converted before this
379-- When processing large results, this function will consume a lot of
380-- client-side memory. Consider using 'fold' instead.
382-- Exceptions that may be thrown:
384-- * 'FormatError': the query string could not be formatted correctly.
386-- * 'QueryError': the result contains no columns (i.e. you should be
387-- using 'execute' instead of 'query').
389-- * 'ResultError': result conversion failed.
391-- * 'SqlError': the postgresql backend returned an error, e.g.
392-- a syntax or type error, or an incorrect table or column name.
393query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r]
394query = queryWith fromRow
396-- | A version of 'query' that does not perform query substitution.
397query_ :: (FromRow r) => Connection -> Query -> IO [r]
398query_ = queryWith_ fromRow
400-- | A version of 'query' taking parser as argument
401queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
402queryWith parser conn template qs = do
403 result <- exec conn =<< formatQuery conn template qs
404 finishQueryWith parser conn template result
406-- | A version of 'query_' taking parser as argument
407queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
408queryWith_ parser conn q@(Query que) = do
409 result <- exec conn que
410 finishQueryWith parser conn q result
412-- | Perform a @SELECT@ or other SQL query that is expected to return
413-- results. Results are streamed incrementally from the server, and
414-- consumed via a left fold.
416-- When dealing with small results, it may be simpler (and perhaps
417-- faster) to use 'query' instead.
419-- This fold is /not/ strict. The stream consumer is responsible for
420-- forcing the evaluation of its result to avoid space leaks.
422-- This is implemented using a database cursor. As such, this requires
423-- a transaction. This function will detect whether or not there is a
424-- transaction in progress, and will create a 'ReadCommitted' 'ReadOnly'
425-- transaction if needed. The cursor is given a unique temporary name,
426-- so the consumer may itself call fold.
428-- Exceptions that may be thrown:
430-- * 'FormatError': the query string could not be formatted correctly.
432-- * 'QueryError': the result contains no columns (i.e. you should be
433-- using 'execute' instead of 'query').
435-- * 'ResultError': result conversion failed.
437-- * 'SqlError': the postgresql backend returned an error, e.g.
438-- a syntax or type error, or an incorrect table or column name.
439fold :: ( FromRow row, ToRow params )
444 -> (a -> row -> IO a)
446fold = foldWithOptions defaultFoldOptions
448-- | A version of 'fold' taking a parser as an argument
449foldWith :: ( ToRow params )
455 -> (a -> row -> IO a)
457foldWith = foldWithOptionsAndParser defaultFoldOptions
459-- | Number of rows to fetch at a time. 'Automatic' currently defaults
460-- to 256 rows, although it might be nice to make this more intelligent
461-- based on e.g. the average size of the rows.
468 fetchQuantity :: !FetchQuantity,
469 transactionMode :: !TransactionMode
472-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
473defaultFoldOptions :: FoldOptions
474defaultFoldOptions = FoldOptions {
475 fetchQuantity = Automatic,
476 transactionMode = TransactionMode ReadCommitted ReadOnly
479-- | The same as 'fold', but this provides a bit more control over
480-- lower-level details. Currently, the number of rows fetched per
481-- round-trip to the server and the transaction mode may be adjusted
482-- accordingly. If the connection is already in a transaction,
483-- then the existing transaction is used and thus the 'transactionMode'
485foldWithOptions :: ( FromRow row, ToRow params )
491 -> (a -> row -> IO a)
493foldWithOptions opts = foldWithOptionsAndParser opts fromRow
495-- | A version of 'foldWithOptions' taking a parser as an argument
496foldWithOptionsAndParser :: (ToRow params)
503 -> (a -> row -> IO a)
505foldWithOptionsAndParser opts parser conn template qs a f = do
506 q <- formatQuery conn template qs
507 doFold opts parser conn template (Query q) a f
509-- | A version of 'fold' that does not perform query substitution.
510fold_ :: (FromRow r) =>
513 -> a -- ^ Initial state for result consumer.
514 -> (a -> r -> IO a) -- ^ Result consumer.
516fold_ = foldWithOptions_ defaultFoldOptions
518-- | A version of 'fold_' taking a parser as an argument
519foldWith_ :: RowParser r
525foldWith_ = foldWithOptionsAndParser_ defaultFoldOptions
527foldWithOptions_ :: (FromRow r) =>
531 -> a -- ^ Initial state for result consumer.
532 -> (a -> r -> IO a) -- ^ Result consumer.
534foldWithOptions_ opts conn query' a f = doFold opts fromRow conn query' query' a f
536-- | A version of 'foldWithOptions_' taking a parser as an argument
537foldWithOptionsAndParser_ :: FoldOptions
541 -> a -- ^ Initial state for result consumer.
542 -> (a -> r -> IO a) -- ^ Result consumer.
544foldWithOptionsAndParser_ opts parser conn query' a f = doFold opts parser conn query' query' a f
552 -> (a -> row -> IO a)
554doFold FoldOptions{..} parser conn _template q a0 f = do
555 stat <- withConnection conn PQ.transactionStatus
557 PQ.TransIdle -> withTransactionMode transactionMode conn go
558 PQ.TransInTrans -> go
559 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
560 -- This _shouldn't_ occur in the current incarnation of
561 -- the library, as we aren't using libpq asynchronously.
562 -- However, it could occur in future incarnations of
563 -- this library or if client code uses the Internal module
564 -- to use raw libpq commands on postgresql-simple connections.
565 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
566 -- This should be turned into a better error message.
567 -- It is probably a bad idea to automatically roll
568 -- back the transaction and start another.
569 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
570 -- Not sure what this means.
575 foldForwardWithParser cursor parser chunkSize f a
577 go = bracket declare closeCursor $ \cursor ->
578 let loop a = fetch cursor a >>=
584-- FIXME: choose the Automatic chunkSize more intelligently
585-- One possibility is to use the type of the results, although this
586-- still isn't a perfect solution, given that common types (e.g. text)
587-- are of highly variable size.
588-- A refinement of this technique is to pick this number adaptively
589-- as results are read in from the database.
590 chunkSize = case fetchQuantity of
594-- | A version of 'fold' that does not transform a state value.
595forEach :: (ToRow q, FromRow r) =>
597 -> Query -- ^ Query template.
598 -> q -- ^ Query parameters.
599 -> (r -> IO ()) -- ^ Result consumer.
601forEach = forEachWith fromRow
602{-# INLINE forEach #-}
604-- | A version of 'forEach' taking a parser as an argument
605forEachWith :: ( ToRow q )
612forEachWith parser conn template qs = foldWith parser conn template qs () . const
613{-# INLINE forEachWith #-}
615-- | A version of 'forEach' that does not perform query substitution.
616forEach_ :: (FromRow r) =>
618 -> Query -- ^ Query template.
619 -> (r -> IO ()) -- ^ Result consumer.
621forEach_ = forEachWith_ fromRow
622{-# INLINE forEach_ #-}
624forEachWith_ :: RowParser r
629forEachWith_ parser conn template = foldWith_ parser conn template () . const
630{-# INLINE forEachWith_ #-}
635-- SQL-based applications are somewhat notorious for their
636-- susceptibility to attacks through the injection of maliciously
637-- crafted data. The primary reason for widespread vulnerability to
638-- SQL injections is that many applications are sloppy in handling
639-- user data when constructing SQL queries.
641-- This library provides a 'Query' type and a parameter substitution
642-- facility to address both ease of use and security.
646-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
647-- exposes a tiny API that is not compatible with the 'ByteString'
648-- API; this makes it difficult to construct queries from fragments of
649-- strings. The 'query' and 'execute' functions require queries to be
652-- To most easily construct a query, enable GHC's @OverloadedStrings@
653-- language extension and write your query as a normal literal string.
655-- > {-# LANGUAGE OverloadedStrings #-}
657-- > import Database.PostgreSQL.Simple
661-- > conn <- connectPostgreSQL ""
662-- > [Only i] <- query_ conn "select 2 + 2"
665-- A 'Query' value does not represent the actual query that will be
666-- executed, but is a template for constructing the final query.
670-- Since applications need to be able to construct queries with
671-- parameters that change, this library provides a query substitution
674-- The 'Query' template accepted by 'query' and 'execute' can contain
675-- any number of \"@?@\" characters. Both 'query' and 'execute'
676-- accept a third argument, typically a tuple. When constructing the
677-- real query to execute, these functions replace the first \"@?@\" in
678-- the template with the first element of the tuple, the second
679-- \"@?@\" with the second element, and so on. If necessary, each
680-- tuple element will be quoted and escaped prior to substitution;
681-- this defeats the single most common injection vector for malicious
684-- For example, given the following 'Query' template:
686-- > select * from user where first_name = ? and age > ?
688-- And a tuple of this form:
690-- > ("Boris" :: String, 37 :: Int)
692-- The query to be executed will look like this after substitution:
694-- > select * from user where first_name = 'Boris' and age > 37
696-- If there is a mismatch between the number of \"@?@\" characters in
697-- your template and the number of elements in your tuple, a
698-- 'FormatError' will be thrown.
700-- Note that the substitution functions do not attempt to parse or
701-- validate your query. It's up to you to write syntactically valid
702-- SQL, and to ensure that each \"@?@\" in your query template is
703-- matched with the right tuple element.
707-- Automated type inference means that you will often be able to avoid
708-- supplying explicit type signatures for the elements of a tuple.
709-- However, sometimes the compiler will not be able to infer your
710-- types. Consider a case where you write a numeric literal in a
713-- > query conn "select ? + ?" (40,2)
715-- The above query will be rejected by the compiler, because it does
716-- not know the specific numeric types of the literals @40@ and @2@.
717-- This is easily fixed:
719-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
721-- The same kind of problem can arise with string literals if you have
722-- the @OverloadedStrings@ language extension enabled. Again, just
723-- use an explicit type signature if this happens.
725-- Finally, remember that the compiler must be able to infer the type
726-- of a query's /results/ as well as its parameters. We might like
727-- the following example to work:
729-- > print =<< query_ conn "select 2 + 2"
731-- Unfortunately, while a quick glance tells us that the result type
732-- should be a single row containing a single numeric column, the
733-- compiler has no way to infer what the types are. We can easily fix
734-- this by providing an explicit type annotation:
736-- > xs <- query_ conn "select 2 + 2"
737-- > print (xs :: [Only Int])
741-- Haskell lacks a single-element tuple type, so if you have just one
742-- value you want substituted into a query or a single-column result,
743-- what should you do?
745-- The obvious approach would appear to be something like this:
747-- > instance (ToField a) => ToRow a where
750-- Unfortunately, this wreaks havoc with type inference, so we take a
751-- different tack. To represent a single value @val@ as a parameter, write
752-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
754-- Here's an example using a singleton list:
756-- > execute conn "insert into users (first_name) values (?)"
759-- A row of /n/ query results is represented using an /n/-tuple, so
760-- you should use 'Only' to represent a single-column result.
764-- Suppose you want to write a query using an @IN@ clause:
766-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
768-- In such cases, it's common for both the elements and length of the
769-- list after the @IN@ keyword to vary from query to query.
771-- To address this case, use the 'In' type wrapper, and use a single
772-- \"@?@\" character to represent the list. Omit the parentheses
773-- around the list; these will be added for you.
777-- > query conn "select * from users where first_name in ?" $
778-- > Only $ In ["Anna", "Boris", "Carla"]
780-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
781-- substituted instead, to ensure that your clause remains
782-- syntactically valid.
786-- If you know that you have many rows of data to insert into a table,
787-- it is much more efficient to perform all the insertions in a single
788-- multi-row @INSERT@ statement than individually.
790-- The 'executeMany' function is intended specifically for helping
791-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
792-- query substitution are different than those for 'execute'.
794-- What 'executeMany' searches for in your 'Query' template is a
795-- single substring of the form:
799-- The rules are as follows:
801-- * The keyword @VALUES@ is matched case insensitively.
803-- * There must be no other \"@?@\" characters anywhere in your
806-- * There must be one or more \"@?@\" in the parentheses.
808-- * Extra white space is fine.
810-- The last argument to 'executeMany' is a list of parameter
811-- tuples. These will be substituted into the query where the @(?,?)@
812-- string appears, in a form suitable for use in a multi-row @INSERT@
815-- Here is an example:
818-- > "insert into users (first_name,last_name) values (?,?)"
819-- > [("Boris","Karloff"),("Ed","Wood")]
821-- The query that will be executed here will look like this
822-- (reformatted for tidiness):
824-- > insert into users (first_name,last_name) values
825-- > ('Boris','Karloff'),('Ed','Wood')
829-- PostgreSQL supports returning values from data manipulation statements
830-- such as @INSERT@ and @UPDATE@. You can use these statements by
831-- using 'query' instead of 'execute'. For multi-tuple inserts,
832-- use 'returning' instead of 'executeMany'.
834-- For example, were there an auto-incrementing @id@ column and
835-- timestamp column @t@ that defaulted to the present time for the
836-- @sales@ table, then the following query would insert two new
837-- sales records and also return their new @id@s and timestamps.
839-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
840-- > xs :: [(Int, UTCTime)] <- query conn q (15,"Sawdust")
841-- > ys :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
845-- The 'query' and 'query_' functions return a list of values in the
846-- 'FromRow' typeclass. This class performs automatic extraction
847-- and type conversion of rows from a query result.
849-- Here is a simple example of how to extract results:
851-- > import qualified Data.Text as Text
853-- > xs <- query_ conn "select name,age from users"
854-- > forM_ xs $ \(name,age) ->
855-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
857-- Notice two important details about this code:
859-- * The number of columns we ask for in the query template must
860-- exactly match the number of elements we specify in a row of the
861-- result tuple. If they do not match, a 'ResultError' exception
864-- * Sometimes, the compiler needs our help in specifying types. It
865-- can infer that @name@ must be a 'Text', due to our use of the
866-- @unpack@ function. However, we have to tell it the type of @age@,
867-- as it has no other information to determine the exact type.
871-- The type of a result tuple will look something like this:
875-- Although SQL can accommodate @NULL@ as a value for any of these
876-- types, Haskell cannot. If your result contains columns that may be
877-- @NULL@, be sure that you use 'Maybe' in those positions of your
880-- > (Text, Maybe Int, Int)
882-- If 'query' encounters a @NULL@ in a row where the corresponding
883-- Haskell type is not 'Maybe', it will throw a 'ResultError'
888-- To specify that a query returns a single-column result, use the
891-- > xs <- query_ conn "select id from users"
892-- > forM_ xs $ \(Only dbid) -> {- ... -}
896-- Conversion of SQL values to Haskell values is somewhat
897-- permissive. Here are the rules.
899-- * For numeric types, any Haskell type that can accurately represent
900-- all values of the given PostgreSQL type is considered \"compatible\".
901-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
902-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
903-- represent a @SMALLINT@, so it is considered compatble with those types.
905-- * A numeric compatibility check is based only on the type of a
906-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
907-- @BIGINT@ column will be considered incompatible with a Haskell
908-- 'Int16', even if it contains the value @1@.
910-- * If a numeric incompatibility is found, 'query' will throw a
913-- * The 'String' and 'Text' types are assumed to be encoded as
914-- UTF-8. If you use some other encoding, decoding may fail or give
915-- wrong results. In such cases, write a @newtype@ wrapper and a
916-- 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