Skip to content

Python API reference

Use this page to look up exact signatures, defaults, return types, and exceptions. Begin with the Python quickstart or the Python overview if you are choosing an entry point.

Looking for Section
connect, Database, Connection, and cursors Database objects
Large results, requests, COPY, and prepared statements Requests and streaming
Event-loop wrappers Asyncio
Checkpoint, backup, events, and extensions Management and events
Codecs and Arrow Values and adapters
DB-API errors Exceptions

The remainder of this page is generated from the frozen Python API inventory, source type annotations, and docstrings. A documentation build fails when a public export is missing from the inventory or reference grouping.

Product metadata

Runtime identity, capability discovery, and DB-API module metadata.

Name Meaning
postgamma.__version__ Python package version.
postgamma.apilevel PEP 249 API level, currently 2.0.
postgamma.threadsafety PEP 249 thread-safety level, currently 2.
postgamma.paramstyle PEP 249 cursor parameter style, currently numeric.

library_info

library_info() -> dict[str, object]

Return the loaded native library identity and capability mask.

capabilities

capabilities() -> Capability

Return the optional capabilities advertised by the loaded kernel.

Capability

Bases: IntFlag

Optional capabilities advertised by the loaded PostGamma kernel.

PREPARED_STATEMENTS class-attribute instance-attribute

PREPARED_STATEMENTS = _native.CAP_PREPARED_STATEMENTS

CHUNKED_RESULTS class-attribute instance-attribute

CHUNKED_RESULTS = _native.CAP_CHUNKED_RESULTS

COPY_IN class-attribute instance-attribute

COPY_IN = _native.CAP_COPY_IN

COPY_OUT class-attribute instance-attribute

COPY_OUT = _native.CAP_COPY_OUT

ARROW_C_DATA class-attribute instance-attribute

ARROW_C_DATA = _native.CAP_ARROW_C_DATA

NOTIFICATIONS class-attribute instance-attribute

NOTIFICATIONS = _native.CAP_NOTIFICATIONS

REQUEST_NOTICES class-attribute instance-attribute

REQUEST_NOTICES = _native.CAP_REQUEST_NOTICES

STATUS_TELEMETRY class-attribute instance-attribute

STATUS_TELEMETRY = _native.CAP_STATUS_TELEMETRY

INSTANCE_EVENTS class-attribute instance-attribute

INSTANCE_EVENTS = _native.CAP_INSTANCE_EVENTS

MANAGEMENT_OPERATIONS class-attribute instance-attribute

MANAGEMENT_OPERATIONS = _native.CAP_MANAGEMENT_OPERATIONS

MULTIPLE_INSTANCES class-attribute instance-attribute

MULTIPLE_INSTANCES = _native.CAP_MULTIPLE_INSTANCES

NATIVE_EXTENSION_LOADING class-attribute instance-attribute

NATIVE_EXTENSION_LOADING = (
    _native.CAP_NATIVE_EXTENSION_LOADING
)

LOGICAL_BACKUP class-attribute instance-attribute

LOGICAL_BACKUP = _native.CAP_LOGICAL_BACKUP

LOGICAL_RESTORE class-attribute instance-attribute

LOGICAL_RESTORE = _native.CAP_LOGICAL_RESTORE

PHYSICAL_BACKUP class-attribute instance-attribute

PHYSICAL_BACKUP = _native.CAP_PHYSICAL_BACKUP

MAINTENANCE class-attribute instance-attribute

MAINTENANCE = _native.CAP_MAINTENANCE

BUNDLED_EXTENSIONS class-attribute instance-attribute

BUNDLED_EXTENSIONS = _native.CAP_BUNDLED_EXTENSIONS

Database objects

Lazy instances, logical sessions, materialized results, and DB-API cursors.

Database

Database(
    path: str | PathLike[str],
    *,
    mode: OpenMode | str = OpenMode.OPEN_OR_CREATE,
    settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    worker_count: int = 4,
    timeout: float | None = _DEFAULT_TIMEOUT_SECONDS,
    resource_root: str | PathLike[str] | None = None,
    executable_path: str | PathLike[str] | None = None,
    result_buffer_limit: int = 0,
    maximum_value_size: int = 0,
    event_queue_capacity: int = 64
)

A lazy in-process PostgreSQL instance backed by one cluster directory.

path names the persistent PostgreSQL cluster directory, not a DSN, server address, SQL database name, or SQLite-style file. The directory is initialized on first open when mode permits creation and it does not already contain a compatible cluster. Construction alone does not open it.

Parameters:

Name Type Description Default
path str | PathLike[str]

Persistent cluster directory. A relative path is resolved when the instance first opens; its parent directory must already exist.

required
mode OpenMode | str

Whether to open or create, require an existing cluster, or create a new cluster only when the final path does not exist.

OPEN_OR_CREATE
settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Instance/startup PostgreSQL settings as a mapping or iterable of name/value pairs. Values are converted to strings.

None
worker_count int

Number of carrier workers available to logical sessions. The native PostgreSQL 19 kernel requires at least two.

4
timeout float | None

Default operation deadline in seconds, or None for no deadline.

_DEFAULT_TIMEOUT_SECONDS
resource_root str | PathLike[str] | None

Advanced override for the bundled PostgreSQL resource pack. Installed wheels resolve this automatically.

None
executable_path str | PathLike[str] | None

Advanced PostgreSQL executable-identity override. Installed wheels resolve it to bin/postgres in their private resource pack; the embedded lifecycle does not launch it.

None
result_buffer_limit int

Maximum materialized result bytes, or zero for the embedded default.

0
maximum_value_size int

Maximum individual value bytes, or zero for the embedded default.

0
event_queue_capacity int

Maximum number of routed instance events.

64
Note

Entering the context, calling :meth:open, opening a connection, or executing through the database triggers the first open. A closed Database object cannot be reopened; construct a new object for the same persistent path.

path instance-attribute

path = os.fspath(path)

mode instance-attribute

mode = OpenMode.parse(mode)

settings instance-attribute

settings = _normalize_settings(settings)

worker_count instance-attribute

worker_count = _positive_int(worker_count, 'worker_count')

timeout instance-attribute

timeout = _normalize_timeout(timeout)

resource_root instance-attribute

resource_root = (
    os.fspath(resource_root)
    if resource_root is not None
    else None
)

executable_path instance-attribute

executable_path = (
    os.fspath(executable_path)
    if executable_path is not None
    else None
)

result_buffer_limit instance-attribute

result_buffer_limit = _nonnegative_int(
    result_buffer_limit, "result_buffer_limit"
)

maximum_value_size instance-attribute

maximum_value_size = _nonnegative_int(
    maximum_value_size, "maximum_value_size"
)

event_queue_capacity instance-attribute

event_queue_capacity = _positive_int(
    event_queue_capacity, "event_queue_capacity"
)

_handle instance-attribute

_handle: Any | None = None

_owner_pid instance-attribute

_owner_pid: int | None = None

_closed instance-attribute

_closed = False

_lock instance-attribute

_lock = threading.RLock()

_connections instance-attribute

_connections: WeakSet[Connection] = weakref.WeakSet()

_operations instance-attribute

_operations: WeakSet[Any] = weakref.WeakSet()

_event_handlers instance-attribute

_event_handlers: dict[int | None, list[Any]] = {}

_request_event_handlers instance-attribute

