Skip to main content

pgsqlasync2fast-fastapi

Simple and fast PostgreSQL async module for FastAPI with multi-database support and automatic database creation.

📖 Conventions reference: this package follows the 2fast-handbook for ecosystem conventions (structure, versioning, README, commits, release).

Features

  • ✅ Multiple Database Connections: Configure and manage multiple PostgreSQL databases
  • ✅ Async Support: Built on SQLAlchemy 2.0+ async engine with asyncpg
  • ✅ Database Creation: Automatic database creation with superuser support
  • ✅ FastAPI Integration: Ready-to-use dependencies for seamless FastAPI integration
  • ✅ Connection Pooling: Configurable connection pools per database
  • ✅ Health Checks: Built-in connection health monitoring
  • ✅ Lazy Loading: Engines created only when needed
  • ✅ Type Safe: Full Pydantic settings with validation

Installation

pip install pgsqlasync2fast-fastapi

Quick Start

1. Configure your databases in .env

# Default database connection
DB_CONNECTIONS__DEFAULT__HOST=localhost
DB_CONNECTIONS__DEFAULT__PORT=5432
DB_CONNECTIONS__DEFAULT__USERNAME=myuser
DB_CONNECTIONS__DEFAULT__PASSWORD=mypassword
DB_CONNECTIONS__DEFAULT__DATABASE=mydb

# Business database connection
DB_CONNECTIONS__BUSINESS__HOST=localhost
DB_CONNECTIONS__BUSINESS__PORT=5432
DB_CONNECTIONS__BUSINESS__USERNAME=business_user
DB_CONNECTIONS__BUSINESS__PASSWORD=business_password
DB_CONNECTIONS__BUSINESS__DATABASE=business_db

# Admin connection with superuser privileges
DB_CONNECTIONS__ADMIN__HOST=localhost
DB_CONNECTIONS__ADMIN__PORT=5432
DB_CONNECTIONS__ADMIN__USERNAME=postgres
DB_CONNECTIONS__ADMIN__PASSWORD=postgres_password
DB_CONNECTIONS__ADMIN__DATABASE=postgres
DB_CONNECTIONS__ADMIN__IS_SUPERUSER=true

2. Use in FastAPI

from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from pgsqlasync2fast_fastapi import (
    get_db_session,
    startup_database,
    shutdown_database
)

app = FastAPI()

@app.on_event("startup")
async def startup():
    await startup_database()

@app.on_event("shutdown")
async def shutdown():
    await shutdown_database()

@app.get("/users")
async def get_users(session: AsyncSession = Depends(get_db_session)):
    result = await session.execute(text("SELECT * FROM users"))
    users = result.fetchall()
    return {"users": users}

3. Use Multiple Databases

from functools import partial
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from pgsqlasync2fast_fastapi import get_db_session

# Create dependency for business database
get_business_session = partial(get_db_session, connection_name="business")

@app.get("/business/data")
async def get_business_data(session: AsyncSession = Depends(get_business_session)):
    result = await session.execute(text("SELECT * FROM business_data"))
    return {"data": result.fetchall()}

4. Create Databases Programmatically

from pgsqlasync2fast_fastapi import create_database, database_exists

# Create a new database (requires a connection with is_superuser=true)
if not await database_exists("new_database"):
    await create_database("new_database", owner="myuser")
    print("Database created!")

Configuration

Environment Variables

All configuration is done through environment variables with the prefix DB_:

Connection Settings

DB_CONNECTIONS__<NAME>__HOST=localhost          # Database host
DB_CONNECTIONS__<NAME>__PORT=5432               # Database port
DB_CONNECTIONS__<NAME>__USERNAME=user           # Database username
DB_CONNECTIONS__<NAME>__PASSWORD=pass           # Database password
DB_CONNECTIONS__<NAME>__DATABASE=dbname         # Database name
DB_CONNECTIONS__<NAME>__IS_SUPERUSER=false      # Superuser privileges

Pool Settings (Optional)

DB_CONNECTIONS__<NAME>__POOL_SIZE=5             # Connection pool size
DB_CONNECTIONS__<NAME>__MAX_OVERFLOW=10         # Max overflow connections
DB_CONNECTIONS__<NAME>__POOL_TIMEOUT=30         # Pool timeout in seconds
DB_CONNECTIONS__<NAME>__POOL_RECYCLE=3600       # Recycle connections after seconds

Global Settings

DB_DEFAULT_CONNECTION=default                    # Default connection name
DB_ECHO=false                                    # Global SQLAlchemy echo mode

