pqi
Safe HaskellNone
LanguageHaskell2010

Pqi

Description

A driver-agnostic reproduction of the postgresql-libpq API (version 0.11, the pipelining-capable release).

The connection is reified as a single class IsConnection c parameterised over the connection type. Result accessors live in the independent IsResult r class, and cancellation handles in IsCancel k. IsResult (ResultOf c) and IsCancel (CancelOf c) are superclass constraints of IsConnection c, so callers who have access to a connection get result inspection and cancellation automatically.

Function names, argument order, and semantics mirror the API of the C library binding postgresql-libpq. The only deliberate departures are:

  • Connection, Result, and Cancel become the class parameter c and the associated types ResultOf c / CancelOf c.
  • OIDs are a plain Word32 and row/column/parameter indices and LoFds are a plain Int32, rather than the C-specific newtypes of the original.
  • Ambiguous, rarely-useful helpers (e.g. resStatus) are omitted, libpqVersion is omitted too.
  • There's no invalidOid constant. It's just 0.
  • The unescapeBytea helper is bundled in this library and implemented natively without IO.
Synopsis

Type classes

class (IsResult (ResultOf c), IsCancel (CancelOf c)) => IsConnection c where Source #

The single flat capability class: establishing, closing, inspecting, querying, escaping, async commands, pipelining, cancellation handle creation, notifications, copy, large objects, and control.

See the individual capability-class documentation (now inlined below) for semantics of each method.

Associated Types

type ResultOf c Source #

The result type produced by this connection.

type CancelOf c Source #

The cancellation-handle type produced by this connection.

Methods

connectdb :: ByteString -> IO c Source #

Make a new (blocking) connection from a conninfo string.

connectStart :: ByteString -> IO c Source #

Begin establishing a connection asynchronously.

connectPoll :: c -> IO PollingStatus Source #

Drive an asynchronous connection attempt forward.

newNullConnection :: IO c Source #

A sentinel "null" connection.

isNullConnection :: c -> Bool Source #

Whether a connection is the null sentinel.

finish :: c -> IO () Source #

Close the connection and release its resources.

reset :: c -> IO () Source #

Reset the communication channel to the server (blocking).

resetStart :: c -> IO Bool Source #

Begin resetting the connection asynchronously.

resetPoll :: c -> IO PollingStatus Source #

Drive an asynchronous reset forward.

db :: c -> IO (Maybe ByteString) Source #

The database name of the connection.

user :: c -> IO (Maybe ByteString) Source #

The user name of the connection.

pass :: c -> IO (Maybe ByteString) Source #

The password of the connection.

host :: c -> IO (Maybe ByteString) Source #

The server host name of the connection.

port :: c -> IO (Maybe ByteString) Source #

The port of the connection.

options :: c -> IO (Maybe ByteString) Source #

The command-line options passed in the connection request.

status :: c -> IO ConnStatus Source #

Current connection status.

transactionStatus :: c -> IO TransactionStatus Source #

Current in-transaction status of the server.

parameterStatus :: c -> ByteString -> IO (Maybe ByteString) Source #

Look up a current parameter setting reported by the server.

protocolVersion :: c -> IO Int Source #

The frontend/backend protocol version.

serverVersion :: c -> IO Int Source #

The server version, as an integer of the form MMmmpp.

errorMessage :: c -> IO (Maybe ByteString) Source #

The most recent error message, if any.

Note: unlike the structured fields available via resultErrorField, the flat message text is formatted locally by the driver, so adapters are not expected to produce byte-identical strings.

socket :: c -> IO (Maybe Fd) Source #

The file descriptor of the connection socket.

backendPID :: c -> IO Int32 Source #

The process ID of the backend serving this connection.

connectionNeedsPassword :: c -> IO Bool Source #

Whether the connection authentication method required a password but none was available.

connectionUsedPassword :: c -> IO Bool Source #

Whether the connection authentication used a password.

exec :: c -> ByteString -> IO (Maybe (ResultOf c)) Source #

Submit a command and wait for the result.

execParams :: c -> ByteString -> [Maybe (Word32, ByteString, Format)] -> Format -> IO (Maybe (ResultOf c)) Source #

Submit a parameterized command. Each parameter is given as (type oid, value, format), or Nothing for SQL NULL. The final Format selects the result format.

prepare :: c -> ByteString -> ByteString -> Maybe [Word32] -> IO (Maybe (ResultOf c)) Source #

Prepare a named statement. The OID list, when supplied, fixes parameter types; Nothing leaves them to be inferred.

