-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Mid-Level PostgreSQL client library -- -- Mid-Level PostgreSQL client library, forked from mysql-simple. @package postgresql-simple @version 0.4.2.3 module Database.PostgreSQL.Simple.Time.Internal getDay :: Parser Day getDate :: Parser Date getTimeOfDay :: Parser TimeOfDay getLocalTime :: Parser LocalTime getLocalTimestamp :: Parser LocalTimestamp getTimeZone :: Parser TimeZone getZonedTime :: Parser ZonedTime getZonedTimestamp :: Parser ZonedTimestamp getUTCTime :: Parser UTCTime getUTCTimestamp :: Parser UTCTimestamp module Database.PostgreSQL.Simple.SqlQQ -- | sql is a quasiquoter that eases the syntactic burden of writing -- big sql statements in Haskell source code. For example: -- --
--   {-# LANGUAGE QuasiQuotes #-}
--   
--   query conn [sql| SELECT column_a, column_b
--                      FROM table1 NATURAL JOIN table2
--                     WHERE ? <= time AND time < ?
--                       AND name LIKE ?
--                     ORDER BY size DESC
--                     LIMIT 100                        |]
--              (beginTime,endTime,string)
--   
-- -- This quasiquoter attempts to mimimize whitespace; otherwise the above -- query would consist of approximately half whitespace when sent to the -- database backend. It also recognizes and strips out standard sql -- comments --. -- -- The implementation of the whitespace reducer is currently incomplete. -- Thus it can mess up your syntax in cases where whitespace should be -- preserved as-is. It does preserve whitespace inside standard SQL -- string literals. But it can get confused by the non-standard -- PostgreSQL string literal syntax (which is the default setting in -- PostgreSQL 8 and below), the extended escape string syntax, quoted -- identifiers, and other similar constructs. -- -- Of course, this caveat only applies to text written inside the SQL -- quasiquoter; whitespace reduction is a compile-time computation and -- thus will not touch the string parameter above, which is a -- run-time value. -- -- Also note that this will not work if the substring |] is -- contained in the query. sql :: QuasiQuoter -- | Time types that supports positive and negative infinity. Also includes -- new time parsers and printers with better performance than GHC's time -- package. -- -- The parsers only understand the specific variant of ISO 8601 that -- PostgreSQL emits, and the printers attempt to duplicate this syntax. -- Thus the datestyle parameter for the connection must be set -- to ISO. -- -- These parsers and printers likely have problems and shortcomings. Some -- that I know of: -- -- 1 TimestampTZs before a timezone-dependent point in time -- cannot be parsed, because the parsers can only handle timezone offsets -- of a integer number of minutes. However, PostgreSQL will include -- seconds in the offset, depending on the historical time standards for -- the city identifying the time zone. -- -- This boundary point often marks an event of some interest. In the US -- for example, timestamptzs before 1883-Nov-18 -- 12:00:00 local time cannot be parsed. This is the moment Standard -- Railway Time went live. Concretely, PostgreSQL will emit -- 1883-11-18 12:03:57-04:56:02 instead of 1883-11-18 -- 11:59:59-05 when the timezone parameter for the -- connection is set to America/New_York. -- --
    --
  1. Dates and times surrounding 1582-Feb-24, the date the -- Gregorian Calendar was introduced, should be investigated for -- conversion errors.
  2. --
  3. Points in time Before Christ are not also not supported. For -- example, PostgreSQL will emit 0045-01-01 BC for a value of a -- date type. This is the year that the Julian Calendar was -- adopted.
  4. --
