Safe Haskell | None |
---|---|
Language | Haskell2010 |
Synopsis
- module Database.PostgreSQL.Query.Entity
- module Database.PostgreSQL.Query.Functions
- module Database.PostgreSQL.Query.SqlBuilder
- module Database.PostgreSQL.Query.TH
- module Database.PostgreSQL.Query.Types
- data Connection
- connect :: ConnectInfo -> IO Connection
- defaultConnectInfo :: ConnectInfo
- connectPostgreSQL :: ByteString -> IO Connection
- data ConnectInfo = ConnectInfo {}
- class ToField a where
- class ToRow a where
- class FromField a where
- fromField :: FieldParser a
- class FromRow a where
- newtype Query = Query {}
- newtype Only a = Only {
- fromOnly :: a
- newtype In a = In a
- newtype Oid = Oid CUInt
- data Values a = Values [QualifiedIdentifier] [a]
- data h :. t = h :. t
- newtype PGArray a = PGArray {
- fromPGArray :: [a]
- newtype HStoreList = HStoreList {
- fromHStoreList :: [(Text, Text)]
- newtype HStoreMap = HStoreMap {
- fromHStoreMap :: Map Text Text
- class ToHStore a where
- toHStore :: a -> HStoreBuilder
- data HStoreBuilder
- hstore :: (ToHStoreText a, ToHStoreText b) => a -> b -> HStoreBuilder
- parseHStoreList :: ByteString -> Either String HStoreList
- class ToHStoreText a where
- toHStoreText :: a -> HStoreText
- data HStoreText
Common usage modules
module Database.PostgreSQL.Query.TH
Some re-exports from postgresql-simple
data Connection #
Instances
Eq Connection | |
Defined in Database.PostgreSQL.Simple.Internal (==) :: Connection -> Connection -> Bool # (/=) :: Connection -> Connection -> Bool # |
connect :: ConnectInfo -> IO Connection #
Connect with the given username to the given database. Will throw an exception if it cannot connect.
defaultConnectInfo :: ConnectInfo #
Default information for setting up a connection.
Defaults are as follows:
- Server on
localhost
- Port on
5432
- User
postgres
- No password
- Database
postgres
Use as in the following example:
connect defaultConnectInfo { connectHost = "db.example.com" }
connectPostgreSQL :: ByteString -> IO Connection #
Attempt to make a connection based on a libpq connection string. See https://www.postgresql.org/docs/9.5/static/libpq-connect.html#LIBPQ-CONNSTRING for more information. Also note that environment variables also affect parameters not provided, parameters provided as the empty string, and a few other things; see https://www.postgresql.org/docs/9.5/static/libpq-envars.html for details. 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 filesystem 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 a 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. The path of the pgpass
file may be specified by setting
the PGPASSFILE
environment variable. See
https://www.postgresql.org/docs/9.5/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 of the trust
authentication method for
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 https://www.postgresql.org/docs/9.5/static/client-authentication.html for more information regarding the authentication process.
SSL/TLS will typically "just work" if your postgresql server supports or
requires it. However, note that libpq is trivially vulnerable to a MITM
attack without setting additional SSL connection parameters. In
particular, sslmode
needs to be set to require
, verify-ca
, or
verify-full
in order to perform certificate validation. When sslmode
is require
, then you will also need to specify a sslrootcert
file,
otherwise no validation of the server's identity will be performed.
Client authentication via certificates is also possible via the
sslcert
and sslkey
parameters. See
https://www.postgresql.org/docs/9.5/static/libpq-ssl.html
for detailed information regarding libpq and SSL.
data ConnectInfo #
ConnectInfo | |
|
Instances
A type that may be used as a single parameter to a SQL query.
Instances
A collection type that can be turned into a list of rendering
Action
s.
Instances should use the toField
method of the ToField
class
to perform conversion of each element of the collection.
You can derive ToRow
for your data type using GHC generics, like this:
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} import GHC.Generics (Generic
) import Database.PostgreSQL.Simple (ToRow
) data User = User { name :: String, fileQuota :: Int } deriving (Generic
,ToRow
)
Note that this only works for product types (e.g. records) and does not support sum types or recursive types.
Nothing
Instances
A type that may be converted from a SQL type.
fromField :: FieldParser a #
Convert a SQL value to a Haskell value.
Returns a list of exceptions if the conversion fails. In the case of
library instances, this will usually be a single ResultError
, but
may be a UnicodeException
.
Note that retaining any reference to the Field
argument causes
the entire LibPQ.
to be retained. Thus, implementations
of Result
fromField
should return results that do not refer to this value
after the result have been evaluated to WHNF.
Note that as of postgresql-simple-0.4.0.0
, the ByteString
value
has already been copied out of the LibPQ.
before it has
been passed to Result
fromField
. This is because for short strings, it's
cheaper to copy the string than to set up a finalizer.
Instances
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 } instanceFromRow
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.
You can also derive FromRow
for your data type using GHC generics, like
this:
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} import GHC.Generics (Generic
) import Database.PostgreSQL.Simple (FromRow
) data User = User { name :: String, fileQuota :: Int } deriving (Generic
,FromRow
)
Note that this only works for product types (e.g. records) and does not support sum types or recursive types.
Note that field
evaluates its 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
.
Nothing
Instances
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.
The 1-tuple type or single-value "collection".
This type is structurally equivalent to the
Identity
type, but its intent is more
about serving as the anonymous 1-tuple type missing from Haskell for attaching
typeclass instances.
Parameter usage example:
encodeSomething (Only
(42::Int))
Result usage example:
xs <- decodeSomething
forM_ xs $ \(Only
id) -> {- ... -}
Instances
Functor Only | |
Eq a => Eq (Only a) | |
Data a => Data (Only a) | |
Defined in Data.Tuple.Only gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Only a -> c (Only a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Only a) # toConstr :: Only a -> Constr # dataTypeOf :: Only a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Only a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Only a)) # gmapT :: (forall b. Data b => b -> b) -> Only a -> Only a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Only a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Only a -> r # gmapQ :: (forall d. Data d => d -> u) -> Only a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Only a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Only a -> m (Only a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Only a -> m (Only a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Only a -> m (Only a) # | |
Ord a => Ord (Only a) | |
Read a => Read (Only a) | |
Show a => Show (Only a) | |
Generic (Only a) | |
NFData a => NFData (Only a) | |
Defined in Data.Tuple.Only | |
FromField a => FromRow (Maybe (Only a)) | |
FromField a => FromRow (Only a) | |
Defined in Database.PostgreSQL.Simple.FromRow | |
ToField a => ToRow (Only a) | |
Defined in Database.PostgreSQL.Simple.ToRow | |
type Rep (Only a) | |
Defined in Data.Tuple.Only |
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]))
Note that In []
expands to (null)
, which works as expected in
the query above, but evaluates to the logical null value on every
row instead of TRUE
. This means that changing the query above
to ... id NOT in ?
and supplying the empty list as the parameter
returns zero rows, instead of all of them as one would expect.
Since postgresql doesn't seem to provide a syntax for actually specifying an empty list, which could solve this completely, there are two workarounds particularly worth mentioning, namely:
Use postgresql-simple's
Values
type instead, which can handle the empty case correctly. Note however that while specifying the postgresql type"int4"
is mandatory in the empty case, specifying the haskell typeValues (Only Int)
would not normally be needed in realistic use cases.query c "select * from whatever where id not in ?" (Only (Values ["int4"] [] :: Values (Only Int)))
Use sql's
COALESCE
operator to turn a logicalnull
into the correct boolean. Note however that the correct boolean depends on the use case:query c "select * from whatever where coalesce(id NOT in ?, TRUE)" (Only (In [] :: In [Int]))
query c "select * from whatever where coalesce(id IN ?, FALSE)" (Only (In [] :: In [Int]))
Note that at as of PostgreSQL 9.4, the query planner cannot see inside the
COALESCE
operator, so if you have an index onid
then you probably don't want to write the last example withCOALESCE
, which would result in a table scan. There are further caveats ifid
can be null or you want null treated sensibly as a component ofIN
orNOT IN
.
In 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 ON TRUE ) 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
or serial
, _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 https://www.postgresql.org/docs/9.5/static/sql-values.html for more information.
Values [QualifiedIdentifier] [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 ....
h :. t infixr 3 |
Instances
(Eq h, Eq t) => Eq (h :. t) | |
(Ord h, Ord t) => Ord (h :. t) | |
Defined in Database.PostgreSQL.Simple.Types | |
(Read h, Read t) => Read (h :. t) | |
(Show h, Show t) => Show (h :. t) | |
(FromRow a, FromRow b) => FromRow (a :. b) | |
Defined in Database.PostgreSQL.Simple.FromRow | |
(ToRow a, ToRow b) => ToRow (a :. b) | |
Defined in Database.PostgreSQL.Simple.ToRow |
Wrap a list for use as a PostgreSQL array.
PGArray | |
|
Instances
Functor PGArray | |
Eq a => Eq (PGArray a) | |
Ord a => Ord (PGArray a) | |
Defined in Database.PostgreSQL.Simple.Types | |
Read a => Read (PGArray a) | |
Show a => Show (PGArray a) | |
(FromField a, Typeable a) => FromField (PGArray a) | any postgresql array whose elements are compatible with type |
Defined in Database.PostgreSQL.Simple.FromField fromField :: FieldParser (PGArray a) # | |
ToField a => ToField (PGArray a) | |
Defined in Database.PostgreSQL.Simple.ToField |
newtype HStoreList #
HStoreList | |
|
Instances
Show HStoreList | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation showsPrec :: Int -> HStoreList -> ShowS # show :: HStoreList -> String # showList :: [HStoreList] -> ShowS # | |
ToHStore HStoreList | hstore |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStore :: HStoreList -> HStoreBuilder # | |
FromField HStoreList | hstore |
ToField HStoreList | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toField :: HStoreList -> Action # |
toHStore :: a -> HStoreBuilder #
Instances
ToHStore HStoreBuilder | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStore :: HStoreBuilder -> HStoreBuilder # | |
ToHStore HStoreList | hstore |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStore :: HStoreList -> HStoreBuilder # | |
ToHStore HStoreMap | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStore :: HStoreMap -> HStoreBuilder # |
data HStoreBuilder #
Represents valid hstore syntax.
Instances
Semigroup HStoreBuilder | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation (<>) :: HStoreBuilder -> HStoreBuilder -> HStoreBuilder # sconcat :: NonEmpty HStoreBuilder -> HStoreBuilder # stimes :: Integral b => b -> HStoreBuilder -> HStoreBuilder # | |
Monoid HStoreBuilder | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation mempty :: HStoreBuilder # mappend :: HStoreBuilder -> HStoreBuilder -> HStoreBuilder # mconcat :: [HStoreBuilder] -> HStoreBuilder # | |
ToHStore HStoreBuilder | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStore :: HStoreBuilder -> HStoreBuilder # | |
ToField HStoreBuilder | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toField :: HStoreBuilder -> Action # |
hstore :: (ToHStoreText a, ToHStoreText b) => a -> b -> HStoreBuilder #
class ToHStoreText a where #
toHStoreText :: a -> HStoreText #
Instances
ToHStoreText ByteString | Assumed to be UTF-8 encoded |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: ByteString -> HStoreText # | |
ToHStoreText ByteString | Assumed to be UTF-8 encoded |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: ByteString -> HStoreText # | |
ToHStoreText Text | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: Text -> HStoreText # | |
ToHStoreText Text | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: Text -> HStoreText # | |
ToHStoreText HStoreText | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: HStoreText -> HStoreText # |
data HStoreText #
Represents escape text, ready to be the key or value to a hstore value
Instances
Semigroup HStoreText | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation (<>) :: HStoreText -> HStoreText -> HStoreText # sconcat :: NonEmpty HStoreText -> HStoreText # stimes :: Integral b => b -> HStoreText -> HStoreText # | |
Monoid HStoreText | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation mempty :: HStoreText # mappend :: HStoreText -> HStoreText -> HStoreText # mconcat :: [HStoreText] -> HStoreText # | |
ToHStoreText HStoreText | |
Defined in Database.PostgreSQL.Simple.HStore.Implementation toHStoreText :: HStoreText -> HStoreText # |