execPrepared :: c -> ByteString -> [Maybe (ByteString, Format)] -> Format -> IO (Maybe (ResultOf c)) Source #

Execute a previously prepared statement. Each parameter is (value, format), or Nothing for SQL NULL.

describePrepared :: c -> ByteString -> IO (Maybe (ResultOf c)) Source #

Describe a prepared statement.

describePortal :: c -> ByteString -> IO (Maybe (ResultOf c)) Source #

Describe a portal.

escapeStringConn :: c -> ByteString -> IO (Maybe ByteString) Source #

Escape a string for safe inclusion in an SQL literal.

escapeByteaConn :: c -> ByteString -> IO (Maybe ByteString) Source #

Escape binary data for use within a bytea literal.

escapeIdentifier :: c -> ByteString -> IO (Maybe ByteString) Source #

Escape a string for use as an SQL identifier (e.g. a table or column name), including the surrounding double quotes.

sendQuery :: c -> ByteString -> IO Bool Source #

Submit a command without waiting for the result.

sendQueryParams :: c -> ByteString -> [Maybe (Word32, ByteString, Format)] -> Format -> IO Bool Source #

Asynchronous execParams.

sendPrepare :: c -> ByteString -> ByteString -> Maybe [Word32] -> IO Bool Source #

Asynchronous prepare.

sendQueryPrepared :: c -> ByteString -> [Maybe (ByteString, Format)] -> Format -> IO Bool Source #

Asynchronous execPrepared.

sendDescribePrepared :: c -> ByteString -> IO Bool Source #

Asynchronous describePrepared.

sendDescribePortal :: c -> ByteString -> IO Bool Source #

Asynchronous describePortal.

getResult :: c -> IO (Maybe (ResultOf c)) Source #

Collect the next result from an asynchronous command.

consumeInput :: c -> IO Bool Source #

Read input from the server into the driver's buffer.

isBusy :: c -> IO Bool Source #

Whether a command is busy (a getResult would block).

setnonblocking :: c -> Bool -> IO Bool Source #

Set the non-blocking flag of the connection.

isnonblocking :: c -> IO Bool Source #

Whether the connection is in non-blocking mode.

setSingleRowMode :: c -> IO Bool Source #

Select single-row mode for the currently executing query.

flush :: c -> IO FlushStatus Source #

Flush queued output data to the server.

pipelineStatus :: c -> IO PipelineStatus Source #

Current pipeline-mode status.

enterPipelineMode :: c -> IO Bool Source #

Enter pipeline mode.

exitPipelineMode :: c -> IO Bool Source #

Leave pipeline mode.

pipelineSync :: c -> IO Bool Source #

Mark a synchronization point in a pipeline.

sendFlushRequest :: c -> IO Bool Source #

Request the server to flush its output buffer in pipeline mode.

getCancel :: c -> IO (Maybe (CancelOf c)) Source #

Obtain a cancellation handle for the connection.

notifies :: c -> IO (Maybe Notify) Source #

Return the next notification from the queue, if any.

disableNoticeReporting :: c -> IO () Source #

Stop accumulating notices for retrieval via getNotice.

enableNoticeReporting :: c -> IO () Source #

Start accumulating notices for retrieval via getNotice.

getNotice :: c -> IO (Maybe ByteString) Source #

Retrieve the next accumulated notice, if any.

putCopyData :: c -> ByteString -> IO CopyInResult Source #

Send data on a COPY FROM STDIN connection.

putCopyEnd :: c -> Maybe ByteString -> IO CopyInResult Source #

Signal the end of COPY FROM STDIN; Just aborts with the given error.

getCopyData :: c -> Bool -> IO CopyOutResult Source #

Receive data on a COPY TO STDOUT connection. The Bool selects non-blocking mode.

loCreat :: c -> IO (Maybe Word32) Source #

Create a new large object.

loCreate :: c -> Word32 -> IO (Maybe Word32) Source #

Create a new large object with the given OID.

loImport :: c -> FilePath -> IO (Maybe Word32) Source #

Import a file as a new large object.

loImportWithOid :: c -> FilePath -> Word32 -> IO (Maybe Word32) Source #

Import a file as a new large object with the given OID.

loExport :: c -> Word32 -> FilePath -> IO (Maybe ()) Source #

Export a large object to a file.

loOpen :: c -> Word32 -> IOMode -> IO (Maybe Int32) Source #

Open a large object.

loWrite :: c -> Int32 -> ByteString -> IO (Maybe Int) Source #

Write to an open large object.

loRead :: c -> Int32 -> Int -> IO (Maybe ByteString) Source #

