DB performance: WAL mode, indexes, and query optimization #127
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Cang's SQLite database currently has a single index (on
pathfor dedup) and runs in default journal mode. With ~30k snapshots and growing, several operations feel sluggish:list_motion_snapshots_for_range— no index onmotionorrecorded_atThe fix involves four changes: enable WAL mode, add two covering indexes, rewrite queries to use range scans (so the indexes are actually used), and serve scrubber images by snapshot ID (PK lookup) instead of re-running the filtered query on every frame.
Plan
1. Enable WAL mode
In
open_db(), addPRAGMA journal_mode=WALandPRAGMA synchronous=NORMAL. This allows concurrent reads during writes, eliminating the login hang when a periodic scan is in progress.2. Schema V4 — two new indexes
Create a V4 migration that adds:
idx_snapshots_camera_recordedon(camera, recorded_at)— coverslist_snapshots_for_dayandlatest_snapshot_per_cameraidx_snapshots_motion_recordedon(motion, recorded_at)— coverslist_motion_snapshots_for_range3. Rewrite queries for index-friendly range scans
The current queries use
DATE(recorded_at) = ?which prevents index usage. Rewrite to range scans using ISO 8601 lexicographic ordering:list_snapshots_for_day:recorded_at >= ? AND recorded_at < ?(day boundaries)list_motion_snapshots_for_range:recorded_at >= ? AND recorded_at < ?(with computed end-date + 1)list_snapshots_for_daybecome full-datetime comparisons4. Serve scrubber images by snapshot ID
Currently
snapshot_image()re-runslist_snapshots_for_day()on every frame to find the nth snapshot's path. Instead:idvalues to thesnapshots_jsonpayload in the templateGET /snapshots/{id}/imgthat does a PK lookupFiles touched
src/cang/db.py— WAL pragma, V4 migration, query rewrites, newsnapshot_by_idfunctionsrc/cang/web/routes/snapshots.py— new by-ID image route, pass IDs in JSONsrc/cang/web/templates/scrubber.html— JS changes to use ID-based URLstests/test_db.py— tests for new indexes, query rewrites, and by-ID lookuptests/test_db_queries.py— tests for updated motion range querytests/web/test_snapshot_scrubber.py— tests for by-ID image servingBranch
perf/issue-127-db-indexes-walCommits
:zap: Enable WAL mode, add performance indexes, rewrite queries for range scans:zap: Serve scrubber images by snapshot ID via PK lookupPR