Kentlo's picture
쀑볡닡변 κ°€λŠ₯ 버전
08348fb
# ==============================================
# db.py
# ==============================================
import os
from pathlib import Path
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker, declarative_base
# ----------------------------------------------
# 1. 경둜 및 DB μ„€μ •
# ----------------------------------------------
BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR / "data"
DATA_DIR.mkdir(parents=True, exist_ok=True)
DB_PATH = DATA_DIR / "questions.db"
DATABASE_URL = f"sqlite:///{DB_PATH.as_posix()}"
# ----------------------------------------------
# 2. SQLAlchemy Engine 생성
# ----------------------------------------------
# check_same_thread=False: SQLiteλ₯Ό λ©€ν‹° μŠ€λ ˆλ“œ ν™˜κ²½(FastAPI λ“±)μ—μ„œ μ“Έ λ•Œ ν•„μˆ˜
engine = create_engine(
DATABASE_URL,
connect_args={"check_same_thread": False},
echo=False, # SQL λ‘œκ·Έκ°€ ν•„μš”ν•˜λ©΄ True둜 λ³€κ²½
future=True
)
# ----------------------------------------------
# 3. Session μ„€μ •
# ----------------------------------------------
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
# ----------------------------------------------
# 4. Base λͺ¨λΈ (ORM 곡톡 λΆ€λͺ¨)
# ----------------------------------------------
Base = declarative_base()
# ----------------------------------------------
# 5. DB μ΄ˆκΈ°ν™” ν•¨μˆ˜ (ν…Œμ΄λΈ” 생성 및 확인)
# ----------------------------------------------
def init_db():
# λͺ¨λΈλ“€μ„ μ—¬κΈ°μ„œ import ν•΄μ•Ό Base.metadata에 등둝됨
# (μˆœν™˜ μ°Έμ‘° λ°©μ§€λ₯Ό μœ„ν•΄ ν•¨μˆ˜ λ‚΄λΆ€ import ꢌμž₯)
from models import Question, Attempt
# ν…Œμ΄λΈ” 생성 (이미 있으면 λ¬΄μ‹œν•¨)
Base.metadata.create_all(bind=engine)
print(f"\n[INFO] βœ… Database Connected: {DB_PATH}")
print("──────────────────────────────────────────────")
# μƒμ„±λœ ν…Œμ΄λΈ” ꡬ쑰 확인 (λ””λ²„κΉ…μš©)
inspector = inspect(engine)
table_names = inspector.get_table_names()
if not table_names:
print("⚠️ No tables found. Did you define classes in models.py?")
for table in table_names:
print(f"πŸ“˜ Table: {table}")
for col in inspector.get_columns(table):
# 컬럼λͺ…, νƒ€μž… 좜λ ₯
print(f" β€’ {col['name']:<15} {str(col['type'])}")
print("──────────────────────────────────────────────\n")
# ----------------------------------------------
# 6. Dependency (FastAPI λ“±μ—μ„œ μ‚¬μš©)
# ----------------------------------------------
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()