HUTAMS_AUDIO/app/db/database.py

37 lines
1.1 KiB
Python

"""
SQLAlchemy 엔진 및 세션 설정 모듈.
프로젝트 루트 디렉토리에 whisper.db SQLite 파일을 생성합니다.
"""
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
# 프로젝트 루트 기준 DB 경로
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DATABASE_URL = f"sqlite:///{os.path.join(BASE_DIR, 'whisper.db')}"
engine = create_engine(
DATABASE_URL,
connect_args={"check_same_thread": False}, # SQLite + 멀티스레드 허용
echo=False # SQL 쿼리 로깅: 필요 시 True로 변경
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
class Base(DeclarativeBase):
pass
def get_db():
"""FastAPI Depends용 DB 세션 제공 함수 (컨텍스트 매니저)"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def init_db():
"""모든 테이블을 생성 (최초 1회 실행)"""
# models.py를 임포트하여 Base 메타데이터에 테이블 등록
from app.db import models # noqa: F401
Base.metadata.create_all(bind=engine)