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
67 , SomePostgreSqlException(..)
73 -- * Connection management
74 , Base.connectPostgreSQL
78 , Base.ConnectInfo(..)
79 , Base.defaultConnectInfo
80 , Base.postgreSQLConnectionString
81 -- * Queries that return results
84 -- ** Queries taking parser as argument
87 -- * Queries that stream results
98 -- ** Queries that stream results taking a parser as an argument
100 , foldWithOptionsAndParser
102 , foldWithOptionsAndParser_
106 -- * Statements that do not return results
111 -- * Transaction handling
118 -- * Helper functions
123import Data.ByteString.Builder (Builder, byteString, char8)
124import Control.Applicative ((<$>))
125import Control.Exception as E
126import Data.ByteString (ByteString)
127import Data.Int (Int64)
128import Data.List (intersperse)
129import Data.Monoid (mconcat)
130import Database.PostgreSQL.Simple.Compat ((<>), toByteString)
131import Database.PostgreSQL.Simple.Cursor
132import Database.PostgreSQL.Simple.FromField (ResultError(..))
133import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134import Database.PostgreSQL.Simple.ToField (Action(..))
135import Database.PostgreSQL.Simple.ToRow (ToRow(..))
136import Database.PostgreSQL.Simple.Types
137 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
138import Database.PostgreSQL.Simple.Internal as Base
139import Database.PostgreSQL.Simple.Internal.PQResultUtils
140import Database.PostgreSQL.Simple.Transaction
141import qualified Database.PostgreSQL.LibPQ as PQ
142import qualified Data.ByteString.Char8 as B
145-- | Format a query string.
147-- This function is exposed to help with debugging and logging. Do not
148-- use it to prepare queries for execution.
150-- String parameters are escaped according to the character set in use
151-- on the 'Connection'.
153-- Throws 'FormatError' if the query string could not be formatted
155formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
156formatQuery conn q@(Query template) qs
157 | null xs && '?' `B.notElem` template = return template
158 | otherwise = toByteString <$> buildQuery conn q template xs
161-- | Format a query string with a variable number of rows.
163-- This function is exposed to help with debugging and logging. Do not
164-- use it to prepare queries for execution.
166-- The query string must contain exactly one substitution group,
167-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
168-- followed by an \"@(@\" character, a series of one or more \"@?@\"
169-- characters separated by commas, and a \"@)@\" character. White
170-- space in a substitution group is permitted.
172-- Throws 'FormatError' if the query string could not be formatted
174formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
175formatMany _ q [] = fmtError "no rows supplied" q []
176formatMany conn q@(Query template) qs = do
177 case parseTemplate template of
178 Just (before, qbits, after) -> do
179 bs <- mapM (buildQuery conn q qbits . toRow) qs
180 return . toByteString . mconcat $ byteString before :
181 intersperse (char8 ',') bs ++
183 Nothing -> fmtError "syntax error in multi-row template" q []
185-- Split the input string into three pieces, @before@, @qbits@, and @after@,
186-- following this grammar:
188-- start: ^ before qbits after $
189-- before: ([^?]* [^?\w])? 'VALUES' \s*
190-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
194-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
196-- This would be much more concise with some sort of regex engine.
197-- 'formatMany' used to use pcre-light instead of this hand-written parser,
198-- but pcre is a hassle to install on Windows.
199parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
200parseTemplate template =
201 -- Convert input string to uppercase, to facilitate searching.
202 search $ B.map toUpper_ascii template
204 -- Search for the next occurrence of "VALUES"
206 case B.breakSubstring "VALUES" bs of
208 -- If "VALUES" is not present in the string, or any '?' characters
209 -- were encountered prior to it, fail.
210 | B.null y || ('?' `B.elem` x)
213 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
214 -- try the next occurrence.
215 | not (B.null x) && isIdent (B.last x)
216 -> search $ B.drop 6 y
218 -- Otherwise, we have a legitimate "VALUES" token.
220 -> parseQueryBits $ skipSpace $ B.drop 6 y
222 -- Parse '(' \s* '?' \s* . If this doesn't match
223 -- (and we don't consume a '?'), look for another "VALUES".
225 -- qb points to the open paren (if present), meaning it points to the
226 -- beginning of the "qbits" production described above. This is why we
227 -- pass it down to finishQueryBits.
229 | Just ('(', skipSpace -> bs1) <- B.uncons qb
230 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
231 = finishQueryBits qb bs2
235 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
237 -- Since we've already consumed at least one '?', there's no turning back.
238 -- The parse has to succeed here, or the whole thing fails
239 -- (because we don't allow '?' to appear outside of the VALUES list).
240 finishQueryBits qb bs0
241 | Just (')', bs1) <- B.uncons bs0
242 = if '?' `B.elem` bs1
244 else Just $ slice3 template qb bs1
245 | Just (',', skipSpace -> bs1) <- B.uncons bs0
246 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
247 = finishQueryBits qb bs2
251 -- Slice a string into three pieces, given the start offset of the second
252 -- and third pieces. Each "offset" is actually a tail of the uppercase
253 -- version of the template string. Its length is used to infer the offset.
255 -- It is important to note that we only slice the original template.
256 -- We don't want our all-caps trick messing up the actual query string.
257 slice3 source p1 p2 =
260 (s1, source') = B.splitAt (B.length source - B.length p1) source
261 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
263 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
266 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
267 -- in the PostgreSQL source. No need to check [a-z], since we converted
268 -- the whole string to uppercase.
269 isIdent c = (c >= '0' && c <= '9')
270 || (c >= 'A' && c <= 'Z')
271 || (c >= '\x80' && c <= '\xFF')
275 -- Based on {space} in scan.l
276 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
278 skipSpace = B.dropWhile isSpace_ascii
281buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
282buildQuery conn q template xs =
283 zipParams (split template) <$> mapM (buildAction conn q xs) xs
285 -- This part escapes double '??'s to make literal '?'s possible
286 -- in PostgreSQL queries using the JSON operators: @?@, @?|@ and @?&@
287 let (h,t) = breakOnSingleQuestionMark s
291 else split (B.tail t)
292 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
294 zipParams _ _ = fmtError (show countSingleQs ++
295 " single '?' characters, but " ++
296 show (length xs) ++ " parameters") q xs
297 countSingleQs = go 0 template
298 where go i "" = (i :: Int)
299 go i bs = case qms of
300 ("?","?") -> go i nextQMBS
301 ("?",_) -> go (i+1) nextQMBS
303 where qms = B.splitAt 1 qmBS
304 (qmBS,nextQMBS) = B.splitAt 2 qmBS'
305 qmBS' = B.dropWhile (/= '?') bs
307-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
308-- expected to return results.
310-- Returns the number of rows affected.
312-- Throws 'FormatError' if the query could not be formatted correctly, or
313-- a 'SqlError' exception if the backend returns an error.
314execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
315execute conn template qs = do
316 result <- exec conn =<< formatQuery conn template qs
317 finishExecute conn template result
319-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
320-- expected to return results.
322-- Returns the number of rows affected. If the list of parameters is empty,
323-- this function will simply return 0 without issuing the query to the backend.
324-- If this is not desired, consider using the 'Values' constructor instead.
326-- Throws 'FormatError' if the query could not be formatted correctly, or
327-- a 'SqlError' exception if the backend returns an error.
329-- For example, here's a command that inserts two rows into a table
333-- executeMany c [sql|
334-- INSERT INTO sometable VALUES (?,?)
335-- |] [(1, \"hello\"),(2, \"world\")]
338-- Here's an canonical example of a multi-row update command:
341-- executeMany c [sql|
344-- FROM (VALUES (?,?)) as upd(x,y)
345-- WHERE sometable.x = upd.x
346-- |] [(1, \"hello\"),(2, \"world\")]
349executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
350executeMany _ _ [] = return 0
351executeMany conn q qs = do
352 result <- exec conn =<< formatMany conn q qs
353 finishExecute conn q result
355-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
356-- query that accepts multi-row input and is expected to return results.
357-- Note that it is possible to write
358-- @'query' conn "INSERT ... RETURNING ..." ...@
359-- in cases where you are only inserting a single row, and do not need
360-- functionality analogous to 'executeMany'.
362-- If the list of parameters is empty, this function will simply return @[]@
363-- without issuing the query to the backend. If this is not desired,
364-- consider using the 'Values' constructor instead.
366-- Throws 'FormatError' if the query could not be formatted correctly.
367returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
368returning = returningWith fromRow
370-- | A version of 'returning' taking parser as argument
371returningWith :: (ToRow q) => RowParser r -> Connection -> Query -> [q] -> IO [r]
372returningWith _ _ _ [] = return []
373returningWith parser conn q qs = do
374 result <- exec conn =<< formatMany conn q qs
375 finishQueryWith parser conn q result
377-- | Perform a @SELECT@ or other SQL query that is expected to return
378-- results. All results are retrieved and converted before this
381-- When processing large results, this function will consume a lot of
382-- client-side memory. Consider using 'fold' instead.
384-- Exceptions that may be thrown:
386-- * 'FormatError': the query string could not be formatted correctly.
388-- * 'QueryError': the result contains no columns (i.e. you should be
389-- using 'execute' instead of 'query').
391-- * 'ResultError': result conversion failed.
393-- * 'SqlError': the postgresql backend returned an error, e.g.
394-- a syntax or type error, or an incorrect table or column name.
395query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r]
396query = queryWith fromRow
398-- | A version of 'query' that does not perform query substitution.
399query_ :: (FromRow r) => Connection -> Query -> IO [r]
400query_ = queryWith_ fromRow
402-- | A version of 'query' taking parser as argument
403queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
404queryWith parser conn template qs = do
405 result <- exec conn =<< formatQuery conn template qs
406 finishQueryWith parser conn template result
408-- | A version of 'query_' taking parser as argument
409queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
410queryWith_ parser conn q@(Query que) = do
411 result <- exec conn que
412 finishQueryWith parser conn q result
414-- | Perform a @SELECT@ or other SQL query that is expected to return
415-- results. Results are streamed incrementally from the server, and
416-- consumed via a left fold.
418-- When dealing with small results, it may be simpler (and perhaps
419-- faster) to use 'query' instead.
421-- This fold is /not/ strict. The stream consumer is responsible for
422-- forcing the evaluation of its result to avoid space leaks.
424-- This is implemented using a database cursor. As such, this requires
425-- a transaction. This function will detect whether or not there is a
426-- transaction in progress, and will create a 'ReadCommitted' 'ReadOnly'
427-- transaction if needed. The cursor is given a unique temporary name,
428-- so the consumer may itself call fold.
430-- Exceptions that may be thrown:
432-- * 'FormatError': the query string could not be formatted correctly.
434-- * 'QueryError': the result contains no columns (i.e. you should be
435-- using 'execute' instead of 'query').
437-- * 'ResultError': result conversion failed.
439-- * 'SqlError': the postgresql backend returned an error, e.g.
440-- a syntax or type error, or an incorrect table or column name.
441fold :: ( FromRow row, ToRow params )
446 -> (a -> row -> IO a)
448fold = foldWithOptions defaultFoldOptions
450-- | A version of 'fold' taking a parser as an argument
451foldWith :: ( ToRow params )
457 -> (a -> row -> IO a)
459foldWith = foldWithOptionsAndParser defaultFoldOptions
461-- | Number of rows to fetch at a time. 'Automatic' currently defaults
462-- to 256 rows, although it might be nice to make this more intelligent
463-- based on e.g. the average size of the rows.
470 fetchQuantity :: !FetchQuantity,
471 transactionMode :: !TransactionMode
474-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
475defaultFoldOptions :: FoldOptions
476defaultFoldOptions = FoldOptions {
477 fetchQuantity = Automatic,
478 transactionMode = TransactionMode ReadCommitted ReadOnly
481-- | The same as 'fold', but this provides a bit more control over
482-- lower-level details. Currently, the number of rows fetched per
483-- round-trip to the server and the transaction mode may be adjusted
484-- accordingly. If the connection is already in a transaction,
485-- then the existing transaction is used and thus the 'transactionMode'
487foldWithOptions :: ( FromRow row, ToRow params )
493 -> (a -> row -> IO a)
495foldWithOptions opts = foldWithOptionsAndParser opts fromRow
497-- | A version of 'foldWithOptions' taking a parser as an argument
498foldWithOptionsAndParser :: (ToRow params)
505 -> (a -> row -> IO a)
507foldWithOptionsAndParser opts parser conn template qs a f = do
508 q <- formatQuery conn template qs
509 doFold opts parser conn template (Query q) a f
511-- | A version of 'fold' that does not perform query substitution.
512fold_ :: (FromRow r) =>
515 -> a -- ^ Initial state for result consumer.
516 -> (a -> r -> IO a) -- ^ Result consumer.
518fold_ = foldWithOptions_ defaultFoldOptions
520-- | A version of 'fold_' taking a parser as an argument
521foldWith_ :: RowParser r
527foldWith_ = foldWithOptionsAndParser_ defaultFoldOptions
529foldWithOptions_ :: (FromRow r) =>
533 -> a -- ^ Initial state for result consumer.
534 -> (a -> r -> IO a) -- ^ Result consumer.
536foldWithOptions_ opts conn query' a f = doFold opts fromRow conn query' query' a f
538-- | A version of 'foldWithOptions_' taking a parser as an argument
539foldWithOptionsAndParser_ :: FoldOptions
543 -> a -- ^ Initial state for result consumer.
544 -> (a -> r -> IO a) -- ^ Result consumer.
546foldWithOptionsAndParser_ opts parser conn query' a f = doFold opts parser conn query' query' a f
554 -> (a -> row -> IO a)
556doFold FoldOptions{..} parser conn _template q a0 f = do
557 stat <- withConnection conn PQ.transactionStatus
559 PQ.TransIdle -> withTransactionMode transactionMode conn go
560 PQ.TransInTrans -> go
561 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
562 -- This _shouldn't_ occur in the current incarnation of
563 -- the library, as we aren't using libpq asynchronously.
564 -- However, it could occur in future incarnations of
565 -- this library or if client code uses the Internal module
566 -- to use raw libpq commands on postgresql-simple connections.
567 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
568 -- This should be turned into a better error message.
569 -- It is probably a bad idea to automatically roll
570 -- back the transaction and start another.
571 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
572 -- Not sure what this means.
577 foldForwardWithParser cursor parser chunkSize f a
579 go = bracket declare closeCursor $ \cursor ->
580 let loop a = fetch cursor a >>=
586-- FIXME: choose the Automatic chunkSize more intelligently
587-- One possibility is to use the type of the results, although this
588-- still isn't a perfect solution, given that common types (e.g. text)
589-- are of highly variable size.
590-- A refinement of this technique is to pick this number adaptively
591-- as results are read in from the database.
592 chunkSize = case fetchQuantity of
596-- | A version of 'fold' that does not transform a state value.
597forEach :: (ToRow q, FromRow r) =>
599 -> Query -- ^ Query template.
600 -> q -- ^ Query parameters.
601 -> (r -> IO ()) -- ^ Result consumer.
603forEach = forEachWith fromRow
604{-# INLINE forEach #-}
606-- | A version of 'forEach' taking a parser as an argument
607forEachWith :: ( ToRow q )
614forEachWith parser conn template qs = foldWith parser conn template qs () . const
615{-# INLINE forEachWith #-}
617-- | A version of 'forEach' that does not perform query substitution.
618forEach_ :: (FromRow r) =>
620 -> Query -- ^ Query template.
621 -> (r -> IO ()) -- ^ Result consumer.
623forEach_ = forEachWith_ fromRow
624{-# INLINE forEach_ #-}
626forEachWith_ :: RowParser r
631forEachWith_ parser conn template = foldWith_ parser conn template () . const
632{-# INLINE forEachWith_ #-}
637-- SQL-based applications are somewhat notorious for their
638-- susceptibility to attacks through the injection of maliciously
639-- crafted data. The primary reason for widespread vulnerability to
640-- SQL injections is that many applications are sloppy in handling
641-- user data when constructing SQL queries.
643-- This library provides a 'Query' type and a parameter substitution
644-- facility to address both ease of use and security.
648-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
649-- exposes a tiny API that is not compatible with the 'ByteString'
650-- API; this makes it difficult to construct queries from fragments of
651-- strings. The 'query' and 'execute' functions require queries to be
654-- To most easily construct a query, enable GHC's @OverloadedStrings@
655-- language extension and write your query as a normal literal string.
657-- > {-# LANGUAGE OverloadedStrings #-}
659-- > import Database.PostgreSQL.Simple
663-- > conn <- connectPostgreSQL ""
664-- > [Only i] <- query_ conn "select 2 + 2"
667-- A 'Query' value does not represent the actual query that will be
668-- executed, but is a template for constructing the final query.
672-- Since applications need to be able to construct queries with
673-- parameters that change, this library provides a query substitution
676-- The 'Query' template accepted by 'query' and 'execute' can contain
677-- any number of \"@?@\" characters. Both 'query' and 'execute'
678-- accept a third argument, typically a tuple. When constructing the
679-- real query to execute, these functions replace the first \"@?@\" in
680-- the template with the first element of the tuple, the second
681-- \"@?@\" with the second element, and so on. If necessary, each
682-- tuple element will be quoted and escaped prior to substitution;
683-- this defeats the single most common injection vector for malicious
686-- For example, given the following 'Query' template:
688-- > select * from user where first_name = ? and age > ?
690-- And a tuple of this form:
692-- > ("Boris" :: String, 37 :: Int)
694-- The query to be executed will look like this after substitution:
696-- > select * from user where first_name = 'Boris' and age > 37
698-- If there is a mismatch between the number of \"@?@\" characters in
699-- your template and the number of elements in your tuple, a
700-- 'FormatError' will be thrown.
702-- Note that the substitution functions do not attempt to parse or
703-- validate your query. It's up to you to write syntactically valid
704-- SQL, and to ensure that each \"@?@\" in your query template is
705-- matched with the right tuple element.
709-- Automated type inference means that you will often be able to avoid
710-- supplying explicit type signatures for the elements of a tuple.
711-- However, sometimes the compiler will not be able to infer your
712-- types. Consider a case where you write a numeric literal in a
715-- > query conn "select ? + ?" (40,2)
717-- The above query will be rejected by the compiler, because it does
718-- not know the specific numeric types of the literals @40@ and @2@.
719-- This is easily fixed:
721-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
723-- The same kind of problem can arise with string literals if you have
724-- the @OverloadedStrings@ language extension enabled. Again, just
725-- use an explicit type signature if this happens.
727-- Finally, remember that the compiler must be able to infer the type
728-- of a query's /results/ as well as its parameters. We might like
729-- the following example to work:
731-- > print =<< query_ conn "select 2 + 2"
733-- Unfortunately, while a quick glance tells us that the result type
734-- should be a single row containing a single numeric column, the
735-- compiler has no way to infer what the types are. We can easily fix
736-- this by providing an explicit type annotation:
738-- > xs <- query_ conn "select 2 + 2"
739-- > print (xs :: [Only Int])
743-- Haskell lacks a single-element tuple type, so if you have just one
744-- value you want substituted into a query or a single-column result,
745-- what should you do?
747-- The obvious approach would appear to be something like this:
749-- > instance (ToField a) => ToRow a where
752-- Unfortunately, this wreaks havoc with type inference, so we take a
753-- different tack. To represent a single value @val@ as a parameter, write
754-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
756-- Here's an example using a singleton list:
758-- > execute conn "insert into users (first_name) values (?)"
761-- A row of /n/ query results is represented using an /n/-tuple, so
762-- you should use 'Only' to represent a single-column result.
766-- Suppose you want to write a query using an @IN@ clause:
768-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
770-- In such cases, it's common for both the elements and length of the
771-- list after the @IN@ keyword to vary from query to query.
773-- To address this case, use the 'In' type wrapper, and use a single
774-- \"@?@\" character to represent the list. Omit the parentheses
775-- around the list; these will be added for you.
779-- > query conn "select * from users where first_name in ?" $
780-- > Only $ In ["Anna", "Boris", "Carla"]
782-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
783-- substituted instead, to ensure that your clause remains
784-- syntactically valid.
788-- If you know that you have many rows of data to insert into a table,
789-- it is much more efficient to perform all the insertions in a single
790-- multi-row @INSERT@ statement than individually.
792-- The 'executeMany' function is intended specifically for helping
793-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
794-- query substitution are different than those for 'execute'.
796-- What 'executeMany' searches for in your 'Query' template is a
797-- single substring of the form:
801-- The rules are as follows:
803-- * The keyword @VALUES@ is matched case insensitively.
805-- * There must be no other \"@?@\" characters anywhere in your
808-- * There must be one or more \"@?@\" in the parentheses.
810-- * Extra white space is fine.
812-- The last argument to 'executeMany' is a list of parameter
813-- tuples. These will be substituted into the query where the @(?,?)@
814-- string appears, in a form suitable for use in a multi-row @INSERT@
817-- Here is an example:
820-- > "insert into users (first_name,last_name) values (?,?)"
821-- > [("Boris","Karloff"),("Ed","Wood")]
823-- The query that will be executed here will look like this
824-- (reformatted for tidiness):
826-- > insert into users (first_name,last_name) values
827-- > ('Boris','Karloff'),('Ed','Wood')
831-- PostgreSQL supports returning values from data manipulation statements
832-- such as @INSERT@ and @UPDATE@. You can use these statements by
833-- using 'query' instead of 'execute'. For multi-tuple inserts,
834-- use 'returning' instead of 'executeMany'.
836-- For example, were there an auto-incrementing @id@ column and
837-- timestamp column @t@ that defaulted to the present time for the
838-- @sales@ table, then the following query would insert two new
839-- sales records and also return their new @id@s and timestamps.
841-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
842-- > xs :: [(Int, UTCTime)] <- query conn q (15,"Sawdust")
843-- > ys :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
847-- The 'query' and 'query_' functions return a list of values in the
848-- 'FromRow' typeclass. This class performs automatic extraction
849-- and type conversion of rows from a query result.
851-- Here is a simple example of how to extract results:
853-- > import qualified Data.Text as Text
855-- > xs <- query_ conn "select name,age from users"
856-- > forM_ xs $ \(name,age) ->
857-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
859-- Notice two important details about this code:
861-- * The number of columns we ask for in the query template must
862-- exactly match the number of elements we specify in a row of the
863-- result tuple. If they do not match, a 'ResultError' exception
866-- * Sometimes, the compiler needs our help in specifying types. It
867-- can infer that @name@ must be a 'Text', due to our use of the
868-- @unpack@ function. However, we have to tell it the type of @age@,
869-- as it has no other information to determine the exact type.
873-- The type of a result tuple will look something like this:
877-- Although SQL can accommodate @NULL@ as a value for any of these
878-- types, Haskell cannot. If your result contains columns that may be
879-- @NULL@, be sure that you use 'Maybe' in those positions of your
882-- > (Text, Maybe Int, Int)
884-- If 'query' encounters a @NULL@ in a row where the corresponding
885-- Haskell type is not 'Maybe', it will throw a 'ResultError'
890-- To specify that a query returns a single-column result, use the
893-- > xs <- query_ conn "select id from users"
894-- > forM_ xs $ \(Only dbid) -> {- ... -}
898-- Conversion of SQL values to Haskell values is somewhat
899-- permissive. Here are the rules.
901-- * For numeric types, any Haskell type that can accurately represent
902-- all values of the given PostgreSQL type is considered \"compatible\".
903-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
904-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
905-- represent a @SMALLINT@, so it is considered compatible with those types.
907-- * A numeric compatibility check is based only on the type of a
908-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
909-- @BIGINT@ column will be considered incompatible with a Haskell
910-- 'Int16', even if it contains the value @1@.
912-- * If a numeric incompatibility is found, 'query' will throw a
915-- * The 'String' and 'Text' types are assumed to be encoded as
916-- UTF-8. If you use some other encoding, decoding may fail or give
917-- wrong results. In such cases, write a @newtype@ wrapper and a
918-- 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