Files
stupid-simple-network-inven…/backend/database.py
T
olivier a0b5a55daf fix: isolate tests on in-memory SQLite to protect production database
Tests were importing the production engine and dropping all tables on
teardown, corrupting topology.db in the Docker volume. Set DATABASE_URL
to sqlite:///:memory: before any import in the test file, and use
StaticPool in database.py when running against :memory: so all
connections share the same in-memory database.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 18:22:32 +02:00

38 lines
976 B
Python

import sqlite3
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker, declarative_base
import os
os.makedirs("data", exist_ok=True)
_DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./data/topology.db")
_engine_kwargs: dict = {"connect_args": {"check_same_thread": False}}
if ":memory:" in _DATABASE_URL:
from sqlalchemy.pool import StaticPool
_engine_kwargs["poolclass"] = StaticPool
engine = create_engine(_DATABASE_URL, **_engine_kwargs)
@event.listens_for(Engine, "connect")
def _set_sqlite_pragma(dbapi_conn, _record):
if isinstance(dbapi_conn, sqlite3.Connection):
cursor = dbapi_conn.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()