API Reference

Dependencies

get_db_session(connection_name: str = "default")

FastAPI dependency that provides an async database session with automatic commit/rollback.

@app.get("/items")
async def get_items(session: AsyncSession = Depends(get_db_session)):
    result = await session.execute(text("SELECT * FROM items"))
    return result.fetchall()

get_db_engine(connection_name: str = "default")

FastAPI dependency that provides the async engine for a connection.

@app.get("/health")
async def health_check(engine: AsyncEngine = Depends(get_db_engine)):
    async with engine.connect() as conn:
        await conn.execute(text("SELECT 1"))
    return {"status": "healthy"}

get_db_manager()

FastAPI dependency that provides the DatabaseManager singleton.

@app.get("/connections")
async def list_connections(manager: DatabaseManager = Depends(get_db_manager)):
    return {"connections": manager.list_connections()}

Database Utilities

create_database(database_name: str, owner: Optional[str] = None, connection_name: Optional[str] = None) -> bool

Create a new database using a superuser connection.

created = await create_database("my_new_db", owner="myuser")
if created:
    print("Database created successfully!")

database_exists(database_name: str, connection_name: Optional[str] = None) -> bool

Check if a database exists.

if await database_exists("my_db"):
    print("Database exists!")

drop_database(database_name: str, connection_name: Optional[str] = None, force: bool = False) -> bool

Drop a database (requires superuser).

dropped = await drop_database("old_db", force=True)

list_databases(connection_name: Optional[str] = None) -> List[str]

List all databases.

databases = await list_databases()
for db in databases:
    print(f"  - {db}")

Startup/Shutdown

startup_database(config: Optional[DatabaseSettings] = None) -> DatabaseManager

Initialize database connections on application startup.

@app.on_event("startup")
async def startup():
    await startup_database()

shutdown_database() -> None

Close all database connections on application shutdown.

@app.on_event("shutdown")
async def shutdown():
    await shutdown_database()

Examples

See the examples/ directory for complete working examples:

  • basic_usage.py - Basic database connection and queries
  • multi_database.py - Using multiple database connections
  • fastapi_integration.py - Complete FastAPI application
  • database_creation.py - Creating databases programmatically

Seeders (v0.9.0+)

Reusable, tenant-agnostic seeder primitives. The engine seeds a single database at a time; multi-tenant orchestration lives in tenants2fast.

from pgsqlasync2fast_fastapi import SeederEngine, SeederFilters

engine = SeederEngine(
    manifest_path="app/seeders/manifest.json",
    model_registry={"clients": Client, "products": Product},
    profile="dev",
    database_factory=lambda name: get_engine(name),
)

result = await engine.seed("my_database")
# Optional filters:
result = await engine.seed(
    "my_database",
    filters=SeederFilters(tables=["clients"]),
)

Manifest v2.0

{
  "version": "2.0",
  "strict": true,
  "on_failure": "rollback_all",
  "uuid_namespace": "01234567-89ab-cdef-0123-456789abcdef",
  "boot": {
    "dev": {
      "tables": {
        "clients": {"file": "boot/clients.json", "mode": "upsert"}
      }
    }
  },
  "on_demand": {
    "demo": {
      "tables": {
        "clients": {"file": "on_demand/demo/clients.json", "mode": "insert_only"}
      }
    }
  },
  "polymorphic_fks": {
    "addresses": {
      "addressable_id": {
        "discriminator": "addressable_type",
        "map": {"client": "clients", "supplier": "suppliers"}
      }
    }
  }
}

Key behaviors

  • Explicit UUID literals: seed JSON should ship explicit UUIDs (preferably uuid7, generated once). The engine never rewrites them. seed_uuid(table, id, namespace) (uuid5) remains only as a legacy aid to derive UUIDs from integer ids; new data should not rely on it.
  • Natural-key idempotency: a table can declare natural_key (e.g. name), so re-seeding matches existing rows by that key instead of the primary key.
  • Efficient upsert: existing rows are compared field by field; UPDATE is issued only when something actually changed.
  • Rollback: on_failure = rollback_all | rollback_table | skip. Only tables with real changes are rolled back (SeederLog).
  • Strict mode: strict: true aborts before any write when validation fails.
  • Conflict resolution: unique_keys + conflict_resolution (validate default, or park_and_upsert for transient unique collisions).
  • FK resolution: integer FKs are rewritten to deterministic UUIDs when present; a polymorphic FK map supports discriminated relations.
  • Public helpers: load_table_data() reads one table/profile; Validator via validate_seeders/validate_seeders_report.