-- -- However, it should be noted that the old parsers also had issues 1 and -- 3. Also, the new parsers now correctly handle time zones that include -- minutes in their offset. Most notably, this includes all of India and -- parts of Canada and Australia. -- -- PostgreSQL uses the zoneinfo database for its time zone information. -- You can read more about PostgreSQL's date and time types at -- http://www.postgresql.org/docs/9.1/static/datatype-datetime.html, -- and zoneinfo at http://en.wikipedia.org/wiki/Tz_database. module Database.PostgreSQL.Simple.Time data Unbounded a NegInfinity :: Unbounded a Finite :: !a -> Unbounded a PosInfinity :: Unbounded a type Date = Unbounded Day type UTCTimestamp = Unbounded UTCTime type ZonedTimestamp = Unbounded ZonedTime type LocalTimestamp = Unbounded LocalTime parseDay :: ByteString -> Either String Day parseUTCTime :: ByteString -> Either String UTCTime parseZonedTime :: ByteString -> Either String ZonedTime parseLocalTime :: ByteString -> Either String LocalTime parseTimeOfDay :: ByteString -> Either String TimeOfDay parseDate :: ByteString -> Either String Date parseUTCTimestamp :: ByteString -> Either String UTCTimestamp parseZonedTimestamp :: ByteString -> Either String ZonedTimestamp parseLocalTimestamp :: ByteString -> Either String LocalTimestamp dayToBuilder :: Day -> Builder utcTimeToBuilder :: UTCTime -> Builder zonedTimeToBuilder :: ZonedTime -> Builder localTimeToBuilder :: LocalTime -> Builder timeOfDayToBuilder :: TimeOfDay -> Builder timeZoneToBuilder :: TimeZone -> Builder dateToBuilder :: Date -> Builder utcTimestampToBuilder :: UTCTimestamp -> Builder zonedTimestampToBuilder :: ZonedTimestamp -> Builder localTimestampToBuilder :: LocalTimestamp -> Builder unboundedToBuilder :: (a -> Builder) -> (Unbounded a -> Builder) -- | This module contains portions of the pg_type table that are -- relevant to postgresql-simple and are believed to not change between -- PostgreSQL versions. module Database.PostgreSQL.Simple.TypeInfo.Static -- | A structure representing some of the metadata regarding a PostgreSQL -- type, mostly taken from the pg_type table. data TypeInfo Basic :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString Array :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typelem :: TypeInfo -> !TypeInfo Range :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString rngsubtype :: TypeInfo -> !TypeInfo Composite :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> {-# UNPACK #-} !Oid -> !(Vector Attribute) -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typrelid :: TypeInfo -> {-# UNPACK #-} !Oid attributes :: TypeInfo -> !(Vector Attribute) staticTypeInfo :: Oid -> Maybe TypeInfo bool :: TypeInfo bytea :: TypeInfo char :: TypeInfo name :: TypeInfo int8 :: TypeInfo int2 :: TypeInfo int4 :: TypeInfo regproc :: TypeInfo text :: TypeInfo oid :: TypeInfo tid :: TypeInfo xid :: TypeInfo cid :: TypeInfo xml :: TypeInfo point :: TypeInfo lseg :: TypeInfo path :: TypeInfo box :: TypeInfo polygon :: TypeInfo line :: TypeInfo cidr :: TypeInfo float4 :: TypeInfo float8 :: TypeInfo abstime :: TypeInfo reltime :: TypeInfo tinterval :: TypeInfo unknown :: TypeInfo circle :: TypeInfo money :: TypeInfo macaddr :: TypeInfo inet :: TypeInfo bpchar :: TypeInfo varchar :: TypeInfo date :: TypeInfo time :: TypeInfo timestamp :: TypeInfo timestamptz :: TypeInfo interval :: TypeInfo timetz :: TypeInfo bit :: TypeInfo varbit :: TypeInfo numeric :: TypeInfo refcursor :: TypeInfo record :: TypeInfo void :: TypeInfo uuid :: TypeInfo json :: TypeInfo -- | Deprecated: Use TypeInfo instead module Database.PostgreSQL.Simple.BuiltinTypes data BuiltinType Bool :: BuiltinType ByteA :: BuiltinType Char :: BuiltinType Name :: BuiltinType Int8 :: BuiltinType Int2 :: BuiltinType Int4 :: BuiltinType RegProc :: BuiltinType Text :: BuiltinType Oid :: BuiltinType Tid :: BuiltinType Xid :: BuiltinType Cid :: BuiltinType Xml :: BuiltinType Point :: BuiltinType LSeg :: BuiltinType Path :: BuiltinType Box :: BuiltinType Polygon :: BuiltinType Line :: BuiltinType Cidr :: BuiltinType Float4 :: BuiltinType Float8 :: BuiltinType AbsTime :: BuiltinType RelTime :: BuiltinType TInterval :: BuiltinType Unknown :: BuiltinType Circle :: BuiltinType Money :: BuiltinType MacAddr :: BuiltinType Inet :: BuiltinType BpChar :: BuiltinType VarChar :: BuiltinType Date :: BuiltinType Time :: BuiltinType Timestamp :: BuiltinType TimestampTZ :: BuiltinType Interval :: BuiltinType TimeTZ :: BuiltinType Bit :: BuiltinType VarBit :: BuiltinType Numeric :: BuiltinType RefCursor :: BuiltinType Record :: BuiltinType Void :: BuiltinType UUID :: BuiltinType JSON :: BuiltinType builtin2oid :: BuiltinType -> Oid oid2builtin :: Oid -> Maybe BuiltinType builtin2typname :: BuiltinType -> ByteString oid2typname :: Oid -> Maybe ByteString instance Typeable BuiltinType instance Eq BuiltinType instance Ord BuiltinType instance Enum BuiltinType instance Bounded BuiltinType instance Read BuiltinType instance Show BuiltinType -- | A Postgres array parser and pretty-printer. module Database.PostgreSQL.Simple.Arrays -- | Parse one of three primitive field formats: array, quoted and plain. arrayFormat :: Char -> Parser ArrayFormat data ArrayFormat Array :: [ArrayFormat] -> ArrayFormat Plain :: ByteString -> ArrayFormat Quoted :: ByteString -> ArrayFormat array :: Char -> Parser [ArrayFormat] -- | Recognizes a quoted string. quoted :: Parser ByteString -- | Recognizes a plain string literal, not containing quotes or brackets -- and not containing the delimiter character. plain :: Char -> Parser ByteString -- | Format an array format item, using the delimiter character if the item -- is itself an array. fmt :: Char -> ArrayFormat -> ByteString -- | Format a list of array format items, inserting the appropriate -- delimiter between them. When the items are arrays, they will be -- delimited with commas; otherwise, they are delimited with the -- passed-in-delimiter. delimit :: Char -> [ArrayFormat] -> ByteString -- | Format an array format item, using the delimiter character if the item -- is itself an array, optionally applying quoting rules. Creates copies -- for safety when used in FromField instances. fmt' :: Bool -> Char -> ArrayFormat -> ByteString -- | Escape a string according to Postgres double-quoted string format. esc :: ByteString -> ByteString instance Eq ArrayFormat instance Show ArrayFormat instance Ord ArrayFormat -- | Basic types. module Database.PostgreSQL.Simple.Types -- | A placeholder for the SQL NULL value. data Null Null :: Null -- | A placeholder for the PostgreSQL DEFAULT value. data Default Default :: Default -- | A single-value "collection". -- -- This is useful if you need to supply a single parameter to a SQL -- query, or extract a single column from a SQL result. -- -- Parameter example: -- --
--   query c "select x from scores where x > ?" (Only (42::Int))
--   
-- -- Result example: -- --
--   xs <- query_ c "select id from users"
--   forM_ xs $ \(Only id) -> {- ... -}
--   
newtype Only a Only :: a -> Only a fromOnly :: Only a -> a -- | Wrap a list of values for use in an IN clause. Replaces a -- single "?" character with a parenthesized list of rendered -- values. -- -- Example: -- --
--   query c "select * from whatever where id in ?" (Only (In [3,4,5]))
--   
newtype In a In :: a -> In a -- | Wrap binary data for use as a bytea value. newtype Binary a Binary :: a -> Binary a fromBinary :: Binary a -> a -- | Wrap text for use as sql identifier, i.e. a table or column name. newtype Identifier Identifier :: Text -> Identifier fromIdentifier :: Identifier -> Text -- | Wrap text for use as (maybe) qualified identifier, i.e. a table with -- schema, or column with table. data QualifiedIdentifier QualifiedIdentifier :: (Maybe Text) -> Text -> QualifiedIdentifier -- | A query string. This type is intended to make it difficult to -- construct a SQL query by concatenating string fragments, as that is an -- extremely common way to accidentally introduce SQL injection -- vulnerabilities into an application. -- -- This type is an instance of IsString, so the easiest way to -- construct a query is to enable the OverloadedStrings language -- extension and then simply write the query in double quotes. -- --
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   import Database.PostgreSQL.Simple
--   
--   q :: Query
--   q = "select ?"
--   
-- -- The underlying type is a ByteString, and literal Haskell -- strings that contain Unicode characters will be correctly transformed -- to UTF-8. newtype Query Query :: ByteString -> Query fromQuery :: Query -> ByteString newtype Oid :: * Oid :: CUInt -> Oid -- | A composite type to parse your custom data structures without having -- to define dummy newtype wrappers every time. -- --
--   instance FromRow MyData where ...
--   
-- --
--   instance FromRow MyData2 where ...
--   
-- -- then I can do the following for free: -- --
--   res <- query' c ...
--   forM res $ \(MyData{..} :. MyData2{..}) -> do
--     ....
--   
data (:.) h t (:.) :: h -> t -> :. h t newtype Savepoint Savepoint :: Query -> Savepoint -- | Wrap a list for use as a PostgreSQL array. newtype PGArray a PGArray :: [a] -> PGArray a fromPGArray :: PGArray a -> [a] -- | Represents a VALUES table literal, usable as an alternative -- to executeMany and returning. The main advantage is -- that you can parametrize more than just a single VALUES -- expression. For example, here's a query to insert a thing into one -- table and some attributes of that thing into another, returning the -- new id generated by the database: -- --
--   query c [sql|
--       WITH new_thing AS (
--         INSERT INTO thing (name) VALUES (?) RETURNING id
--       ), new_attributes AS (
--         INSERT INTO thing_attributes
--            SELECT new_thing.id, attrs.*
--              FROM new_thing JOIN ? attrs
--       ) SELECT * FROM new_thing
--    |] ("foo", Values [  "int4", "text"    ]
--                      [ ( 1    , "hello" )
--                      , ( 2    , "world" ) ])
--   
-- -- (Note this example uses writable common table expressions, which were -- added in PostgreSQL 9.1) -- -- The second parameter gets expanded into the following SQL syntax: -- --
--   (VALUES (1::"int4",'hello'::"text"),(2,'world'))
--   
-- -- When the list of attributes is empty, the second parameter expands to: -- --
--   (VALUES (null::"int4",null::"text") LIMIT 0)
--   
-- -- By contrast, executeMany and returning don't issue -- the query in the empty case, and simply return 0 and -- [] respectively. This behavior is usually correct given their -- intended use cases, but would certainly be wrong in the example above. -- -- The first argument is a list of postgresql type names. Because this is -- turned into a properly quoted identifier, the type name is case -- sensitive and must be as it appears in the pg_type table. -- Thus, you must write timestamptz instead of timestamp -- with time zone, int4 instead of integer, -- _int8 instead of bigint[], etcetera. -- -- You may omit the type names, however, if you do so the list of values -- must be non-empty, and postgresql must be able to infer the types of -- the columns from the surrounding context. If the first condition is -- not met, postgresql-simple will throw an exception without issuing the -- query. In the second case, the postgres server will return an error -- which will be turned into a SqlError exception. -- -- See http://www.postgresql.org/docs/9.3/static/sql-values.html -- for more information. data Values a Values :: [QualifiedIdentifier] -> [a] -> Values a instance Typeable Null instance Typeable Default instance Typeable Query instance Typeable1 Only instance Typeable1 In instance Typeable1 Binary instance Typeable Identifier instance Typeable QualifiedIdentifier instance Typeable1 PGArray instance Typeable2 :. instance Typeable Savepoint instance Typeable1 Values instance Read Null instance Show Null instance Read Default instance Show Default instance Eq Query instance Ord Query instance Eq a => Eq (Only a) instance Ord a => Ord (Only a) instance Read a => Read (Only a) instance Show a => Show (Only a) instance Functor Only instance Eq a => Eq (In a) instance Ord a => Ord (In a) instance Read a => Read (In a) instance Show a => Show (In a) instance Functor In instance Eq a => Eq (Binary a) instance Ord a => Ord (Binary a) instance Read a => Read (Binary a) instance Show a => Show (Binary a) instance Functor Binary instance Eq Identifier instance Ord Identifier instance Read Identifier instance Show Identifier instance IsString Identifier instance Eq QualifiedIdentifier instance Ord QualifiedIdentifier instance Read QualifiedIdentifier instance Show QualifiedIdentifier instance Eq a => Eq (PGArray a) instance Ord a => Ord (PGArray a) instance Read a => Read (PGArray a) instance Show a => Show (PGArray a) instance Functor PGArray instance (Eq h, Eq t) => Eq (h :. t) instance (Ord h, Ord t) => Ord (h :. t) instance (Show h, Show t) => Show (h :. t) instance (Read h, Read t) => Read (h :. t) instance Eq Savepoint instance Ord Savepoint instance Show Savepoint instance Read Savepoint instance Eq a => Eq (Values a) instance Ord a => Ord (Values a) instance Show a => Show (Values a) instance Read a => Read (Values a) instance IsString QualifiedIdentifier instance Hashable QualifiedIdentifier instance Hashable Identifier instance Monoid Query instance IsString Query instance Read Query instance Show Query instance Eq Null -- | A Template Haskell macro for efficiently checking membership in a set -- of type oids. module Database.PostgreSQL.Simple.TypeInfo.Macro -- | Returns an expression that has type Oid -> -- Bool, true if the oid is equal to any one of the -- typoids of the given TypeInfos. mkCompats :: [TypeInfo] -> ExpQ -- | Literally substitute the typoid of a TypeInfo -- expression. Returns an expression of type Oid. Useful because -- GHC tends not to fold constants. inlineTypoid :: TypeInfo -> ExpQ -- | The ToField typeclass, for rendering a parameter to a SQL -- query. module Database.PostgreSQL.Simple.ToField -- | How to render an element when substituting it into a query. data Action -- | Render without escaping or quoting. Use for non-text types such as -- numbers, when you are certain that they will not introduce -- formatting vulnerabilities via use of characters such as spaces or -- "'". Plain :: Builder -> Action -- | Escape and enclose in quotes before substituting. Use for all -- text-like types, and anything else that may contain unsafe characters -- when rendered. Escape :: ByteString -> Action -- | Escape binary data for use as a bytea literal. Include -- surrounding quotes. This is used by the Binary newtype wrapper. EscapeByteA :: ByteString -> Action -- | Escape before substituting. Use for all sql identifiers like table, -- column names, etc. This is used by the Identifier newtype -- wrapper. EscapeIdentifier :: ByteString -> Action -- | Concatenate a series of rendering actions. Many :: [Action] -> Action -- | A type that may be used as a single parameter to a SQL query. class ToField a toField :: ToField a => a -> Action -- | Convert a Haskell value to a JSON Value using toJSON and -- convert that to a field using toField. -- -- This can be used as the default implementation for the toField -- method for Haskell types that have a JSON representation in -- PostgreSQL. toJSONField :: ToJSON a => a -> Action -- | Surround a string with single-quote characters: "'" -- -- This function does not perform any other escaping. inQuotes :: Builder -> Builder instance Typeable Action instance ToRow a => ToField (Values a) instance ToField Value instance ToField UUID instance ToField a => ToField (Vector a) instance ToField a => ToField (PGArray a) instance ToField Date instance ToField LocalTimestamp instance ToField ZonedTimestamp instance ToField UTCTimestamp instance ToField TimeOfDay instance ToField Day instance ToField LocalTime instance ToField ZonedTime instance ToField UTCTime instance ToField Text instance ToField [Char] instance ToField Text instance ToField ByteString instance ToField ByteString instance ToField QualifiedIdentifier instance ToField Identifier instance ToField (Binary ByteString) instance ToField (Binary ByteString) instance ToField Scientific instance ToField Double instance ToField Float instance ToField Oid instance ToField Word64 instance ToField Word instance ToField Word32 instance ToField Word16 instance ToField Word8 instance ToField Integer instance ToField Int64 instance ToField Int instance ToField Int32 instance ToField Int16 instance ToField Int8 instance ToField Bool instance ToField Default instance ToField Null instance ToField a => ToField (In [a]) instance ToField a => ToField (Maybe a) instance ToField Action instance Show Action -- | The ToRow typeclass, for rendering a collection of parameters -- to a SQL query. -- -- Predefined instances are provided for tuples containing up to ten -- elements. module Database.PostgreSQL.Simple.ToRow -- | A collection type that can be turned into a list of rendering -- Actions. -- -- Instances should use the render method of the Param -- class to perform conversion of each element of the collection. class ToRow a toRow :: ToRow a => a -> [Action] instance (ToRow a, ToRow b) => ToRow (a :. b) instance ToField a => ToRow [a] instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g, ToField h, ToField i, ToField j) => ToRow (a, b, c, d, e, f, g, h, i, j) instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g, ToField h, ToField i) => ToRow (a, b, c, d, e, f, g, h, i) instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g, ToField h) => ToRow (a, b, c, d, e, f, g, h) instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g) => ToRow (a, b, c, d, e, f, g) instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f) => ToRow (a, b, c, d, e, f) instance (ToField a, ToField b, ToField c, ToField d, ToField e) => ToRow (a, b, c, d, e) instance (ToField a, ToField b, ToField c, ToField d) => ToRow (a, b, c, d) instance (ToField a, ToField b, ToField c) => ToRow (a, b, c) instance (ToField a, ToField b) => ToRow (a, b) instance ToField a => ToRow (Only a) instance ToRow () -- | The Ok type is a simple error handler, basically equivalent to -- Either [SomeException]. This type (without the list) was used -- to handle conversion errors in early versions of postgresql-simple. -- -- One of the primary reasons why this type was introduced is that -- Either SomeException had not been provided an instance for -- Alternative, and it would have been a bad idea to provide an -- orphaned instance for a commonly-used type and typeclass included in -- base. -- -- Extending the failure case to a list of SomeExceptions enables -- a more sensible Alternative instance definitions: -- <|> concatinates the list of exceptions when both cases -- fail, and empty is defined as 'Errors []'. Though -- <|> one could pick one of two exceptions, and throw away -- the other, and have empty provide a generic exception, this -- avoids cases where empty overrides a more informative exception -- and allows you to see all the different ways your computation has -- failed. module Database.PostgreSQL.Simple.Ok data Ok a Errors :: [SomeException] -> Ok a Ok :: !a -> Ok a -- | a way to reify a list of exceptions into a single exception newtype ManyErrors ManyErrors :: [SomeException] -> ManyErrors instance Typeable1 Ok instance Typeable ManyErrors instance Show a => Show (Ok a) instance Functor Ok instance Show ManyErrors instance Exception ManyErrors instance Monad Ok instance MonadPlus Ok instance Alternative Ok instance Applicative Ok instance Eq a => Eq (Ok a) -- | Internal bits. This interface is less stable and can change at any -- time. In particular this means that while the rest of the -- postgresql-simple package endeavors to follow the package versioning -- policy, this module does not. Also, at the moment there are things in -- here that aren't particularly internal and are exported elsewhere; -- these will eventually disappear from this module. module Database.PostgreSQL.Simple.Internal -- | A Field represents metadata about a particular field -- -- You don't particularly want to retain these structures for a long -- period of time, as they will retain the entire query result, not just -- the field metadata data Field Field :: !Result -> {-# UNPACK #-} !Column -> {-# UNPACK #-} !Oid -> Field result :: Field -> !Result column :: Field -> {-# UNPACK #-} !Column -- | This returns the type oid associated with the column. Analogous to -- libpq's PQftype. typeOid :: Field -> {-# UNPACK #-} !Oid type TypeInfoCache = IntMap TypeInfo data Connection Connection :: {-# UNPACK #-} !(MVar Connection) -> {-# UNPACK #-} !(MVar TypeInfoCache) -> {-# UNPACK #-} !(IORef Int64) -> Connection connectionHandle :: Connection -> {-# UNPACK #-} !(MVar Connection) connectionObjects :: Connection -> {-# UNPACK #-} !(MVar TypeInfoCache) connectionTempNameCounter :: Connection -> {-# UNPACK #-} !(IORef Int64) data SqlError SqlError :: ByteString -> ExecStatus -> ByteString -> ByteString -> ByteString -> SqlError sqlState :: SqlError -> ByteString sqlExecStatus :: SqlError -> ExecStatus sqlErrorMsg :: SqlError -> ByteString sqlErrorDetail :: SqlError -> ByteString sqlErrorHint :: SqlError -> ByteString fatalError :: ByteString -> SqlError -- | Exception thrown if query is used to perform an -- INSERT-like operation, or execute is used to perform -- a SELECT-like operation. data QueryError QueryError :: String -> Query -> QueryError qeMessage :: QueryError -> String qeQuery :: QueryError -> Query data ConnectInfo ConnectInfo :: String -> Word16 -> String -> String -> String -> ConnectInfo connectHost :: ConnectInfo -> String connectPort :: ConnectInfo -> Word16 connectUser :: ConnectInfo -> String connectPassword :: ConnectInfo -> String connectDatabase :: ConnectInfo -> String -- | Default information for setting up a connection. -- -- Defaults are as follows: -- -- -- -- Use as in the following example: -- --
--   connect defaultConnectInfo { connectHost = "db.example.com" }
--   
defaultConnectInfo :: ConnectInfo -- | Connect with the given username to the given database. Will throw an -- exception if it cannot connect. connect :: ConnectInfo -> IO Connection -- | Attempt to make a connection based on a libpq connection string. See -- http://www.postgresql.org/docs/9.3/static/libpq-connect.html -- for more information. Here is an example with some of the most -- commonly used parameters: -- --
--   host='db.somedomain.com' port=5432 ...
--   
-- -- This attempts to connect to db.somedomain.com:5432. Omitting -- the port will normally default to 5432. -- -- On systems that provide unix domain sockets, omitting the host -- parameter will cause libpq to attempt to connect via unix domain -- sockets. The default path to the socket is constructed from the port -- number and the DEFAULT_PGSOCKET_DIR constant defined in the -- pg_config_manual.h header file. Connecting via unix sockets -- tends to use the peer authentication method, which is very -- secure and does not require a password. -- -- On Windows and other systems without unix domain sockets, omitting the -- host will default to localhost. -- --
--   ... dbname='postgres' user='postgres' password='secret \' \\ pw'
--   
-- -- This attempts to connect to database named postgres with user -- postgres and password secret ' \ pw. Backslash -- characters will have to be double-quoted in literal Haskell strings, -- of course. Omitting dbname and user will both -- default to the system username that the client process is running as. -- -- Omitting password will default to an appropriate password -- found in the pgpass file, or no password at all if a matching -- line is not found. See -- http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html for -- more information regarding this file. -- -- As all parameters are optional and the defaults are sensible, the -- empty connection string can be useful for development and exploratory -- use, assuming your system is set up appropriately. -- -- On Unix, such a setup would typically consist of a local postgresql -- server listening on port 5432, as well as a system user, database -- user, and database sharing a common name, with permissions granted to -- the user on the database. -- -- On Windows, in addition you will either need pg_hba.conf to -- specify the use the trust authentication method for the the -- connection, which may not be appropriate for multiuser or production -- machines, or you will need to use a pgpass file with the -- password or md5 authentication methods. -- -- See -- http://www.postgresql.org/docs/9.3/static/client-authentication.html -- for more information regarding the authentication process. connectPostgreSQL :: ByteString -> IO Connection -- | Turns a ConnectInfo data structure into a libpq connection -- string. postgreSQLConnectionString :: ConnectInfo -> ByteString oid2int :: Oid -> Int exec :: Connection -> ByteString -> IO Result -- | A version of execute that does not perform query -- substitution. execute_ :: Connection -> Query -> IO Int64 finishExecute :: Connection -> Query -> Result -> IO Int64 throwResultError :: ByteString -> Result -> ExecStatus -> IO a disconnectedError :: SqlError -- | Atomically perform an action with the database handle, if there is -- one. withConnection :: Connection -> (Connection -> IO a) -> IO a close :: Connection -> IO () newNullConnection :: IO Connection data Row Row :: {-# UNPACK #-} !Row -> !Result -> Row row :: Row -> {-# UNPACK #-} !Row rowresult :: Row -> !Result newtype RowParser a RP :: ReaderT Row (StateT Column Conversion) a -> RowParser a unRP :: RowParser a -> ReaderT Row (StateT Column Conversion) a liftRowParser :: IO a -> RowParser a newtype Conversion a Conversion :: (Connection -> IO (Ok a)) -> Conversion a runConversion :: Conversion a -> Connection -> IO (Ok a) liftConversion :: IO a -> Conversion a conversionMap :: (Ok a -> Ok b) -> Conversion a -> Conversion b conversionError :: Exception err => err -> Conversion a newTempName :: Connection -> IO Query fdError :: ByteString -> IOError instance Typeable SqlError instance Typeable QueryError instance Typeable ConnectInfo instance Show SqlError instance Eq QueryError instance Show QueryError instance Eq ConnectInfo instance Read ConnectInfo instance Show ConnectInfo instance Functor RowParser instance Applicative RowParser instance Alternative RowParser instance Monad RowParser instance MonadPlus Conversion instance Monad Conversion instance Alternative Conversion instance Applicative Conversion instance Functor Conversion instance Exception QueryError instance Exception SqlError -- | Support for PostgreSQL's Large Objects; see -- http://www.postgresql.org/docs/9.1/static/largeobjects.html for -- more information. -- -- Note that Large Object File Descriptors are only valid within a single -- database transaction, so if you are interested in using anything -- beyond loCreat, loCreate, and loUnlink, you will -- need to run the entire sequence of functions in a transaction. As -- loImport and loExport are simply C functions that call -- loCreat, loOpen, loRead, and loWrite, and -- do not perform any transaction handling themselves, they also need to -- be wrapped in an explicit transaction. module Database.PostgreSQL.Simple.LargeObjects loCreat :: Connection -> IO Oid loCreate :: Connection -> Oid -> IO Oid loImport :: Connection -> FilePath -> IO Oid loImportWithOid :: Connection -> FilePath -> Oid -> IO Oid loExport :: Connection -> Oid -> FilePath -> IO () loOpen :: Connection -> Oid -> IOMode -> IO LoFd loWrite :: Connection -> LoFd -> ByteString -> IO Int loRead :: Connection -> LoFd -> Int -> IO ByteString loSeek :: Connection -> LoFd -> SeekMode -> Int -> IO Int loTell :: Connection -> LoFd -> IO Int loTruncate :: Connection -> LoFd -> Int -> IO () loClose :: Connection -> LoFd -> IO () loUnlink :: Connection -> Oid -> IO () newtype Oid :: * Oid :: CUInt -> Oid -- | LoFd is a Large Object (pseudo) File Descriptor. It is understood by -- libpq but not by operating system calls. data LoFd :: * -- | See openFile data IOMode :: * ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | A mode that determines the effect of hSeek hdl mode -- i. data SeekMode :: * -- | the position of hdl is set to i. AbsoluteSeek :: SeekMode -- | the position of hdl is set to offset i from the -- current position. RelativeSeek :: SeekMode -- | the position of hdl is set to offset i from the end -- of the file. SeekFromEnd :: SeekMode -- | Support for receiving asynchronous notifications via PostgreSQL's -- Listen/Notify mechanism. See -- http://www.postgresql.org/docs/9.1/static/sql-notify.html for -- more information. -- -- Note that on Windows, getNotification currently uses a -- polling loop of 1 second to check for more notifications, due to some -- inadequacies in GHC's IO implementation and interface on that -- platform. See GHC issue #7353 for more information. While this -- workaround is less than ideal, notifications are still better than -- polling the database directly. Notifications do not create any extra -- work for the backend, and are likely cheaper on the client side as -- well. -- -- http://hackage.haskell.org/trac/ghc/ticket/7353 module Database.PostgreSQL.Simple.Notification data Notification Notification :: !CPid -> !ByteString -> !ByteString -> Notification notificationPid :: Notification -> !CPid notificationChannel :: Notification -> !ByteString notificationData :: Notification -> !ByteString -- | Returns a single notification. If no notifications are available, -- getNotification blocks until one arrives. getNotification :: Connection -> IO Notification -- | Non-blocking variant of getNotification. Returns a single -- notification, if available. If no notifications are available, returns -- Nothing. getNotificationNonBlocking :: Connection -> IO (Maybe Notification) -- | Returns the process CPid of the backend server process handling -- this connection. -- -- The backend PID is useful for debugging purposes and for comparison to -- NOTIFY messages (which include the PID of the notifying backend -- process). Note that the PID belongs to a process executing on the -- database server host, not the local host! getBackendPID :: Connection -> IO CPid -- | | Module for parsing errors from postgresql error messages. Currently -- only parses integrity violation errors (class 23). -- -- Note: Success of parsing may depend on language settings. module Database.PostgreSQL.Simple.Errors data ConstraintViolation -- | The field is a column name NotNullViolation :: ByteString -> ConstraintViolation -- | Table name and name of violated constraint ForeignKeyViolation :: ByteString -> ByteString -> ConstraintViolation -- | Name of violated constraint UniqueViolation :: ByteString -> ConstraintViolation -- | Relation name (usually table), constraint name CheckViolation :: ByteString -> ByteString -> ConstraintViolation -- | Tries to convert SqlError to ConstrainViolation, -- checks sqlState and succeedes only if able to parse sqlErrorMsg. -- --
--   createUser = catchJust constraintViolation catcher $ execute conn ...
--     where
--       catcher UniqueViolation "user_login_key" = ...
--       catcher _ = ...
--   
constraintViolation :: SqlError -> Maybe ConstraintViolation -- | Like constraintViolation, but also packs original SqlError. -- --
--   createUser = catchJust constraintViolationE catcher $ execute conn ...
--     where
--       catcher (_, UniqueViolation "user_login_key") = ...
--       catcher (e, _) = throwIO e
--   
constraintViolationE :: SqlError -> Maybe (SqlError, ConstraintViolation) -- | Catches SqlError, tries to convert to ConstraintViolation, re-throws -- on fail. Provides alternative interface to catchJust -- --
--   createUser = catchViolation catcher $ execute conn ...
--     where
--       catcher _ (UniqueViolation "user_login_key") = ...
--       catcher e _ = throwIO e
--   
catchViolation :: (SqlError -> ConstraintViolation -> IO a) -> IO a -> IO a isSerializationError :: SqlError -> Bool isNoActiveTransactionError :: SqlError -> Bool isFailedTransactionError :: SqlError -> Bool instance Typeable ConstraintViolation instance Show ConstraintViolation instance Eq ConstraintViolation instance Ord ConstraintViolation instance Exception ConstraintViolation module Database.PostgreSQL.Simple.Transaction -- | Execute an action inside a SQL transaction. -- -- This function initiates a transaction with a "begin -- transaction" statement, then executes the supplied action. If the -- action succeeds, the transaction will be completed with commit -- before this function returns. -- -- If the action throws any kind of exception (not just a -- PostgreSQL-related exception), the transaction will be rolled back -- using rollback, then the exception will be rethrown. -- -- For nesting transactions, see withSavepoint. withTransaction :: Connection -> IO a -> IO a -- | Execute an action inside a SQL transaction with a given isolation -- level. withTransactionLevel :: IsolationLevel -> Connection -> IO a -> IO a -- | Execute an action inside a SQL transaction with a given transaction -- mode. withTransactionMode :: TransactionMode -> Connection -> IO a -> IO a -- | Like withTransactionMode, but also takes a custom callback to -- determine if a transaction should be retried if an SqlError -- occurs. If the callback returns True, then the transaction will be -- retried. If the callback returns False, or an exception other than an -- SqlError occurs then the transaction will be rolled back and -- the exception rethrown. -- -- This is used to implement withTransactionSerializable. withTransactionModeRetry :: TransactionMode -> (SqlError -> Bool) -> Connection -> IO a -> IO a -- | Execute an action inside of a Serializable transaction. If a -- serialization failure occurs, roll back the transaction and try again. -- Be warned that this may execute the IO action multiple times. -- -- A Serializable transaction creates the illusion that your -- program has exclusive access to the database. This means that, even in -- a concurrent setting, you can perform queries in sequence without -- having to worry about what might happen between one statement and the -- next. -- -- Think of it as STM, but without retry. withTransactionSerializable :: Connection -> IO a -> IO a data TransactionMode TransactionMode :: !IsolationLevel -> !ReadWriteMode -> TransactionMode isolationLevel :: TransactionMode -> !IsolationLevel readWriteMode :: TransactionMode -> !ReadWriteMode -- | Of the four isolation levels defined by the SQL standard, these are -- the three levels distinguished by PostgreSQL as of version 9.0. See -- http://www.postgresql.org/docs/9.1/static/transaction-iso.html -- for more information. Note that prior to PostgreSQL 9.0, -- RepeatableRead was equivalent to Serializable. data IsolationLevel -- | the isolation level will be taken from PostgreSQL's per-connection -- default_transaction_isolation variable, which is initialized -- according to the server's config. The default configuration is -- ReadCommitted. DefaultIsolationLevel :: IsolationLevel ReadCommitted :: IsolationLevel RepeatableRead :: IsolationLevel Serializable :: IsolationLevel data ReadWriteMode -- | the read-write mode will be taken from PostgreSQL's per-connection -- default_transaction_read_only variable, which is initialized -- according to the server's config. The default configuration is -- ReadWrite. DefaultReadWriteMode :: ReadWriteMode ReadWrite :: ReadWriteMode ReadOnly :: ReadWriteMode defaultTransactionMode :: TransactionMode defaultIsolationLevel :: IsolationLevel defaultReadWriteMode :: ReadWriteMode -- | Begin a transaction. begin :: Connection -> IO () -- | Begin a transaction with a given isolation level beginLevel :: IsolationLevel -> Connection -> IO () -- | Begin a transaction with a given transaction mode beginMode :: TransactionMode -> Connection -> IO () -- | Commit a transaction. commit :: Connection -> IO () -- | Rollback a transaction. rollback :: Connection -> IO () -- | Create a savepoint, and roll back to it if an error occurs. This may -- only be used inside of a transaction, and provides a sort of "nested -- transaction". -- -- See -- http://www.postgresql.org/docs/current/static/sql-savepoint.html withSavepoint :: Connection -> IO a -> IO a data Savepoint -- | Create a new savepoint. This may only be used inside of a transaction. newSavepoint :: Connection -> IO Savepoint -- | Destroy a savepoint, but retain its effects. -- -- Warning: this will throw a SqlError matching -- isFailedTransactionError if the transaction is aborted due to -- an error. commit would merely warn and roll back. releaseSavepoint :: Connection -> Savepoint -> IO () -- | Roll back to a savepoint. This will not release the savepoint. rollbackToSavepoint :: Connection -> Savepoint -> IO () -- | Roll back to a savepoint and release it. This is like calling -- rollbackToSavepoint followed by releaseSavepoint, but -- avoids a round trip to the database server. rollbackToAndReleaseSavepoint :: Connection -> Savepoint -> IO () isSerializationError :: SqlError -> Bool isNoActiveTransactionError :: SqlError -> Bool isFailedTransactionError :: SqlError -> Bool instance Show IsolationLevel instance Eq IsolationLevel instance Ord IsolationLevel instance Enum IsolationLevel instance Bounded IsolationLevel instance Show ReadWriteMode instance Eq ReadWriteMode instance Ord ReadWriteMode instance Enum ReadWriteMode instance Bounded ReadWriteMode instance Show TransactionMode instance Eq TransactionMode -- | This module provides convenient and efficient access to parts of the -- pg_type metatable. At the moment, this requires PostgreSQL -- 8.4 if you need to work with types that do not appear in -- Static. -- -- The current scheme could be more efficient, especially for some use -- cases. In particular, connection pools that use many user-added types -- and connect to a set of servers with identical (or at least -- compatible) pg_type and associated tables could share a -- common typeinfo cache, thus saving memory and communication between -- the client and server. module Database.PostgreSQL.Simple.TypeInfo -- | Returns the metadata of the type with a particular oid. To find this -- data, getTypeInfo first consults postgresql-simple's built-in -- staticTypeInfo table, then checks the connection's typeinfo -- cache. Finally, the database's pg_type table will be queried -- only if necessary, and the result will be stored in the connections's -- cache. getTypeInfo :: Connection -> Oid -> IO TypeInfo -- | A structure representing some of the metadata regarding a PostgreSQL -- type, mostly taken from the pg_type table. data TypeInfo Basic :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString Array :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typelem :: TypeInfo -> !TypeInfo Range :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString rngsubtype :: TypeInfo -> !TypeInfo Composite :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> {-# UNPACK #-} !Oid -> !(Vector Attribute) -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typrelid :: TypeInfo -> {-# UNPACK #-} !Oid attributes :: TypeInfo -> !(Vector Attribute) data Attribute Attribute :: !ByteString -> !TypeInfo -> Attribute attname :: Attribute -> !ByteString atttype :: Attribute -> !TypeInfo -- | The FromField typeclass, for converting a single value in a row -- returned by a SQL query into a more useful Haskell representation. -- Note that each instance of FromField is documented by a list of -- compatible postgresql types. -- -- A Haskell numeric type is considered to be compatible with all -- PostgreSQL numeric types that are less accurate than it. For instance, -- the Haskell Double type is compatible with the PostgreSQL's -- 32-bit int type because it can represent a int -- exactly. On the other hand, since a Double might lose precision -- if representing PostgreSQL's 64-bit bigint, the two are -- not considered compatible. -- -- Note that the Float and Double instances use -- attoparsec's double conversion routine, which sacrifices some -- accuracy for speed. If you need accuracy, consider first converting -- data to a Scientific or Rational type, and then -- converting to a floating-point type. If you are defining your own -- FromRow instances, this can be acheived simply by -- fromRational <$> field, although -- this idiom is additionally compatible with PostgreSQL's -- numeric type. If this is unacceptable, you may find -- fieldWith useful. -- -- Because FromField is a typeclass, one may provide conversions -- to additional Haskell types without modifying postgresql-simple. This -- is particularly useful for supporting PostgreSQL types that -- postgresql-simple does not support out-of-box. Here's an example of -- what such an instance might look like for a UUID type that implements -- the Read class: -- --
--   import Data.UUID ( UUID )
--   import Database.PostgreSQL.Simple.FromField
--          ( FromField (fromField) , typeOid, returnError, ResultError (..) )
--   import Database.PostgreSQL.Simple.TypeInfo.Static (typoid, uuid)
--   import qualified Data.ByteString.Char8 as B
--   
--   instance FromField UUID where
--      fromField f mdata =
--         if typeOid f /= typoid uuid
--           then returnError Incompatible f ""
--           else case B.unpack `fmap` mdata of
--                  Nothing  -> returnError UnexpectedNull f ""
--                  Just dat ->
--                     case [ x | (x,t) <- reads dat, ("","") <- lex t ] of
--                       [x] -> return x
--                       _   -> returnError ConversionFailed f dat
--   
-- -- Note that because PostgreSQL's uuid type is built into -- postgres and is not provided by an extension, the typeOid of -- uuid does not change and thus we can examine it directly. One -- could hard-code the type oid, or obtain it by other means, but in this -- case we simply pull it out of the static table provided by -- postgresql-simple. -- -- On the other hand if the type is provided by an extension, such as -- PostGIS or hstore, then the typeOid is not -- stable and can vary from database to database. In this case it is -- recommended that FromField instances use typename instead. module Database.PostgreSQL.Simple.FromField -- | A type that may be converted from a SQL type. class FromField a fromField :: FromField a => FieldParser a type FieldParser a = Field -> Maybe ByteString -> Conversion a data Conversion a runConversion :: Conversion a -> Connection -> IO (Ok a) conversionMap :: (Ok a -> Ok b) -> Conversion a -> Conversion b conversionError :: Exception err => err -> Conversion a -- | Exception thrown if conversion from a SQL value to a Haskell value -- fails. data ResultError -- | The SQL and Haskell types are not compatible. Incompatible :: String -> Maybe Oid -> String -> String -> String -> ResultError errSQLType :: ResultError -> String errSQLTableOid :: ResultError -> Maybe Oid errSQLField :: ResultError -> String errHaskellType :: ResultError -> String errMessage :: ResultError -> String -- | A SQL NULL was encountered when the Haskell type did not -- permit it. UnexpectedNull :: String -> Maybe Oid -> String -> String -> String -> ResultError errSQLType :: ResultError -> String errSQLTableOid :: ResultError -> Maybe Oid errSQLField :: ResultError -> String errHaskellType :: ResultError -> String errMessage :: ResultError -> String -- | The SQL value could not be parsed, or could not be represented as a -- valid Haskell value, or an unexpected low-level error occurred (e.g. -- mismatch between metadata and actual data in a row). ConversionFailed :: String -> Maybe Oid -> String -> String -> String -> ResultError errSQLType :: ResultError -> String errSQLTableOid :: ResultError -> Maybe Oid errSQLField :: ResultError -> String errHaskellType :: ResultError -> String errMessage :: ResultError -> String -- | Given one of the constructors from ResultError, the field, and -- an errMessage, this fills in the other fields in the exception -- value and returns it in a 'Left . SomeException' constructor. returnError :: (Typeable a, Exception err) => (String -> Maybe Oid -> String -> String -> String -> err) -> Field -> String -> Conversion a -- | A Field represents metadata about a particular field -- -- You don't particularly want to retain these structures for a long -- period of time, as they will retain the entire query result, not just -- the field metadata data Field -- | Returns the data type name. This is the preferred way of identifying -- types that do not have a stable type oid, such as types provided by -- extensions to PostgreSQL. -- -- More concretely, it returns the typname column associated -- with the type oid in the pg_type table. First, -- postgresql-simple will check the built-in, static table. If the type -- oid is not there, postgresql-simple will check a per-connection cache, -- and then finally query the database's meta-schema. typename :: Field -> Conversion ByteString -- | A structure representing some of the metadata regarding a PostgreSQL -- type, mostly taken from the pg_type table. data TypeInfo Basic :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString Array :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typelem :: TypeInfo -> !TypeInfo Range :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> !TypeInfo -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString rngsubtype :: TypeInfo -> !TypeInfo Composite :: {-# UNPACK #-} !Oid -> {-# UNPACK #-} !Char -> {-# UNPACK #-} !Char -> !ByteString -> {-# UNPACK #-} !Oid -> !(Vector Attribute) -> TypeInfo typoid :: TypeInfo -> {-# UNPACK #-} !Oid typcategory :: TypeInfo -> {-# UNPACK #-} !Char typdelim :: TypeInfo -> {-# UNPACK #-} !Char typname :: TypeInfo -> !ByteString typrelid :: TypeInfo -> {-# UNPACK #-} !Oid attributes :: TypeInfo -> !(Vector Attribute) data Attribute Attribute :: !ByteString -> !TypeInfo -> Attribute attname :: Attribute -> !ByteString atttype :: Attribute -> !TypeInfo typeInfo :: Field -> Conversion TypeInfo typeInfoByOid :: Oid -> Conversion TypeInfo -- | Returns the name of the column. This is often determined by a table -- definition, but it can be set using an as clause. name :: Field -> Maybe ByteString -- | Returns the name of the object id of the table associated -- with the column, if any. Returns Nothing when there is no such -- table; for example a computed column does not have a table associated -- with it. Analogous to libpq's PQftable. tableOid :: Field -> Maybe Oid -- | If the column has a table associated with it, this returns the number -- off the associated table column. Numbering starts from 0. Analogous to -- libpq's PQftablecol. tableColumn :: Field -> Int -- | This returns whether the data was returned in a binary or textual -- format. Analogous to libpq's PQfformat. format :: Field -> Format -- | This returns the type oid associated with the column. Analogous to -- libpq's PQftype. typeOid :: Field -> Oid newtype Oid :: * Oid :: CUInt -> Oid data Format :: * Text :: Format Binary :: Format -- | Parse a field to a JSON Value and convert that into a Haskell -- value using fromJSON. -- -- This can be used as the default implementation for the -- fromField method for Haskell types that have a JSON -- representation in PostgreSQL. -- -- The Typeable constraint is required to show more informative -- error messages when parsing fails. fromJSONField :: (FromJSON a, Typeable a) => FieldParser a instance Typeable ResultError instance Eq ResultError instance Show ResultError instance FromField a => FromField (MVar a) instance FromField a => FromField (IORef a) instance FromField Value instance FromField UUID instance (FromField a, Typeable a) => FromField (IOVector a) instance (FromField a, Typeable a) => FromField (Vector a) instance (FromField a, Typeable a) => FromField (PGArray a) instance (FromField a, FromField b) => FromField (Either a b) instance FromField Date instance FromField LocalTimestamp instance FromField ZonedTimestamp instance FromField UTCTimestamp instance FromField TimeOfDay instance FromField Day instance FromField LocalTime instance FromField ZonedTime instance FromField UTCTime instance FromField [Char] instance FromField Text instance FromField Text instance FromField (Binary ByteString) instance FromField (Binary ByteString) instance FromField ByteString instance FromField Oid instance FromField ByteString instance FromField Scientific instance FromField (Ratio Integer) instance FromField Double instance FromField Float instance FromField Integer instance FromField Int64 instance FromField Int instance FromField Int32 instance FromField Int16 instance FromField Char instance FromField Bool instance FromField Null instance FromField a => FromField (Maybe a) instance FromField () instance Exception ResultError -- | Parsers and printers for hstore, a extended type bundled with -- PostgreSQL providing finite maps from text strings to text strings. -- See http://www.postgresql.org/docs/9.2/static/hstore.html for -- more information. -- -- Note that in order to use this type, a database superuser must install -- it by running a sql script in the share directory. This can be done on -- PostgreSQL 9.1 and later with the command CREATE EXTENSION -- hstore. See -- http://www.postgresql.org/docs/9.2/static/contrib.html for more -- information. module Database.PostgreSQL.Simple.HStore newtype HStoreList HStoreList :: [(Text, Text)] -> HStoreList fromHStoreList :: HStoreList -> [(Text, Text)] newtype HStoreMap HStoreMap :: Map Text Text -> HStoreMap fromHStoreMap :: HStoreMap -> Map Text Text class ToHStore a toHStore :: ToHStore a => a -> HStoreBuilder -- | Represents valid hstore syntax. data HStoreBuilder toBuilder :: HStoreBuilder -> Builder toLazyByteString :: HStoreBuilder -> ByteString hstore :: (ToHStoreText a, ToHStoreText b) => a -> b -> HStoreBuilder class ToHStoreText a toHStoreText :: ToHStoreText a => a -> HStoreText -- | Represents escape text, ready to be the key or value to a hstore value data HStoreText -- | The FromRow typeclass, for converting a row of results returned -- by a SQL query into a more useful Haskell representation. -- -- Predefined instances are provided for tuples containing up to ten -- elements. The instances for Maybe types return Nothing -- if all the columns that would have been otherwise consumed are null, -- otherwise it attempts a regular conversion. module Database.PostgreSQL.Simple.FromRow -- | A collection type that can be converted from a sequence of fields. -- Instances are provided for tuples up to 10 elements and lists of any -- length. -- -- Note that instances can be defined outside of postgresql-simple, which -- is often useful. For example, here's an instance for a user-defined -- pair: -- --
--   data User = User { name :: String, fileQuota :: Int }
--   
--   instance FromRow User where
--        fromRow = User <$> field <*> field
--   
-- -- The number of calls to field must match the number of fields -- returned in a single row of the query result. Otherwise, a -- ConversionFailed exception will be thrown. -- -- Note that field evaluates it's result to WHNF, so the caveats -- listed in mysql-simple and very early versions of postgresql-simple no -- longer apply. Instead, look at the caveats associated with -- user-defined implementations of fromField. class FromRow a fromRow :: FromRow a => RowParser a data RowParser a field :: FromField a => RowParser a fieldWith :: FieldParser a -> RowParser a numFieldsRemaining :: RowParser Int instance (FromRow a, FromRow b) => FromRow (a :. b) instance FromField a => FromRow (Maybe (Vector a)) instance FromField a => FromRow (Vector a) instance FromField a => FromRow (Maybe [a]) instance FromField a => FromRow [a] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i, FromField j) => FromRow (Maybe (a, b, c, d, e, f, g, h, i, j)) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i, FromField j) => FromRow (a, b, c, d, e, f, g, h, i, j) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i) => FromRow (Maybe (a, b, c, d, e, f, g, h, i)) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i) => FromRow (a, b, c, d, e, f, g, h, i) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h) => FromRow (Maybe (a, b, c, d, e, f, g, h)) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h) => FromRow (a, b, c, d, e, f, g, h) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (Maybe (a, b, c, d, e, f, g)) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (a, b, c, d, e, f, g) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (Maybe (a, b, c, d, e, f)) instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (a, b, c, d, e, f) instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (Maybe (a, b, c, d, e)) instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (a, b, c, d, e) instance (FromField a, FromField b, FromField c, FromField d) => FromRow (Maybe (a, b, c, d)) instance (FromField a, FromField b, FromField c, FromField d) => FromRow (a, b, c, d) instance (FromField a, FromField b, FromField c) => FromRow (Maybe (a, b, c)) instance (FromField a, FromField b, FromField c) => FromRow (a, b, c) instance (FromField a, FromField b) => FromRow (Maybe (a, b)) instance (FromField a, FromField b) => FromRow (a, b) instance FromField a => FromRow (Maybe (Only a)) instance FromField a => FromRow (Only a) -- | A mid-level client library for the PostgreSQL database, aimed at ease -- of use and high performance. module Database.PostgreSQL.Simple data Connection -- | A query string. This type is intended to make it difficult to -- construct a SQL query by concatenating string fragments, as that is an -- extremely common way to accidentally introduce SQL injection -- vulnerabilities into an application. -- -- This type is an instance of IsString, so the easiest way to -- construct a query is to enable the OverloadedStrings language -- extension and then simply write the query in double quotes. -- --
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   import Database.PostgreSQL.Simple
--   
--   q :: Query
--   q = "select ?"
--   
-- -- The underlying type is a ByteString, and literal Haskell -- strings that contain Unicode characters will be correctly transformed -- to UTF-8. data Query -- | A collection type that can be turned into a list of rendering -- Actions. -- -- Instances should use the render method of the Param -- class to perform conversion of each element of the collection. class ToRow a -- | A collection type that can be converted from a sequence of fields. -- Instances are provided for tuples up to 10 elements and lists of any -- length. -- -- Note that instances can be defined outside of postgresql-simple, which -- is often useful. For example, here's an instance for a user-defined -- pair: -- --
--   data User = User { name :: String, fileQuota :: Int }
--   
--   instance FromRow User where
--        fromRow = User <$> field <*> field
--   
-- -- The number of calls to field must match the number of fields -- returned in a single row of the query result. Otherwise, a -- ConversionFailed exception will be thrown. -- -- Note that field evaluates it's result to WHNF, so the caveats -- listed in mysql-simple and very early versions of postgresql-simple no -- longer apply. Instead, look at the caveats associated with -- user-defined implementations of fromField. class FromRow a -- | Wrap a list of values for use in an IN clause. Replaces a -- single "?" character with a parenthesized list of rendered -- values. -- -- Example: -- --
--   query c "select * from whatever where id in ?" (Only (In [3,4,5]))
--   
newtype In a In :: a -> In a -- | Wrap binary data for use as a bytea value. newtype Binary a Binary :: a -> Binary a fromBinary :: Binary a -> a -- | A single-value "collection". -- -- This is useful if you need to supply a single parameter to a SQL -- query, or extract a single column from a SQL result. -- -- Parameter example: -- --
--   query c "select x from scores where x > ?" (Only (42::Int))
--   
-- -- Result example: -- --
--   xs <- query_ c "select id from users"
--   forM_ xs $ \(Only id) -> {- ... -}
--   
newtype Only a Only :: a -> Only a fromOnly :: Only a -> a -- | A composite type to parse your custom data structures without having -- to define dummy newtype wrappers every time. -- --
--   instance FromRow MyData where ...
--   
-- --
--   instance FromRow MyData2 where ...
--   
-- -- then I can do the following for free: -- --
--   res <- query' c ...
--   forM res $ \(MyData{..} :. MyData2{..}) -> do
--     ....
--   
data (:.) h t (:.) :: h -> t -> :. h t data SqlError SqlError :: ByteString -> ExecStatus -> ByteString -> ByteString -> ByteString -> SqlError sqlState :: SqlError -> ByteString sqlExecStatus :: SqlError -> ExecStatus sqlErrorMsg :: SqlError -> ByteString sqlErrorDetail :: SqlError -> ByteString sqlErrorHint :: SqlError -> ByteString data ExecStatus :: * -- | The string sent to the server was empty. EmptyQuery :: ExecStatus -- | Successful completion of a command returning no data. CommandOk :: ExecStatus -- | Successful completion of a command returning data (such as a SELECT or -- SHOW). TuplesOk :: ExecStatus -- | Copy Out (from server) data transfer started. CopyOut :: ExecStatus -- | Copy In (to server) data transfer started. CopyIn :: ExecStatus -- | The server's response was not understood. BadResponse :: ExecStatus -- | A nonfatal error (a notice or warning) occurred. NonfatalError :: ExecStatus -- | A fatal error occurred. FatalError :: ExecStatus -- | Exception thrown if a Query could not be formatted correctly. -- This may occur if the number of '?' characters in the query -- string does not match the number of parameters provided. data FormatError -- | Exception thrown if query is used to perform an -- INSERT-like operation, or execute is used to perform -- a SELECT-like operation. data QueryError -- | Exception thrown if conversion from a SQL value to a Haskell value -- fails. data ResultError -- | Attempt to make a connection based on a libpq connection string. See -- http://www.postgresql.org/docs/9.3/static/libpq-connect.html -- for more information. Here is an example with some of the most -- commonly used parameters: -- --
--   host='db.somedomain.com' port=5432 ...
--   
-- -- This attempts to connect to db.somedomain.com:5432. Omitting -- the port will normally default to 5432. -- -- On systems that provide unix domain sockets, omitting the host -- parameter will cause libpq to attempt to connect via unix domain -- sockets. The default path to the socket is constructed from the port -- number and the DEFAULT_PGSOCKET_DIR constant defined in the -- pg_config_manual.h header file. Connecting via unix sockets -- tends to use the peer authentication method, which is very -- secure and does not require a password. -- -- On Windows and other systems without unix domain sockets, omitting the -- host will default to localhost. -- --
--   ... dbname='postgres' user='postgres' password='secret \' \\ pw'
--   
-- -- This attempts to connect to database named postgres with user -- postgres and password secret ' \ pw. Backslash -- characters will have to be double-quoted in literal Haskell strings, -- of course. Omitting dbname and user will both -- default to the system username that the client process is running as. -- -- Omitting password will default to an appropriate password -- found in the pgpass file, or no password at all if a matching -- line is not found. See -- http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html for -- more information regarding this file. -- -- As all parameters are optional and the defaults are sensible, the -- empty connection string can be useful for development and exploratory -- use, assuming your system is set up appropriately. -- -- On Unix, such a setup would typically consist of a local postgresql -- server listening on port 5432, as well as a system user, database -- user, and database sharing a common name, with permissions granted to -- the user on the database. -- -- On Windows, in addition you will either need pg_hba.conf to -- specify the use the trust authentication method for the the -- connection, which may not be appropriate for multiuser or production -- machines, or you will need to use a pgpass file with the -- password or md5 authentication methods. -- -- See -- http://www.postgresql.org/docs/9.3/static/client-authentication.html -- for more information regarding the authentication process. connectPostgreSQL :: ByteString -> IO Connection close :: Connection -> IO () -- | Connect with the given username to the given database. Will throw an -- exception if it cannot connect. connect :: ConnectInfo -> IO Connection data ConnectInfo ConnectInfo :: String -> Word16 -> String -> String -> String -> ConnectInfo connectHost :: ConnectInfo -> String connectPort :: ConnectInfo -> Word16 connectUser :: ConnectInfo -> String connectPassword :: ConnectInfo -> String connectDatabase :: ConnectInfo -> String -- | Default information for setting up a connection. -- -- Defaults are as follows: -- -- -- -- Use as in the following example: -- --
--   connect defaultConnectInfo { connectHost = "db.example.com" }
--   
defaultConnectInfo :: ConnectInfo -- | Turns a ConnectInfo data structure into a libpq connection -- string. postgreSQLConnectionString :: ConnectInfo -> ByteString -- | Perform a SELECT or other SQL query that is expected to -- return results. All results are retrieved and converted before this -- function returns. -- -- When processing large results, this function will consume a lot of -- client-side memory. Consider using fold instead. -- -- Exceptions that may be thrown: -- -- query :: (ToRow q, FromRow r) => Connection -> Query -> q -> IO [r] -- | A version of query that does not perform query substitution. query_ :: FromRow r => Connection -> Query -> IO [r] -- | A version of query taking parser as argument queryWith :: ToRow q => RowParser r -> Connection -> Query -> q -> IO [r] -- | A version of query_ taking parser as argument queryWith_ :: RowParser r -> Connection -> Query -> IO [r] data FoldOptions FoldOptions :: !FetchQuantity -> !TransactionMode -> FoldOptions fetchQuantity :: FoldOptions -> !FetchQuantity transactionMode :: FoldOptions -> !TransactionMode -- | Number of rows to fetch at a time. Automatic currently defaults -- to 256 rows, although it might be nice to make this more intelligent -- based on e.g. the average size of the rows. data FetchQuantity Automatic :: FetchQuantity Fixed :: !Int -> FetchQuantity -- | defaults to Automatic, and TransactionMode -- ReadCommitted ReadOnly defaultFoldOptions :: FoldOptions -- | Perform a SELECT or other SQL query that is expected to -- return results. Results are streamed incrementally from the server, -- and consumed via a left fold. -- -- When dealing with small results, it may be simpler (and perhaps -- faster) to use query instead. -- -- This fold is not strict. The stream consumer is responsible for -- forcing the evaluation of its result to avoid space leaks. -- -- This is implemented using a database cursor. As such, this requires a -- transaction. This function will detect whether or not there is a -- transaction in progress, and will create a ReadCommitted -- ReadOnly transaction if needed. The cursor is given a unique -- temporary name, so the consumer may itself call fold. -- -- Exceptions that may be thrown: -- -- fold :: (FromRow row, ToRow params) => Connection -> Query -> params -> a -> (a -> row -> IO a) -> IO a -- | The same as fold, but this provides a bit more control over -- lower-level details. Currently, the number of rows fetched per -- round-trip to the server and the transaction mode may be adjusted -- accordingly. If the connection is already in a transaction, then the -- existing transaction is used and thus the transactionMode -- option is ignored. foldWithOptions :: (FromRow row, ToRow params) => FoldOptions -> Connection -> Query -> params -> a -> (a -> row -> IO a) -> IO a -- | A version of fold that does not perform query substitution. fold_ :: FromRow r => Connection -> Query -> a -> (a -> r -> IO a) -> IO a foldWithOptions_ :: FromRow r => FoldOptions -> Connection -> Query -> a -> (a -> r -> IO a) -> IO a -- | A version of fold that does not transform a state value. forEach :: (ToRow q, FromRow r) => Connection -> Query -> q -> (r -> IO ()) -> IO () -- | A version of forEach that does not perform query substitution. forEach_ :: FromRow r => Connection -> Query -> (r -> IO ()) -> IO () -- | Execute INSERT ... RETURNING, UPDATE ... RETURNING, -- or other SQL query that accepts multi-row input and is expected to -- return results. Note that it is possible to write query -- conn INSERT ... RETURNING ... ... in cases where you are -- only inserting a single row, and do not need functionality analogous -- to executeMany. -- -- If the list of parameters is empty, this function will simply return -- [] without issuing the query to the backend. If this is not -- desired, consider using the Values constructor instead. -- -- Throws FormatError if the query could not be formatted -- correctly. returning :: (ToRow q, FromRow r) => Connection -> Query -> [q] -> IO [r] -- | Execute an INSERT, UPDATE, or other SQL query that -- is not expected to return results. -- -- Returns the number of rows affected. -- -- Throws FormatError if the query could not be formatted -- correctly, or a SqlError exception if the backend returns an -- error. execute :: ToRow q => Connection -> Query -> q -> IO Int64 -- | A version of execute that does not perform query -- substitution. execute_ :: Connection -> Query -> IO Int64 -- | Execute a multi-row INSERT, UPDATE, or other SQL -- query that is not expected to return results. -- -- Returns the number of rows affected. If the list of parameters is -- empty, this function will simply return 0 without issuing the query to -- the backend. If this is not desired, consider using the -- Values constructor instead. -- -- Throws FormatError if the query could not be formatted -- correctly, or a SqlError exception if the backend returns an -- error. -- -- For example, here's a command that inserts two rows into a table with -- two columns: -- --
--   executeMany c [sql|
--       INSERT INTO sometable VALUES (?,?)
--    |] [(1, "hello"),(2, "world")]
--   
-- -- Here's an canonical example of a multi-row update command: -- --
--   executeMany c [sql|
--       UPDATE sometable
--          SET sometable.y = upd.y
--         FROM (VALUES (?,?)) as upd(x,y)
--        WHERE sometable.x = upd.x
--    |] [(1, "hello"),(2, "world")
--   
executeMany :: ToRow q => Connection -> Query -> [q] -> IO Int64 -- | Execute an action inside a SQL transaction. -- -- This function initiates a transaction with a "begin -- transaction" statement, then executes the supplied action. If the -- action succeeds, the transaction will be completed with commit -- before this function returns. -- -- If the action throws any kind of exception (not just a -- PostgreSQL-related exception), the transaction will be rolled back -- using rollback, then the exception will be rethrown. -- -- For nesting transactions, see withSavepoint. withTransaction :: Connection -> IO a -> IO a -- | Create a savepoint, and roll back to it if an error occurs. This may -- only be used inside of a transaction, and provides a sort of "nested -- transaction". -- -- See -- http://www.postgresql.org/docs/current/static/sql-savepoint.html withSavepoint :: Connection -> IO a -> IO a -- | Begin a transaction. begin :: Connection -> IO () -- | Commit a transaction. commit :: Connection -> IO () -- | Rollback a transaction. rollback :: Connection -> IO () -- | Format a query string with a variable number of rows. -- -- This function is exposed to help with debugging and logging. Do not -- use it to prepare queries for execution. -- -- The query string must contain exactly one substitution group, -- identified by the SQL keyword "VALUES" (case insensitive) -- followed by an "(" character, a series of one or more -- "?" characters separated by commas, and a ")" -- character. White space in a substitution group is permitted. -- -- Throws FormatError if the query string could not be formatted -- correctly. formatMany :: ToRow q => Connection -> Query -> [q] -> IO ByteString -- | Format a query string. -- -- This function is exposed to help with debugging and logging. Do not -- use it to prepare queries for execution. -- -- String parameters are escaped according to the character set in use on -- the Connection. -- -- Throws FormatError if the query string could not be formatted -- correctly. formatQuery :: ToRow q => Connection -> Query -> q -> IO ByteString instance Typeable FormatError instance Eq FormatError instance Show FormatError instance Exception FormatError -- | mid-level support for COPY IN and COPY OUT. See -- http://www.postgresql.org/docs/9.2/static/sql-copy.html for -- more information. -- -- To use this binding, first call copy with an appropriate query -- as documented in the link above. Then, in the case of a COPY TO -- STDOUT query, call getCopyData repeatedly until it returns -- CopyOutDone. In the case of a COPY FROM STDIN query, -- call putCopyData repeatedly and then finish by calling either -- putCopyEnd to proceed or putCopyError to abort. -- -- You cannot issue another query on the same connection while a copy is -- ongoing; this will result in an exception. It is harmless to -- concurrently call getNotification on a connection while it is -- in a CopyIn or CopyOut state, however be aware that -- current versions of the PostgreSQL backend will not deliver -- notifications to a client while a transaction is ongoing. module Database.PostgreSQL.Simple.Copy -- | Issue a COPY FROM STDIN or COPY TO STDOUT query. In -- the former case, the connection's state will change to -- CopyIn; in the latter, CopyOut. The connection must -- be in the ready state in order to call this function. Performs -- parameter subsitution. copy :: ToRow params => Connection -> Query -> params -> IO () -- | Issue a COPY FROM STDIN or COPY TO STDOUT query. In -- the former case, the connection's state will change to -- CopyIn; in the latter, CopyOut. The connection must -- be in the ready state in order to call this function. Does not perform -- parameter subsitution. copy_ :: Connection -> Query -> IO () data CopyOutResult -- | Data representing either exactly one row of the result, or header or -- footer data depending on format. CopyOutRow :: !ByteString -> CopyOutResult -- | No more rows, and a count of the number of rows returned. CopyOutDone :: {-# UNPACK #-} !Int64 -> CopyOutResult -- | Retrieve some data from a COPY TO STDOUT query. A connection -- must be in the CopyOut state in order to call this function. -- If this returns a CopyOutRow, the connection remains in the -- CopyOut state, if it returns CopyOutDone, then the -- connection has reverted to the ready state. getCopyData :: Connection -> IO CopyOutResult -- | Feed some data to a COPY FROM STDIN query. Note that the data -- does not need to represent a single row, or even an integral number of -- rows. The net result of putCopyData conn a >> putCopyData -- conn b is the same as putCopyData conn c whenever c -- == BS.append a b. -- -- A connection must be in the CopyIn state in order to call -- this function, otherwise a SqlError exception will result. The -- connection remains in the CopyIn state after this function is -- called. putCopyData :: Connection -> ByteString -> IO () -- | Completes a COPY FROM STDIN query. Returns the number of rows -- processed. -- -- A connection must be in the CopyIn state in order to call -- this function, otherwise a SqlError exception will result. The -- connection's state changes back to ready after this function is -- called. putCopyEnd :: Connection -> IO Int64 -- | Aborts a COPY FROM STDIN query. The string parameter is -- simply an arbitrary error message that may show up in the PostgreSQL -- server's log. -- -- A connection must be in the CopyIn state in order to call -- this function, otherwise a SqlError exception will result. The -- connection's state changes back to ready after this function is -- called. putCopyError :: Connection -> ByteString -> IO () instance Typeable CopyOutResult instance Eq CopyOutResult instance Show CopyOutResult