feat: pg_trgm search, sort options, populated total count
Backend:
- Migration 0005_search.sql enables pg_trgm and adds GIN indexes
(gin_trgm_ops) on mangas.title and on mangas.author (partial, WHERE
author IS NOT NULL).
- repo::manga::list keeps the existing substring (ILIKE) clause and
adds the `%` operator on title + author so the search tolerates typos
('narto' → 'Naruto'). Both branches share the trgm index. A second
count(*) query (same WHERE clause, indexed) yields the total without
scanning twice in any meaningful sense.
- New ListSort enum (Recent / Title) interpolated into ORDER BY from a
hard-coded match — never from request input, so the format!() is not
a SQL-injection seam. Default stays Recent (created_at DESC).
- api::mangas accepts `?sort=recent|title` (snake_case) via serde and
returns `page.total` as a number instead of null.
- api::pagination::PagedResponse gains a `with_total` constructor.
Backend coverage in tests/api_mangas.rs (4 new cases plus the existing
list_is_empty_initially updated to assert total: 0):
- list_returns_total_count_independent_of_pagination — limit=2 with 3
rows returns 2 items and total=3.
- search_via_trigram_tolerates_typos — `?search=narto` finds Naruto.
- list_sort_title_orders_alphabetically — three out-of-order inserts
come back A→Z.
- search_reflects_filtered_total — search narrows total to 1.
Frontend:
- lib/api/mangas.ts gains a `MangaSort` type and threads `sort` through
listMangas's query-string builder.
- Home page renders a "Sort" select (Recent / Title A→Z) that re-runs
the list query, and shows "Showing N of M" when total is present.
Lockstep version bump to 0.8.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,44 +5,90 @@
|
||||
//! handlers depend only on `sqlx::PgPool`, not on a trait object. Swap to
|
||||
//! a trait + impl if a second backend ever becomes necessary.
|
||||
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain::manga::{Manga, NewManga};
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ListSort {
|
||||
/// Newest first (default).
|
||||
#[default]
|
||||
Recent,
|
||||
/// A→Z by title (case-insensitive).
|
||||
Title,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ListQuery {
|
||||
pub search: Option<String>,
|
||||
pub limit: i64,
|
||||
pub offset: i64,
|
||||
pub sort: ListSort,
|
||||
}
|
||||
|
||||
impl Default for ListQuery {
|
||||
fn default() -> Self {
|
||||
Self { search: None, limit: 50, offset: 0 }
|
||||
Self {
|
||||
search: None,
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
sort: ListSort::Recent,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list(pool: &PgPool, query: &ListQuery) -> AppResult<Vec<Manga>> {
|
||||
let pattern = query.search.as_deref().map(|s| format!("%{}%", s));
|
||||
let rows = sqlx::query_as::<_, Manga>(
|
||||
/// Returns the page of mangas matching `query` plus the unfiltered total
|
||||
/// count for the same filter. The trigram GIN indexes (see 0005_search.sql)
|
||||
/// keep both queries cheap as the library grows.
|
||||
pub async fn list(pool: &PgPool, query: &ListQuery) -> AppResult<(Vec<Manga>, i64)> {
|
||||
// `order_by` is interpolated from a hard-coded enum, never from request
|
||||
// input, so this is not a SQL injection seam.
|
||||
let order_by = match query.sort {
|
||||
ListSort::Recent => "created_at DESC, id",
|
||||
ListSort::Title => "lower(title) ASC, id",
|
||||
};
|
||||
|
||||
let search = query.search.as_deref();
|
||||
|
||||
let list_sql = format!(
|
||||
r#"
|
||||
SELECT id, title, author, description, cover_image_path, created_at, updated_at
|
||||
FROM mangas
|
||||
WHERE $1::text IS NULL
|
||||
OR title ILIKE $1
|
||||
OR COALESCE(author, '') ILIKE $1
|
||||
ORDER BY created_at DESC
|
||||
OR title ILIKE '%' || $1 || '%'
|
||||
OR COALESCE(author, '') ILIKE '%' || $1 || '%'
|
||||
OR title % $1
|
||||
OR (author IS NOT NULL AND author % $1)
|
||||
ORDER BY {order_by}
|
||||
LIMIT $2 OFFSET $3
|
||||
"#,
|
||||
)
|
||||
.bind(pattern)
|
||||
.bind(query.limit)
|
||||
.bind(query.offset)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
"#
|
||||
);
|
||||
|
||||
let rows = sqlx::query_as::<_, Manga>(&list_sql)
|
||||
.bind(search)
|
||||
.bind(query.limit)
|
||||
.bind(query.offset)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let count_sql = r#"
|
||||
SELECT count(*) FROM mangas
|
||||
WHERE $1::text IS NULL
|
||||
OR title ILIKE '%' || $1 || '%'
|
||||
OR COALESCE(author, '') ILIKE '%' || $1 || '%'
|
||||
OR title % $1
|
||||
OR (author IS NOT NULL AND author % $1)
|
||||
"#;
|
||||
let (total,): (i64,) = sqlx::query_as(count_sql)
|
||||
.bind(search)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
|
||||
Ok((rows, total))
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Manga> {
|
||||
|
||||
Reference in New Issue
Block a user