_request_event_handlers: dict[int, list[Any]] = {}

_event_backlog instance-attribute

_event_backlog: deque[Any] = deque()

closed property

closed: bool

Return whether this database object is permanently closed.

opened property

opened: bool

Return whether the lazy native instance has been opened.

waitable property

waitable: int

Return the level-triggered instance event descriptor.

open

open() -> Self

Create or open the cluster and return this database object.

With the default mode="open_or_create", a missing final directory is initialized in a private staging directory and published atomically. A compatible existing cluster is opened without replacing data.

Returns:

Type Description
Self

This database object after the embedded instance is ready.

Raises:

Type Description
OperationalError

The path is missing when creation is disabled, is nonempty but incompatible, is already owned, or cannot be initialized or opened.

ForkedProcessError

The object was inherited across fork().

_ensure_open

_ensure_open() -> Any

connect

connect(
    *,
    user: str = "postgamma",
    database: str = "postgres",
    application_name: str = "postgamma-python",
    settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    autocommit: bool = False,
    timeout: float | None = None
) -> Connection

Open one logical PostgreSQL session owned by this database.

Parameters:

Name Type Description Default
user str

Existing PostgreSQL role. New roles are not created implicitly.

'postgamma'
database str

Existing SQL database inside the cluster. This is not the cluster-directory path.

'postgres'
application_name str

Value reported by PostgreSQL for this session.

'postgamma-python'
settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Session-local PostgreSQL settings.

None
autocommit bool

Commit every statement independently when true. When false, ordinary statements begin an implicit transaction.

False
timeout float | None

Connection operation deadline in seconds. None uses the database default rather than disabling the deadline.

None

Returns:

Type Description
Connection

A logical connection. Closing it leaves this shared database

Connection

instance open.

Raises:

Type Description
DatabaseError

PostgreSQL rejects the SQL database, role, or session options.

OperationalError

The instance cannot start or accept the session.

execute

