ruby2210/rag-chatbot
0
1"""2Database connection and session management for the RAG Chatbot application.3Uses SQLAlchemy with Neon Serverless Postgres.4"""5from sqlalchemy import create_engine6from sqlalchemy.ext.declarative import declarative_base7from sqlalchemy.orm import sessionmaker8from sqlalchemy.orm import Session9from typing import Generator10import os11from .config import settings12 13 14# Create the database engine15engine = create_engine(16 settings.NEON_DATABASE_URL,17 pool_pre_ping=True, # Verify connections before use18 pool_recycle=300, # Recycle connections every 5 minutes19)20 21# Create a configured "Session" class22SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)23 24# Base class for declarative models25Base = declarative_base()26 27 28def get_db() -> Generator[Session, None, None]:29 """30 Dependency function that yields database sessions.31 To be used with FastAPI dependency injection.32 """33 db = SessionLocal()34 try:35 yield db36 finally:37 db.close()38 39 40def init_db():41 """42 Initialize the database tables.43 This function should be called during application startup.44 """45 Base.metadata.create_all(bind=engine)