"""Generated by Drydock. A fresh store with the declared schema, for criteria and tests."""
from __future__ import annotations
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from .db import Database
from .schema import open_database
SCHEMA_PATH = Path(__file__).resolve().parent.parent / "schema.sql"
@contextmanager
def db_session(dsn: str | None = None) -> Iterator[Database]:
"""Open a fresh test store, or inspect an explicitly supplied existing store.
Acceptance criteria use an explicit DSN to read state created through the CLI. Reapplying
the generated initialization script in that case would drop the rows being inspected.
"""
with tempfile.TemporaryDirectory() as directory:
target = dsn or str(Path(directory, "test.db"))
database = open_database(target)
try:
if dsn is None and SCHEMA_PATH.is_file():
database.execute_script(SCHEMA_PATH.read_text(encoding="utf-8"))
yield database
finally:
database.close()
Run artifact