execute(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Result

Execute one autocommitted statement on a temporary connection.

telemetry

telemetry() -> dict[str, int]

Return a synchronized executor, request, and event snapshot.

next_event

next_event(*, timeout: float | None = 0) -> Any | None

Return the next owned log, notice, notification, or overflow event.

add_event_handler

add_event_handler(
    handler: Any, *, kind: int | None = None
) -> None

Register a host-thread event callback, optionally for one event kind.

remove_event_handler

remove_event_handler(
    handler: Any, *, kind: int | None = None
) -> None

Remove a previously registered event callback.

dispatch_events

dispatch_events(*, maximum: int | None = None) -> int

Drain queued events and invoke callbacks on the calling host thread.

checkpoint

checkpoint(
    *, wait: bool = True, timeout: float | None = None
) -> Any

Start an in-process checkpoint and optionally wait for completion.

maintenance

maintenance(
    kind: Any = "vacuum_analyze",
    *,
    database: str | None = None,
    user: str | None = None,
    wait: bool = True,
    timeout: float | None = None
) -> Any

Run VACUUM, ANALYZE, VACUUM ANALYZE, or database REINDEX.

logical_dump

logical_dump(
    stream: Any,
    *,
    flags: int = 0,
    database: str | None = None,
    user: str | None = None,
    channel_capacity: int = 256 * 1024,
    progress_quantum: int = 64 * 1024,
    wait: bool = True,
    timeout: float | None = None
) -> Any

Write an in-process PostgreSQL logical archive to a binary stream.

logical_restore

logical_restore(
    stream: Any,
    *,
    flags: int = 0,
    database: str | None = None,
    user: str | None = None,
    channel_capacity: int = 256 * 1024,
    progress_quantum: int = 64 * 1024,
    wait: bool = True,
    timeout: float | None = None
) -> Any

Restore an in-process PostgreSQL logical archive from a binary stream.

bundled_extensions

bundled_extensions() -> tuple[Any, ...]

Return metadata for extensions statically reviewed into this build.

as_async

as_async() -> Any

Return an asyncio facade over this lazy database object.

close

close(
    *, mode: str = "fast", timeout: float | None = None
) -> None

Close the instance.

A failed or timed-out close leaves the native handle open so the same Database may retry close() with another timeout or mode.

close_before_fork

close_before_fork(*, timeout: float | None = None) -> None

Quiesce and close the instance before the host calls fork().

__enter__

__enter__() -> Self

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

OpenMode

Bases: str, Enum

Explicit policy for opening a persistent cluster path.

OPEN_OR_CREATE class-attribute instance-attribute

OPEN_OR_CREATE = 'open_or_create'

OPEN_EXISTING class-attribute instance-attribute

OPEN_EXISTING = 'open_existing'

CREATE_NEW class-attribute instance-attribute

CREATE_NEW = 'create_new'

parse classmethod

parse(value: OpenMode | str) -> OpenMode

Normalize an enum member or its public string spelling.

__str__

__str__() -> str

Connection

Connection(
    owner: Database,
    handle: Any,
    *,
    autocommit: bool,
    timeout: float | None,
    implicit_release: Any | None
)

One logical PostgreSQL session over the in-memory protocol.

A connection preserves PostgreSQL transaction state, temporary objects, prepared statements, session settings, and notifications across calls. Operations on one connection are serialized; different connections owned by one database may execute concurrently.

Connections returned by top-level :func:postgamma.connect lease a shared process-local Database for their canonical cluster path. The last such connection closes the implicit instance. A connection returned by :meth:Database.connect closes only its logical session.

_database instance-attribute

_database = owner

_handle instance-attribute

_handle = handle

_autocommit instance-attribute

_autocommit = bool(autocommit)

timeout instance-attribute

timeout = timeout

_closed instance-attribute

_closed = False

_close_pending instance-attribute

_close_pending = False

_implicit_release instance-attribute

_implicit_release = implicit_release

_transaction_scope_active instance-attribute

_transaction_scope_active = False

_operation_lock instance-attribute

_operation_lock = threading.RLock()

_request_gate instance-attribute

_request_gate = threading.Lock()

_cursors instance-attribute

_cursors: WeakSet[Cursor] = weakref.WeakSet()

_requests instance-attribute

_requests: WeakSet[Any] = weakref.WeakSet()

_statements instance-attribute

_statements: WeakSet[Any] = weakref.WeakSet()

closed property

closed: bool

Return whether this logical connection is closed.

database property

database: Database

Return the database instance that owns this connection.

autocommit property writable

autocommit: bool

Return whether statements commit without an implicit transaction.

transaction_status property

transaction_status: int

Return the current PostgreSQL transaction-status constant.

id property

id: int

Return the stable PostGamma logical connection identity.

status property

status: Any

Return transaction, pinning, carrier, and request scheduling state.

parameter_status

parameter_status(name: str) -> str | None

Return a PostgreSQL parameter-status value by name.

_require_open

_require_open() -> None

_native_execute

_native_execute(
    sql: str,
    parameters: Sequence[Any] | None,
    timeout: float | None,
) -> Result

execute

execute(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Result

Execute one statement and return a materialized result.

Use PostgreSQL extended-protocol markers such as $1 and $2. DB-API cursor markers such as :1 apply only to :class:Cursor.

Parameters:

Name Type Description Default
sql str

One PostgreSQL statement.

required
parameters Sequence[Any] | None

Values for positional markers, or None.

None
timeout float | None

Statement deadline in seconds. None uses the connection default.

None

Returns:

Type Description
Result

A Python-owned materialized result positioned before its first row.

Raises:

Type Description
QueryTimeoutError

The host-side deadline expires.

QueryCanceledError

This request is canceled.

DatabaseError

PostgreSQL rejects or cannot execute the statement.

stream

stream(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    chunk_rows: int = 1024,
    timeout: float | None = None,
    result_buffer_limit: int = 0,
    on_notice: Any | None = None
) -> Any

Execute a query as bounded, caller-driven row chunks.

execute_script

execute_script(
    sql: str, *, timeout: float | None = None
) -> tuple[Result, ...]

Execute simple-protocol SQL and return every ordered result.

prepare

prepare(
    sql: str,
    *,
    parameter_type_oids: Sequence[int] | None = None
) -> Any

Create a reusable extended-protocol prepared statement.

copy

copy(sql: str, *, timeout: float | None = None) -> Any

Start COPY FROM STDIN or COPY TO STDOUT and return a byte-stream object.

copy_from

copy_from(
    sql: str,
    source: Any,
    *,
    chunk_size: int = 64 * 1024,
    timeout: float | None = None
) -> Result

Copy bytes from a readable object and return PostgreSQL's command result.

copy_to

copy_to(
    sql: str,
    target: Any,
    *,
    chunk_size: int = 64 * 1024,
    timeout: float | None = None
) -> Result

Copy bytes to a writable object and return PostgreSQL's command result.

execute_arrow

execute_arrow(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Any

Execute a query and expose its struct array through Arrow C Data.

as_async

as_async() -> Any

Return an asyncio facade over this connection.

_begin_transaction_if_needed

_begin_transaction_if_needed(
    sql: str, timeout: float | None
) -> None

cursor

cursor() -> Cursor

Create a PEP 249 cursor owned by this connection.

transaction

transaction() -> _TransactionContext

Return a transaction scope that commits or rolls back without closing.

The connection must be idle when the scope is entered. Nested scopes are rejected rather than silently changing transaction ownership.

_claim_transaction_scope

_claim_transaction_scope() -> None

_enter_transaction_scope

_enter_transaction_scope() -> None

_release_transaction_scope

_release_transaction_scope() -> None

_complete_transaction_scope

_complete_transaction_scope(*, commit: bool) -> None

commit

commit() -> None

Commit the active transaction, if any.

rollback

rollback() -> None

Roll back the active transaction, if any.

cancel

cancel() -> bool

Request cancellation of the active operation, if one exists.

close

close(*, timeout: float | None = None) -> None

Close this session and its cursors.

Once native close starts, this connection accepts only further close attempts. A failed or timed-out attempt preserves its handle for that cleanup; closed becomes true only after native close succeeds.

__enter__

__enter__() -> Self

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

Cursor

Cursor(connection: Connection)

PEP 249 cursor backed by materialized PostGamma results.

connection instance-attribute

connection = connection

arraysize instance-attribute

arraysize = 1

_result instance-attribute

_result: Result | None = None

_closed instance-attribute

_closed = False

rowcount instance-attribute

rowcount = -1

lastrowid instance-attribute

lastrowid = None

description instance-attribute

description: tuple[tuple[Any, ...], ...] | None = None

closed property

closed: bool

Return whether this cursor is closed.

_require_open

_require_open() -> None

execute

execute(
    operation: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Self

Execute one numeric-parameter DB-API statement and return this cursor.

executemany

executemany(
    operation: str,
    seq_of_parameters: Iterable[Sequence[Any]],
) -> Self

Execute one statement for each supplied parameter sequence.

callproc

callproc(
    procedure_name: str,
    parameters: Sequence[Any] | None = None,
) -> None

Raise NotSupportedError because procedure calls are unavailable.

fetchone

fetchone() -> tuple[Any, ...] | None

Return the next tuple row, or None when exhausted.

fetchmany

fetchmany(size: int | None = None) -> list[tuple[Any, ...]]

Return up to size rows, defaulting to arraysize.

fetchall

fetchall() -> list[tuple[Any, ...]]

Return every remaining tuple row.

close

close() -> None

Close this cursor without closing its connection.

nextset

nextset() -> None

Return None because the cursor has no later result set.

setinputsizes

setinputsizes(sizes: Any) -> None

Accept the optional PEP 249 input-size hint as a no-op.

setoutputsize

setoutputsize(size: Any, column: Any = None) -> None

Accept the optional PEP 249 output-size hint as a no-op.

__iter__

__iter__() -> Self

__next__

__next__() -> tuple[Any, ...]

__enter__

__enter__() -> Self

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

Result

Result(native: Mapping[str, Any])

A materialized, Python-owned PostgreSQL result.

__slots__ class-attribute instance-attribute

__slots__ = (
    "kind",
    "command_status",
    "columns",
    "_rows",
    "_position",
    "rowcount",
)

kind instance-attribute

kind = int(native['kind'])

command_status instance-attribute

command_status = native['command_status']

columns instance-attribute

columns = tuple(
    Column(*column) for column in native["columns"]
)

_rows instance-attribute

_rows = tuple(
    tuple(
        (
            None
            if value is None
            else decode_value(value[0], value[1], value[2])
        )
        for value in row
    )
    for row in native["rows"]
)

_position instance-attribute

_position = 0

rowcount instance-attribute

rowcount = self._derive_rowcount()

description property

description: tuple[tuple[Any, ...], ...] | None

Return PEP 249 column descriptions, or None without columns.

rows property

rows: tuple[tuple[Any, ...], ...]

Return all rows owned by this materialized result.

_derive_rowcount

_derive_rowcount() -> int

fetchone

fetchone() -> tuple[Any, ...] | None

Return the next row, or None after the result is exhausted.

fetchmany

fetchmany(size: int = 1) -> list[tuple[Any, ...]]

Return up to size rows from the current result position.

fetchall

fetchall() -> list[tuple[Any, ...]]

Return every remaining row and exhaust the result.

__iter__

__iter__() -> Self

__next__

__next__() -> tuple[Any, ...]

Column dataclass

Column(
    name: str | None,
    table_oid: int,
    table_column: int,
    type_oid: int,
    type_size: int,
    type_modifier: int,
    format: int,
)

PostgreSQL result-column metadata independent of PostgreSQL headers.

name instance-attribute

name: str | None

table_oid instance-attribute

table_oid: int

table_column instance-attribute

table_column: int

type_oid instance-attribute

type_oid: int

type_size instance-attribute

type_size: int

type_modifier instance-attribute

type_modifier: int

format instance-attribute

format: int

dbapi_description property

dbapi_description: tuple[Any, ...]

Return this column in the seven-field PEP 249 description form.

connect

connect(
    path: str | PathLike[str],
    *,
    mode: OpenMode | str = OpenMode.OPEN_OR_CREATE,
    database: str = "postgres",
    user: str = "postgamma",
    application_name: str = "postgamma-python",
    settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    connection_settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    worker_count: int = 4,
    autocommit: bool = False,
    timeout: float | None = _DEFAULT_TIMEOUT_SECONDS,
    resource_root: str | PathLike[str] | None = None,
    executable_path: str | PathLike[str] | None = None
) -> Connection

Open a logical session on a shared process-local embedded instance.

path is a PostgreSQL cluster directory. The default mode opens an existing compatible cluster or initializes a missing final directory. All top-level connections for the same canonical path share one embedded instance while retaining independent PostgreSQL session and transaction state.

Parameters:

Name Type Description Default
path str | PathLike[str]

Persistent PostgreSQL cluster-directory path.

required
mode OpenMode | str

open_or_create, open_existing, or create_new.

OPEN_OR_CREATE
database str

Existing PostgreSQL logical database inside the cluster.

'postgres'
user str

Existing PostgreSQL role for the logical session.

'postgamma'
application_name str

PostgreSQL application name for the session.

'postgamma-python'
settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Instance/startup PostgreSQL settings. Repeated top-level connections must request the same instance settings.

None
connection_settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Session-local PostgreSQL settings.

None
worker_count int

Carrier workers shared by sessions on this instance.

4
autocommit bool

Commit each statement independently when true.

False
timeout float | None

Default operation deadline in seconds, or None for no deadline.

_DEFAULT_TIMEOUT_SECONDS
resource_root str | PathLike[str] | None

Advanced resource-pack override; wheels resolve it.

None
executable_path str | PathLike[str] | None

Advanced PostgreSQL executable-identity override; wheels resolve it to bin/postgres in their resource pack and do not launch it.

None

Returns:

Type Description
Connection

An independent logical connection. Its close releases one instance

Connection

lease; the last implicit connection shuts down the shared instance.

Raises:

Type Description
OperationalError

The path violates the requested mode or cannot open.

InterfaceError

Instance options conflict with a live implicit instance.

DatabaseError

PostgreSQL rejects the requested logical database or role.

Example

import postgamma with postgamma.connect("application.pgm", autocommit=True) as connection: ... connection.execute("create table if not exists values_(n int)")

Requests and streaming

Caller-driven requests, bounded rows, COPY, prepared statements, and scheduler state.

Request

Request(
    connection: Connection,
    handle: Any,
    *,
    timeout: float | None,
    on_notice: Any | None = None
)

One ordered, caller-driven PostgreSQL result sequence.

__slots__ class-attribute instance-attribute

__slots__ = (
    "connection",
    "_handle",
    "_closed",
    "_deadline",
    "_on_notice",
    "_copy_ref",
    "_owns_gate",
    "id",
    "waitable",
    "__weakref__",
)

connection instance-attribute

connection = connection

_handle instance-attribute

_handle = None

_closed instance-attribute

_closed = True

_deadline instance-attribute

_deadline = (
    None
    if normalized is None
    else time.monotonic() + normalized
)

_on_notice instance-attribute

_on_notice = on_notice

_copy_ref instance-attribute

_copy_ref: ReferenceType[CopyIn | CopyOut] | None = None

_owns_gate instance-attribute

_owns_gate = False

id instance-attribute

id = int(_native.request_identity(handle))

waitable instance-attribute

waitable = int(_native.request_waitable(handle))

closed property

closed: bool

Return whether this request has released its native handle.

state property

state: int

Inspect the request state without driving progress.

start classmethod

start(
    connection: Connection,
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    chunk_rows: int = 0,
    timeout: float | None = None,
    result_buffer_limit: int = 0,
    script: bool = False,
    on_notice: Any | None = None
) -> Request

Submit SQL and return one caller-driven ordered request.

from_statement classmethod

from_statement(
    statement: PreparedStatement,
    parameters: Sequence[Any] | None,
    *,
    chunk_rows: int,
    timeout: float | None,
    result_buffer_limit: int,
    on_notice: Any | None
) -> Request

Execute a prepared statement as a caller-driven request.

_require_open

_require_open() -> None

_remaining

_remaining() -> float | None

_timed_out

_timed_out() -> None

_take

_take(*, block: bool = True) -> tuple[int, Any | None]

try_next

try_next() -> tuple[int, Result | CopyIn | CopyOut | None]

Take one result without blocking and expose its availability state.

next_result

next_result() -> Result | CopyIn | CopyOut | None

Block for one ordered result, returning None at end of sequence.

_convert

_convert(
    native: dict[str, Any],
) -> Result | CopyIn | CopyOut

results

results() -> Iterator[Result]

Yield all ordinary results and verify the terminal boundary.

progress

progress() -> int

Perform one nonblocking progress step and dispatch ready events.

cancel

cancel() -> bool

Request PostgreSQL cancellation and report whether it was routed.

close

close() -> None

Retire this request and release the connection execution lease.

__enter__

__enter__() -> Request

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

RowStream

RowStream(request: Request)

A bounded synchronous row stream with terminal-result verification.

__slots__ class-attribute instance-attribute

__slots__ = (
    "request",
    "columns",
    "command_status",
    "rowcount",
    "_rows",
    "_chunk_iterator",
    "_rows_seen",
    "_closed",
    "__weakref__",
)

request instance-attribute

request = request

columns instance-attribute

columns: tuple[Column, ...] = ()

command_status instance-attribute

command_status: str | None = None

rowcount instance-attribute

rowcount = -1

_rows instance-attribute

_rows: Iterator[tuple[Any, ...]] = iter(())

_chunk_iterator instance-attribute

_chunk_iterator: Iterator[Result] = self.chunks()

_rows_seen instance-attribute

_rows_seen = 0

_closed instance-attribute

_closed = False

closed property

closed: bool

Return whether this stream reached its terminal boundary or closed.

description property

description: tuple[tuple[Any, ...], ...] | None

Return PEP 249 descriptions after column metadata becomes available.

start classmethod

start(
    connection: Connection,
    sql: str,
    parameters: Sequence[Any] | None,
    *,
    chunk_rows: int,
    timeout: float | None,
    result_buffer_limit: int,
    on_notice: Any | None
) -> RowStream

Submit a bounded-row request and return its stream.

from_request classmethod

from_request(request: Request) -> RowStream

Wrap an existing chunked request as a row stream.

chunks

chunks() -> Iterator[Result]

Yield bounded result chunks and consume the terminal result.

fetchone

fetchone() -> tuple[Any, ...] | None

Return the next streamed row, or None at the terminal boundary.

fetchmany

fetchmany(size: int = 1) -> list[tuple[Any, ...]]

Return up to size rows while preserving bounded native chunks.

fetchall

fetchall() -> list[tuple[Any, ...]]

Materialize and return every remaining streamed row in Python.

close

close() -> None

Retire the active request and close this stream.

__iter__

__iter__() -> RowStream

__next__

__next__() -> tuple[Any, ...]

__enter__

__enter__() -> RowStream

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

CopyIn

CopyIn(request: Request, handle: Any)

Bases: _CopyBase

Partial, backpressure-aware COPY FROM STDIN byte writer.

__slots__ class-attribute instance-attribute

__slots__ = (
    "request",
    "_handle",
    "_closed",
    "_io_ended",
    "command_result",
    "__weakref__",
)

request instance-attribute

request = request

_handle instance-attribute

_handle = handle

_closed instance-attribute

_closed = False

_io_ended instance-attribute

_io_ended = False

command_result instance-attribute

command_result: Result | None = None

closed property

closed: bool

Return whether the COPY handle and its request are closed.

_require_open

_require_open() -> None

_progress_wait

_progress_wait() -> None

_release_copy

_release_copy() -> None

_finish_request

_finish_request() -> Result

abort

abort(message: str | None = None) -> None

Abort COPY and release the active request.

Parameters:

Name Type Description Default
message str | None

Optional PostgreSQL COPY failure message.

None

close

close() -> None

Close COPY and release its request without completing input.

__enter__

__enter__() -> _CopyBase

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

write

write(data: Any) -> int

Write all supplied bytes while honoring native partial progress.

finish

finish(failure_message: str | None = None) -> Result

Finish COPY IN and return PostgreSQL's terminal command result.

copy_from

copy_from(
    source: Any, *, chunk_size: int = 64 * 1024
) -> Result

Copy from a readable binary object until it returns end of input.

CopyOut

CopyOut(request: Request, handle: Any)

Bases: _CopyBase

Partial, backpressure-aware COPY TO STDOUT byte reader.

__slots__ class-attribute instance-attribute

__slots__ = (
    "request",
    "_handle",
    "_closed",
    "_io_ended",
    "command_result",
    "__weakref__",
)

request instance-attribute

request = request

_handle instance-attribute

_handle = handle

_closed instance-attribute

_closed = False

_io_ended instance-attribute

_io_ended = False

command_result instance-attribute

command_result: Result | None = None

closed property

closed: bool

Return whether the COPY handle and its request are closed.

_require_open

_require_open() -> None

_progress_wait

_progress_wait() -> None

_release_copy

_release_copy() -> None

_finish_request

_finish_request() -> Result

abort

abort(message: str | None = None) -> None

Abort COPY and release the active request.

Parameters:

Name Type Description Default
message str | None

Optional PostgreSQL COPY failure message.

None

close

close() -> None

Close COPY and release its request without completing input.

__enter__

__enter__() -> _CopyBase

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

read

read(size: int = 64 * 1024) -> bytes

Read up to size COPY OUT bytes, returning empty bytes at end.

copy_to

copy_to(
    target: Any, *, chunk_size: int = 64 * 1024
) -> Result

Copy all output to a writable binary object and return the result.

PreparedStatement

PreparedStatement(
    connection: Connection, sql: str, handle: Any
)

A reusable prepared statement owned by one logical connection.

__slots__ class-attribute instance-attribute

__slots__ = (
    "connection",
    "sql",
    "_handle",
    "_closed",
    "_description",
    "__weakref__",
)

connection instance-attribute

connection = connection

sql instance-attribute

sql = sql

_handle instance-attribute

_handle = handle

_closed instance-attribute

_closed = False

_description instance-attribute

_description: StatementDescription | None = None

closed property

closed: bool

Return whether this prepared statement is closed.

description property

description: StatementDescription

Describe parameter types and result columns, caching the result.

prepare classmethod

prepare(
    connection: Connection,
    sql: str,
    parameter_type_oids: Sequence[int] | None,
) -> PreparedStatement

Prepare SQL with optional declared parameter type OIDs.

execute

execute(
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None,
    on_notice: Any | None = None
) -> Result

Execute this statement and return one materialized result.

stream

stream(
    parameters: Sequence[Any] | None = None,
    *,
    chunk_rows: int = 1024,
    timeout: float | None = None,
    result_buffer_limit: int = 0,
    on_notice: Any | None = None
) -> RowStream

Execute this statement as a bounded row stream.

close

close() -> None

Release this statement from its owning logical connection.

__enter__

__enter__() -> PreparedStatement

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

StatementDescription dataclass

StatementDescription(
    parameter_type_oids: tuple[int, ...],
    columns: tuple[Column, ...],
)

Prepared-statement parameter OIDs and result-column metadata.

parameter_type_oids instance-attribute

parameter_type_oids: tuple[int, ...]

columns instance-attribute

columns: tuple[Column, ...]

ConnectionStatus dataclass

ConnectionStatus(
    transaction_status: int,
    pin_reasons: PinReason,
    carrier_retained: bool,
    virtual_backend_pid: int,
    connection_id: int,
    active_request_id: int,
)

A synchronized transaction and executor-scheduling snapshot.

transaction_status instance-attribute

transaction_status: int

pin_reasons instance-attribute

pin_reasons: PinReason

carrier_retained instance-attribute

carrier_retained: bool

virtual_backend_pid instance-attribute

virtual_backend_pid: int

connection_id instance-attribute

connection_id: int

active_request_id instance-attribute

active_request_id: int

pinned property

pinned: bool

Return whether this session currently retains a carrier worker.

from_native classmethod

from_native(value: dict[str, Any]) -> ConnectionStatus

Construct a typed status snapshot from the native ABI mapping.

PinReason

Bases: IntFlag

Reasons a logical session currently retains one executor worker.

NONE class-attribute instance-attribute

NONE = 0

TRANSACTION class-attribute instance-attribute

TRANSACTION = _native.PIN_TRANSACTION

ADVISORY_LOCK class-attribute instance-attribute

ADVISORY_LOCK = _native.PIN_ADVISORY_LOCK

PORTAL class-attribute instance-attribute

PORTAL = _native.PIN_PORTAL

COPY class-attribute instance-attribute

COPY = _native.PIN_COPY

OTHER class-attribute instance-attribute

OTHER = _native.PIN_OTHER

Asyncio

Event-loop adapters over the same native handles and level-triggered waitables.

AsyncDatabase

AsyncDatabase(
    database: Database | str | PathLike[str], **options: Any
)

Asyncio facade over a lazy :class:postgamma.Database.

_database instance-attribute

_database = database

_owns_database instance-attribute

_owns_database = False

_closing instance-attribute

_closing = False

sync_database property

sync_database: Database

Return the synchronous database object wrapped by this facade.

open async

open() -> AsyncDatabase

Open the database without blocking the asyncio event loop.

connect async

connect(**options: Any) -> AsyncConnection

Open one logical connection and return its asyncio facade.

execute async

execute(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Result

Execute one autocommitted statement on a temporary connection.

events async

events() -> AsyncIterator[Any]

Yield instance events without occupying a worker thread.

checkpoint async

checkpoint(
    *, timeout: float | None = None
) -> OperationProgress

Run an in-process checkpoint and return its final progress snapshot.

maintenance async

maintenance(
    kind: Any = "vacuum_analyze",
    *,
    timeout: float | None = None,
    **options: Any
) -> OperationProgress

Run one supported maintenance command to completion.

logical_dump async

logical_dump(
    stream: Any,
    *,
    timeout: float | None = None,
    **options: Any
) -> OperationProgress

Write a logical archive through an asynchronous operation driver.

logical_restore async

logical_restore(
    stream: Any,
    *,
    timeout: float | None = None,
    **options: Any
) -> OperationProgress

Restore a logical archive through an asynchronous operation driver.

close async

close(**options: Any) -> None

Close the wrapped database when this facade owns it.

__aenter__ async

__aenter__() -> AsyncDatabase

__aexit__ async

__aexit__(exc_type: Any, exc: Any, traceback: Any) -> None

AsyncConnection

AsyncConnection(connection: Connection)

One serialized asyncio session; other sessions still run concurrently.

_connection instance-attribute

_connection = connection

_lock instance-attribute

_lock = asyncio.Lock()

sync_connection property

sync_connection: Connection

Return the synchronous logical connection wrapped by this facade.

closed property

closed: bool

Return whether the wrapped connection is closed.

_execute_locked async

_execute_locked(
    sql: str,
    parameters: Sequence[Any] | None,
    timeout: float | None,
) -> Result

_begin_if_needed async

_begin_if_needed(sql: str, timeout: float | None) -> None

execute async

execute(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None
) -> Result

Execute one statement through a caller-driven native request.

stream async

stream(
    sql: str,
    parameters: Sequence[Any] | None = None,
    *,
    chunk_rows: int = 1024,
    timeout: float | None = None,
    result_buffer_limit: int = 0,
    on_notice: Any | None = None
) -> AsyncRowStream

Execute SQL and return an asynchronous bounded row stream.

execute_script async

execute_script(
    sql: str, *, timeout: float | None = None
) -> tuple[Result, ...]

Execute simple-protocol SQL and return every ordered result.

prepare async

prepare(
    sql: str,
    *,
    parameter_type_oids: Sequence[int] | None = None
) -> AsyncPreparedStatement

Prepare SQL and return an asynchronous statement facade.

copy async

copy(
    sql: str, *, timeout: float | None = None
) -> AsyncCopy

Start COPY IN or COPY OUT and return an asynchronous byte stream.

commit async

commit() -> None

Commit the current transaction.

rollback async

rollback() -> None

Roll back the current transaction.

transaction

transaction() -> _AsyncTransactionContext

Return a single-use asynchronous transaction scope.

_enter_transaction_scope async

_enter_transaction_scope() -> None

_exit_transaction_scope async

_exit_transaction_scope(
    *, commit: bool, primary_error: BaseException | None
) -> None

cancel

cancel() -> bool

Request cancellation of this connection's active request.

close async

close(**options: Any) -> None

Close the logical connection without blocking the event loop.

__aenter__ async

__aenter__() -> AsyncConnection

__aexit__ async

__aexit__(exc_type: Any, exc: Any, traceback: Any) -> None

AsyncRowStream

AsyncRowStream(request: Request, release: Any)

Async iterator over bounded result chunks without helper threads.

request instance-attribute

request = request

columns instance-attribute

columns: tuple[Any, ...] = ()

command_status instance-attribute

command_status: str | None = None

rowcount instance-attribute

rowcount = -1

_rows instance-attribute

_rows: list[tuple[Any, ...]] = []

_rows_seen instance-attribute

_rows_seen = 0

_release instance-attribute

_release = release

_closed instance-attribute

_closed = False

_finish_close

_finish_close() -> None

fetchone async

fetchone() -> tuple[Any, ...] | None

Return the next streamed row without blocking the event loop.

fetchmany async

fetchmany(size: int = 1) -> list[tuple[Any, ...]]

Return up to size rows from the bounded stream.

aclose async

aclose() -> None

Cancel or retire the request and close this stream.

__aiter__

__aiter__() -> AsyncRowStream

__anext__ async

__anext__() -> tuple[Any, ...]

__aenter__ async

__aenter__() -> AsyncRowStream

__aexit__ async

__aexit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

AsyncCopy

AsyncCopy(copy: CopyIn | CopyOut, release: Any)

Async facade over COPY IN or COPY OUT partial I/O.

_copy instance-attribute

_copy = copy

_release instance-attribute

_release = release

_closed instance-attribute

_closed = False

direction property

direction: str

Return in for COPY IN or out for COPY OUT.

_abort_preserving async

_abort_preserving(primary_error: BaseException) -> None

write async

write(data: Any) -> int

Write all supplied bytes to COPY IN with asynchronous progress.

finish async

finish() -> Result

Finish COPY IN and return PostgreSQL's command result.

copy_from async

copy_from(
    source: Any, *, chunk_size: int = 64 * 1024
) -> Result

Copy from a readable binary object until end of input.

read async

read(size: int = 64 * 1024) -> bytes

Read up to size COPY OUT bytes, or empty bytes at end.

copy_to async

copy_to(
    target: Any, *, chunk_size: int = 64 * 1024
) -> Result

Copy all output to a writable binary object.

_finish_close

_finish_close() -> None

aclose async

aclose() -> None

Abort or retire the active COPY operation and release its request.

__aenter__ async

__aenter__() -> AsyncCopy

__aexit__ async

__aexit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

AsyncPreparedStatement

AsyncPreparedStatement(
    connection: AsyncConnection, statement: Any
)

Asyncio execution facade for one reusable prepared statement.

connection instance-attribute

connection = connection

statement instance-attribute

statement = statement

description property

description: Any

Return the cached or lazily loaded statement description.

execute async

execute(
    parameters: Sequence[Any] | None = None,
    *,
    timeout: float | None = None,
    on_notice: Any | None = None
) -> Result

Execute the prepared statement and materialize one result.

stream async

stream(
    parameters: Sequence[Any] | None = None,
    *,
    chunk_rows: int = 1024,
    timeout: float | None = None,
    result_buffer_limit: int = 0,
    on_notice: Any | None = None
) -> AsyncRowStream

Execute the prepared statement as a bounded asynchronous stream.

close async

close() -> None

Close the underlying prepared statement.

__aenter__ async

__aenter__() -> AsyncPreparedStatement

__aexit__ async

__aexit__(exc_type: Any, exc: Any, traceback: Any) -> None

connect_async async

connect_async(
    path: str | PathLike[str],
    *,
    mode: OpenMode | str = OpenMode.OPEN_OR_CREATE,
    database: str = "postgres",
    user: str = "postgamma",
    application_name: str = "postgamma-python",
    settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    connection_settings: (
        Mapping[str, Any] | Iterable[tuple[str, Any]] | None
    ) = None,
    worker_count: int = 4,
    autocommit: bool = False,
    timeout: float | None = _DEFAULT_TIMEOUT_SECONDS,
    resource_root: str | PathLike[str] | None = None,
    executable_path: str | PathLike[str] | None = None
) -> AsyncConnection

Open one logical session without blocking the asyncio event loop.

This is the asynchronous counterpart of :func:postgamma.connect. It accepts the same options, shares the same process-local instance registry, and returns an already-open :class:AsyncConnection.

Parameters:

Name Type Description Default
path str | PathLike[str]

Persistent PostgreSQL cluster-directory path.

required
mode OpenMode | str

open_or_create, open_existing, or create_new.

OPEN_OR_CREATE
database str

Existing PostgreSQL logical database inside the cluster.

'postgres'
user str

Existing PostgreSQL role for the logical session.

'postgamma'
application_name str

PostgreSQL application name for the session.

'postgamma-python'
settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Instance/startup PostgreSQL settings. Repeated connections must request the same instance settings.

None
connection_settings Mapping[str, Any] | Iterable[tuple[str, Any]] | None

Session-local PostgreSQL settings.

None
worker_count int

Carrier workers shared by sessions on this instance.

4
autocommit bool

Commit each statement independently when true.

False
timeout float | None

Default operation deadline in seconds, or None for no deadline.

_DEFAULT_TIMEOUT_SECONDS
resource_root str | PathLike[str] | None

Advanced resource-pack override; wheels resolve it.

None
executable_path str | PathLike[str] | None

Advanced executable-identity override; wheels resolve it and do not launch that executable.

None

Returns:

Type Description
AsyncConnection

An open asynchronous logical connection whose close releases one

AsyncConnection

process-local instance lease.

Raises:

Type Description
OperationalError

The path violates the requested mode or cannot open.

InterfaceError

Instance options conflict with a live implicit instance.

DatabaseError

PostgreSQL rejects the requested logical database or role.

Management and events

Instance events, bundled-extension metadata, checkpoints, maintenance, and logical archives.

Event dataclass

Event(kind: EventKind, connection_id: int, request_id: int)

Common identity fields carried by every owned instance event.

kind instance-attribute

kind: EventKind

connection_id instance-attribute

connection_id: int

request_id instance-attribute

request_id: int

EventKind

Bases: IntEnum

Kinds delivered through an instance event queue.

LOG class-attribute instance-attribute

LOG = _native.EVENT_LOG

NOTICE class-attribute instance-attribute

NOTICE = _native.EVENT_NOTICE

NOTIFICATION class-attribute instance-attribute

NOTIFICATION = _native.EVENT_NOTIFICATION

OVERFLOW class-attribute instance-attribute

OVERFLOW = _native.EVENT_OVERFLOW

LogEvent dataclass

LogEvent(
    kind: EventKind,
    connection_id: int,
    request_id: int,
    virtual_backend_pid: int,
    severity: str,
    sqlstate: str,
    message: str,
    detail: str,
)

Bases: Event

One structured PostgreSQL log record routed to the host.

virtual_backend_pid instance-attribute

virtual_backend_pid: int

severity instance-attribute

severity: str

sqlstate instance-attribute

sqlstate: str

message instance-attribute

message: str

detail instance-attribute

detail: str

NoticeEvent dataclass

NoticeEvent(
    kind: EventKind,
    connection_id: int,
    request_id: int,
    severity: str,
    sqlstate: str,
    message: str,
    detail: str,
    hint: str,
)

Bases: Event

One structured PostgreSQL notice associated with a request.

severity instance-attribute

severity: str

sqlstate instance-attribute

sqlstate: str

message instance-attribute

message: str

detail instance-attribute

detail: str

hint instance-attribute

hint: str

NotificationEvent dataclass

NotificationEvent(
    kind: EventKind,
    connection_id: int,
    request_id: int,
    virtual_backend_pid: int,
    channel: str,
    payload: str,
)

Bases: Event

One LISTEN/NOTIFY message routed to its logical connection.

virtual_backend_pid instance-attribute

virtual_backend_pid: int

channel instance-attribute

channel: str

payload instance-attribute

payload: str

OverflowEvent dataclass

OverflowEvent(
    kind: EventKind,
    connection_id: int,
    request_id: int,
    dropped_kind: EventKind,
    dropped_count: int,
)

Bases: Event

An observable count of events dropped by the bounded queue.

dropped_kind instance-attribute

dropped_kind: EventKind

dropped_count instance-attribute

dropped_count: int

BundledExtension dataclass

BundledExtension(
    id: str,
    sql_name: str,
    version: str,
    postgresql_major: int,
    sdk_abi_version: int,
    capabilities: int,
)

Borrowed build metadata copied for one reviewed bundled extension.

id instance-attribute

id: str

sql_name instance-attribute

sql_name: str

version instance-attribute

version: str

postgresql_major instance-attribute

postgresql_major: int

sdk_abi_version instance-attribute

sdk_abi_version: int

capabilities instance-attribute

capabilities: int

from_native classmethod

from_native(value: dict[str, Any]) -> BundledExtension

Copy one native bundled-extension metadata mapping.

LogicalFlags

Bases: IntFlag

Composable logical dump and restore options.

NONE class-attribute instance-attribute

NONE = 0

SCHEMA_ONLY class-attribute instance-attribute

SCHEMA_ONLY = _native.LOGICAL_SCHEMA_ONLY

DATA_ONLY class-attribute instance-attribute

DATA_ONLY = _native.LOGICAL_DATA_ONLY

CLEAN class-attribute instance-attribute

CLEAN = _native.LOGICAL_CLEAN

CREATE class-attribute instance-attribute

CREATE = _native.LOGICAL_CREATE

NO_OWNER class-attribute instance-attribute

NO_OWNER = _native.LOGICAL_NO_OWNER

NO_PRIVILEGES class-attribute instance-attribute

NO_PRIVILEGES = _native.LOGICAL_NO_PRIVILEGES

MaintenanceKind

Bases: IntEnum

Supported in-process PostgreSQL maintenance commands.

VACUUM class-attribute instance-attribute

VACUUM = _native.MAINTENANCE_VACUUM

ANALYZE class-attribute instance-attribute

ANALYZE = _native.MAINTENANCE_ANALYZE

VACUUM_ANALYZE class-attribute instance-attribute

VACUUM_ANALYZE = _native.MAINTENANCE_VACUUM_ANALYZE

REINDEX_DATABASE class-attribute instance-attribute

REINDEX_DATABASE = _native.MAINTENANCE_REINDEX_DATABASE

parse classmethod

parse(
    value: MaintenanceKind | str | int,
) -> MaintenanceKind

Normalize a name, integer, or existing enum to a maintenance kind.

Operation

Operation(database: Database, handle: Any)

One in-process checkpoint, maintenance, dump, or restore operation.

__slots__ class-attribute instance-attribute

__slots__ = (
    "database",
    "_handle",
    "_closed",
    "waitable",
    "__weakref__",
)

database instance-attribute

database = database

_handle instance-attribute

_handle = handle

_closed instance-attribute

_closed = False

waitable instance-attribute

waitable = int(_native.operation_waitable(handle))

snapshot property

snapshot: OperationProgress

Return the most recent synchronized operation progress snapshot.

checkpoint classmethod

checkpoint(database: Database) -> Operation

Create a pending checkpoint operation for a database.

maintenance classmethod

maintenance(
    owner: Database,
    *,
    kind: MaintenanceKind | str | int,
    database_name: str | None = None,
    user: str | None = None
) -> Operation

Create a pending VACUUM, ANALYZE, or REINDEX operation.

logical_dump classmethod

logical_dump(
    database: Database, stream: Any, **options: Any
) -> Operation

Create a pending logical dump writing to a binary stream.

logical_restore classmethod

logical_restore(
    database: Database, stream: Any, **options: Any
) -> Operation

Create a pending logical restore reading from a binary stream.

_logical classmethod

_logical(
    owner: Database,
    stream: Any,
    *,
    dump: bool,
    flags: int,
    database_name: str | None = None,
    user: str | None,
    channel_capacity: int,
    progress_quantum: int
) -> Operation

_require_open

_require_open() -> None

progress

progress() -> OperationState

Submit or advance this operation once and return its state.

wait

wait(*, timeout: float | None = None) -> OperationProgress

Drive this operation to a terminal state within a deadline.

cancel

cancel() -> None

Request cancellation when the operation kind permits it.

close

close() -> None

Retire and release this operation handle.

__await__

__await__() -> Any

__enter__

__enter__() -> Operation

__exit__

__exit__(exc_type: Any, exc: Any, traceback: Any) -> None

__del__

__del__() -> None

OperationKind

Bases: IntEnum

Kinds of management operations supported by the current kernel.

CHECKPOINT class-attribute instance-attribute

CHECKPOINT = _native.OPERATION_KIND_CHECKPOINT

LOGICAL_DUMP class-attribute instance-attribute

LOGICAL_DUMP = _native.OPERATION_KIND_LOGICAL_DUMP

LOGICAL_RESTORE class-attribute instance-attribute

LOGICAL_RESTORE = _native.OPERATION_KIND_LOGICAL_RESTORE

MAINTENANCE class-attribute instance-attribute

MAINTENANCE = _native.OPERATION_KIND_MAINTENANCE

OperationPhase

Bases: IntEnum

Stable progress phases shared by management operations.

PENDING class-attribute instance-attribute

PENDING = _native.OPERATION_PHASE_PENDING

STARTING class-attribute instance-attribute

STARTING = _native.OPERATION_PHASE_STARTING

DATABASE class-attribute instance-attribute

DATABASE = _native.OPERATION_PHASE_DATABASE

ARCHIVE_IO class-attribute instance-attribute

ARCHIVE_IO = _native.OPERATION_PHASE_ARCHIVE_IO

HOST_IO class-attribute instance-attribute

HOST_IO = _native.OPERATION_PHASE_HOST_IO

FINALIZING class-attribute instance-attribute

FINALIZING = _native.OPERATION_PHASE_FINALIZING

TERMINAL class-attribute instance-attribute

TERMINAL = _native.OPERATION_PHASE_TERMINAL

OperationProgress dataclass

OperationProgress(
    kind: OperationKind,
    state: OperationState,
    phase: OperationPhase,
    bytes_received: int,
    bytes_produced: int,
    total_bytes: int,
    objects_completed: int,
    objects_total: int,
)

A synchronized management-operation progress snapshot.

kind instance-attribute

kind: OperationKind

state instance-attribute

state: OperationState

phase instance-attribute

phase: OperationPhase

bytes_received instance-attribute

bytes_received: int

bytes_produced instance-attribute

bytes_produced: int

total_bytes instance-attribute

total_bytes: int

objects_completed instance-attribute

objects_completed: int

objects_total instance-attribute

objects_total: int

from_native classmethod

from_native(value: dict[str, Any]) -> OperationProgress

Construct a typed progress snapshot from the native ABI mapping.

OperationState

Bases: IntEnum

Lifecycle states for a caller-driven management operation.

PENDING class-attribute instance-attribute

PENDING = _native.OPERATION_PENDING

RUNNING class-attribute instance-attribute

RUNNING = _native.OPERATION_RUNNING

COMPLETED class-attribute instance-attribute

COMPLETED = _native.OPERATION_COMPLETED

CANCELED class-attribute instance-attribute

CANCELED = _native.OPERATION_CANCELED

FAILED class-attribute instance-attribute

FAILED = _native.OPERATION_FAILED

Values and adapters

Lossless unknown values, explicit encoders, custom codecs, and Arrow C Data export.

RawValue dataclass

RawValue(oid: int, format: int, data: bytes)

A lossless value returned for an OID without a registered decoder.

oid instance-attribute

oid: int

format instance-attribute

format: int

data instance-attribute

data: bytes

text

text(encoding: str = 'utf-8') -> str

Decode a text-format raw value with the requested encoding.

EncodedParameter dataclass

EncodedParameter(
    oid: int, format: int, is_null: bool, data: bytes
)

One explicit PostgreSQL parameter representation for a custom encoder.

oid instance-attribute

oid: int

format instance-attribute

format: int

is_null instance-attribute

is_null: bool

data instance-attribute

data: bytes

native

native() -> tuple[int, int, bool, bytes]

Return the tuple consumed by the native parameter adapter.

Json dataclass

Json(value: Any)

Explicitly encode a Python value as jsonb.

value instance-attribute

value: Any

Array dataclass

Array(values: Sequence[Any], oid: int = 0)

Explicit PostgreSQL array value with an optional array type OID.

values instance-attribute

values: Sequence[Any]

oid class-attribute instance-attribute

oid: int = 0

register_codec

register_codec(
    *,
    oid: int,
    decoder: Decoder,
    python_type: type[Any] | None = None,
    encoder: Encoder | None = None
) -> None

Register an application or bundled-extension codec.

Registration is process-wide and affects values decoded after the call. A Python encoder is optional, but its type and callable must be supplied together.

unregister_codec

unregister_codec(
    oid: int, python_type: type[Any] | None = None
) -> None

Remove a previously registered custom codec.

ArrowResult

ArrowResult(capsules: tuple[Any, Any])

A one-shot Arrow struct array exported through the PyCapsule protocol.

The PostGamma kernel does not link an Arrow runtime. Consumers such as PyArrow, Polars, and DataFusion take ownership through __arrow_c_array__.

__slots__ class-attribute instance-attribute

__slots__ = ('_capsules',)

_capsules instance-attribute

_capsules: tuple[Any, Any] | None = capsules

consumed property

consumed: bool

Return whether Arrow capsule ownership has already transferred.

__arrow_c_array__

__arrow_c_array__(
    requested_schema: Any = None,
) -> tuple[Any, Any]

DB-API constructors and type objects

PEP 249 constructors and comparison objects.

Name Meaning
postgamma.STRING DB-API string type comparison object.
postgamma.BINARY DB-API binary type comparison object.
postgamma.NUMBER DB-API numeric type comparison object.
postgamma.DATETIME DB-API date and time type comparison object.
postgamma.ROWID DB-API row identifier type comparison object.

Date

Date(year: int, month: int, day: int) -> datetime.date

Construct the date value required by PEP 249.

Time

Time(hour: int, minute: int, second: int) -> datetime.time

Construct the time value required by PEP 249.

Timestamp

Timestamp(
    year: int,
    month: int,
    day: int,
    hour: int,
    minute: int,
    second: int,
) -> datetime.datetime

Construct the timestamp value required by PEP 249.

DateFromTicks

DateFromTicks(ticks: float) -> datetime.date

Construct a local date from seconds since the epoch.

TimeFromTicks

TimeFromTicks(ticks: float) -> datetime.time

Construct a local time from seconds since the epoch.

TimestampFromTicks

TimestampFromTicks(ticks: float) -> datetime.datetime

Construct a local timestamp from seconds since the epoch.

Binary

Binary(value: Any) -> bytes

Convert a bytes-like value to the PEP 249 binary representation.

Exceptions

PEP 249 errors plus explicit timeout, cancellation, and fork failures.

Warning

Bases: Exception

A non-fatal database warning.

Error

Error(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: Exception

Base class for every PostGamma database exception.

status instance-attribute

status = status

status_name instance-attribute

status_name = status_name

sqlstate instance-attribute

sqlstate = sqlstate

severity instance-attribute

severity = severity

detail instance-attribute

detail = detail

hint instance-attribute

hint = hint

InterfaceError

InterfaceError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: Error

The host-facing API or process lifecycle contract was violated.

DatabaseError

DatabaseError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: Error

Base class for errors reported by PostgreSQL.

DataError

DataError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

A value could not be processed.

OperationalError

OperationalError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

The database operation failed for an operational reason.

IntegrityError

IntegrityError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

A relational integrity constraint was violated.

InternalError

InternalError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

The database reported an internal failure.

ProgrammingError

ProgrammingError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

SQL or API usage was invalid.

NotSupportedError

NotSupportedError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: DatabaseError

The requested capability is not implemented by this build.

QueryCanceledError

QueryCanceledError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: OperationalError

A running request was canceled.

QueryTimeoutError

QueryTimeoutError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: OperationalError

A request exceeded its host-side deadline.

ForkedProcessError

ForkedProcessError(
    message: str,
    *,
    status: int | None = None,
    status_name: str | None = None,
    sqlstate: str | None = None,
    severity: str | None = None,
    detail: str | None = None,
    hint: str | None = None
)

Bases: InterfaceError

An inherited handle was used in a child created with fork().