Files
ImpTune/imptune/db/database.py
T
kawa 356c2ee690 feat(03-01): implement printer and client CRUD with HTMX/Alpine.js UI
- imptune/api/printers.py: POST /printers (all form fields, checkbox->bool,
  FK resolution), DELETE /printers/{id}, grouped list renderer with LEFT JOIN
- imptune/api/clients.py: POST /clients with duplicate-name handling
- imptune/api/pages.py: GET /printers and GET /clients page routes
- imptune/main.py: register printers + clients routers; close db on shutdown
- imptune/db/database.py: close existing connection before re-init (test isolation)
- templates: printers.html, clients.html, printer_form.html (Alpine.js port
  auto-derivation), printer_list.html (grouped by client), client_list.html
- tests/conftest.py: close test-thread db connection in fixture teardown
- tests/test_printer_crud.py: updated to use list(select().where()) for DB
  queries (avoids Peewee thread-local cursor caching across test boundaries)

Auto-fix [Rule 1 - Bug]: DB test isolation — Peewee thread-local connections
persisted across tests causing stale DB reads; fixed via conftest teardown and
lifespan db.close() on shutdown.
2026-04-10 12:56:09 +02:00

37 lines
1.1 KiB
Python

"""Peewee SQLite database instance and initialization."""
from peewee import SqliteDatabase
from imptune.config import DB_PATH
# Deferred init — path is set at runtime via init_db() so tests can override DB_PATH
db = SqliteDatabase(None)
def init_db() -> None:
"""Initialize the SQLite database with WAL mode and foreign keys.
Idempotent — safe to call on every application startup.
Creates all ORM tables if they do not already exist.
Closes any existing connection before re-initializing so that test
fixtures can monkeypatch DB_PATH between test runs.
"""
from imptune.db.models import Client, Driver, Printer, Icon
# Re-read DB_PATH each time so tests can patch imptune.config.DB_PATH
import imptune.config as cfg
# Close any lingering connection from a previous run (important for tests)
if not db.is_closed():
db.close()
db.init(
cfg.DB_PATH,
pragmas={
"journal_mode": "wal",
"foreign_keys": 1,
},
)
db.connect(reuse_if_open=True)
db.create_tables([Client, Driver, Printer, Icon], safe=True)