Spaces:
Sleeping
Sleeping
File size: 4,033 Bytes
5be081e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | """
Database Package Initialization for Todo API
Owner: Database Reliability Engineer
Purpose: Central database module exports and initialization
Architecture: Async/await with SQLModel and Neon PostgreSQL
This module provides:
- Database connection management (get_session, get_engine)
- SQLModel models (Todo, TodoCreate, TodoUpdate, TodoResponse)
- Initialization utilities (create_tables, init_database)
- Health check functions
Usage:
from backend.src.db import get_session, Todo, TodoCreate
from backend.src.db import init_database
# Initialize database on startup
await init_database()
# Use in FastAPI routes
@app.get("/api/todos")
async def list_todos(session: AsyncSession = Depends(get_session)):
# Query todos with user isolation
pass
"""
import logging
from sqlalchemy.ext.asyncio import AsyncSession, AsyncEngine
from sqlalchemy import text
# Import connection utilities
from .connection import (
get_engine,
get_session,
get_session_factory,
create_tables,
close_engine,
check_database_health,
)
# Import models
from .models import (
Todo,
TodoBase,
TodoCreate,
TodoUpdate,
TodoResponse,
)
# Import chat models (Phase III)
from ..models.conversation import Conversation
from ..models.message import Message
# Configure logging
logger = logging.getLogger("database")
async def init_database() -> None:
"""
Initialize the database for the Todo API.
This function should be called once during application startup.
Steps:
1. Create all SQLModel tables (todos table)
2. Create composite index for query optimization
3. Verify database connectivity
Note:
- Better Auth tables are managed separately (not created here)
- Only creates tables that don't exist (IF NOT EXISTS)
- Safe to call multiple times (idempotent)
Raises:
Exception: If database initialization fails
"""
logger.info("Initializing database for Todo API...")
try:
# Step 1: Create all SQLModel tables
await create_tables()
logger.info("✓ Database tables created")
# Step 2: Create composite index for optimized queries
# Index: (user_id, is_completed) for "show my incomplete todos" queries
engine = get_engine()
async with engine.begin() as conn:
# Check if index exists before creating
await conn.execute(text("""
CREATE INDEX IF NOT EXISTS idx_todos_user_completed
ON todos(user_id, is_completed);
"""))
logger.info("✓ Composite index created (user_id, is_completed)")
# Step 3: Verify database connectivity
is_healthy = await check_database_health()
if not is_healthy:
raise ConnectionError("Database health check failed")
logger.info("✓ Database health check passed")
logger.info("Database initialization complete")
except Exception as e:
logger.error(f"Database initialization failed: {e}")
raise
async def cleanup_database() -> None:
"""
Cleanup database connections during application shutdown.
This function should be called during application shutdown to:
- Close all database connections
- Release connection pool resources
- Ensure graceful shutdown
Usage:
@app.on_event("shutdown")
async def shutdown():
await cleanup_database()
"""
logger.info("Cleaning up database connections...")
await close_engine()
logger.info("Database cleanup complete")
# Export all public components
__all__ = [
# Connection utilities
"get_engine",
"get_session",
"get_session_factory",
"create_tables",
"close_engine",
"check_database_health",
# Models
"Todo",
"TodoBase",
"TodoCreate",
"TodoUpdate",
"TodoResponse",
# Chat models (Phase III)
"Conversation",
"Message",
# Initialization
"init_database",
"cleanup_database",
]
|