Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 2025-08-01 - [Avoid correlated subqueries in list_books]
## 2025-08-01 - [Avoid correlated subqueries in list_books]
**Learning:** SQLite correlated subqueries in the SELECT clause (e.g., COUNT(), group_concat()) evaluate on the full result set before LIMIT/OFFSET are applied, causing N+1 performance bottlenecks for large lists.
**Action:** Use a CTE to evaluate WHERE, ORDER BY, LIMIT, and OFFSET first, then select from the limited rows and apply correlated subqueries.
13 changes: 9 additions & 4 deletions src-tauri/src/library/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1339,10 +1339,15 @@ impl Repository {
LEFT JOIN book_files bf ON bf.book_id = lb.id
GROUP BY lb.id, lb.title, lb.authors_json"
} else {
"SELECT b.id, b.title, b.authors_json, COUNT(DISTINCT bf.file_id) AS file_count
FROM books b
LEFT JOIN book_files bf ON bf.book_id = b.id
GROUP BY b.id, b.title, b.authors_json"
"WITH limited_books AS (
SELECT id, title, authors_json
FROM books
LIMIT 200
)
SELECT lb.id, lb.title, lb.authors_json, COUNT(DISTINCT bf.file_id) AS file_count
FROM limited_books lb
LEFT JOIN book_files bf ON bf.book_id = lb.id
GROUP BY lb.id, lb.title, lb.authors_json"
};
let mut stmt = conn.prepare(query)?;

Expand Down