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 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 -- * Extracting results
49 -- ** Handling null values
52 -- ** Type conversions
65 , FormatError(fmtMessage, fmtQuery, fmtParams)
66 , QueryError(qeMessage, qeQuery)
67 , ResultError(errSQLType, errHaskellType, errMessage)
68 -- * Connection management
70 , Base.connectPostgreSQL
71 , Base.postgreSQLConnectionString
72 , Base.defaultConnectInfo
74 -- * Queries that return results
77 -- * Queries that stream results
87 -- * Statements that do not return results
92 -- * Transaction handling
97 , defaultTransactionMode
98 , defaultIsolationLevel
99 , defaultReadWriteMode
100 , withTransactionLevel
101 , withTransactionMode
108 -- * Helper functions
113import Blaze.ByteString.Builder
114 ( Builder, fromByteString, toByteString )
115import Blaze.ByteString.Builder.Char8 (fromChar)
116import Control.Applicative ((<$>), pure)
117import Control.Concurrent.MVar
118import Control.Exception
119 ( Exception, onException, throw, throwIO, finally )
120import Control.Monad (foldM)
121import Data.ByteString (ByteString)
122import Data.Int (Int64)
123import qualified Data.IntMap as IntMap
124import Data.List (intersperse)
125import Data.Monoid (mappend, mconcat)
126import Data.Typeable (Typeable)
127import Database.PostgreSQL.Simple.BuiltinTypes
128 ( oid2builtin, builtin2typname )
129import Database.PostgreSQL.Simple.Compat ( mask )
130import Database.PostgreSQL.Simple.FromField (ResultError(..))
131import Database.PostgreSQL.Simple.FromRow (FromRow(..))
132import Database.PostgreSQL.Simple.Ok
133import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
134import Database.PostgreSQL.Simple.ToRow (ToRow(..))
135import Database.PostgreSQL.Simple.Types
136 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
137import Database.PostgreSQL.Simple.Internal as Base
138import qualified Database.PostgreSQL.LibPQ as PQ
139import qualified Data.ByteString.Char8 as B
140import qualified Data.Text as T
141import qualified Data.Text.Encoding as TE
142import qualified Data.Vector as V
143import Control.Monad.Trans.Reader
144import Control.Monad.Trans.State.Strict
146-- | Exception thrown if a 'Query' could not be formatted correctly.
147-- This may occur if the number of \'@?@\' characters in the query
148-- string does not match the number of parameters provided.
149data FormatError = FormatError {
152 , fmtParams :: [ByteString]
153 } deriving (Eq, Show, Typeable)
155instance Exception FormatError
157-- | Format a query string.
159-- This function is exposed to help with debugging and logging. Do not
160-- use it to prepare queries for execution.
162-- String parameters are escaped according to the character set in use
163-- on the 'Connection'.
165-- Throws 'FormatError' if the query string could not be formatted
167formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
168formatQuery conn q@(Query template) qs
169 | null xs && '?' `B.notElem` template = return template
170 | otherwise = toByteString <$> buildQuery conn q template xs
173-- | Format a query string with a variable number of rows.
175-- This function is exposed to help with debugging and logging. Do not
176-- use it to prepare queries for execution.
178-- The query string must contain exactly one substitution group,
179-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
180-- followed by an \"@(@\" character, a series of one or more \"@?@\"
181-- characters separated by commas, and a \"@)@\" character. White
182-- space in a substitution group is permitted.
184-- Throws 'FormatError' if the query string could not be formatted
186formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
187formatMany _ q [] = fmtError "no rows supplied" q []
188formatMany conn q@(Query template) qs = do
189 case parseTemplate template of
190 Just (before, qbits, after) -> do
191 bs <- mapM (buildQuery conn q qbits . toRow) qs
192 return . toByteString . mconcat $ fromByteString before :
193 intersperse (fromChar ',') bs ++
194 [fromByteString after]
195 Nothing -> fmtError "syntax error in query template for executeMany" q []
197-- Split the input string into three pieces, @before@, @qbits@, and @after@,
198-- following this grammar:
200-- start: ^ before qbits after $
201-- before: ([^?]* [^?\w])? 'VALUES' \s*
202-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
206-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
208-- This would be much more concise with some sort of regex engine.
209-- 'formatMany' used to use pcre-light instead of this hand-written parser,
210-- but pcre is a hassle to install on Windows.
211parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
212parseTemplate template =
213 -- Convert input string to uppercase, to facilitate searching.
214 search $ B.map toUpper_ascii template
216 -- Search for the next occurrence of "VALUES"
218 case B.breakSubstring "VALUES" bs of
220 -- If "VALUES" is not present in the string, or any '?' characters
221 -- were encountered prior to it, fail.
222 | B.null y || ('?' `B.elem` x)
225 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
226 -- try the next occurrence.
227 | not (B.null x) && isIdent (B.last x)
228 -> search $ B.drop 6 y
230 -- Otherwise, we have a legitimate "VALUES" token.
232 -> parseQueryBits $ skipSpace $ B.drop 6 y
234 -- Parse '(' \s* '?' \s* . If this doesn't match
235 -- (and we don't consume a '?'), look for another "VALUES".
237 -- qb points to the open paren (if present), meaning it points to the
238 -- beginning of the "qbits" production described above. This is why we
239 -- pass it down to finishQueryBits.
241 | Just ('(', skipSpace -> bs1) <- B.uncons qb
242 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
243 = finishQueryBits qb bs2
247 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
249 -- Since we've already consumed at least one '?', there's no turning back.
250 -- The parse has to succeed here, or the whole thing fails
251 -- (because we don't allow '?' to appear outside of the VALUES list).
252 finishQueryBits qb bs0
253 | Just (')', bs1) <- B.uncons bs0
254 = if '?' `B.elem` bs1
256 else Just $ slice3 template qb bs1
257 | Just (',', skipSpace -> bs1) <- B.uncons bs0
258 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
259 = finishQueryBits qb bs2
263 -- Slice a string into three pieces, given the start offset of the second
264 -- and third pieces. Each "offset" is actually a tail of the uppercase
265 -- version of the template string. Its length is used to infer the offset.
267 -- It is important to note that we only slice the original template.
268 -- We don't want our all-caps trick messing up the actual query string.
269 slice3 source p1 p2 =
272 (s1, source') = B.splitAt (B.length source - B.length p1) source
273 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
275 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
278 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
279 -- in the PostgreSQL source. No need to check [a-z], since we converted
280 -- the whole string to uppercase.
281 isIdent c = (c >= '0' && c <= '9')
282 || (c >= 'A' && c <= 'Z')
283 || (c >= '\x80' && c <= '\xFF')
287 -- Based on {space} in scan.l
288 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
290 skipSpace = B.dropWhile isSpace_ascii
292escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
293escapeStringConn conn s =
294 withConnection conn $ \c ->
295 PQ.escapeStringConn c s >>= checkError c
297escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
298escapeByteaConn conn s =
299 withConnection conn $ \c ->
300 PQ.escapeByteaConn c s >>= checkError c
302checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
303checkError _ (Just x) = return $ Right x
304checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
306buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
307buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
308 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
309 (inQuotes . fromByteString)
310 utf8ToString = T.unpack . TE.decodeUtf8
311 sub (Plain b) = pure b
312 sub (Escape s) = quote <$> escapeStringConn conn s
313 sub (EscapeBytea s) = quote <$> escapeByteaConn conn s
314 sub (Many ys) = mconcat <$> mapM sub ys
315 split s = fromByteString h : if B.null t then [] else split (B.tail t)
316 where (h,t) = B.break (=='?') s
317 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
319 zipParams _ _ = fmtError (show (B.count '?' template) ++
320 " '?' characters, but " ++
321 show (length xs) ++ " parameters") q xs
323-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
324-- expected to return results.
326-- Returns the number of rows affected.
328-- Throws 'FormatError' if the query could not be formatted correctly.
329execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
330execute conn template qs = do
331 result <- exec conn =<< formatQuery conn template qs
332 finishExecute conn template result
334-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
335-- expected to return results.
337-- Returns the number of rows affected.
339-- Throws 'FormatError' if the query could not be formatted correctly.
340executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
341executeMany _ _ [] = return 0
342executeMany conn q qs = do
343 result <- exec conn =<< formatMany conn q qs
344 finishExecute conn q result
346-- | Perform a @SELECT@ or other SQL query that is expected to return
347-- results. All results are retrieved and converted before this
350-- When processing large results, this function will consume a lot of
351-- client-side memory. Consider using 'fold' instead.
353-- Exceptions that may be thrown:
355-- * 'FormatError': the query string could not be formatted correctly.
357-- * 'QueryError': the result contains no columns (i.e. you should be
358-- using 'execute' instead of 'query').
360-- * 'ResultError': result conversion failed.
361query :: (ToRow q, FromRow r)
362 => Connection -> Query -> q -> IO [r]
363query conn template qs = do
364 result <- exec conn =<< formatQuery conn template qs
365 finishQuery conn template result
367-- | A version of 'query' that does not perform query substitution.
368query_ :: (FromRow r) => Connection -> Query -> IO [r]
369query_ conn q@(Query que) = do
370 result <- exec conn que
371 finishQuery conn q result
373-- | Perform a @SELECT@ or other SQL query that is expected to return
374-- results. Results are streamed incrementally from the server, and
375-- consumed via a left fold.
377-- When dealing with small results, it may be simpler (and perhaps
378-- faster) to use 'query' instead.
380-- This fold is /not/ strict. The stream consumer is responsible for
381-- forcing the evaluation of its result to avoid space leaks.
383-- Exceptions that may be thrown:
385-- * 'FormatError': the query string could not be formatted correctly.
387-- * 'QueryError': the result contains no columns (i.e. you should be
388-- using 'execute' instead of 'query').
390-- * 'ResultError': result conversion failed.
392fold :: ( FromRow row, ToRow params )
397 -> (a -> row -> IO a)
399fold = foldWithOptions defaultFoldOptions
407 fetchQuantity :: !FetchQuantity,
408 transactionMode :: !TransactionMode
411defaultFoldOptions :: FoldOptions
412defaultFoldOptions = FoldOptions {
413 fetchQuantity = Automatic,
414 transactionMode = TransactionMode ReadCommitted ReadOnly
417foldWithOptions :: ( FromRow row, ToRow params )
423 -> (a -> row -> IO a)
425foldWithOptions opts conn template qs a f = do
426 q <- formatQuery conn template qs
427 doFold opts conn template (Query q) a f
429-- | A version of 'fold' that does not perform query substitution.
430fold_ :: (FromRow r) =>
433 -> a -- ^ Initial state for result consumer.
434 -> (a -> r -> IO a) -- ^ Result consumer.
436fold_ = foldWithOptions_ defaultFoldOptions
439foldWithOptions_ :: (FromRow r) =>
443 -> a -- ^ Initial state for result consumer.
444 -> (a -> r -> IO a) -- ^ Result consumer.
446foldWithOptions_ opts conn query a f = doFold opts conn query query a f
449doFold :: ( FromRow row )
455 -> (a -> row -> IO a)
457doFold FoldOptions{..} conn _template q a f = do
458 stat <- withConnection conn PQ.transactionStatus
460 PQ.TransIdle -> withTransactionMode transactionMode conn go
461 PQ.TransInTrans -> go
462 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
463 -- This _shouldn't_ occur in the current incarnation of
464 -- the library, as we aren't using libpq asynchronously.
465 -- However, it could occur in future incarnations of
466 -- this library or if client code uses the Internal module
467 -- to use raw libpq commands on postgresql-simple connections.
468 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
469 -- This should be turned into a better error message.
470 -- It is probably a bad idea to automatically roll
471 -- back the transaction and start another.
472 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
473 -- Not sure what this means.
476 -- FIXME: what about name clashes with already-declared cursors?
477 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
479 loop a `finally` execute_ conn "CLOSE fold"
481-- FIXME: choose the Automatic chunkSize more intelligently
482-- One possibility is to use the type of the results, although this
483-- still isn't a perfect solution, given that common types (e.g. text)
484-- are of highly variable size.
485-- A refinement of this technique is to pick this number adaptively
486-- as results are read in from the database.
487 chunkSize = case fetchQuantity of
491 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
492 if null rs then return a else foldM f a rs >>= loop
494-- | A version of 'fold' that does not transform a state value.
495forEach :: (ToRow q, FromRow r) =>
497 -> Query -- ^ Query template.
498 -> q -- ^ Query parameters.
499 -> (r -> IO ()) -- ^ Result consumer.
501forEach conn template qs = fold conn template qs () . const
502{-# INLINE forEach #-}
504-- | A version of 'forEach' that does not perform query substitution.
505forEach_ :: (FromRow r) =>
507 -> Query -- ^ Query template.
508 -> (r -> IO ()) -- ^ Result consumer.
510forEach_ conn template = fold_ conn template () . const
511{-# INLINE forEach_ #-}
513forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
514forM' lo hi m = loop hi []
522finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
523finishQuery conn q result = do
524 status <- PQ.resultStatus result
527 throwIO $ QueryError "query: Empty query" q
529 throwIO $ QueryError "query resulted in a command response" q
531 ncols <- PQ.nfields result
532 let unCol (PQ.Col x) = fromIntegral x :: Int
533 typenames <- V.generateM (unCol ncols)
534 (\(PQ.Col . fromIntegral -> col) -> do
535 getTypename conn =<< PQ.ftype result col)
536 nrows <- PQ.ntuples result
537 ncols <- PQ.nfields result
538 forM' 0 (nrows-1) $ \row -> do
539 let rw = Row row typenames result
540 case runStateT (runReaderT (unRP fromRow) rw) 0 of
541 Ok (val,col) | col == ncols -> return val
543 vals <- forM' 0 (ncols-1) $ \c -> do
544 v <- PQ.getvalue result row c
545 return ( typenames V.! unCol c
547 throw (ConversionFailed
548 (show (unCol ncols) ++ " values: " ++ show vals)
549 (show (unCol col) ++ " slots in target type")
550 "mismatch between number of columns to \
551 \convert and number in target type")
552 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
553 Errors [x] -> throwIO x
554 Errors xs -> throwIO $ ManyErrors xs
556 throwIO $ QueryError "query: COPY TO is not supported" q
558 throwIO $ QueryError "query: COPY FROM is not supported" q
559 PQ.BadResponse -> throwResultError "query" result status
560 PQ.NonfatalError -> throwResultError "query" result status
561 PQ.FatalError -> throwResultError "query" result status
563ellipsis :: ByteString -> ByteString
565 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
569-- | Of the four isolation levels defined by the SQL standard,
570-- these are the three levels distinguished by PostgreSQL as of version 9.0.
571-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
572-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
573-- was equivalent to 'Serializable'.
576 = DefaultIsolationLevel -- ^ the isolation level will be taken from
577 -- PostgreSQL's per-connection
578 -- @default_transaction_isolation@ variable,
579 -- which is initialized according to the
580 -- server's config. The default configuration
581 -- is 'ReadCommitted'.
585 deriving (Show, Eq, Ord, Enum, Bounded)
588 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
589 -- PostgreSQL's per-connection
590 -- @default_transaction_read_only@ variable,
591 -- which is initialized according to the
592 -- server's config. The default configuration
596 deriving (Show, Eq, Ord, Enum, Bounded)
598data TransactionMode = TransactionMode {
599 isolationLevel :: !IsolationLevel,
600 readWriteMode :: !ReadWriteMode
601 } deriving (Show, Eq)
603defaultTransactionMode :: TransactionMode
604defaultTransactionMode = TransactionMode
605 defaultIsolationLevel
608defaultIsolationLevel :: IsolationLevel
609defaultIsolationLevel = DefaultIsolationLevel
611defaultReadWriteMode :: ReadWriteMode
612defaultReadWriteMode = DefaultReadWriteMode
614-- | Execute an action inside a SQL transaction.
616-- This function initiates a transaction with a \"@begin
617-- transaction@\" statement, then executes the supplied action. If
618-- the action succeeds, the transaction will be completed with
619-- 'Base.commit' before this function returns.
621-- If the action throws /any/ kind of exception (not just a
622-- PostgreSQL-related exception), the transaction will be rolled back using
623-- 'rollback', then the exception will be rethrown.
624withTransaction :: Connection -> IO a -> IO a
625withTransaction = withTransactionMode defaultTransactionMode
627-- | Execute an action inside a SQL transaction with a given isolation level.
628withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
629withTransactionLevel lvl
630 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
632-- | Execute an action inside a SQL transaction with a given transaction mode.
633withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
634withTransactionMode mode conn act =
635 mask $ \restore -> do
637 r <- restore act `onException` rollback conn
641-- | Rollback a transaction.
642rollback :: Connection -> IO ()
643rollback conn = execute_ conn "ABORT" >> return ()
645-- | Commit a transaction.
646commit :: Connection -> IO ()
647commit conn = execute_ conn "COMMIT" >> return ()
649-- | Begin a transaction.
650begin :: Connection -> IO ()
651begin = beginMode defaultTransactionMode
653-- | Begin a transaction with a given isolation level
654beginLevel :: IsolationLevel -> Connection -> IO ()
655beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
657-- | Begin a transaction with a given transaction mode
658beginMode :: TransactionMode -> Connection -> IO ()
659beginMode mode conn = do
660 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
663 isolevel = case isolationLevel mode of
664 DefaultIsolationLevel -> ""
665 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
666 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
667 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
668 readmode = case readWriteMode mode of
669 DefaultReadWriteMode -> ""
670 ReadWrite -> " READ WRITE"
671 ReadOnly -> " READ ONLY"
673fmtError :: String -> Query -> [Action] -> a
674fmtError msg q xs = throw FormatError {
677 , fmtParams = map twiddle xs
679 where twiddle (Plain b) = toByteString b
680 twiddle (Escape s) = s
681 twiddle (EscapeBytea s) = s
682 twiddle (Many ys) = B.concat (map twiddle ys)
686-- SQL-based applications are somewhat notorious for their
687-- susceptibility to attacks through the injection of maliciously
688-- crafted data. The primary reason for widespread vulnerability to
689-- SQL injections is that many applications are sloppy in handling
690-- user data when constructing SQL queries.
692-- This library provides a 'Query' type and a parameter substitution
693-- facility to address both ease of use and security.
697-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
698-- exposes a tiny API that is not compatible with the 'ByteString'
699-- API; this makes it difficult to construct queries from fragments of
700-- strings. The 'query' and 'execute' functions require queries to be
703-- To most easily construct a query, enable GHC's @OverloadedStrings@
704-- language extension and write your query as a normal literal string.
706-- > {-# LANGUAGE OverloadedStrings #-}
708-- > import Database.PostgreSQL.Simple
711-- > conn <- connect defaultConnectInfo
712-- > query conn "select 2 + 2"
714-- A 'Query' value does not represent the actual query that will be
715-- executed, but is a template for constructing the final query.
719-- Since applications need to be able to construct queries with
720-- parameters that change, this library provides a query substitution
723-- The 'Query' template accepted by 'query' and 'execute' can contain
724-- any number of \"@?@\" characters. Both 'query' and 'execute'
725-- accept a third argument, typically a tuple. When constructing the
726-- real query to execute, these functions replace the first \"@?@\" in
727-- the template with the first element of the tuple, the second
728-- \"@?@\" with the second element, and so on. If necessary, each
729-- tuple element will be quoted and escaped prior to substitution;
730-- this defeats the single most common injection vector for malicious
733-- For example, given the following 'Query' template:
735-- > select * from user where first_name = ? and age > ?
737-- And a tuple of this form:
739-- > ("Boris" :: String, 37 :: Int)
741-- The query to be executed will look like this after substitution:
743-- > select * from user where first_name = 'Boris' and age > 37
745-- If there is a mismatch between the number of \"@?@\" characters in
746-- your template and the number of elements in your tuple, a
747-- 'FormatError' will be thrown.
749-- Note that the substitution functions do not attempt to parse or
750-- validate your query. It's up to you to write syntactically valid
751-- SQL, and to ensure that each \"@?@\" in your query template is
752-- matched with the right tuple element.
756-- Automated type inference means that you will often be able to avoid
757-- supplying explicit type signatures for the elements of a tuple.
758-- However, sometimes the compiler will not be able to infer your
759-- types. Consider a case where you write a numeric literal in a
762-- > query conn "select ? + ?" (40,2)
764-- The above query will be rejected by the compiler, because it does
765-- not know the specific numeric types of the literals @40@ and @2@.
766-- This is easily fixed:
768-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
770-- The same kind of problem can arise with string literals if you have
771-- the @OverloadedStrings@ language extension enabled. Again, just
772-- use an explicit type signature if this happens.
776-- Haskell lacks a single-element tuple type, so if you have just one
777-- value you want substituted into a query, what should you do?
779-- The obvious approach would appear to be something like this:
781-- > instance (Param a) => QueryParam a where
784-- Unfortunately, this wreaks havoc with type inference, so we take a
785-- different tack. To represent a single value @val@ as a parameter, write
786-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
788-- Here's an example using a singleton list:
790-- > execute conn "insert into users (first_name) values (?)"
795-- Suppose you want to write a query using an @IN@ clause:
797-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
799-- In such cases, it's common for both the elements and length of the
800-- list after the @IN@ keyword to vary from query to query.
802-- To address this case, use the 'In' type wrapper, and use a single
803-- \"@?@\" character to represent the list. Omit the parentheses
804-- around the list; these will be added for you.
808-- > query conn "select * from users where first_name in ?" $
809-- > In ["Anna", "Boris", "Carla"]
811-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
812-- substituted instead, to ensure that your clause remains
813-- syntactically valid.
817-- If you know that you have many rows of data to insert into a table,
818-- it is much more efficient to perform all the insertions in a single
819-- multi-row @INSERT@ statement than individually.
821-- The 'executeMany' function is intended specifically for helping
822-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
823-- query substitution are different than those for 'execute'.
825-- What 'executeMany' searches for in your 'Query' template is a
826-- single substring of the form:
830-- The rules are as follows:
832-- * The keyword @VALUES@ is matched case insensitively.
834-- * There must be no other \"@?@\" characters anywhere in your
837-- * There must one or more \"@?@\" in the parentheses.
839-- * Extra white space is fine.
841-- The last argument to 'executeMany' is a list of parameter
842-- tuples. These will be substituted into the query where the @(?,?)@
843-- string appears, in a form suitable for use in a multi-row @INSERT@
846-- Here is an example:
849-- > "insert into users (first_name,last_name) values (?,?)"
850-- > [("Boris","Karloff"),("Ed","Wood")]
852-- The query that will be executed here will look like this
853-- (reformatted for tidiness):
855-- > insert into users (first_name,last_name) values
856-- > ('Boris','Karloff'),('Ed','Wood')
860-- The 'query' and 'query_' functions return a list of values in the
861-- 'FromRow' typeclass. This class performs automatic extraction
862-- and type conversion of rows from a query result.
864-- Here is a simple example of how to extract results:
866-- > import qualified Data.Text as Text
868-- > xs <- query_ conn "select name,age from users"
869-- > forM_ xs $ \(name,age) ->
870-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
872-- Notice two important details about this code:
874-- * The number of columns we ask for in the query template must
875-- exactly match the number of elements we specify in a row of the
876-- result tuple. If they do not match, a 'ResultError' exception
879-- * Sometimes, the compiler needs our help in specifying types. It
880-- can infer that @name@ must be a 'Text', due to our use of the
881-- @unpack@ function. However, we have to tell it the type of @age@,
882-- as it has no other information to determine the exact type.
886-- The type of a result tuple will look something like this:
890-- Although SQL can accommodate @NULL@ as a value for any of these
891-- types, Haskell cannot. If your result contains columns that may be
892-- @NULL@, be sure that you use 'Maybe' in those positions of of your
895-- > (Text, Maybe Int, Int)
897-- If 'query' encounters a @NULL@ in a row where the corresponding
898-- Haskell type is not 'Maybe', it will throw a 'ResultError'
903-- To specify that a query returns a single-column result, use the
906-- > xs <- query_ conn "select id from users"
907-- > forM_ xs $ \(Only dbid) -> {- ... -}
911-- Conversion of SQL values to Haskell values is somewhat
912-- permissive. Here are the rules.
914-- * For numeric types, any Haskell type that can accurately represent
915-- all values of the given PostgreSQL type is considered \"compatible\".
916-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
917-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
918-- represent a @SMALLINT@, so it is considered compatble with those types.
920-- * A numeric compatibility check is based only on the type of a
921-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
922-- @BIGINT@ column will be considered incompatible with a Haskell
923-- 'Int16', even if it contains the value @1@.
925-- * If a numeric incompatibility is found, 'query' will throw a
928-- * The 'String' and 'Text' types are assumed to be encoded as
929-- UTF-8. If you use some other encoding, decoding may fail or give
930-- wrong results. In such cases, write a @newtype@ wrapper and a
931-- custom 'Result' instance to handle your encoding.
933getTypename :: Connection -> PQ.Oid -> IO ByteString
934getTypename conn@Connection{..} oid =
935 case oid2builtin oid of
936 Just builtin -> return $! builtin2typname builtin
937 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
938 case IntMap.lookup (oid2int oid) oidmap of
939 Just name -> return (oidmap, name)
941 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
943 name <- case names of
944 [] -> return $ throw SqlError {
946 sqlErrorMsg = "invalid type oid",
950 _ -> fail "typename query returned more than one result"
951 -- oid is a primary key, so the query should
952 -- never return more than one result
953 return (IntMap.insert (oid2int oid) name oidmap, name)
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