59 lines
2.1 KiB
Python

import os
import logging
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from app.core.config import settings
logger = logging.getLogger(__name__)
# Ensure the database directory exists with proper error handling
try:
DB_DIR = settings.DB_DIR
DB_DIR.mkdir(parents=True, exist_ok=True)
logger.info(f"Database directory created at: {DB_DIR}")
except (PermissionError, OSError) as e:
# If we can't create the directory, log the error and try a fallback location
logger.error(f"Failed to create database directory at {DB_DIR}: {str(e)}")
# Fallback to a directory in the current working directory
DB_DIR = Path(os.getcwd()) / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
logger.info(f"Using fallback database directory: {DB_DIR}")
# Create the database URL
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
logger.info(f"Using database URL: {SQLALCHEMY_DATABASE_URL}")
# Create the engine with proper error handling
try:
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
logger.info("Database engine initialized successfully")
except SQLAlchemyError as e:
logger.error(f"Failed to initialize database engine: {str(e)}")
# Create a dummy engine and session for the app to at least start
# This will cause database operations to fail, but the app will start
engine = None
SessionLocal = None
def get_db():
if SessionLocal is None:
# If SessionLocal is None, the database engine failed to initialize
# Log an error and raise an exception
logger.error("Cannot get database session: Database engine not initialized")
raise SQLAlchemyError("Database engine not initialized")
db = SessionLocal()
try:
yield db
except SQLAlchemyError as e:
logger.error(f"Database error: {str(e)}")
raise
finally:
db.close()