1{-# LANGUAGE DeriveDataTypeable #-}
2{-# LANGUAGE NamedFieldPuns #-}
3{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE PatternGuards #-}
5{-# LANGUAGE RecordWildCards #-}
6{-# LANGUAGE ViewPatterns #-}
8------------------------------------------------------------------------------
10-- Module: Database.PostgreSQL.Simple
11-- Copyright: (c) 2011 MailRank, Inc.
12-- (c) 2011-2012 Leon P Smith
14-- Maintainer: Leon P Smith <leon@melding-monads.com>
15-- Stability: experimental
16-- Portability: portable
18-- A mid-level client library for the PostgreSQL database, aimed at ease of
19-- use and high performance.
21------------------------------------------------------------------------------
23module Database.PostgreSQL.Simple
31 -- ** Parameter substitution
37 -- ** Substituting a single parameter
40 -- ** Representing a list of values
43 -- ** Modifying multiple rows at once
46 -- * Extracting results
49 -- ** Handling null values
52 -- ** Type conversions
67 , FormatError(fmtMessage, fmtQuery, fmtParams)
68 , QueryError(qeMessage, qeQuery)
69 , ResultError(errSQLType, errHaskellType, errMessage)
70 -- * Connection management
72 , Base.connectPostgreSQL
73 , Base.postgreSQLConnectionString
74 , Base.defaultConnectInfo
76 -- * Queries that return results
79 -- * Queries that stream results
89 -- * Statements that do not return results
94 -- * Transaction handling
99 , defaultTransactionMode
100 , defaultIsolationLevel
101 , defaultReadWriteMode
102 , withTransactionLevel
103 , withTransactionMode
110 -- * Helper functions
115import Blaze.ByteString.Builder
116 ( Builder, fromByteString, toByteString )
117import Blaze.ByteString.Builder.Char8 (fromChar)
118import Control.Applicative ((<$>), pure)
119import Control.Concurrent.MVar
120import Control.Exception
121 ( Exception, onException, throw, throwIO, finally )
122import Control.Monad (foldM)
123import Data.ByteString (ByteString)
124import Data.Int (Int64)
125import qualified Data.IntMap as IntMap
126import Data.List (intersperse)
127import Data.Monoid (mappend, mconcat)
128import Data.Typeable (Typeable)
129import Database.PostgreSQL.Simple.BuiltinTypes
130 ( oid2builtin, builtin2typname )
131import Database.PostgreSQL.Simple.Compat ( mask )
132import Database.PostgreSQL.Simple.FromField (ResultError(..))
133import Database.PostgreSQL.Simple.FromRow (FromRow(..))
134import Database.PostgreSQL.Simple.Ok
135import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes)
136import Database.PostgreSQL.Simple.ToRow (ToRow(..))
137import Database.PostgreSQL.Simple.Types
138 ( Binary(..), In(..), Only(..), Query(..), (:.)(..) )
139import Database.PostgreSQL.Simple.Internal as Base
140import qualified Database.PostgreSQL.LibPQ as PQ
141import qualified Data.ByteString.Char8 as B
142import qualified Data.Text as T
143import qualified Data.Text.Encoding as TE
144import qualified Data.Vector as V
145import Control.Monad.Trans.Reader
146import Control.Monad.Trans.State.Strict
148-- | Exception thrown if a 'Query' could not be formatted correctly.
149-- This may occur if the number of \'@?@\' characters in the query
150-- string does not match the number of parameters provided.
151data FormatError = FormatError {
154 , fmtParams :: [ByteString]
155 } deriving (Eq, Show, Typeable)
157instance Exception FormatError
159-- | Format a query string.
161-- This function is exposed to help with debugging and logging. Do not
162-- use it to prepare queries for execution.
164-- String parameters are escaped according to the character set in use
165-- on the 'Connection'.
167-- Throws 'FormatError' if the query string could not be formatted
169formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString
170formatQuery conn q@(Query template) qs
171 | null xs && '?' `B.notElem` template = return template
172 | otherwise = toByteString <$> buildQuery conn q template xs
175-- | Format a query string with a variable number of rows.
177-- This function is exposed to help with debugging and logging. Do not
178-- use it to prepare queries for execution.
180-- The query string must contain exactly one substitution group,
181-- identified by the SQL keyword \"@VALUES@\" (case insensitive)
182-- followed by an \"@(@\" character, a series of one or more \"@?@\"
183-- characters separated by commas, and a \"@)@\" character. White
184-- space in a substitution group is permitted.
186-- Throws 'FormatError' if the query string could not be formatted
188formatMany :: (ToRow q) => Connection -> Query -> [q] -> IO ByteString
189formatMany _ q [] = fmtError "no rows supplied" q []
190formatMany conn q@(Query template) qs = do
191 case parseTemplate template of
192 Just (before, qbits, after) -> do
193 bs <- mapM (buildQuery conn q qbits . toRow) qs
194 return . toByteString . mconcat $ fromByteString before :
195 intersperse (fromChar ',') bs ++
196 [fromByteString after]
197 Nothing -> fmtError "syntax error in query template for executeMany" q []
199-- Split the input string into three pieces, @before@, @qbits@, and @after@,
200-- following this grammar:
202-- start: ^ before qbits after $
203-- before: ([^?]* [^?\w])? 'VALUES' \s*
204-- qbits: '(' \s* '?' \s* (',' \s* '?' \s*)* ')'
208-- \w: [A-Z] | [a-z] | [\x80-\xFF] | '_' | '$' | [0-9]
210-- This would be much more concise with some sort of regex engine.
211-- 'formatMany' used to use pcre-light instead of this hand-written parser,
212-- but pcre is a hassle to install on Windows.
213parseTemplate :: ByteString -> Maybe (ByteString, ByteString, ByteString)
214parseTemplate template =
215 -- Convert input string to uppercase, to facilitate searching.
216 search $ B.map toUpper_ascii template
218 -- Search for the next occurrence of "VALUES"
220 case B.breakSubstring "VALUES" bs of
222 -- If "VALUES" is not present in the string, or any '?' characters
223 -- were encountered prior to it, fail.
224 | B.null y || ('?' `B.elem` x)
227 -- If "VALUES" is preceded by an identifier character (a.k.a. \w),
228 -- try the next occurrence.
229 | not (B.null x) && isIdent (B.last x)
230 -> search $ B.drop 6 y
232 -- Otherwise, we have a legitimate "VALUES" token.
234 -> parseQueryBits $ skipSpace $ B.drop 6 y
236 -- Parse '(' \s* '?' \s* . If this doesn't match
237 -- (and we don't consume a '?'), look for another "VALUES".
239 -- qb points to the open paren (if present), meaning it points to the
240 -- beginning of the "qbits" production described above. This is why we
241 -- pass it down to finishQueryBits.
243 | Just ('(', skipSpace -> bs1) <- B.uncons qb
244 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
245 = finishQueryBits qb bs2
249 -- Parse (',' \s* '?' \s*)* ')' [^?]* .
251 -- Since we've already consumed at least one '?', there's no turning back.
252 -- The parse has to succeed here, or the whole thing fails
253 -- (because we don't allow '?' to appear outside of the VALUES list).
254 finishQueryBits qb bs0
255 | Just (')', bs1) <- B.uncons bs0
256 = if '?' `B.elem` bs1
258 else Just $ slice3 template qb bs1
259 | Just (',', skipSpace -> bs1) <- B.uncons bs0
260 , Just ('?', skipSpace -> bs2) <- B.uncons bs1
261 = finishQueryBits qb bs2
265 -- Slice a string into three pieces, given the start offset of the second
266 -- and third pieces. Each "offset" is actually a tail of the uppercase
267 -- version of the template string. Its length is used to infer the offset.
269 -- It is important to note that we only slice the original template.
270 -- We don't want our all-caps trick messing up the actual query string.
271 slice3 source p1 p2 =
274 (s1, source') = B.splitAt (B.length source - B.length p1) source
275 (s2, source'') = B.splitAt (B.length p1 - B.length p2) source'
277 toUpper_ascii c | c >= 'a' && c <= 'z' = toEnum (fromEnum c - 32)
280 -- Based on the definition of {ident_cont} in src/backend/parser/scan.l
281 -- in the PostgreSQL source. No need to check [a-z], since we converted
282 -- the whole string to uppercase.
283 isIdent c = (c >= '0' && c <= '9')
284 || (c >= 'A' && c <= 'Z')
285 || (c >= '\x80' && c <= '\xFF')
289 -- Based on {space} in scan.l
290 isSpace_ascii c = (c == ' ') || (c >= '\t' && c <= '\r')
292 skipSpace = B.dropWhile isSpace_ascii
294escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
295escapeStringConn conn s =
296 withConnection conn $ \c ->
297 PQ.escapeStringConn c s >>= checkError c
299escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString)
300escapeByteaConn conn s =
301 withConnection conn $ \c ->
302 PQ.escapeByteaConn c s >>= checkError c
304checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a)
305checkError _ (Just x) = return $ Right x
306checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c
308buildQuery :: Connection -> Query -> ByteString -> [Action] -> IO Builder
309buildQuery conn q template xs = zipParams (split template) <$> mapM sub xs
310 where quote = either (\msg -> fmtError (utf8ToString msg) q xs)
311 (inQuotes . fromByteString)
312 utf8ToString = T.unpack . TE.decodeUtf8
313 sub (Plain b) = pure b
314 sub (Escape s) = quote <$> escapeStringConn conn s
315 sub (EscapeByteA s) = quote <$> escapeByteaConn conn s
316 sub (Many ys) = mconcat <$> mapM sub ys
317 split s = fromByteString h : if B.null t then [] else split (B.tail t)
318 where (h,t) = B.break (=='?') s
319 zipParams (t:ts) (p:ps) = t `mappend` p `mappend` zipParams ts ps
321 zipParams _ _ = fmtError (show (B.count '?' template) ++
322 " '?' characters, but " ++
323 show (length xs) ++ " parameters") q xs
325-- | Execute an @INSERT@, @UPDATE@, or other SQL query that is not
326-- expected to return results.
328-- Returns the number of rows affected.
330-- Throws 'FormatError' if the query could not be formatted correctly.
331execute :: (ToRow q) => Connection -> Query -> q -> IO Int64
332execute conn template qs = do
333 result <- exec conn =<< formatQuery conn template qs
334 finishExecute conn template result
336-- | Execute a multi-row @INSERT@, @UPDATE@, or other SQL query that is not
337-- expected to return results.
339-- Returns the number of rows affected.
341-- Throws 'FormatError' if the query could not be formatted correctly.
342executeMany :: (ToRow q) => Connection -> Query -> [q] -> IO Int64
343executeMany _ _ [] = return 0
344executeMany conn q qs = do
345 result <- exec conn =<< formatMany conn q qs
346 finishExecute conn q result
348-- | Perform a @SELECT@ or other SQL query that is expected to return
349-- results. All results are retrieved and converted before this
352-- When processing large results, this function will consume a lot of
353-- client-side memory. Consider using 'fold' instead.
355-- Exceptions that may be thrown:
357-- * 'FormatError': the query string could not be formatted correctly.
359-- * 'QueryError': the result contains no columns (i.e. you should be
360-- using 'execute' instead of 'query').
362-- * 'ResultError': result conversion failed.
363query :: (ToRow q, FromRow r)
364 => Connection -> Query -> q -> IO [r]
365query conn template qs = do
366 result <- exec conn =<< formatQuery conn template qs
367 finishQuery conn template result
369-- | A version of 'query' that does not perform query substitution.
370query_ :: (FromRow r) => Connection -> Query -> IO [r]
371query_ conn q@(Query que) = do
372 result <- exec conn que
373 finishQuery conn q result
375-- | Perform a @SELECT@ or other SQL query that is expected to return
376-- results. Results are streamed incrementally from the server, and
377-- consumed via a left fold.
379-- When dealing with small results, it may be simpler (and perhaps
380-- faster) to use 'query' instead.
382-- This fold is /not/ strict. The stream consumer is responsible for
383-- forcing the evaluation of its result to avoid space leaks.
385-- Exceptions that may be thrown:
387-- * 'FormatError': the query string could not be formatted correctly.
389-- * 'QueryError': the result contains no columns (i.e. you should be
390-- using 'execute' instead of 'query').
392-- * 'ResultError': result conversion failed.
394fold :: ( FromRow row, ToRow params )
399 -> (a -> row -> IO a)
401fold = foldWithOptions defaultFoldOptions
409 fetchQuantity :: !FetchQuantity,
410 transactionMode :: !TransactionMode
413defaultFoldOptions :: FoldOptions
414defaultFoldOptions = FoldOptions {
415 fetchQuantity = Automatic,
416 transactionMode = TransactionMode ReadCommitted ReadOnly
419foldWithOptions :: ( FromRow row, ToRow params )
425 -> (a -> row -> IO a)
427foldWithOptions opts conn template qs a f = do
428 q <- formatQuery conn template qs
429 doFold opts conn template (Query q) a f
431-- | A version of 'fold' that does not perform query substitution.
432fold_ :: (FromRow r) =>
435 -> a -- ^ Initial state for result consumer.
436 -> (a -> r -> IO a) -- ^ Result consumer.
438fold_ = foldWithOptions_ defaultFoldOptions
441foldWithOptions_ :: (FromRow r) =>
445 -> a -- ^ Initial state for result consumer.
446 -> (a -> r -> IO a) -- ^ Result consumer.
448foldWithOptions_ opts conn query a f = doFold opts conn query query a f
451doFold :: ( FromRow row )
457 -> (a -> row -> IO a)
459doFold FoldOptions{..} conn _template q a f = do
460 stat <- withConnection conn PQ.transactionStatus
462 PQ.TransIdle -> withTransactionMode transactionMode conn go
463 PQ.TransInTrans -> go
464 PQ.TransActive -> fail "foldWithOpts FIXME: PQ.TransActive"
465 -- This _shouldn't_ occur in the current incarnation of
466 -- the library, as we aren't using libpq asynchronously.
467 -- However, it could occur in future incarnations of
468 -- this library or if client code uses the Internal module
469 -- to use raw libpq commands on postgresql-simple connections.
470 PQ.TransInError -> fail "foldWithOpts FIXME: PQ.TransInError"
471 -- This should be turned into a better error message.
472 -- It is probably a bad idea to automatically roll
473 -- back the transaction and start another.
474 PQ.TransUnknown -> fail "foldWithOpts FIXME: PQ.TransUnknown"
475 -- Not sure what this means.
478 -- FIXME: what about name clashes with already-declared cursors?
479 _ <- execute_ conn ("DECLARE fold NO SCROLL CURSOR FOR "
481 loop a `finally` execute_ conn "CLOSE fold"
483-- FIXME: choose the Automatic chunkSize more intelligently
484-- One possibility is to use the type of the results, although this
485-- still isn't a perfect solution, given that common types (e.g. text)
486-- are of highly variable size.
487-- A refinement of this technique is to pick this number adaptively
488-- as results are read in from the database.
489 chunkSize = case fetchQuantity of
493 rs <- query conn "FETCH FORWARD ? FROM fold" (Only chunkSize)
494 if null rs then return a else foldM f a rs >>= loop
496-- | A version of 'fold' that does not transform a state value.
497forEach :: (ToRow q, FromRow r) =>
499 -> Query -- ^ Query template.
500 -> q -- ^ Query parameters.
501 -> (r -> IO ()) -- ^ Result consumer.
503forEach conn template qs = fold conn template qs () . const
504{-# INLINE forEach #-}
506-- | A version of 'forEach' that does not perform query substitution.
507forEach_ :: (FromRow r) =>
509 -> Query -- ^ Query template.
510 -> (r -> IO ()) -- ^ Result consumer.
512forEach_ conn template = fold_ conn template () . const
513{-# INLINE forEach_ #-}
515forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
516forM' lo hi m = loop hi []
524finishQuery :: (FromRow r) => Connection -> Query -> PQ.Result -> IO [r]
525finishQuery conn q result = do
526 status <- PQ.resultStatus result
529 throwIO $ QueryError "query: Empty query" q
531 throwIO $ QueryError "query resulted in a command response" q
533 ncols <- PQ.nfields result
534 let unCol (PQ.Col x) = fromIntegral x :: Int
535 typenames <- V.generateM (unCol ncols)
536 (\(PQ.Col . fromIntegral -> col) -> do
537 getTypename conn =<< PQ.ftype result col)
538 nrows <- PQ.ntuples result
539 ncols <- PQ.nfields result
540 forM' 0 (nrows-1) $ \row -> do
541 let rw = Row row typenames result
542 case runStateT (runReaderT (unRP fromRow) rw) 0 of
543 Ok (val,col) | col == ncols -> return val
545 vals <- forM' 0 (ncols-1) $ \c -> do
546 v <- PQ.getvalue result row c
547 return ( typenames V.! unCol c
549 throw (ConversionFailed
550 (show (unCol ncols) ++ " values: " ++ show vals)
551 (show (unCol col) ++ " slots in target type")
552 "mismatch between number of columns to \
553 \convert and number in target type")
554 Errors [] -> throwIO $ ConversionFailed "" "" "unknown error"
555 Errors [x] -> throwIO x
556 Errors xs -> throwIO $ ManyErrors xs
558 throwIO $ QueryError "query: COPY TO is not supported" q
560 throwIO $ QueryError "query: COPY FROM is not supported" q
561 PQ.BadResponse -> throwResultError "query" result status
562 PQ.NonfatalError -> throwResultError "query" result status
563 PQ.FatalError -> throwResultError "query" result status
565ellipsis :: ByteString -> ByteString
567 | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
571-- | Of the four isolation levels defined by the SQL standard,
572-- these are the three levels distinguished by PostgreSQL as of version 9.0.
573-- See <http://www.postgresql.org/docs/9.1/static/transaction-iso.html>
574-- for more information. Note that prior to PostgreSQL 9.0, 'RepeatableRead'
575-- was equivalent to 'Serializable'.
578 = DefaultIsolationLevel -- ^ the isolation level will be taken from
579 -- PostgreSQL's per-connection
580 -- @default_transaction_isolation@ variable,
581 -- which is initialized according to the
582 -- server's config. The default configuration
583 -- is 'ReadCommitted'.
587 deriving (Show, Eq, Ord, Enum, Bounded)
590 = DefaultReadWriteMode -- ^ the read-write mode will be taken from
591 -- PostgreSQL's per-connection
592 -- @default_transaction_read_only@ variable,
593 -- which is initialized according to the
594 -- server's config. The default configuration
598 deriving (Show, Eq, Ord, Enum, Bounded)
600data TransactionMode = TransactionMode {
601 isolationLevel :: !IsolationLevel,
602 readWriteMode :: !ReadWriteMode
603 } deriving (Show, Eq)
605defaultTransactionMode :: TransactionMode
606defaultTransactionMode = TransactionMode
607 defaultIsolationLevel
610defaultIsolationLevel :: IsolationLevel
611defaultIsolationLevel = DefaultIsolationLevel
613defaultReadWriteMode :: ReadWriteMode
614defaultReadWriteMode = DefaultReadWriteMode
616-- | Execute an action inside a SQL transaction.
618-- This function initiates a transaction with a \"@begin
619-- transaction@\" statement, then executes the supplied action. If
620-- the action succeeds, the transaction will be completed with
621-- 'Base.commit' before this function returns.
623-- If the action throws /any/ kind of exception (not just a
624-- PostgreSQL-related exception), the transaction will be rolled back using
625-- 'rollback', then the exception will be rethrown.
626withTransaction :: Connection -> IO a -> IO a
627withTransaction = withTransactionMode defaultTransactionMode
629-- | Execute an action inside a SQL transaction with a given isolation level.
630withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a
631withTransactionLevel lvl
632 = withTransactionMode defaultTransactionMode { isolationLevel = lvl }
634-- | Execute an action inside a SQL transaction with a given transaction mode.
635withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a
636withTransactionMode mode conn act =
637 mask $ \restore -> do
639 r <- restore act `onException` rollback conn
643-- | Rollback a transaction.
644rollback :: Connection -> IO ()
645rollback conn = execute_ conn "ABORT" >> return ()
647-- | Commit a transaction.
648commit :: Connection -> IO ()
649commit conn = execute_ conn "COMMIT" >> return ()
651-- | Begin a transaction.
652begin :: Connection -> IO ()
653begin = beginMode defaultTransactionMode
655-- | Begin a transaction with a given isolation level
656beginLevel :: IsolationLevel -> Connection -> IO ()
657beginLevel lvl = beginMode defaultTransactionMode { isolationLevel = lvl }
659-- | Begin a transaction with a given transaction mode
660beginMode :: TransactionMode -> Connection -> IO ()
661beginMode mode conn = do
662 _ <- execute_ conn $! Query (B.concat ["BEGIN", isolevel, readmode])
665 isolevel = case isolationLevel mode of
666 DefaultIsolationLevel -> ""
667 ReadCommitted -> " ISOLATION LEVEL READ COMMITTED"
668 RepeatableRead -> " ISOLATION LEVEL REPEATABLE READ"
669 Serializable -> " ISOLATION LEVEL SERIALIZABLE"
670 readmode = case readWriteMode mode of
671 DefaultReadWriteMode -> ""
672 ReadWrite -> " READ WRITE"
673 ReadOnly -> " READ ONLY"
675fmtError :: String -> Query -> [Action] -> a
676fmtError msg q xs = throw FormatError {
679 , fmtParams = map twiddle xs
681 where twiddle (Plain b) = toByteString b
682 twiddle (Escape s) = s
683 twiddle (EscapeByteA s) = s
684 twiddle (Many ys) = B.concat (map twiddle ys)
688-- SQL-based applications are somewhat notorious for their
689-- susceptibility to attacks through the injection of maliciously
690-- crafted data. The primary reason for widespread vulnerability to
691-- SQL injections is that many applications are sloppy in handling
692-- user data when constructing SQL queries.
694-- This library provides a 'Query' type and a parameter substitution
695-- facility to address both ease of use and security.
699-- A 'Query' is a @newtype@-wrapped 'ByteString'. It intentionally
700-- exposes a tiny API that is not compatible with the 'ByteString'
701-- API; this makes it difficult to construct queries from fragments of
702-- strings. The 'query' and 'execute' functions require queries to be
705-- To most easily construct a query, enable GHC's @OverloadedStrings@
706-- language extension and write your query as a normal literal string.
708-- > {-# LANGUAGE OverloadedStrings #-}
710-- > import Database.PostgreSQL.Simple
713-- > conn <- connect defaultConnectInfo
714-- > query conn "select 2 + 2"
716-- A 'Query' value does not represent the actual query that will be
717-- executed, but is a template for constructing the final query.
721-- Since applications need to be able to construct queries with
722-- parameters that change, this library provides a query substitution
725-- The 'Query' template accepted by 'query' and 'execute' can contain
726-- any number of \"@?@\" characters. Both 'query' and 'execute'
727-- accept a third argument, typically a tuple. When constructing the
728-- real query to execute, these functions replace the first \"@?@\" in
729-- the template with the first element of the tuple, the second
730-- \"@?@\" with the second element, and so on. If necessary, each
731-- tuple element will be quoted and escaped prior to substitution;
732-- this defeats the single most common injection vector for malicious
735-- For example, given the following 'Query' template:
737-- > select * from user where first_name = ? and age > ?
739-- And a tuple of this form:
741-- > ("Boris" :: String, 37 :: Int)
743-- The query to be executed will look like this after substitution:
745-- > select * from user where first_name = 'Boris' and age > 37
747-- If there is a mismatch between the number of \"@?@\" characters in
748-- your template and the number of elements in your tuple, a
749-- 'FormatError' will be thrown.
751-- Note that the substitution functions do not attempt to parse or
752-- validate your query. It's up to you to write syntactically valid
753-- SQL, and to ensure that each \"@?@\" in your query template is
754-- matched with the right tuple element.
758-- Automated type inference means that you will often be able to avoid
759-- supplying explicit type signatures for the elements of a tuple.
760-- However, sometimes the compiler will not be able to infer your
761-- types. Consider a case where you write a numeric literal in a
764-- > query conn "select ? + ?" (40,2)
766-- The above query will be rejected by the compiler, because it does
767-- not know the specific numeric types of the literals @40@ and @2@.
768-- This is easily fixed:
770-- > query conn "select ? + ?" (40 :: Double, 2 :: Double)
772-- The same kind of problem can arise with string literals if you have
773-- the @OverloadedStrings@ language extension enabled. Again, just
774-- use an explicit type signature if this happens.
778-- Haskell lacks a single-element tuple type, so if you have just one
779-- value you want substituted into a query, what should you do?
781-- The obvious approach would appear to be something like this:
783-- > instance (Param a) => QueryParam a where
786-- Unfortunately, this wreaks havoc with type inference, so we take a
787-- different tack. To represent a single value @val@ as a parameter, write
788-- a singleton list @[val]@, use 'Just' @val@, or use 'Only' @val@.
790-- Here's an example using a singleton list:
792-- > execute conn "insert into users (first_name) values (?)"
797-- Suppose you want to write a query using an @IN@ clause:
799-- > select * from users where first_name in ('Anna', 'Boris', 'Carla')
801-- In such cases, it's common for both the elements and length of the
802-- list after the @IN@ keyword to vary from query to query.
804-- To address this case, use the 'In' type wrapper, and use a single
805-- \"@?@\" character to represent the list. Omit the parentheses
806-- around the list; these will be added for you.
810-- > query conn "select * from users where first_name in ?" $
811-- > In ["Anna", "Boris", "Carla"]
813-- If your 'In'-wrapped list is empty, the string @\"(null)\"@ will be
814-- substituted instead, to ensure that your clause remains
815-- syntactically valid.
819-- If you know that you have many rows of data to insert into a table,
820-- it is much more efficient to perform all the insertions in a single
821-- multi-row @INSERT@ statement than individually.
823-- The 'executeMany' function is intended specifically for helping
824-- with multi-row @INSERT@ and @UPDATE@ statements. Its rules for
825-- query substitution are different than those for 'execute'.
827-- What 'executeMany' searches for in your 'Query' template is a
828-- single substring of the form:
832-- The rules are as follows:
834-- * The keyword @VALUES@ is matched case insensitively.
836-- * There must be no other \"@?@\" characters anywhere in your
839-- * There must one or more \"@?@\" in the parentheses.
841-- * Extra white space is fine.
843-- The last argument to 'executeMany' is a list of parameter
844-- tuples. These will be substituted into the query where the @(?,?)@
845-- string appears, in a form suitable for use in a multi-row @INSERT@
848-- Here is an example:
851-- > "insert into users (first_name,last_name) values (?,?)"
852-- > [("Boris","Karloff"),("Ed","Wood")]
854-- The query that will be executed here will look like this
855-- (reformatted for tidiness):
857-- > insert into users (first_name,last_name) values
858-- > ('Boris','Karloff'),('Ed','Wood')
862-- The 'query' and 'query_' functions return a list of values in the
863-- 'FromRow' typeclass. This class performs automatic extraction
864-- and type conversion of rows from a query result.
866-- Here is a simple example of how to extract results:
868-- > import qualified Data.Text as Text
870-- > xs <- query_ conn "select name,age from users"
871-- > forM_ xs $ \(name,age) ->
872-- > putStrLn $ Text.unpack name ++ " is " ++ show (age :: Int)
874-- Notice two important details about this code:
876-- * The number of columns we ask for in the query template must
877-- exactly match the number of elements we specify in a row of the
878-- result tuple. If they do not match, a 'ResultError' exception
881-- * Sometimes, the compiler needs our help in specifying types. It
882-- can infer that @name@ must be a 'Text', due to our use of the
883-- @unpack@ function. However, we have to tell it the type of @age@,
884-- as it has no other information to determine the exact type.
888-- The type of a result tuple will look something like this:
892-- Although SQL can accommodate @NULL@ as a value for any of these
893-- types, Haskell cannot. If your result contains columns that may be
894-- @NULL@, be sure that you use 'Maybe' in those positions of of your
897-- > (Text, Maybe Int, Int)
899-- If 'query' encounters a @NULL@ in a row where the corresponding
900-- Haskell type is not 'Maybe', it will throw a 'ResultError'
905-- To specify that a query returns a single-column result, use the
908-- > xs <- query_ conn "select id from users"
909-- > forM_ xs $ \(Only dbid) -> {- ... -}
913-- Conversion of SQL values to Haskell values is somewhat
914-- permissive. Here are the rules.
916-- * For numeric types, any Haskell type that can accurately represent
917-- all values of the given PostgreSQL type is considered \"compatible\".
918-- For instance, you can always extract a PostgreSQL 16-bit @SMALLINT@
919-- column to a Haskell 'Int'. The Haskell 'Float' type can accurately
920-- represent a @SMALLINT@, so it is considered compatble with those types.
922-- * A numeric compatibility check is based only on the type of a
923-- column, /not/ on its values. For instance, a PostgreSQL 64-bit
924-- @BIGINT@ column will be considered incompatible with a Haskell
925-- 'Int16', even if it contains the value @1@.
927-- * If a numeric incompatibility is found, 'query' will throw a
930-- * The 'String' and 'Text' types are assumed to be encoded as
931-- UTF-8. If you use some other encoding, decoding may fail or give
932-- wrong results. In such cases, write a @newtype@ wrapper and a
933-- custom 'Result' instance to handle your encoding.
935getTypename :: Connection -> PQ.Oid -> IO ByteString
936getTypename conn@Connection{..} oid =
937 case oid2builtin oid of
938 Just builtin -> return $! builtin2typname builtin
939 Nothing -> modifyMVar connectionObjects $ \oidmap -> do
940 case IntMap.lookup (oid2int oid) oidmap of
941 Just name -> return (oidmap, name)
943 names <- query conn "SELECT typname FROM pg_type WHERE oid=?"
945 name <- case names of
946 [] -> return $ throw SqlError {
948 sqlErrorMsg = "invalid type oid",
952 _ -> fail "typename query returned more than one result"
953 -- oid is a primary key, so the query should
954 -- never return more than one result
955 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