class Connection (View source)

The connection to the PostgreSQL server.

See the [General Usage](pq/Connection/: General Usage) page for an introduction on how to use this class.

Constants

PERSISTENT

(Re-)open a persistent connection.

ASYNC

If the connection is not already open, perform the connection attempt [asynchronously](pq/Connection/: Asynchronous Usage).

OK

Everything well; if a connection has been newly and synchronously created, the connection will always have this status right after creation.

BAD

Broken connection; consider pq\Connection::reset() or recreation.

STARTED

Waiting for connection to be made.

MADE

Connection okay; waiting to send.

AWAITING_RESPONSE

Waiting for a response from the server.

AUTH_OK

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

SSL_STARTUP

Negotiating SSL encryption.

SETENV

Negotiating environment-driven parameter settings.

TRANS_IDLE

No active transaction.

TRANS_ACTIVE

A transaction command is in progress.

TRANS_INTRANS

Idling in a valid transaction block.

TRANS_INERROR

Idling in a failed transaction block.

TRANS_UNKNOWN

Bad connection.

POLLING_FAILED

The connection procedure has failed.

POLLING_READING

Select for read-readiness.

POLLING_WRITING

Select for write-readiness.

POLLING_OK

The connection has been successfully made.

EVENT_NOTICE

Register the event handler for notices.

EVENT_RESULT

Register the event handler for any created results.

EVENT_RESET

Register the event handler for connection resets.

Properties

int read-only $status

A connection status constant value.

int read-only $transactionStatus

A transaction status constant value.

resource read-only $socket

The server socket resource.

bool read-only $busy

Whether the connection is busy with [asynchronous operations](pq/Connection/: Asynchronous Usage).

string read-only $errorMessage

Any error message on failure.

array read-only $eventHandlers

List of registered event handlers.

string $encoding

Connection character set.

bool $unbuffered

Whether to fetch [asynchronous](pq/Connection/: Asynchronous Usage) results in unbuffered mode, i.e. each row generates a distinct pq\Result.

bool $nonblocking

Whether to set the underlying socket nonblocking, useful for asynchronous handling of writes. See also pq\Connection::flush().

string read-only $db

The database name of the connection.

string read-only $user

The user name of the connection.

string read-only $pass

The password of the connection.

string read-only $host

The server host name of the connection.

string read-only $port

The port of the connection.

string read-only $options

The command-line options passed in the connection request.

int $defaultFetchType

Default fetch type for future pq\Result instances.

int $defaultAutoConvert

Default conversion bitmask for future pq\Result instances.

int $defaultTransactionIsolation

Default transaction isolation level for future pq\Transaction instances.

bool $defaultTransactionReadonly

Default transaction readonlyness for future pq\Transaction instances.

bool $defaultTransactionDeferrable

Default transaction deferrability for future pq\Transaction instances.

Methods

__construct(string $dsn = "", int $flags = 0)

Create a new PostgreSQL connection.

declare(string $name, int $flags, string $query)

Declare a cursor for a query.

declareAsync(string $name, int $flags, string $query)

[Asynchronously](pq/Connection/: Asynchronous Usage) declare a cursor for a query.

string|false
escapeBytea(string $binary)

Escape binary data for use within a query with the type bytea.

exec(string $query)

[Execute one or multiple SQL queries](pq/Connection/: Executing Queries) on the connection.

execAsync(string $query, callable $callback = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) [execute an SQL query](pq/Connection: Executing Queries) on the connection.

execParams(string $query, array $params, array $types = null)

[Execute an SQL query](pq/Connection: Executing Queries) with properly escaped parameters substituted.

execParamsAsync(string $query, array $params, array $types = null, callable $cb = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) [execute an SQL query](pq/Connection: Executing Queries) with properly escaped parameters substituted.

bool
flush()

Flush pending writes on the connection.

Result|null
getResult()

Fetch the result of an [asynchronous](pq/Connection/: Asynchronous Usage) query.

listen(string $channel, callable $listener)

Listen on $channel for notifications.

listenAsync(string $channel, callable $listener)

[Asynchronously](pq/Connection/: Asynchronous Usage) start listening on $channel for notifications.

