postgresql-query-1.3.1: Sql interpolating quasiquote plus some kind of primitive ORM using it

Safe HaskellNone
LanguageHaskell2010

Database.PostgreSQL.Query

Contents

Synopsis

Common usage modules

Some re-exports from postgresql-simple

data Connection :: *

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 http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING 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 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. 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 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 http://www.postgresql.org/docs/9.3/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 parameters in the connection string. In particular, sslmode needs to set be require, verify-ca, or verify-full to perform certificate validation. When sslmode is require, then you will also need to have 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.

class ToRow a where

A collection type that can be turned into a list of rendering Actions.

Instances should use the toField method of the ToField class to perform conversion of each element of the collection.

Methods

toRow :: a -> [Action]

ToField a collection of values.

Instances

ToRow () 
ToField a => ToRow [a] 
ToField a => ToRow (Only a) 
(ToField a, ToField b) => ToRow (a, b) 
(ToRow a, ToRow b) => ToRow ((:.) a b) 
(ToField a, ToField b, ToField c) => ToRow (a, b, c) 
(ToField a, ToField b, ToField c, ToField d) => ToRow (a, b, c, d) 
(ToField a, ToField b, ToField c, ToField d, ToField e) => ToRow (a, b, c, d, e) 
(ToField a, ToField b, ToField c, ToField d, ToField e, ToField f) => ToRow (a, b, c, d, e, f) 
(ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g) => ToRow (a, b, c, d, e, f, g) 
(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) 
(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) 
(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) 

class FromField a where

A type that may be converted from a SQL type.

Methods

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.Result to be retained. Thus, implementations of 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.Result before it has been passed to fromField. This is because for short strings, it's cheaper to copy the string than to set up a finalizer.

Instances

FromField Bool

bool

FromField Char

"char"

FromField Double

int2, int4, float4, float8 (Uses attoparsec's double routine, for better accuracy convert to Scientific or Rational first)

FromField Float

int2, float4 (Uses attoparsec's double routine, for better accuracy convert to Scientific or Rational first)

FromField Int

int2, int4, and if compiled as 64-bit code, int8 as well. This library was compiled as 64-bit code.

FromField Int16

int2

FromField Int32

int2, int4

FromField Int64

int2, int4, int8

FromField Integer

int2, int4, int8

FromField ()

void

FromField ByteString

bytea, name, text, "char", bpchar, varchar, unknown

FromField ByteString

bytea, name, text, "char", bpchar, varchar, unknown

FromField Scientific

int2, int4, float4, float8, numeric

FromField Text

name, text, "char", bpchar, varchar

FromField UTCTime

timestamptz

FromField Value

json

FromField Text

name, text, "char", bpchar, varchar

FromField Oid

oid

FromField HStoreList

hstore

FromField HStoreMap 
FromField Null

compatible with any data type, but the value must be null

FromField LocalTimestamp

timestamp

FromField UTCTimestamp

timestamptz

FromField ZonedTimestamp

timestamptz

FromField Date

date

FromField LocalTime

timestamp

FromField ZonedTime

timestamptz

FromField TimeOfDay

time

FromField Day

date

FromField UUID

uuid

FromField InetText 
FromField [Char]

name, text, "char", bpchar, varchar

FromField (Ratio Integer)

int2, int4, float4, float8, numeric

FromField a => FromField (Maybe a)

For dealing with null values. Compatible with any postgresql type compatible with type a. Note that the type is not checked if the value is null, although it is inadvisable to rely on this behavior.

FromField a => FromField (MVar a)

Compatible with the same set of types as a. Note that modifying the MVar does not have any effects outside the local process on the local machine.

FromField a => FromField (IORef a)

Compatible with the same set of types as a. Note that modifying the IORef does not have any effects outside the local process on the local machine.

FromField (CI Text)

citext

FromField (CI Text)

citext

FromField (Binary ByteString)

bytea

FromField (Binary ByteString)

bytea

(FromField a, Typeable * a) => FromField (PGArray a)

any postgresql array whose elements are compatible with type a

(FromField a, Typeable * a) => FromField (Vector a) 
(FromField a, Typeable * a) => FromField (IOVector a) 
(FromField a, FromField b) => FromField (Either a b)

Compatible with both types. Conversions to type b are preferred, the conversion to type a will be tried after the Right conversion fails.

class FromRow a where

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.

Methods

fromRow :: RowParser a

Instances

FromField a => FromRow [a] 
FromField a => FromRow (Maybe [a]) 
(FromField a, FromField b) => FromRow (Maybe (a, b)) 
(FromField a, FromField b, FromField c) => FromRow (Maybe (a, b, c)) 
(FromField a, FromField b, FromField c, FromField d) => FromRow (Maybe (a, b, c, d)) 
(FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (Maybe (a, b, c, d, e)) 
(FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (Maybe (a, b, c, d, e, f)) 
(FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (Maybe (a, b, c, d, e, f, g)) 
(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)) 
(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)) 
(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)) 
FromField a => FromRow (Maybe (Only a)) 
FromField a => FromRow (Maybe (Vector a)) 
FromField a => FromRow (Only a) 
FromField a => FromRow (Vector a) 
(FromField a, FromField b) => FromRow (a, b) 
(FromRow a, FromRow b) => FromRow ((:.) a b) 
(FromField a, FromField b, FromField c) => FromRow (a, b, c) 
(FromField a, FromField b, FromField c, FromField d) => FromRow (a, b, c, d) 
(FromField a, FromField b, FromField c, FromField d, FromField e) => FromRow (a, b, c, d, e) 
(FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRow (a, b, c, d, e, f) 
(FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRow (a, b, c, d, e, f, g) 
(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) 
(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) 
(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) 

newtype Query :: *

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.

Constructors

Query 

newtype Only 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) -> {- ... -}

Constructors

Only 

Fields

fromOnly :: a
 

Instances

Functor Only 
Eq a => Eq (Only a) 
Ord a => Ord (Only a) 
Read a => Read (Only a) 
Show a => Show (Only a) 
FromField a => FromRow (Maybe (Only a)) 
FromField a => FromRow (Only a) 
ToField a => ToRow (Only a) 
Typeable (* -> *) Only 

newtype In 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]))

