|
|
|
|
|
|
|
|
import os
|
|
|
from pathlib import Path
|
|
|
from sqlalchemy import create_engine
|
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
|
|
|
|
from models import Base
|
|
|
|
|
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
|
DATA_DIR = BASE_DIR / "data"
|
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
DB_PATH = str(DATA_DIR / "db.sqlite")
|
|
|
|
|
|
|
|
|
engine = create_engine(
|
|
|
f"sqlite:///{DB_PATH}",
|
|
|
connect_args={"check_same_thread": False},
|
|
|
echo=False,
|
|
|
pool_pre_ping=True,
|
|
|
future=True,
|
|
|
)
|
|
|
|
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
|
|
|
|
|
def init_db() -> None:
|
|
|
"""
|
|
|
Cria as tabelas caso não existam (com base no models.Base).
|
|
|
Execute isso no boot do app.
|
|
|
"""
|
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
def get_session_safe():
|
|
|
"""
|
|
|
Retorna uma sessão do SQLAlchemy para uso com 'with' ou try/finally.
|
|
|
Obs.: Lembre-se de fechar: db.close()
|
|
|
"""
|
|
|
return SessionLocal() |