Read from an open large object.

loSeek :: c -> Int32 -> SeekMode -> Int -> IO (Maybe Int) Source #

Seek within an open large object.

loTell :: c -> Int32 -> IO (Maybe Int) Source #

Report the current seek position of an open large object.

loTruncate :: c -> Int32 -> Int -> IO (Maybe ()) Source #

Truncate an open large object.

loClose :: c -> Int32 -> IO (Maybe ()) Source #

Close an open large object.

loUnlink :: c -> Word32 -> IO (Maybe ()) Source #

Remove a large object.

clientEncoding :: c -> IO ByteString Source #

The current client encoding name.

setClientEncoding :: c -> ByteString -> IO Bool Source #

Set the client encoding.

setErrorVerbosity :: c -> Verbosity -> IO Verbosity Source #

Set error verbosity, returning the previous setting.

class IsResult r where Source #

Result-accessor methods, independent of the connection type that produced the result. This allows row decoders and projection functions (such as observeResult in pqi-conformance) to operate on any result type without knowing the originating connection.

Methods

resultStatus :: r -> IO ExecStatus Source #

The status of the result.

resultErrorMessage :: r -> IO (Maybe ByteString) Source #

The flat error message associated with the result, if any. Best-effort; see the note on errorMessage.

resultErrorField :: r -> FieldCode -> IO (Maybe ByteString) Source #

A single structured field of the result's error report.

unsafeFreeResult :: r -> IO () Source #

Free the result. Adapters that manage results with the garbage collector may implement this as a no-op; for the C-backed adapter it frees the underlying PGresult, after which the result must not be used.

ntuples :: r -> IO Int32 Source #

Number of rows (tuples) in the result.

nfields :: r -> IO Int32 Source #

Number of columns (fields) in the result.

fname :: r -> Int32 -> IO (Maybe ByteString) Source #

Name of the column at the given index.

fnumber :: r -> ByteString -> IO (Maybe Int32) Source #

Index of the column with the given name, if present.

ftable :: r -> Int32 -> IO Word32 Source #

OID of the table the given column was fetched from, or 0.

ftablecol :: r -> Int32 -> IO Int32 Source #

Column number (within its table) that the given result column was fetched from, or 0.

fformat :: r -> Int32 -> IO Format Source #

Format (text or binary) of the given column.

ftype :: r -> Int32 -> IO Word32 Source #

Data type OID of the given column.

fmod :: r -> Int32 -> IO Int Source #

Type modifier of the given column.

fsize :: r -> Int32 -> IO Int Source #

Server-side storage size of the given column's type, or a negative value for variable size.

getvalue :: r -> Int32 -> Int32 -> IO (Maybe ByteString) Source #

Value at (row, column), or Nothing for SQL NULL. Delegates to getvalue' by default in case the adapter provides a copying variant.

getvalue' :: r -> Int32 -> Int32 -> IO (Maybe ByteString) Source #

Like getvalue, but always returns a copy that remains valid after the result is freed.

getisnull :: r -> Int32 -> Int32 -> IO Bool Source #

Whether the value at (row, column) is SQL NULL.

getlength :: r -> Int32 -> Int32 -> IO Int Source #

Length in bytes of the value at (row, column).

nparams :: r -> IO Int32 Source #

Number of parameters of a prepared statement (for a describePrepared result).

paramtype :: r -> Int32 -> IO Word32 Source #

Data type OID of the given prepared-statement parameter.

cmdStatus :: r -> IO (Maybe ByteString) Source #

The command status tag of the result (e.g. "INSERT 0 1").

cmdTuples :: r -> IO (Maybe ByteString) Source #

The number of rows affected by the command, as text.

class IsCancel k where Source #

Cancellation of in-progress commands, isolated from the connection type.

Methods

cancel :: k -> IO (Either ByteString ()) Source #

Request cancellation of the in-progress command via the handle.

Shared types

data Format Source #

Format of a parameter or result column: textual or binary.

Constructors

Text 
Binary 

Instances

Instances details
Eq Format Source # 
Instance details

Defined in Pqi

Methods

(==) :: Format -> Format -> Bool #

(/=) :: Format -> Format -> Bool #

Ord Format Source # 
Instance details

Defined in Pqi

Bounded Format Source # 
Instance details

Defined in Pqi

Enum Format Source # 
Instance details

Defined in Pqi

Show Format Source # 
Instance details

Defined in Pqi

data ExecStatus Source #

Status of a command result, as reported by PQresultStatus.

Constructors

EmptyQuery

The string sent to the server was empty.

