GitHub

PgConnection

API reference for PgConnection.

A connected, authenticated PostgreSQL session (or a pinned view of one).

Attributes

AttributeTypeDescription
configPgConnectionConfig
process_idint

The backend's process id.

basePgConnection

The unpinned connection (a pool's item).

is_deadbool

Whether the session has failed for good (or was closed).

needs_retirebool

Whether a pool should replace the session: it is dead, or a cancel was not confirmed.

pinEffect[PgConnection, Never, Scope]

Reserve the session until the scope closes; statements through the connection given skip the line, those through this one wait. Pinning a pinned connection gives it back. Once released, the pinned connection fails every statement; releasing it while a statement, a stream or a listener is still open closes the session.

interruptEffect[None]

Ask PostgreSQL to cancel the running statement. Never fails; does nothing through a released pin.

Functions

__init__

__init__(shared, lease=None) -> None
ParameterTypeDescription
shared_Shared
lease_Lease | None = None
def __init__(self, shared: _Shared, lease: _Lease | None = None) -> None:
    self._shared = shared
    self._lease = lease

on_retire

on_retire(hook) -> None

Run hook once the session dies (a pool replaces it).

ParameterTypeDescription
hookCallable[[], Effect[None]]
def on_retire(self, hook: Callable[[], Effect[None]]) -> None:
    """Run ``hook`` once the session dies (a pool replaces it)."""
    self._shared.retire_hooks.append(hook)

query

query(sql, params=(), prepare=True) -> Effect[Result, SqlError]

Run sql with params bound to $1, $2, ...; rows by column name. prepare=False skips the prepared statements.

ParameterTypeDescription
sqlstr
paramsSequence[object] = ()
preparebool = True

Returns Effect[Result, SqlError]

def query(
    self, sql: str, params: Sequence[object] = (), prepare: bool = True
) -> Effect[Result, SqlError]:
    """Run ``sql`` with ``params`` bound to ``$1``, ``$2``, ...; rows by
    column name. ``prepare=False`` skips the prepared statements."""
    values = tuple(params)
    return self._statement(lambda session: session.query(sql, values, prepare))

query_values

query_values(sql, params=(), prepare=True) -> Effect[list[tuple[Any, ...]], SqlError]

query, with rows as tuples in column order.

ParameterTypeDescription
sqlstr
paramsSequence[object] = ()
preparebool = True

Returns Effect[list[tuple[Any, ...]], SqlError]

def query_values(
    self, sql: str, params: Sequence[object] = (), prepare: bool = True
) -> Effect[list[tuple[Any, ...]], SqlError]:
    """``query``, with rows as tuples in column order."""
    values = tuple(params)
    return self._statement(lambda session: session.query_values(sql, values, prepare))

stream

stream(sql, params=()) -> Stream[Row, SqlError]

The rows of sql, read as the stream is pulled. The session is pinned while the stream runs; ending it early cancels the statement.

ParameterTypeDescription
sqlstr
paramsSequence[object] = ()

Returns Stream[Row, SqlError]

def stream(self, sql: str, params: Sequence[object] = ()) -> Stream[Row, SqlError]:
    """The rows of ``sql``, read as the stream is pulled. The session is
    pinned while the stream runs; ending it early cancels the
    statement."""
    from pyfect import stream as stream_module

    values = tuple(params)

    def opened(pinned: PgConnection) -> Effect[Stream[Row, SqlError], SqlError, Scope]:
        return pinned._open_stream(sql, values)

    return stream_module.unwrap(self.pin.flat_map(opened))

listen

listen(channel, *, capacity=DEFAULT_LISTEN_CAPACITY) -> Effect[Dequeue[Notification, SqlError], SqlError, Scope]

Listen on channel: a queue of its notifications, once PostgreSQL confirmed LISTEN. The session stays pinned until the scope closes, which runs UNLISTEN (closing a session that does not answer within five seconds) and shuts the queue down, interrupting its takers. If the session fails, the queue fails with its error. The queue holds at most capacity notifications not yet taken; one more fails it (after those) with an error saying the listener fell behind. The scope must close before the client's layer does: closing the pool waits for the pinned session.

ParameterTypeDescription
channelstr
capacityint = DEFAULT_LISTEN_CAPACITY

Returns Effect[Dequeue[Notification, SqlError], SqlError, Scope]

def listen(
    self, channel: str, *, capacity: int = DEFAULT_LISTEN_CAPACITY
) -> Effect[Dequeue[Notification, SqlError], SqlError, Scope]:
    """Listen on ``channel``: a queue of its notifications, once
    PostgreSQL confirmed ``LISTEN``. The session stays pinned until the
    scope closes, which runs ``UNLISTEN`` (closing a session that does
    not answer within five seconds) and shuts the queue down,
    interrupting its takers. If the session fails, the queue fails with
    its error. The queue holds at most ``capacity`` notifications not
    yet taken; one more fails it (after those) with an error saying the
    listener fell behind. The scope must close before the client's
    layer does: closing the pool waits for the pinned session."""
    check_capacity(capacity)
    error = validate_channel_name(channel, "listen")
    if error is not None:
        return fail(error)
    connection = self

    def body(restore: Restore) -> Effect[Dequeue[Notification, SqlError], SqlError, Scope]:
        def in_scope(parent: CloseableScope) -> Effect[Any, SqlError, Scope]:
            return parent.fork().flat_map(
                lambda scope: restore(
                    connection._listen_in(channel, capacity, scope)
                ).tap_cause(lambda cause: scope.close(Failure(cause)))
            )

        return Scope().flat_map(in_scope)

    return uninterruptible_mask(body)