diff --git a/app/db/session.py b/app/db/session.py index 90fe9a5..ab0f912 100644 --- a/app/db/session.py +++ b/app/db/session.py @@ -3,7 +3,7 @@ import sqlite3 import os from typing import Generator -from sqlalchemy import create_engine, event +from sqlalchemy import create_engine, event, text from sqlalchemy.orm import sessionmaker from app.core.config import settings, DB_DIR @@ -88,6 +88,8 @@ def optimize_sqlite_connection(dbapi_connection, connection_record): """Configure SQLite connection for better reliability.""" try: # These are essential for SQLite stability + # Note: We use raw SQL here because these are SQLite-specific PRAGMA commands + # They are executed at the DBAPI level, not through SQLAlchemy ORM dbapi_connection.execute("PRAGMA journal_mode=WAL") dbapi_connection.execute("PRAGMA synchronous=NORMAL") except Exception as e: @@ -113,7 +115,7 @@ def get_db() -> Generator: print(f"Database connection attempt {attempt + 1}") # Test connection with a simple query - db.execute("SELECT 1") + db.execute(text("SELECT 1")) # Connection succeeded print("Database connection successful") @@ -126,12 +128,22 @@ def get_db() -> Generator: db.close() db = None - error_msg = f"Database connection attempt {attempt + 1} failed: {e}" + # Provide more detailed error messages for common issues + if isinstance(e, ImportError) and "No module named" in str(e): + error_msg = f"Database connection failed due to missing module: {e}. Please check requirements.txt and install missing dependencies." + elif "no such table" in str(e).lower(): + error_msg = f"Database connection failed: Table doesn't exist: {e}. Make sure to run all migrations with 'alembic upgrade head'." + elif "sqlalchemy.exc.argumenterror" in str(e).lower(): + error_msg = f"Database connection failed: SQLAlchemy Argument Error: {e}. Make sure all raw SQL is wrapped with text()." + else: + error_msg = f"Database connection attempt {attempt + 1} failed: {e}" + print(error_msg) # Log critical error details import traceback + print(f"Error type: {type(e).__name__}") print(f"Error traceback: {traceback.format_exc()}") # Check if we can directly access database