Skip to main content

Async and sync PostgreSQL connection pool for multi-database applications

Project description

metapg.pool

High-performance PostgreSQL connection pool with async and sync support

metapg.pool provides async and sync PostgreSQL connection pooling built on psycopg3. It supports multiple databases, smart connection reuse, and context-aware operations.

Installation

pip install metapg.pool

Quick Start

from metapg.pool import init_pool, cursor, transaction, events

# Initialize pool
init_pool(dsn="postgresql://localhost/mydb")

# Async usage
async with cursor() as cur:
    await cur.execute("SELECT * FROM users")
    users = await cur.fetchall()

# Sync usage (same interface!)
with cursor() as cur:
    cur.execute("SELECT * FROM users")
    users = cur.fetchall()

Features

  • Smart Cursor - Same API for both async and sync operations
  • Smart Transaction - Nested transaction support with automatic savepoints
  • Events (LISTEN/NOTIFY) - Pub/sub with dedicated connections
  • Multi-Database - Manage multiple PostgreSQL databases with named pools
  • Context-Aware - Smart connection reuse with contextvars
  • Zero-Config - Works out of the box with sensible defaults

Smart Cursor

The cursor() function returns a SmartCursor that automatically adapts to sync or async context:

from metapg.pool import cursor

# Async
async with cursor() as cur:
    await cur.execute("SELECT * FROM users")
    users = await cur.fetchall()

# Sync
with cursor() as cur:
    cur.execute("SELECT * FROM users")
    users = cur.fetchall()

Smart Transaction

The transaction() function returns a SmartTransaction for atomic operations:

from metapg.pool import transaction, cursor

# Async
async with transaction():
    async with cursor() as cur:
        await cur.execute("INSERT INTO users (name) VALUES (%s)", ("Alice",))
        await cur.execute("INSERT INTO logs (msg) VALUES (%s)", ("User created",))

# Sync
with transaction():
    with cursor() as cur:
        cur.execute("INSERT INTO users (name) VALUES (%s)", ("Bob",))

Events (LISTEN/NOTIFY)

The events() context manager provides pub/sub functionality with PostgreSQL's LISTEN/NOTIFY:

from metapg.pool import events

# Async
async with events() as ev:
    await ev.listen("orders", "inventory")
    await ev.notify("orders", "new_order:123")

    async for msg in ev:
        print(f"{msg.channel}: {msg.payload}")
        if should_stop:
            break

# Sync
with events() as ev:
    ev.listen("orders")
    ev.notify("orders", "new_order:456")

    for msg in ev:
        print(f"{msg.channel}: {msg.payload}")
        if should_stop:
            break

Events API

  • ev.listen(*channels) - Subscribe to channels
  • ev.unlisten(*channels) - Unsubscribe from channels
  • ev.notify(channel, payload) - Send a notification
  • Iterate ev to receive messages

Pool Management

from metapg.pool import init_pool, get_pool, close_pool, close_all_pools

# Initialize pools (creates both async and sync pools)
init_pool(
    dsn="postgresql://user:pass@host:port/dbname",
    db_name="default",
    min_size=1,
    max_size=20,
    application_name="my-app"
)

# Get existing pool
pool = get_pool("default")

# Close specific pool
await close_pool("default")

# Close all pools
await close_all_pools()

Multi-Database Support

from metapg.pool import init_pool, cursor

# Initialize multiple databases
init_pool(dsn="postgresql://localhost/app", db_name="app")
init_pool(dsn="postgresql://localhost/analytics", db_name="analytics")

# Query different databases
async with cursor("app") as cur:
    await cur.execute("SELECT * FROM users")

async with cursor("analytics") as cur:
    await cur.execute("SELECT * FROM events")

Environment Variables

  • DATABASE_URL - Default database connection string
  • DATABASE_URL_{NAME} - Connection string for named database (e.g., DATABASE_URL_ANALYTICS)
  • METAPG_APPLICATION_NAME - Application name for connections
  • PGAPPNAME - PostgreSQL standard application name (fallback)

License

MIT License

Part of metapg

This package is part of the metapg project for PostgreSQL operations.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

metapg_pool-0.3.1.tar.gz (99.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

metapg_pool-0.3.1-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file metapg_pool-0.3.1.tar.gz.

File metadata

  • Download URL: metapg_pool-0.3.1.tar.gz
  • Upload date:
  • Size: 99.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.1

File hashes

Hashes for metapg_pool-0.3.1.tar.gz
Algorithm Hash digest
SHA256 1ae08c119ccbd4e9ee37e3199bd860ef0c2d99c543f224eb9ba9a249a66b23c5
MD5 c53d6b85dbe6564c39d66f48a902f88b
BLAKE2b-256 c5384006db45b8ccf432c44be9e5465880abde6bfe19b433ecbfc7e3ee5dcf5e

See more details on using hashes here.

File details

Details for the file metapg_pool-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for metapg_pool-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3337548f9fd93ce4632262a47dce3956f8b4bc772ad580a1bae0f08719a20d2a
MD5 54e332ef63c5487a2066a2f0312f8622
BLAKE2b-256 b2c6ee90b5a204697eb9e550d9f5ff462219791b278bd67809a70669714c5a6f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page