Seed-id adoption (migrating older databases)

When literals change or a project migrates from derived ids, use adopt_explicit_ids before seeding:

from pgsqlasync2fast_fastapi import SeederEngine, adopt_explicit_ids

engine = SeederEngine(manifest_path=..., model_registry=..., profile="dev")
async with AsyncSession(engine_for_connection) as session:
    await adopt_explicit_ids(session, engine)   # strategy="auto"
    await session.commit()

On PostgreSQL it updates primary keys in place and relies on ON UPDATE CASCADE FKs (see pgsqlasync2fast_fastapi.migrations.fk_cascade, used by package/app migration chains). On SQLite it falls back to the copy/repoint/delete strategy. dry_run=True returns the plan without writing; seed_all does this automatically with adopt_ids=True.

Composition: packages + app

seed_all runs every registered package and supports additive apps, overrides and opt-outs:

results = await seed_all("dev")                       # all packages, adopts ids
results = await seed_all("dev", exclude_packages=["pkg-b"])
results = await seed_all("dev", include_packages=["app-seeders"])
  • PackageSeederConfig.overrides: take exclusive ownership of a table.
  • PackageSeederConfig.disabled: skip a package.
  • set_package_enabled / disable_package_seeders / enable_package_seeders.
  • Conflicting overlaps without overrides raise at registration.

Packages ship their own seeders (Fase 1.5)

Packages register their seeders at import time, so a consuming app only needs RUN_SEEDERS=true to get every package's boot data:

# permissions2fast/__init__.py
from pgsqlasync2fast_fastapi import (
    PackageSeederConfig,
    register_package_seeders,
)

register_package_seeders(PackageSeederConfig(
    package_name="permissions2fast-fastapi",
    manifest_path="permissions2fast_fastapi/seeders/manifest.json",
    model_registry={"roles": Role, "permissions": Permission},
    connection="auth",
    priority=10,
))

Then the app runs every registered package in priority order:

from pgsqlasync2fast_fastapi.seeders import seed_all

results = await seed_all("dev")  # dict: package_name -> SeedingResult

Validate seeders in CI

validate_seeders() checks a manifest and its JSON files without a database, so a broken seeder never reaches a release:

from pgsqlasync2fast_fastapi import validate_seeders

def test_seeders_are_valid():
    errors = validate_seeders(
        manifest_path="permissions2fast_fastapi/seeders/manifest.json",
        model_registry={"roles": Role, "permissions": Permission},
    )
    assert errors == []

Checks: manifest/layer/profile exist, every table has a model, every file exists, JSON is a list, no unknown keys, and no duplicate unique_keys.

License

MIT License - see LICENSE file for details.

Author

Angel Daniel Sanchez Castillo - angeldaniel.sanchezcastillo@gmail.com

Metadata

Release files for pgsqlasync2fast-fastapi 0.9.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pgsqlasync2fast-fastapi 0.9.2
File Size Uploaded Provenance Actions
pgsqlasync2fast_fastapi-0.9.2.tar.gz 97.3 kB Without provenance Details for pgsqlasync2fast_fastapi-0.9.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pgsqlasync2fast-fastapi 0.9.2
File Interpreter ABI Platform Actions
pgsqlasync2fast_fastapi-0.9.2-py3-none-any.whl Python 3 none any Details for pgsqlasync2fast_fastapi-0.9.2-py3-none-any.whl

Total release size: 158.1 kB

Release files / pgsqlasync2fast_fastapi-0.9.2.tar.gz

Download URL pgsqlasync2fast_fastapi-0.9.2.tar.gz
Size 97.3 kB
Tags Source
SHA-256 checksum
How to use checksums
49222edd4be9a9b0f23463e2deee5b5ded864fdb9a5baefab3f2cc7d22b77ad7
BLAKE2b-256 checksum
How to use checksums
27feb16515ef0285b35b0a7596679d34942ecead53de9a90937bbd96a30035e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Release files / pgsqlasync2fast_fastapi-0.9.2-py3-none-any.whl

Download URL pgsqlasync2fast_fastapi-0.9.2-py3-none-any.whl
Size 60.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
560c7cd1b1d2ddc56040b9b9c03c57e35aa1420192a93667ac824e2371431ab6
BLAKE2b-256 checksum
How to use checksums
07de74ba40ff45c89a17f23cfb47dbbb23e94fae689d9b1b2490d289f24ac5c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Security for pgsqlasync2fast-fastapi 0.9.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page