CommandOk

Successful completion of a command returning no data.

TuplesOk

Successful completion of a command returning data (such as a SELECT or SHOW).

CopyOut

Copy Out (from server) data transfer started.

CopyIn

Copy In (to server) data transfer started.

CopyBoth

Copy In/Out data transfer started.

BadResponse

The server's response was not understood.

NonfatalError

A nonfatal error (a notice or warning) occurred.

FatalError

A fatal error occurred.

SingleTuple

The ResultOf contains a single result tuple from the current command. This status occurs only when single-row mode has been selected for the query.

PipelineSync

The ResultOf represents a synchronization point in pipeline mode, requested by pipelineSync. This status occurs only in pipeline mode.

PipelineAbort

The ResultOf represents a pipeline that has received an error from the server. getResult must be called repeatedly, and each time it will return this status code until the end of the current pipeline, at which point it will return PipelineSync and normal processing can resume.

data ConnStatus Source #

Status of a connection, as reported by PQstatus.

Constructors

ConnectionOk

The connection is ready.

ConnectionBad

The connection procedure has failed.

ConnectionStarted

Waiting for connection to be made.

ConnectionMade

Connection OK; waiting to send.

ConnectionAwaitingResponse

Waiting for a response from the server.

ConnectionAuthOk

Received authentication; waiting for backend start-up to finish.

ConnectionSetEnv

Negotiating environment-driven parameter settings.

ConnectionSSLStartup

Negotiating SSL encryption.

data TransactionStatus Source #

Current in-transaction status of the server, as reported by PQtransactionStatus.

Constructors

TransIdle

Currently idle.

TransActive

A command is in progress.

TransInTrans

Idle, within a transaction block.

TransInError

Idle, within a failed transaction.

TransUnknown

Connection is bad.

Instances

Instances details
Eq TransactionStatus Source # 
Instance details

Defined in Pqi

Ord TransactionStatus Source # 
Instance details

Defined in Pqi

Bounded TransactionStatus Source # 
Instance details

Defined in Pqi

Enum TransactionStatus Source # 
Instance details

Defined in Pqi

Show TransactionStatus Source # 
Instance details

Defined in Pqi

data PollingStatus Source #

Result of a non-blocking connection-polling step.

data PipelineStatus Source #

Pipeline-mode status of a connection, as reported by PQpipelineStatus.

Constructors

PipelineOn

The connection is in pipeline mode.

PipelineOff

The connection is not in pipeline mode.

PipelineAborted

The connection is in pipeline mode and an error occurred while processing the current pipeline.

data FieldCode Source #

Field identifier for the structured fields of an error report, as accepted by PQresultErrorField.

Instances

Instances details
Eq FieldCode Source # 
Instance details

Defined in Pqi

Ord FieldCode Source # 
Instance details

Defined in Pqi

Bounded FieldCode Source # 
Instance details

Defined in Pqi

Enum FieldCode Source # 
Instance details

Defined in Pqi

Show FieldCode Source # 
Instance details

Defined in Pqi

data Verbosity Source #

Verbosity of error reporting, as set by PQsetErrorVerbosity.

Instances

Instances details
Eq Verbosity Source # 
Instance details

Defined in Pqi

Ord Verbosity Source # 
Instance details

Defined in Pqi

Bounded Verbosity Source # 
Instance details

Defined in Pqi

Enum Verbosity Source # 
Instance details

Defined in Pqi

Show Verbosity Source # 
Instance details

Defined in Pqi

data FlushStatus Source #

Result of attempting to flush the output buffer in non-blocking mode.

data Notify Source #

An asynchronous notification, as returned by notifies.

Constructors

Notify 

Instances

Instances details
Eq Notify Source # 
Instance details

Defined in Pqi

Methods

(==) :: Notify -> Notify -> Bool #

(/=) :: Notify -> Notify -> Bool #

Ord Notify Source # 
Instance details

Defined in Pqi

Show Notify Source # 
Instance details

Defined in Pqi

Connection-independent helpers

unescapeBytea :: ByteString -> ByteString Source #

Convert the textual representation of a bytea value, as produced by the server, back into raw bytes. Both the modern \x hex format (lowercase x only) and the legacy escape format are accepted.

Malformed input is tolerated exactly the way PQunescapeBytea tolerates it: in hex format, characters that are not hex digits (including whitespace) are silently skipped, and a hex digit whose pair character is invalid is dropped; in escape format, an invalid escape simply drops the backslash, and an octal escape must start with 0..3. Input is treated as a C string: the first NUL byte terminates processing.