Run artifact

build/LayersTesting/persistence/postgres.py

"""PostgreSQL engine for ``db.py``.

Shipped by Drydock and copied into the build unchanged. Do not edit it here.

PostgreSQL is the production engine: it enforces ``VARCHAR(n)`` length, requires a referenced
table to exist before the table citing it, and returns a generated key through ``RETURNING``
rather than through a cursor attribute.
"""

from __future__ import annotations

import re
import threading
from typing import Any

try:
    from .db import Driver, PersistenceError
except ImportError:  # flat layout
    from db import Driver, PersistenceError

__all__ = ["PostgresDriver"]


class PostgresDriver(Driver):
    """One connection per thread, opened on first use, matching the SQLite caller contract."""

    def prepare_schema(self, sql: str) -> str:
        parts = re.split(r"('(?:''|[^'])*')", sql)
        for index in range(0, len(parts), 2):
            parts[index] = re.sub(
                r'("[a-z][a-z0-9_]*"\s+)INTEGER PRIMARY KEY',
                r'\1INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY', parts[index],
            )
        return "".join(parts)


    paramstyle = "format"
    returning = True

    def __init__(self, dsn: str) -> None:
        self._dsn = dsn
        self._local = threading.local()
        self._pinned: Any = None

    def connect(self) -> Any:
        if self._pinned is not None:
            return self._pinned
        connection = getattr(self._local, "connection", None)
        if connection is None:
            connection = self._open()
            self._local.connection = connection
        return connection

    def pin(self) -> Any:
        # Shared across threads on purpose; ``Database`` serializes every operation on it.
        if self._pinned is None:
            self._pinned = self._open()
        return self._pinned

    def identity(self) -> str:
        return self._dsn

    def _open(self) -> Any:
        connection = _driver_module().connect(self._dsn)
        # Autocommit by default; an explicit BEGIN suspends it until ROLLBACK.
        connection.autocommit = True
        return connection

    def close(self) -> None:
        if self._pinned is not None:
            self._pinned.close()
            self._pinned = None
            return
        connection = getattr(self._local, "connection", None)
        if connection is not None:
            connection.close()
            self._local.connection = None

    def inserted_key(self, cursor: Any) -> Any:
        row = cursor.fetchone()
        return row[0] if row else None


def _driver_module() -> Any:
    """Import the DB-API driver lazily, so this file imports without PostgreSQL installed."""
    try:
        import psycopg  # type: ignore[import-not-found]
    except ImportError:
        try:
            import psycopg2 as psycopg  # type: ignore[import-not-found,no-redef]
        except ImportError as exc:
            raise PersistenceError(
                "PostgreSQL was selected by the DSN but no driver is installed. "
                "Add `psycopg[binary]` to the project's dependencies."
            ) from exc
    return psycopg