notify(string $channel, string $message)

Notify all listeners on $channel with $message.

notifyAsync(string $channel, string $message)

[Asynchronously](pq/Connection/: Asynchronous Usage) start notifying all listeners on $channel with $message.

bool
off(string $event)

Stops listening for an event type.

int
on(string $event, callable $callback)

Listen for an event.

int
poll()

Poll an [asynchronously](pq/Connection/: Asynchronous Usage) operating connection.

prepare(string $name, string $query, array $types = null)

Prepare a named statement for later execution with pq\Statement::execute().

prepareAsync(string $name, string $query, array $types = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) prepare a named statement for later execution with pq\Statement::exec().

string|false
quote(string $payload)

Quote a string for safe use in a query.

string|false
quoteName(string $name)

Quote an identifier for safe usage as name.

reset()

Attempt to reset a possibly broken connection to a working state.

resetAsync()

[Asynchronously](pq/Connection/: Asynchronous Usage) reset a possibly broken connection to a working state.

setConverter(Converter $converter)

Set a data type converter.

startTransaction(int $isolation = \pq\Transaction::READ_COMMITTED, bool $readonly = false, bool $deferrable = false)

Begin a transaction.

startTransactionAsync(int $isolation = \pq\Transaction::READ_COMMITTED, bool $readonly = false, bool $deferrable = false)

[Asynchronously](pq/Connection/: Asynchronous Usage) begin a transaction.

bool
trace(resource $stream = null)

Trace protocol communication with the server.

string|false
unescapeBytea(string $bytea)

Unescape bytea data retrieved from the server.

unlisten(string $channel)

Stop listening for notifications on channel $channel.

unlistenAsync(string $channel)

[Asynchronously](pq/Connection/: Asynchronous Usage) stop listening for notifications on channel $channel.

unsetConverter(Converter $converter)

Stop applying a data type converter.

Details

__construct(string $dsn = "", int $flags = 0)

Create a new PostgreSQL connection.

See also [General Usage](pq/Connection/: General Usage).

Parameters

string $dsn

A connection string as described in the PostgreSQL documentation.

int $flags

See connection flag constants.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

Cursor declare(string $name, int $flags, string $query)

Declare a cursor for a query.

Parameters

string $name

The identifying name of the cursor.

int $flags

Any combination of pq\Cursor constants.

string $query

The query for which to open a cursor.

Return Value

Cursor

an open cursor instance.

Exceptions

InvalidArgumentException
RuntimeException
BadMethodCallException

Cursor declareAsync(string $name, int $flags, string $query)

[Asynchronously](pq/Connection/: Asynchronous Usage) declare a cursor for a query.

NOTE: If pq\Connection::$unbuffered is TRUE, each call to pq\Connection::getResult() will generate a distinct pq\Result containing exactly one row.

Parameters

string $name

The identifying name of the cursor.

int $flags

Any combination of pq\Cursor constants.

string $query

The query for which to open a cursor.

Return Value

Cursor

an open cursor instance.

Exceptions

InvalidArgumentException
RuntimeException
BadMethodCallException

string|false escapeBytea(string $binary)

Escape binary data for use within a query with the type bytea.

NOTE: The result is not wrapped in single quotes.

Parameters

string $binary

The binary data to escape.

Return Value

string|false

string the escaped binary data. or FALSE if escaping fails.

Exceptions

BadMethodCallException

Result exec(string $query)

[Execute one or multiple SQL queries](pq/Connection/: Executing Queries) on the connection.

NOTE: Only the last result will be returned, if the query string contains more than one SQL query.

Parameters

string $query

The queries to send to the server, separated by semi-colon.

Return Value

Result

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException
DomainException

execAsync(string $query, callable $callback = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) [execute an SQL query](pq/Connection: Executing Queries) on the connection.

NOTE: If pq\Connection::$unbuffered is TRUE, each call to pq\Connection::getResult() will generate a distinct pq\Result containing exactly one row.

Parameters

string $query

The query to send to the server.

callable $callback

as function(pq\Result $res) The callback to execute when the query finishes.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

Result execParams(string $query, array $params, array $types = null)

[Execute an SQL query](pq/Connection: Executing Queries) with properly escaped parameters substituted.

