53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from pathlib import Path
|
|
import os
|
|
|
|
# Get project root directory and create a storage directory
|
|
PROJECT_ROOT = Path(
|
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
)
|
|
DB_DIR = PROJECT_ROOT / "storage" / "db"
|
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
# SQLite database URL
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
|
|
|
# Create the SQLAlchemy engine
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
# Create a SessionLocal class
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Create a Base class for declarative models
|
|
Base = declarative_base()
|
|
|
|
|
|
# Create tables (important for first run)
|
|
def create_tables():
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
# Dependency to get a database session
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
# Test the connection
|
|
db.execute("SELECT 1")
|
|
yield db
|
|
except Exception as e:
|
|
# Log the error (in a real-world application)
|
|
print(f"Database connection error: {e}")
|
|
# Provide a user-friendly error
|
|
from fastapi import HTTPException, status
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="Database connection error. Please try again later.",
|
|
)
|
|
finally:
|
|
db.close()
|