perf: precompute mangas.sort_author for the author sort

?sort=author used a correlated min(lower(a.name)) subquery as the ORDER BY
key, evaluated per filter-matching row before LIMIT. Materialize it into
mangas.sort_author (indexed by mangas_sort_author_idx), maintained by triggers
on manga_authors and backfilled in the migration, so the sort is a plain
indexed column read. Author names are immutable, so only join changes matter.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-11 14:29:26 +02:00
parent c11df3182c
commit 5b1ce581f3
6 changed files with 107 additions and 13 deletions

View File

@@ -326,6 +326,54 @@ async fn patch_updates_status_authors_and_genres(pool: PgPool) {
assert_eq!(body["genres"][0]["name"], "Drama");
}
#[sqlx::test(migrations = "./migrations")]
async fn patch_authors_updates_precomputed_sort_author(pool: PgPool) {
// The precomputed mangas.sort_author (used by ?sort=author) must track
// author edits: changing the alphabetically-first author reorders the
// author sort. Two mangas whose relative author order flips after a PATCH.
let h = common::harness(pool.clone());
let (_, cookie) = common::register_user(&h.app).await;
let a = id_of(&create_manga(&h.app, &cookie, json!({ "title": "A", "authors": ["Zeta"] })).await);
let _b = id_of(&create_manga(&h.app, &cookie, json!({ "title": "B", "authors": ["Mid"] })).await);
// Initially: Mid < Zeta, so B before A.
let ids = list_titles(&h.app, "sort=author&order=asc").await;
assert_eq!(ids, vec!["B", "A"]);
// Re-author A to "Alpha", which now sorts first.
let resp = h
.app
.clone()
.oneshot(common::patch_json_with_cookie(
&format!("/api/v1/mangas/{a}"),
json!({ "authors": ["Alpha"] }),
&cookie,
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Now A (Alpha) sorts before B (Mid) — proving sort_author was recomputed.
let ids = list_titles(&h.app, "sort=author&order=asc").await;
assert_eq!(ids, vec!["A", "B"]);
}
async fn list_titles(app: &axum::Router, query: &str) -> Vec<String> {
let resp = app
.clone()
.oneshot(common::get(&format!("/api/v1/mangas?{query}")))
.await
.unwrap();
let body = common::body_json(resp).await;
body["items"]
.as_array()
.unwrap()
.iter()
.map(|m| m["title"].as_str().unwrap().to_string())
.collect()
}
#[sqlx::test(migrations = "./migrations")]
async fn patch_404_on_unknown_id(pool: PgPool) {
let h = common::harness(pool);