Parameters

string $query

The query to execute.

array $params

The parameter list to substitute.

array $types

Corresponding list of type OIDs for the parameters.

Return Value

Result

Exceptions

InvalidArgumentException
RuntimeException
DomainException

execParamsAsync(string $query, array $params, array $types = null, callable $cb = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) [execute an SQL query](pq/Connection: Executing Queries) with properly escaped parameters substituted.

NOTE: If pq\Connection::$unbuffered is TRUE, each call to pq\Connection::getResult() will generate a distinct pq\Result containing exactly one row.

Parameters

string $query

The query to execute.

array $params

The parameter list to substitute.

array $types

Corresponding list of type OIDs for the parameters.

callable $cb

as function(\pq\Result $res) : void Result handler callback.

Exceptions

InvalidArgumentException
RuntimeException
BadMethodCallException

bool flush()

Flush pending writes on the connection.

Call after sending any command or data on a nonblocking connection.

If it returns FALSE, wait for the socket to become read or write-ready. If it becomes write-ready, call pq\Connection::flush() again. If it becomes read-ready, call pq\Connection::poll(), then call pq\Connection::flush() again. Repeat until pq\Connection::flush() returns TRUE.

NOTE: This method was added in v1.1.0, resp. v2.1.0.

Return Value

bool

whether everything has been flushed.

Exceptions

InvalidArgumentException
RuntimeException

Result|null getResult()

Fetch the result of an [asynchronous](pq/Connection/: Asynchronous Usage) query.

If the query hasn't finished yet, the call will block until the result is available.

Return Value

Result|null

NULL if there has not been a query or \pq\Result when the query has finished

Exceptions

InvalidArgumentException
BadMethodCallException

listen(string $channel, callable $listener)

Listen on $channel for notifications.

See pq\Connection::unlisten().

Parameters

string $channel

The channel to listen on.

callable $listener

as function(string $channel, string $message, int $pid) A callback automatically called whenever a notification on $channel arrives.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

listenAsync(string $channel, callable $listener)

[Asynchronously](pq/Connection/: Asynchronous Usage) start listening on $channel for notifications.

See pq\Connection::listen().

Parameters

string $channel

The channel to listen on.

callable $listener

as function(string $channel, string $message, int $pid) A callback automatically called whenever a notification on $channel arrives.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

notify(string $channel, string $message)

Notify all listeners on $channel with $message.

Parameters

string $channel

The channel to notify.

string $message

The message to send.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

notifyAsync(string $channel, string $message)

[Asynchronously](pq/Connection/: Asynchronous Usage) start notifying all listeners on $channel with $message.

Parameters

string $channel

The channel to notify.

string $message

The message to send.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

bool off(string $event)

Stops listening for an event type.

Parameters

string $event

Any pq\Connection::EVENT_*.

Return Value

bool success.

Exceptions

InvalidArgumentException
BadMethodCallException

int on(string $event, callable $callback)

Listen for an event.

Parameters

string $event

Any pq\Connection::EVENT_*.

callable $callback

