app.database module#
Database engines and session factories (sync and async) for the app.
This module centralizes SQLAlchemy setup. It exposes reusable, process-wide
engine singletons and companion session factories for both synchronous and
asynchronous usage. When targeting SQLite, it applies pragmatic defaults to
improve concurrency (WAL) and resilience (busy timeout) via connection event
hooks. All ORM models inherit from the exported Base.
See Also#
app.modelsDeclarative ORM models (bound to
app.database.Base).app.schemasPydantic schemas mirroring ORM shapes.
app.mainFastAPI app wiring request-scoped DB sessions.
app.configSource of
settings.DATABASE_URL.
Notes#
Primary role: provide ready-to-use SQLAlchemy engines and session factories and a declarative
Basefor model definitions.Key dependencies:
app.config.settings.DATABASE_URLmust be defined; SQLAlchemy (sync/async) drivers must be available for the chosen URL.Invariants: engines are module-level singletons; SQLite engines use
check_same_thread=Falseand have PRAGMAjournal_mode=WALandbusy_timeoutset at connect time.
Examples#
>>> # Ensure schema exists (tables are created if missing)
>>> from app.database import ensure_database_schema
>>> ensure_database_schema()
>>> # Sync usage
>>> from app.database import SessionLocal
>>> with SessionLocal() as session:
... pass
>>> # Async usage
>>> from app.database import AsyncSessionLocal
>>> async def get_count() -> int:
... async with AsyncSessionLocal() as session:
... return 0
- class app.database.Base(*args: Any, **kwargs: Any)[source]#
Bases:
DeclarativeBaseDeclarative base for all ORM models.
All SQLAlchemy ORM models in this project must inherit from this base. The metadata bound to this base is used by
ensure_database_schema()to create database tables.Notes
Exposed so that
app.modelscan subclass it for all entities.Keeps a single metadata registry for consistent schema management.
- app.database.ensure_database_schema() None[source]#
Create missing tables based on ORM metadata.
Delegates to SQLAlchemy’s
Base.metadata.create_allusing the configured synchronous engine. This is idempotent and safe to call during startup or migrations bootstrap.- Raises:
SQLAlchemyErrorIf the schema creation step fails (for example due to missing privileges or an unavailable database).
See also
app.modelsEntities whose tables are created from the metadata.
app.mainApplication startup that may call this function.
Examples
>>> from app.database import ensure_database_schema >>> ensure_database_schema()