31 lines
786 B
Python
31 lines
786 B
Python
# -*- coding: utf-8 -*-
|
||
"""Database Engine & Session – SQLite (lokal) oder PostgreSQL (Produktion)."""
|
||
|
||
from sqlalchemy import create_engine
|
||
from sqlalchemy.orm import sessionmaker, Session
|
||
|
||
from .config import DATABASE_URL
|
||
from .core.models import Base
|
||
|
||
engine = create_engine(
|
||
DATABASE_URL,
|
||
echo=False,
|
||
connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {},
|
||
)
|
||
|
||
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||
|
||
|
||
def init_db():
|
||
"""Erstellt alle Tabellen falls sie noch nicht existieren."""
|
||
Base.metadata.create_all(bind=engine)
|
||
|
||
|
||
def get_db() -> Session:
|
||
"""Dependency für FastAPI – liefert eine DB-Session pro Request."""
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|