as function(pq\Connection $c[, pq\Result $r) The callback to invoke on event.

Return Value

int

number of previously attached event listeners.

Exceptions

InvalidArgumentException
BadMethodCallException

int poll()

Poll an [asynchronously](pq/Connection/: Asynchronous Usage) operating connection.

See pq\Connection::resetAsync() for an usage example.

Return Value

int

pq\Connection::POLLING_* constant

Exceptions

InvalidArgumentException
RuntimeException
BadMethodCallException

Statement prepare(string $name, string $query, array $types = null)

Prepare a named statement for later execution with pq\Statement::execute().

Parameters

string $name

The identifying name of the prepared statement.

string $query

The query to prepare.

array $types

An array of type OIDs for the substitution parameters.

Return Value

Statement

a prepared statement instance.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

Statement prepareAsync(string $name, string $query, array $types = null)

[Asynchronously](pq/Connection/: Asynchronous Usage) prepare a named statement for later execution with pq\Statement::exec().

NOTE: If pq\Connection::$unbuffered is TRUE, each call to pq\Connection::getResult() will generate a distinct pq\Result containing exactly one row.

Parameters

string $name

The identifying name of the prepared statement.

string $query

The query to prepare.

array $types

An array of type OIDs for the substitution parameters.

Return Value

Statement

a prepared statement instance.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

string|false quote(string $payload)

Quote a string for safe use in a query.

The result is truncated at any zero byte and wrapped in single quotes.

NOTE: Beware of matching character encodings.

Parameters

string $payload

The payload to quote for use in a query.

Return Value

string|false

string a single-quote wrapped string safe for literal use in a query. or FALSE if quoting fails.

Exceptions

BadMethodCallException

string|false quoteName(string $name)

Quote an identifier for safe usage as name.

NOTE: Beware of case-sensitivity.

Parameters

string $name

The name to quote.

Return Value

string|false

string the quoted identifier. or FALSE if quoting fails.

Exceptions

BadMethodCallException

reset()

Attempt to reset a possibly broken connection to a working state.

resetAsync()

[Asynchronously](pq/Connection/: Asynchronous Usage) reset a possibly broken connection to a working state.

setConverter(Converter $converter)

Set a data type converter.

Parameters

Converter $converter

An instance implementing pq\Converter.

Exceptions

InvalidArgumentException
BadMethodCallException

Transaction startTransaction(int $isolation = \pq\Transaction::READ_COMMITTED, bool $readonly = false, bool $deferrable = false)

Begin a transaction.

Parameters

int $isolation

Any pq\Transaction isolation level constant (defaults to pq\Connection::$defaultTransactionIsolation).

bool $readonly

Whether the transaction executes only reads (defaults to pq\Connection::$defaultTransactionReadonly).

bool $deferrable

Whether the transaction is deferrable (defaults to pq\Connection::$defaultTransactionDeferrable).

NOTE: A transaction can only be deferrable if it also is readonly and serializable. See the official PostgreSQL documentation for further information.

Return Value

Transaction

a begun transaction instance.

Exceptions

BadMethodCallException
RuntimeException
InvalidArgumentException

Transaction startTransactionAsync(int $isolation = \pq\Transaction::READ_COMMITTED, bool $readonly = false, bool $deferrable = false)

[Asynchronously](pq/Connection/: Asynchronous Usage) begin a transaction.

Parameters

int $isolation

Any pq\Transaction isolation level constant (defaults to pq\Connection::$defaultTransactionIsolation).

bool $readonly

Whether the transaction executes only reads (defaults to pq\Connection::$defaultTransactionReadonly).

bool $deferrable

Whether the transaction is deferrable (defaults to pq\Connection::$defaultTransactionDeferrable).

NOTE: A transaction can only be deferrable if it also is readonly and serializable. See the official PostgreSQL documentation for further information.

Return Value

Transaction

an asynchronously begun transaction instance.

Exceptions

BadMethodCallException
RuntimeException
InvalidArgumentException

bool trace(resource $stream = null)

Trace protocol communication with the server.

NOTE: Calling pq\Connection::trace() without argument or NULL stops tracing.

Parameters

resource $stream

The resource to which the protocol trace will be output. (The stream must be castable to STDIO).

Return Value

bool success.

Exceptions

BadMethodCallException

string|false unescapeBytea(string $bytea)

Unescape bytea data retrieved from the server.

Parameters

string $bytea

Bytea data retrieved from the server.

Return Value

string|false

string unescaped binary data. or FALSE if unescaping fails.

Exceptions

BadMethodCallException

unlisten(string $channel)

Stop listening for notifications on channel $channel.

See pq\Connection::listen().

Parameters

string $channel

The name of a channel which is currently listened on.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

unlistenAsync(string $channel)

[Asynchronously](pq/Connection/: Asynchronous Usage) stop listening for notifications on channel $channel.

See pq\Connection::unlisten() and pq\Connection::listenAsync().

Parameters

string $channel

The name of a channel which is currently listened on.

Exceptions

InvalidArgumentException
BadMethodCallException
RuntimeException

unsetConverter(Converter $converter)

Stop applying a data type converter.

Parameters

Converter $converter

A converter previously set with pq\Connection::setConverter().

Exceptions

InvalidArgumentException
BadMethodCallException