Constructors

In a 

Instances

Functor In 
Eq a => Eq (In a) 
Ord a => Ord (In a) 
Read a => Read (In a) 
Show a => Show (In a) 
ToField a => ToField (In [a]) 
Typeable (* -> *) In 

newtype Oid :: *

Constructors

Oid CUInt 

data Values 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.

Constructors

Values [QualifiedIdentifier] [a] 

Instances

Eq a => Eq (Values a) 
Ord a => Ord (Values a) 
Read a => Read (Values a) 
Show a => Show (Values a) 
ToRow a => ToField (Values a) 
Typeable (* -> *) Values 

data h :. t :: * -> * -> * infixr 3

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
  ....

Constructors

h :. t infixr 3 

Instances

(Eq h, Eq t) => Eq ((:.) h t) 
(Ord h, Ord t) => Ord ((:.) h t) 
(Read h, Read t) => Read ((:.) h t) 
(Show h, Show t) => Show ((:.) h t) 
(FromRow a, FromRow b) => FromRow ((:.) a b) 
(ToRow a, ToRow b) => ToRow ((:.) a b) 
Typeable (* -> * -> *) (:.) 

newtype PGArray a :: * -> *

Wrap a list for use as a PostgreSQL array.

Constructors

PGArray 

Fields

fromPGArray :: [a]
 

Instances

Functor PGArray 
Eq a => Eq (PGArray a) 
Ord a => Ord (PGArray a) 
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 a

ToField a => ToField (PGArray a) 
Typeable (* -> *) PGArray 

data HStoreBuilder :: *

Represents valid hstore syntax.

class ToHStoreText a where

Methods

toHStoreText :: a -> HStoreText

Instances

data HStoreText :: *

Represents escape text, ready to be the key or value to a hstore value

sqlQQ :: QuasiQuoter Source

Deprecated: Use sqlExp instead