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 returns results
48 -- * Extracting results
51 -- ** Handling null values
54 -- ** Type conversions
70 , FormatError(fmtMessage, fmtQuery, fmtParams)
71 , QueryError(qeMessage, qeQuery)
72 , ResultError(errSQLType, errHaskellType, errMessage)
73 -- * Connection management
75 , Base.connectPostgreSQL
76 , Base.postgreSQLConnectionString
77 , Base.defaultConnectInfo
79 -- * Queries that return results
82 -- ** Queries taking parser as argument
85 -- * Queries that stream results
96 -- * Statements that do not return results
101 -- * Transaction handling
108 -- * Helper functions
113import Blaze.ByteString.Builder
114 ( Builder, fromByteString, toByteString )
115import Blaze.ByteString.Builder.Char8 (fromChar)
116import Blaze.Text ( integral )
117import Control.Applicative ((<$>), pure)
118import Control.Exception as E
119import Control.Monad (foldM)
120import Data.ByteString (ByteString)
121import Data.Int (Int64)
122import Data.List (intersperse)
123import Data.Monoid (mconcat)
124import Data.Typeable (Typeable)
125import Database.PostgreSQL.Simple.Compat ( (<>) )
126import Database.PostgreSQL.Simple.FromField (ResultError(..))
127import Database.PostgreSQL.Simple.FromRow (FromRow(..))
128import Database.PostgreSQL.Simple.Ok
129import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
130import Database.PostgreSQL.Simple.ToRow (ToRow(..))
131import Database.PostgreSQL.Simple.Types
132 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
133import Database.PostgreSQL.Simple.Internal as Base
134import Database.PostgreSQL.Simple.Transaction
135import Database.PostgreSQL.Simple.TypeInfo
136import qualified Database.PostgreSQL.LibPQ as PQ
137import qualified Data.ByteString.Char8 as B
138import qualified Data.Text as T
139import qualified Data.Text.Encoding as TE
140import Control.Monad.Trans.Reader
141import Control.Monad.Trans.State.Strict
143-- | Exception thrown if a 'Query' could not be formatted correctly.
144-- This may occur if the number of \'@?@\' characters in the query
145-- string does not match the number of parameters provided.
146data FormatError = FormatError {
149 , fmtParams :: [ByteString]
150 } deriving (Eq, Show, Typeable)
152instance Exception FormatError
154-- | Format a query string.
156-- This function is exposed to help with debugging and logging. Do not
157-- use it to prepare queries for execution.
159-- String parameters are escaped according to the character set in use
160-- on the 'Connection'.
162-- Throws 'FormatError' if the query string could not be formatted
164formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
165formatQuery conn q@(Query template) qs
166 | null xs && '?' `B.notElem` template = return template
167 | otherwise = toByteString <$> buildQuery conn q template xs
170-- | Format a query string with a variable number of rows.
172-- This function is exposed to help with debugging and logging. Do not
173-- use it to prepare queries for execution.
175-- The query string must contain exactly one substitution group,
176-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
177-- followed by an \"@(@\" character, a series of one or more \"@?@\"
178-- characters separated by commas, and a \"@)@\" character. White
179-- space in a substitution group is permitted.
181-- Throws 'FormatError' if the query string could not be formatted
183formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
184formatMany _ q [] = fmtError "no rows supplied" q []
185formatMany conn q@(Query template) qs = do
186 case parseTemplate template of
187 Just (before, qbits, after) -> do
188 bs <- mapM (buildQuery conn q qbits . toRow) qs
189 return . toByteString . mconcat $ fromByteString before :
190 intersperse (fromChar ',') bs ++
191 [fromByteString after]
192 Nothing -> fmtError "syntax error in multi-row template" q []
194-- Split the input string into three pieces, @before@, @qbits@, and @after@,
195-- following this grammar:
197-- start: ^ before qbits after $
198-- before: ([^?]* [^?\w])? 'VALUES' \s*
199-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
203-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
205-- This would be much more concise with some sort of regex engine.
206-- 'formatMany' used to use pcre-light instead of this hand-written parser,
207-- but pcre is a hassle to install on Windows.
208parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
209parseTemplate template =
210 -- Convert input string to uppercase, to facilitate searching.
211 search $ B.map toUpper_ascii template
213 -- Search for the next occurrence of "VALUES"
215 case B.breakSubstring "VALUES" bs of
217 -- If "VALUES" is not present in the string, or any '?' characters
218 -- were encountered prior to it, fail.
219 | B.null y || ('?' `B.elem` x)
222 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
223 -- try the next occurrence.
224 | not (B.null x) && isIdent (B.last x)
225 -> search $ B.drop 6 y
227 -- Otherwise, we have a legitimate "VALUES" token.
229 -> parseQueryBits $ skipSpace $ B.drop 6 y
231 -- Parse '(' \s* '?' \s* . If this doesn't match
232 -- (and we don't consume a '?'), look for another "VALUES".
234 -- qb points to the open paren (if present), meaning it points to the
235 -- beginning of the "qbits" production described above. This is why we
236 -- pass it down to finishQueryBits.
238 | Just ('(', skipSpace -> bs1) <- B.uncons qb
239 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
240 = finishQueryBits qb bs2
244 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
246 -- Since we've already consumed at least one '?', there's no turning back.
247 -- The parse has to succeed here, or the whole thing fails
248 -- (because we don't allow '?' to appear outside of the VALUES list).
249 finishQueryBits qb bs0
250 | Just (')', bs1) <- B.uncons bs0
251 = if '?' `B.elem` bs1
253 else Just $ slice3 template qb bs1
254 | Just (',', skipSpace -> bs1) <- B.uncons bs0
255 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
256 = finishQueryBits qb bs2
260 -- Slice a string into three pieces, given the start offset of the second
261 -- and third pieces. Each "offset" is actually a tail of the uppercase
262 -- version of the template string. Its length is used to infer the offset.
264 -- It is important to note that we only slice the original template.
265 -- We don't want our all-caps trick messing up the actual query string.
266 slice3 source p1 p2 =
269 (s1, source') = B.splitAt (B.length source - B.length p1) source
270 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
272 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
275 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
276 -- in the PostgreSQL source. No need to check [a-z], since we converted
277 -- the whole string to uppercase.
278 isIdent c = (c >= '0' && c <= '9')
279 || (c >= 'A' && c <= 'Z')
280 || (c >= '\x80' && c <= '\xFF')
284 -- Based on {space} in scan.l
285 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
287 skipSpace = B.dropWhile isSpace_ascii
289escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
290escapeStringConn = escapeWrap PQ.escapeStringConn
292escapeIdentifier :: Connection -> ByteString -> IO (Either ByteString ByteString)
293escapeIdentifier = escapeWrap PQ.escapeIdentifier
295escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
296escapeByteaConn = escapeWrap PQ.escapeByteaConn
298escapeWrap :: (PQ.Connection -> ByteString -> IO (Maybe ByteString))
301 -> IO (Either ByteString ByteString)
303 withConnection conn $ \c ->
304 f c s >>= checkError c
306checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
307checkError _ (Just x) = return $ Right x
308checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
310buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
311buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
312 where err' msg = fmtError (utf8ToString msg) q xs
313 quote = either err' (inQuotes . fromByteString)
314 utf8ToString = T.unpack . TE.decodeUtf8
315 sub (Plain b) = pure b
316 sub (Escape s) = quote <$> escapeStringConn conn s
317 sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
318 sub (EscapeIdentifier s) = either err' fromByteString <$>
319 escapeIdentifier conn s
320 sub (Many ys) = mconcat <$> mapM sub ys
321 split s = fromByteString h : if B.null t then [] else split (B.tail t)
322 where (h,t) = B.break (=='?') s
323 zipParams (t:ts) (p:ps) = t <> p <> zipParams ts ps
325 zipParams _ _ = fmtError (show (B.count '?' template) ++
326 " '?' characters, but " ++
327 show (length xs) ++ " parameters") q xs
329-- | Execute an @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, or
335-- a 'SqlError' exception if the backend returns an error.
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. If the list of parameters is empty,
345-- this function will simply return 0 without issuing the query to the backend.
346-- If this is not desired, consider using the 'Values' constructor instead.
348-- Throws 'FormatError' if the query could not be formatted correctly, or
349-- a 'SqlError' exception if the backend returns an error.
351-- For example, here's a command that inserts two rows into a table
355-- executeMany c [sql|
356-- INSERT INTO sometable VALUES (?,?)
357-- |] [(1, \"hello\"),(2, \"world\")]
360-- Here's an canonical example of a multi-row update command:
363-- executeMany c [sql|
365-- SET sometable.y = upd.y
366-- FROM (VALUES (?,?)) as upd(x,y)
367-- WHERE sometable.x = upd.x
368-- |] [(1, \"hello\"),(2, \"world\")
371executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
372executeMany _ _ [] = return 0
373executeMany conn q qs = do
374 result <- exec conn =<< formatMany conn q qs
375 finishExecute conn q result
377-- | Execute @INSERT ... RETURNING@, @UPDATE ... RETURNING@, or other SQL
378-- query that accepts multi-row input and is expected to return results.
379-- Note that it is possible to write
380-- @'query' conn "INSERT ... RETURNING ..." ...@
381-- in cases where you are only inserting a single row, and do not need
382-- functionality analogous to 'executeMany'.
384-- If the list of parameters is empty, this function will simply return @[]@
385-- without issuing the query to the backend. If this is not desired,
386-- consider using the 'Values' constructor instead.
388-- Throws 'FormatError' if the query could not be formatted correctly.
389returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r]
390returning _ _ [] = return []
391returning conn q qs = do
392 result <- exec conn =<< formatMany conn q qs
393 finishQuery conn q result
395-- | Perform a @SELECT@ or other SQL query that is expected to return
396-- results. All results are retrieved and converted before this
399-- When processing large results, this function will consume a lot of
400-- client-side memory. Consider using 'fold' instead.
402-- Exceptions that may be thrown:
404-- * 'FormatError': the query string could not be formatted correctly.
406-- * 'QueryError': the result contains no columns (i.e. you should be
407-- using 'execute' instead of 'query').
409-- * 'ResultError': result conversion failed.
411-- * 'SqlError': the postgresql backend returned an error, e.g.
412-- a syntax or type error, or an incorrect table or column name.
413query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r]
414query = queryWith fromRow
416-- | A version of 'query' that does not perform query substitution.
417query_ :: (FromRow r) => Connection -> Query -> IO [r]
418query_ = queryWith_ fromRow
420-- | A version of 'query' taking parser as argument
421queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r]
422queryWith parser conn template qs = do
423 result <- exec conn =<< formatQuery conn template qs
424 finishQueryWith parser conn template result
426-- | A version of 'query_' taking parser as argument
427queryWith_ :: RowParser r -> Connection -> Query -> IO [r]
428queryWith_ parser conn q@(Query que) = do
429 result <- exec conn que
430 finishQueryWith parser conn q result
432-- | Perform a @SELECT@ or other SQL query that is expected to return
433-- results. Results are streamed incrementally from the server, and
434-- consumed via a left fold.
436-- When dealing with small results, it may be simpler (and perhaps
437-- faster) to use 'query' instead.
439-- This fold is /not/ strict. The stream consumer is responsible for
440-- forcing the evaluation of its result to avoid space leaks.
442-- This is implemented using a database cursor. As such, this requires
443-- a transaction. This function will detect whether or not there is a
444-- transaction in progress, and will create a 'ReadCommitted' 'ReadOnly'
445-- transaction if needed. The cursor is given a unique temporary name,
446-- so the consumer may itself call fold.
448-- Exceptions that may be thrown:
450-- * 'FormatError': the query string could not be formatted correctly.
452-- * 'QueryError': the result contains no columns (i.e. you should be
453-- using 'execute' instead of 'query').
455-- * 'ResultError': result conversion failed.
457-- * 'SqlError': the postgresql backend returned an error, e.g.
458-- a syntax or type error, or an incorrect table or column name.
459fold :: ( FromRow row, ToRow params )
464 -> (a -> row -> IO a)
466fold = foldWithOptions defaultFoldOptions
468-- | Number of rows to fetch at a time. 'Automatic' currently defaults
469-- to 256 rows, although it might be nice to make this more intelligent
470-- based on e.g. the average size of the rows.
477 fetchQuantity :: !FetchQuantity,
478 transactionMode :: !TransactionMode
481-- | defaults to 'Automatic', and 'TransactionMode' 'ReadCommitted' 'ReadOnly'
482defaultFoldOptions :: FoldOptions
483defaultFoldOptions = FoldOptions {
484 fetchQuantity = Automatic,
485 transactionMode = TransactionMode ReadCommitted ReadOnly
488-- | The same as 'fold', but this provides a bit more control over
489-- lower-level details. Currently, the number of rows fetched per
490-- round-trip to the server and the transaction mode may be adjusted
491-- accordingly. If the connection is already in a transaction,
492-- then the existing transaction is used and thus the 'transactionMode'
494foldWithOptions :: ( FromRow row, ToRow params )
500 -> (a -> row -> IO a)
502foldWithOptions opts conn template qs a f = do
503 q <- formatQuery conn template qs
504 doFold opts conn template (Query q) a f
506-- | A version of 'fold' that does not perform query substitution.
507fold_ :: (FromRow r) =>
510 -> a -- ^ Initial state for result consumer.
511 -> (a -> r -> IO a) -- ^ Result consumer.
513fold_ = foldWithOptions_ defaultFoldOptions
516foldWithOptions_ :: (FromRow r) =>
520 -> a -- ^ Initial state for result consumer.
521 -> (a -> r -> IO a) -- ^ Result consumer.
523foldWithOptions_ opts conn query a f = doFold opts conn query query a f
526doFold :: ( FromRow row )
532 -> (a -> row -> IO a)
534doFold FoldOptions{..} conn _template q a0 f = do
535 stat <- withConnection conn PQ.transactionStatus
537 PQ.TransIdle -> withTransactionMode transactionMode conn go
538 PQ.TransInTrans -> go
539 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
540 -- This _shouldn't_ occur in the current incarnation of
541 -- the library, as we aren't using libpq asynchronously.
542 -- However, it could occur in future incarnations of
543 -- this library or if client code uses the Internal module
544 -- to use raw libpq commands on postgresql-simple connections.
545 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
546 -- This should be turned into a better error message.
547 -- It is probably a bad idea to automatically roll
548 -- back the transaction and start another.
549 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
550 -- Not sure what this means.
553 name <- newTempName conn
554 _ <- execute_ conn $ mconcat
555 [ "DECLARE ", name, " NO SCROLL CURSOR FOR ", q ]
557 fetch (Query name) = query_ conn $
558 Query (toByteString (fromByteString "FETCH FORWARD "
559 <> integral chunkSize
560 <> fromByteString " FROM "
561 <> fromByteString name
564 (execute_ conn ("CLOSE " <> name) >> return ()) `E.catch` \ex ->
565 -- Don't throw exception if CLOSE failed because the transaction is
566 -- aborted. Otherwise, it will throw away the original error.
567 if isFailedTransactionError ex then return () else throwIO ex
569 go = bracket declare close $ \name ->
572 if null rs then return a else foldM f a rs >>= loop
575-- FIXME: choose the Automatic chunkSize more intelligently
576-- One possibility is to use the type of the results, although this
577-- still isn't a perfect solution, given that common types (e.g. text)
578-- are of highly variable size.
579-- A refinement of this technique is to pick this number adaptively
580-- as results are read in from the database.
581 chunkSize = case fetchQuantity of
585-- | A version of 'fold' that does not transform a state value.
586forEach :: (ToRow q, FromRow r) =>
588 -> Query -- ^ Query template.
589 -> q -- ^ Query parameters.
590 -> (r -> IO ()) -- ^ Result consumer.
592forEach conn template qs = fold conn template qs () . const
593{-# INLINE forEach #-}
595-- | A version of 'forEach' that does not perform query substitution.
596forEach_ :: (FromRow r) =>
598 -> Query -- ^ Query template.
599 -> (r -> IO ()) -- ^ Result consumer.
601forEach_ conn template = fold_ conn template () . const
602{-# INLINE forEach_ #-}
604forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
605forM' lo hi m = loop hi []
613finishQuery :: FromRow r => Connection -> Query -> PQ.Result -> IO [r]
614finishQuery = finishQueryWith fromRow
616finishQueryWith :: RowParser r -> Connection -> Query -> PQ.Result -> IO [r]
617finishQueryWith parser conn q result = do
618 status <- PQ.resultStatus result
621 throwIO $ QueryError "query: Empty query" q
623 throwIO $ QueryError "query resulted in a command response" q
625 let unCol (PQ.Col x) = fromIntegral x :: Int
626 nrows <- PQ.ntuples result
627 ncols <- PQ.nfields result
628 forM' 0 (nrows-1) $ \row -> do
629 let rw = Row row result
630 okvc <- runConversion (runStateT (runReaderT (unRP parser) rw) 0) conn
632 Ok (val,col) | col == ncols -> return val
634 vals <- forM' 0 (ncols-1) $ \c -> do
635 tinfo <- getTypeInfo conn =<< PQ.ftype result c
636 v <- PQ.getvalue result row c
639 throw (ConversionFailed
640 (show (unCol ncols) ++ " values: " ++ show vals)
643 (show (unCol col) ++ " slots in target type")
644 "mismatch between number of columns to \
645 \convert and number in target type")
646 Errors [] -> throwIO $ ConversionFailed "" Nothing "" "" "unknown error"
647 Errors [x] -> throwIO x
648 Errors xs -> throwIO $ ManyErrors xs
650 throwIO $ QueryError "query: COPY TO is not supported" q
652 throwIO $ QueryError "query: COPY FROM is not supported" q
653 PQ.BadResponse -> throwResultError "query" result status
654 PQ.NonfatalError -> throwResultError "query" result status
655 PQ.FatalError -> throwResultError "query" result status
657ellipsis :: ByteString -> ByteString
659 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
662fmtError :: String -> Query -> [Action] -> a
663fmtError msg q xs = throw FormatError {
666 , fmtParams = map twiddle xs
668 where twiddle (Plain b) = toByteString b
669 twiddle (Escape s) = s
670 twiddle (EscapeByteA s) = s
671 twiddle (EscapeIdentifier s) = s
672 twiddle (Many ys) = B.concat (map twiddle ys)
676-- SQL-based applications are somewhat notorious for their
677-- susceptibility to attacks through the injection of maliciously
678-- crafted data. The primary reason for widespread vulnerability to
679-- SQL injections is that many applications are sloppy in handling
680-- user data when constructing SQL queries.
682-- This library provides a 'Query' type and a parameter substitution
683-- facility to address both ease of use and security.
687-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
688-- exposes a tiny API that is not compatible with the 'ByteString'
689-- API; this makes it difficult to construct queries from fragments of
690-- strings. The 'query' and 'execute' functions require queries to be
693-- To most easily construct a query, enable GHC's @OverloadedStrings@
694-- language extension and write your query as a normal literal string.
696-- > {-# LANGUAGE OverloadedStrings #-}
698-- > import Database.PostgreSQL.Simple
700-- > hello :: IO [Only Int]
702-- > conn <- connectPostgreSQL ""
703-- > query_ conn "select 2 + 2"
705-- A 'Query' value does not represent the actual query that will be
706-- executed, but is a template for constructing the final query.
710-- Since applications need to be able to construct queries with
711-- parameters that change, this library provides a query substitution
714-- The 'Query' template accepted by 'query' and 'execute' can contain
715-- any number of \"@?@\" characters. Both 'query' and 'execute'
716-- accept a third argument, typically a tuple. When constructing the
717-- real query to execute, these functions replace the first \"@?@\" in
718-- the template with the first element of the tuple, the second
719-- \"@?@\" with the second element, and so on. If necessary, each
720-- tuple element will be quoted and escaped prior to substitution;
721-- this defeats the single most common injection vector for malicious
724-- For example, given the following 'Query' template:
726-- > select * from user where first_name = ? and age > ?
728-- And a tuple of this form:
730-- > ("Boris" :: String, 37 :: Int)
732-- The query to be executed will look like this after substitution:
734-- > select * from user where first_name = 'Boris' and age > 37
736-- If there is a mismatch between the number of \"@?@\" characters in
737-- your template and the number of elements in your tuple, a
738-- 'FormatError' will be thrown.
740-- Note that the substitution functions do not attempt to parse or
741-- validate your query. It's up to you to write syntactically valid
742-- SQL, and to ensure that each \"@?@\" in your query template is
743-- matched with the right tuple element.
747-- Automated type inference means that you will often be able to avoid
748-- supplying explicit type signatures for the elements of a tuple.
749-- However, sometimes the compiler will not be able to infer your
750-- types. Consider a case where you write a numeric literal in a
753-- > query conn "select ? + ?" (40,2)
755-- The above query will be rejected by the compiler, because it does
756-- not know the specific numeric types of the literals @40@ and @2@.
757-- This is easily fixed:
759-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
761-- The same kind of problem can arise with string literals if you have
762-- the @OverloadedStrings@ language extension enabled. Again, just
763-- use an explicit type signature if this happens.
767-- Haskell lacks a single-element tuple type, so if you have just one
768-- value you want substituted into a query, what should you do?
770-- The obvious approach would appear to be something like this:
772-- > instance (ToField a) => ToRow a where
775-- Unfortunately, this wreaks havoc with type inference, so we take a
776-- different tack. To represent a single value @val@ as a parameter, write
777-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
779-- Here's an example using a singleton list:
781-- > execute conn "insert into users (first_name) values (?)"
786-- Suppose you want to write a query using an @IN@ clause:
788-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
790-- In such cases, it's common for both the elements and length of the
791-- list after the @IN@ keyword to vary from query to query.
793-- To address this case, use the 'In' type wrapper, and use a single
794-- \"@?@\" character to represent the list. Omit the parentheses
795-- around the list; these will be added for you.
799-- > query conn "select * from users where first_name in ?" $
800-- > In ["Anna", "Boris", "Carla"]
802-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
803-- substituted instead, to ensure that your clause remains
804-- syntactically valid.
808-- If you know that you have many rows of data to insert into a table,
809-- it is much more efficient to perform all the insertions in a single
810-- multi-row @INSERT@ statement than individually.
812-- The 'executeMany' function is intended specifically for helping
813-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
814-- query substitution are different than those for 'execute'.
816-- What 'executeMany' searches for in your 'Query' template is a
817-- single substring of the form:
821-- The rules are as follows:
823-- * The keyword @VALUES@ is matched case insensitively.
825-- * There must be no other \"@?@\" characters anywhere in your
828-- * There must be one or more \"@?@\" in the parentheses.
830-- * Extra white space is fine.
832-- The last argument to 'executeMany' is a list of parameter
833-- tuples. These will be substituted into the query where the @(?,?)@
834-- string appears, in a form suitable for use in a multi-row @INSERT@
837-- Here is an example:
840-- > "insert into users (first_name,last_name) values (?,?)"
841-- > [("Boris","Karloff"),("Ed","Wood")]
843-- The query that will be executed here will look like this
844-- (reformatted for tidiness):
846-- > insert into users (first_name,last_name) values
847-- > ('Boris','Karloff'),('Ed','Wood')
851-- PostgreSQL supports returning values from data manipulation statements
852-- such as @INSERT@ and @UPDATE@. You can use these statements by
853-- using 'query' instead of 'execute'. For multi-tuple inserts,
854-- use 'returning' instead of 'executeMany'.
856-- For example, were there an auto-incrementing @id@ column and
857-- timestamp column @t@ that defaulted to the present time for the
858-- @sales@ table, then the following query would insert two new
859-- sales records and also return their new @id@s and timestamps.
861-- > let q = "insert into sales (amount, label) values (?,?) returning id, t"
862-- > xs :: [(Int, UTCTime)] <- query conn q (15,"Sawdust")
863-- > ys :: [(Int, UTCTime)] <- returning conn q [(20,"Chips"),(300,"Wood")]
867-- The 'query' and 'query_' functions return a list of values in the
868-- 'FromRow' typeclass. This class performs automatic extraction
869-- and type conversion of rows from a query result.
871-- Here is a simple example of how to extract results:
873-- > import qualified Data.Text as Text
875-- > xs <- query_ conn "select name,age from users"
876-- > forM_ xs $ \(name,age) ->
877-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
879-- Notice two important details about this code:
881-- * The number of columns we ask for in the query template must
882-- exactly match the number of elements we specify in a row of the
883-- result tuple. If they do not match, a 'ResultError' exception
886-- * Sometimes, the compiler needs our help in specifying types. It
887-- can infer that @name@ must be a 'Text', due to our use of the
888-- @unpack@ function. However, we have to tell it the type of @age@,
889-- as it has no other information to determine the exact type.
893-- The type of a result tuple will look something like this:
897-- Although SQL can accommodate @NULL@ as a value for any of these
898-- types, Haskell cannot. If your result contains columns that may be
899-- @NULL@, be sure that you use 'Maybe' in those positions of your
902-- > (Text, Maybe Int, Int)
904-- If 'query' encounters a @NULL@ in a row where the corresponding
905-- Haskell type is not 'Maybe', it will throw a 'ResultError'
910-- To specify that a query returns a single-column result, use the
913-- > xs <- query_ conn "select id from users"
914-- > forM_ xs $ \(Only dbid) -> {- ... -}
918-- Conversion of SQL values to Haskell values is somewhat
919-- permissive. Here are the rules.
921-- * For numeric types, any Haskell type that can accurately represent
922-- all values of the given PostgreSQL type is considered \"compatible\".
923-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
924-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
925-- represent a @SMALLINT@, so it is considered compatble with those types.
927-- * A numeric compatibility check is based only on the type of a
928-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
929-- @BIGINT@ column will be considered incompatible with a Haskell
930-- 'Int16', even if it contains the value @1@.
932-- * If a numeric incompatibility is found, 'query' will throw a
935-- * The 'String' and 'Text' types are assumed to be encoded as
936-- UTF-8. If you use some other encoding, decoding may fail or give
937-- wrong results. In such cases, write a @newtype@ wrapper and a
938-- 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