Database Module
database
Database connection and session management.
This module provides async database engine initialization and session management for SQLModel/SQLAlchemy. It uses connection pooling and is designed to be initialized once during application startup.
Functions
init_engine
Initialize the async engine and sessionmaker.
Creates a connection pool and session factory. Should be called once during application startup (typically in FastAPI lifespan). Reads DATABASE_URL from environment variables.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If DATABASE_URL environment variable is not set. |
Note
Uses connection pooling with: - pool_size: 5 connections - max_overflow: 10 additional connections - pool_pre_ping: True (validates connections before use)
Source code in bitonicai/database.py
get_session
async
FastAPI dependency that provides a scoped async session.
Yields a database session that is automatically closed after the request. Use this as a FastAPI dependency in route handlers.
Yields:
| Name | Type | Description |
|---|---|---|
AsyncSession |
AsyncGenerator[AsyncSession, None]
|
Database session instance. |
Example
Source code in bitonicai/database.py
create_all_tables
async
Create database tables using SQLModel metadata.
Creates all tables defined in SQLModel entities. This is typically only used for development or testing. In production, use Alembic migrations instead.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If engine is not initialized (call init_engine first). |
Source code in bitonicai/database.py
dispose_engine
async
Dispose of the engine and close all connections.
Closes all database connections and cleans up the connection pool. Should be called during application shutdown (typically in FastAPI lifespan).