# patroni.psycopg module

Abstraction layer for `psycopg` module.

This module is able to handle both `pyscopg2` and `psycopg`, and it exposes a common interface for both. `psycopg2` takes precedence. `psycopg` will only be used if `psycopg2` is either absent or older than `2.5.4`.

exception patroni.psycopg.DatabaseError

  Bases: `Error`

  Error related to the database engine.

exception patroni.psycopg.Error

  Bases: `Exception`

  Base class for error exceptions.

  __init__(*args, **kwargs)
  cursor

    The cursor that raised the exception, if available, else None

  diag

    A Diagnostics object to get further information about the error

  pgcode

    The error code returned by the backend, if available, else None

  pgerror

    The error message returned by the backend, if available, else None

exception patroni.psycopg.OperationalError

  Bases: `DatabaseError`

  Error related to database operation (disconnect, memory allocation etc).

exception patroni.psycopg.ProgrammingError

  Bases: `DatabaseError`

  Error related to database programming (SQL error, table not found etc).

patroni.psycopg.connect(*args: Any, **kwargs: Any) → connection | Connection[Any]

  Get a connection to the database.

  Note

  The connection will have `autocommit` enabled.

  It also enforces `search_path=pg_catalog` for non-replication connections to mitigate security issues as Patroni relies on superuser connections.

  Parameters:

    - args – positional arguments to call `connect()` function from `psycopg` module.

    - kwargs – keyword arguments to call `connect()` function from `psycopg` module.

  Returns:

    a connection to the database. Can be either a `psycopg.Connection` if using `psycopg`, or a `psycopg2.extensions.connection` if using `psycopg2`.

patroni.psycopg.quote_ident(value: Any, conn: cursor | connection | Connection[Any] | None = None) → str

  Quote value as a SQL identifier.

  Parameters:

    - value – value to be quoted.

    - conn – connection to evaluate the returning string into. Can be either a `psycopg.Connection` if using `psycopg`, or a `psycopg2.extensions.connection` if using `psycopg2`.

  Returns:

    value quoted as a SQL identifier.

patroni.psycopg.quote_literal(value: Any, conn: Any | None = None) → str

  Quote value as a SQL literal.

  Note

  value is quoted through `psycopg2` adapters.

  Parameters:

    - value – value to be quoted.

    - conn – if a connection is given then `quote_literal()` checks if any special handling based on server parameters needs to be applied to value before quoting it as a SQL literal.

  Returns:

    value quoted as a SQL literal.