PostgresClient

The PostgresClient provides a high-level interface for executing database queries and commands.

API Reference

class prs_commons.db.PostgresClient(*args: Any, **kwargs: Any)[source]

High-level asynchronous PostgreSQL database client.

This class provides a convenient interface for executing database operations while delegating connection pooling and transaction management to the underlying PostgresConnection instance. It implements the singleton pattern to ensure consistent database access throughout the application.

Key Features: - High-level query execution methods (fetch_one, fetch_all, execute) - Transaction management through the connection context manager - Type hints and comprehensive error handling

Note

Connection pooling is managed by the PostgresConnection class. This class serves as a thin wrapper that provides a more convenient API for common database operations.

Parameters:
  • dsn – The connection string for the PostgreSQL database. If not provided, it will be constructed from environment variables (DB_USER, DB_PASSWORD, etc.)

  • min_size – Minimum number of connections to keep in the pool (default: 1)

  • max_size – Maximum number of connections in the pool (default: 50)

The PostgresClient provides a high-level interface for executing database queries and commands.

Example Usage:

from prs_commons.db.postgres import PostgresConnection, PostgresClient
import asyncio

async def main():
    # Initialize connection manager
    db_conn = PostgresConnection()
    await db_conn.connect()

    # Initialize client
    db = PostgresClient()

    # Use a connection
    async with db_conn.get_connection() as conn:
        # Fetch a single row
        user = await db.fetch_one(
            conn,
            "SELECT * FROM users WHERE id = $1",
            1
        )
        print(f"User: {user}")

        # Execute an update
        success, result = await db.execute(
            conn,
            "UPDATE users SET last_login = NOW() WHERE id = $1 RETURNING id",
            1
        )
        if success:
            print(f"Updated user ID: {result}")


if __name__ == "__main__":
    asyncio.run(main())
__init__() None[source]

Initialize the PostgreSQL client.

Note: This will only initialize the instance once due to the singleton pattern. Subsequent calls with different parameters will be ignored.

async fetch_one(connection: Connection, query: str, *args: Any, timeout: float | None = None) Dict[str, Any] | None[source]

Fetch a single row from the database.

Parameters:
  • query – The SQL query to execute

  • *args – Query parameters

  • timeout – Optional timeout in seconds

Returns:

A dictionary representing the row, or None if no rows were found

async fetch_all(connection: Connection, query: str, *args: Any, timeout: float | None = None) List[Dict[str, Any]][source]

Fetch multiple rows from the database.

Parameters:
  • query – The SQL query to execute

  • *args – Query parameters

  • timeout – Optional timeout in seconds

Returns:

A list of dictionaries, where each dictionary represents a row

async execute(connection: Connection, query: str, *args: Any, timeout: float | None = None) Tuple[bool, int | str][source]

Execute a write query (INSERT, UPDATE, DELETE) and return the result.

This is a convenience method for executing write operations without explicit transaction management. Each call runs in its own transaction.

Parameters:
  • query – The SQL query to execute

  • *args – Query parameters

  • timeout – Optional timeout in seconds

Returns:

  • (True, affected_rows) on success

  • (False, error_message) on failure

Return type:

Tuple[bool, Union[int, str]]

Example

```python success, result = await db.execute(

“UPDATE users SET active = $1 WHERE id = $2”, True, 123

) if success:

print(f”Updated {result} rows”)

```

async execute_returning(connection: Connection, query: str, *args: Any, timeout: float | None = None) Tuple[bool, Dict[str, Any] | None][source]

Execute a query that returns the affected row.

Parameters:
  • query – The SQL query to execute

  • *args – Query parameters

  • timeout – Optional timeout in seconds

Returns:

A tuple of (success, result_dict) where result_dict is the affected row or None if no rows were affected

Error Handling

The client raises the following exceptions:

  • ValueError: If required environment variables are missing

  • asyncpg.PostgresError: For database-related errors

  • RuntimeError: For connection or db state errors

  • Exception: For other unexpected errors

See Also