Skip to content

Scaffold async database connection#2

Closed
podmar wants to merge 1 commit into
mainfrom
feat/db-connection
Closed

Scaffold async database connection#2
podmar wants to merge 1 commit into
mainfrom
feat/db-connection

Conversation

@podmar

@podmar podmar commented May 28, 2026

Copy link
Copy Markdown
Owner

Covers async DB connection layer.

Changes

  • app/database.py — async SQLAlchemy engine, session factory, and create_db_and_tables() startup hook
  • app/main.py — wired lifespan context manager to call create_db_and_tables() on startup
  • pyproject.toml — added sqlmodel, asyncpg, python-dotenv

Why these packages

  • SQLModel unifies SQLAlchemy (DB layer) and Pydantic (API layer) into one model class, avoiding duplicate schema definitions
  • asyncpg is the native async Postgres driver — the standard psycopg2 would block the event loop on every query
  • python-dotenv loads .env locally; on hosted platforms the env var comes from the platform directly and dotenv silently no-ops

Key patterns

  • One engine per process (connection pool, not per-request connections)
  • get_session as a FastAPI Depends — opens before the handler, guaranteed close/rollback after
  • expire_on_commit=False — keeps objects readable post-commit without a follow-up query (required in async, where lazy loading isn't available)
  • lifespan over the deprecated @app.on_event("startup")

@podmar podmar closed this May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant