* docs: define ebook architecture matching audiobooks * docs: plan ebook audiobook-parity implementation * feat: add ebook scanner parser foundation * fix: harden ebook scanner foundation * fix: handle ebook isbn labels * fix: guard ebook subtree scans * feat: scan ebook libraries in core * fix: preserve ebook scan people credits * fix: refresh ebook scan metadata safely * feat: persist ebook series membership * test: cover ebook series persistence decisions * fix: address ebook scanner PR review * docs: clarify ebook foundation PR scope * feat: add ebook metadata enricher * fix: harden ebook poster cache * feat: wire ebook metadata sync task * feat: expose ebook library metadata setup * feat: add ebook catalog scope support * feat: add ebook detail view * feat: label ebook file versions by format * feat: use file-size copy for downloads * feat: use file language in download dialog * test: cover ebook detail authors and downloads * fix: drop narrator credits from ebook scanner merges * fix: align ebook collection filters with book media * fix: drop asin provider ids from ebook enrichment * fix: force ebook people refresh for stale narrators * chore: omit ebook planning docs from branch * feat: add ebook detail related content * feat: add ebook reader file entrypoint * feat: render ebooks with foliate reader * feat: persist ebook reader progress * feat: add ebook reader controls * feat: extract ebook pdf metadata * feat: favor scanner isbn during ebook enrichment * feat: extract fbz ebook metadata * feat: count cbz ebook pages * feat: show ebook file page counts * feat: show ebook download summaries * feat: switch ebook reader files * feat: prefer epub for ebook read action * feat: surface ebook reader progress * feat: sync ebook reader progress cache * feat: hide ebook read action for unsupported files * feat: filter ebook reader file selector * fix: serve fbz ebook archives with reader mime type * fix: detect fbz ebooks from compound filename * fix: authorize fbz ebooks from compound filename * fix: scope ebook catalog facets * fix: reject narrator queries for ebooks * fix: build ebook recommendation text from authors * fix: include ebooks in embedding eligibility * fix: include ebooks in recommendation media mix * fix: include ebooks in recently added recommendations * feat: include ebook progress in recommendation signals * feat: include ebooks in continue watching sections * feat: include ebooks in catalog progress metrics * fix: read ebook isbn from epub metadata * fix: filter ebook asin provider aliases * fix: fall back from unsupported ebook reader files * fix: sort ebook catalogs by reader progress * fix: filter ebook catalogs by reader progress * fix: include ebooks in last watched catalog filters * feat: reflect ebook reader progress in item user state * feat: share ebook progress state across item surfaces * feat: report ebook scan progress * fix: include ebook activity in recommendations * fix: expose ebook reader progress on item detail * fix: support ebook subtree scans * fix: honor profile header for ebook item progress * fix: add ebook library default sections * fix: route ebook continue cards to reader * fix: hide watched toggle for ebooks * fix: route ebook watch tonight cards to reader * fix: route ebook hero actions to reader * fix: detect archive ebook reader formats by filename * feat: cache embedded ebook covers during scan * fix: encode ebook hero reader links * fix: persist non-epub ebook reader progress * fix: scope narrator catalog badges to audiobooks * fix: merge ebook reader progress during item repair * fix: label ebook progress filters as read * fix: show ebook related rails as book covers * fix: remove txt ebook reader support * fix: reject txt ebook reader files * fix: label ebook advanced filters as read * fix: label ebook personalized sorts as read * fix: remove plain text reader loader path * test: cover ebook unread catalog rules * fix: preserve ebook reader library context * fix: link ebook genres with library scope * fix: encode related rail item links * fix: encode catalog card item links * fix: encode hero and continue item links * fix: encode watch tonight item links * fix: encode recommendation and search item links * test: cover ebook scan format set * fix: label ebook search results clearly * fix: make global search prompt media neutral * fix: encode catalog read API ids * fix: encode item API ids * fix: include ebook reader vendor in docker build * fix: make ebook reader build clean * fix: clean ebook embedded descriptions * docs: plan ebook reader shell parity * feat: add ebook reader shell controls * fix: widen ebook scrolled reader flow * fix: remove scrolled reader content width cap * docs: plan ebook reader full parity * feat: persist ebook reader config * feat: add ebook annotations and bookmarks * feat: add ebook reader tools and aids * feat: add ebook advanced reader settings * fix: keep ebook reader panel in viewport * fix: use foliate sizing units for ebook scroll flow * fix: keep ebook settings controls readable * fix: simplify ebook reader settings controls * feat(ebooks): extract local covers during scan (#98) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): add reader profiles and ruler (#99) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * Merge branch 'main' into work/ebooks-reader-base Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(docker): copy foliate-js vendor into Dockerfile.dev frontend stage foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): render Continue Reading sections as upright poster cards All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): stop related-rail highlight ring clipping on detail pages Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): harden ebook scanning against data loss and bad metadata - Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): make enrichment failures non-terminal with dedicated backoff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): gate ebook progress on hidden history and centralize threshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(recommendations): correct watcher counting and wire ebook taste signals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): harden ebook reader endpoints and serve a Content-Security-Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(api): native read-state endpoints for ebooks - POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts progress 1.0 preserving the reader's file/location (or picks the preferred reader file for never-opened books); mark unread mirrors video unwatch semantics and deletes the progress row. - /history/remove accepts ebooks: hides via user_history_hidden_items without touching the reading position (hidden != unread; next reading activity resurfaces the book, mirroring video re-watch). - Access-filter checks match the video branch; shared logic lives in ebook_read_state.go. Sort metrics/user-state thresholds use the shared constant; profile-header fallback deduplicated. Clients: response is {type: "ebook", affected_count: 1, played: bool}; the existing watched SSE event fires. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): harden the ebook reader UI - Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): mark read/unread affordances for ebooks - Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: record the PR #124 review and hardening pass Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
918 lines
32 KiB
Go
918 lines
32 KiB
Go
package catalog
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestBuildSortClause_LastAirDateUsesNullsLast(t *testing.T) {
|
|
// Migration 103 denormalized the aired-episode aggregate onto
|
|
// media_items.last_air_date_at, replacing the per-row correlated
|
|
// MAX(e.air_date) subquery and the sort-time derived-table JOIN
|
|
// (audit 2026-05-01 §2.1 hot path #1).
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{
|
|
Field: "last_air_date",
|
|
Order: "desc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 0 {
|
|
t.Fatalf("expected no args, got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 0 {
|
|
t.Fatalf("expected no joins (denormalized column), got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "mi.last_air_date_at") {
|
|
t.Fatalf("expected last_air_date sort to read mi.last_air_date_at, got %q", plan.OrderBy)
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "NULLS LAST") {
|
|
t.Fatalf("expected last_air_date sort to push undated items last, got %q", plan.OrderBy)
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "LOWER(COALESCE(NULLIF(BTRIM(mi.sort_title), ''), mi.title)) ASC") {
|
|
t.Fatalf("expected title tie-breaker, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_ReleaseDateUsesNullsLast(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").BuildSortClause(QuerySort{
|
|
Field: "release_date",
|
|
Order: "desc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortClause returned error: %v", err)
|
|
}
|
|
if len(args) != 0 {
|
|
t.Fatalf("expected no args, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "COALESCE(mi.release_date::text, NULLIF(BTRIM(mi.first_air_date), '')) DESC") {
|
|
t.Fatalf("expected release_date sort clause, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "NULLS LAST") {
|
|
t.Fatalf("expected release_date sort to push undated items last, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_ReleaseDateUsesEpisodeAirDateForEpisodeScope(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").
|
|
WithMediaScope("episode").
|
|
BuildSortClause(QuerySort{
|
|
Field: "release_date",
|
|
Order: "desc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortClause returned error: %v", err)
|
|
}
|
|
if len(args) != 0 {
|
|
t.Fatalf("expected no args, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "mi.episode_air_date DESC") {
|
|
t.Fatalf("expected episode release_date sort to use raw episode_air_date, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "NULLS LAST") {
|
|
t.Fatalf("expected episode release_date sort to push undated items last, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_TitleUsesEpisodeSortKeyForEpisodeScope(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").
|
|
WithMediaScope("episode").
|
|
BuildSortClause(QuerySort{
|
|
Field: "title",
|
|
Order: "asc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortClause returned error: %v", err)
|
|
}
|
|
if len(args) != 0 {
|
|
t.Fatalf("expected no args, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "ORDER BY mi.sort_key ASC, mi.content_id ASC") {
|
|
t.Fatalf("expected episode title sort to use indexed sort_key, got %q", clause)
|
|
}
|
|
if strings.Contains(clause, "BTRIM(mi.sort_title)") {
|
|
t.Fatalf("episode title sort should not recompute sort_title expression, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_AddedAtUsesScopedFirstSeenAt(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithLibraryScope([]int{3, 7}).
|
|
BuildSortPlan(QuerySort{Field: "added_at", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 2 || plan.Args[0] != 3 || plan.Args[1] != 7 {
|
|
t.Fatalf("expected scoped library args [3 7], got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "SELECT mil.content_id, MIN(mil.first_seen_at) AS added_at") {
|
|
t.Fatalf("expected aggregated first_seen_at join, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "mil.media_folder_id IN ($1, $2)") {
|
|
t.Fatalf("expected scoped library filter, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "sort_added.added_at DESC NULLS LAST") {
|
|
t.Fatalf("expected joined added_at ordering, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_AddedAtFallsBackToCreatedAtWithoutLibraryScope(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{Field: "added_at", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 0 {
|
|
t.Fatalf("expected no args, got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 0 {
|
|
t.Fatalf("expected no joins without library scope, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "mi.created_at DESC") {
|
|
t.Fatalf("expected created_at fallback without library scope, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuild_AddedAtInLastAcceptsYears(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{{
|
|
Match: "all",
|
|
Rules: []QueryRule{{Field: "added_at", Op: "in_last", Value: "1y"}},
|
|
}},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 0 {
|
|
t.Fatalf("expected no args, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "mi.created_at >= NOW() - INTERVAL '1 years'") {
|
|
t.Fatalf("expected added_at in_last to use created_at and years interval, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_ReleaseDateInLastComparesDateExpression(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{{
|
|
Match: "all",
|
|
Rules: []QueryRule{{Field: "release_date", Op: "in_last", Value: "1y"}},
|
|
}},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 0 {
|
|
t.Fatalf("expected no args, got %v", args)
|
|
}
|
|
for _, want := range []string{
|
|
"COALESCE(mi.release_date, CASE WHEN NULLIF(BTRIM(mi.first_air_date), '') ~",
|
|
">= (CURRENT_DATE - INTERVAL '1 years')::date",
|
|
} {
|
|
if !strings.Contains(clause, want) {
|
|
t.Fatalf("expected release_date in_last clause to contain %q, got %q", want, clause)
|
|
}
|
|
}
|
|
if strings.Contains(clause, "release_date::text") || strings.Contains(clause, "NOW() - INTERVAL") {
|
|
t.Fatalf("release_date in_last must not compare text to timestamp, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestParseDurationRejectsMalformedInput(t *testing.T) {
|
|
if _, err := parseDuration("1'; SELECT 1; --d"); err == nil {
|
|
t.Fatal("expected malformed duration to be rejected")
|
|
}
|
|
if got, err := parseDuration("2Y"); err != nil || got != "2 years" {
|
|
t.Fatalf("parseDuration(2Y) = %q, %v; want 2 years", got, err)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_ContentRatingUsesRankedOrdering(t *testing.T) {
|
|
clause, _, err := NewQueryBuilder("mi").BuildSortClause(QuerySort{
|
|
Field: "content_rating",
|
|
Order: "asc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortClause returned error: %v", err)
|
|
}
|
|
if !strings.Contains(clause, "WHEN UPPER(NULLIF(BTRIM(mi.content_rating), '')) = 'TV-14' THEN 2") {
|
|
t.Fatalf("expected maturity rank CASE expression, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "LOWER(COALESCE(NULLIF(BTRIM(mi.content_rating), ''), '~~~~')) ASC") {
|
|
t.Fatalf("expected normalized label ordering, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_ResolutionUsesRankedFileQualities(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{
|
|
Field: "resolution",
|
|
Order: "desc",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "WHEN '2160P' THEN 4") || !strings.Contains(plan.Joins[0], "WHEN '4320P' THEN 5") {
|
|
t.Fatalf("expected resolution ranking CASE expression, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "GROUP BY mf.content_id") {
|
|
t.Fatalf("expected grouped file stats join, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "sort_files.max_resolution_rank DESC NULLS LAST") {
|
|
t.Fatalf("expected sparse resolution sort to push missing items last, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_FileSortsUseScopedLibraryPlaceholdersAfterExistingArgs(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithLibraryScope([]int{6}).
|
|
WithArgIdx(4).
|
|
BuildSortPlan(QuerySort{Field: "resolution", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 1 || plan.Args[0] != 6 {
|
|
t.Fatalf("expected scoped library arg [6], got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "mf.media_folder_id IN ($4)") {
|
|
t.Fatalf("expected offset placeholder in file-sort join, got %q", plan.Joins[0])
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_AddedAtUsesScopedLibraryPlaceholdersAfterExistingArgs(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithLibraryScope([]int{6}).
|
|
WithArgIdx(4).
|
|
BuildSortPlan(QuerySort{Field: "added_at", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 1 || plan.Args[0] != 6 {
|
|
t.Fatalf("expected scoped library arg [6], got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "mil.media_folder_id IN ($4)") {
|
|
t.Fatalf("expected offset placeholder in added_at join, got %q", plan.Joins[0])
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_AddedAtUsesEpisodeLibraryMembershipForEpisodeScope(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithMediaScope("episode").
|
|
WithLibraryScope([]int{6}).
|
|
BuildSortPlan(QuerySort{Field: "added_at", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "JOIN episode_libraries sort_added") {
|
|
t.Fatalf("expected episode added_at join to use episode_libraries, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "sort_added.media_folder_id = $1") {
|
|
t.Fatalf("expected direct episode added_at join to bind one library, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "sort_added.episode_id = mi.content_id") {
|
|
t.Fatalf("expected episode added_at join to match episode content_id, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "ORDER BY sort_added.first_seen_at DESC, mi.sort_key ASC, mi.content_id ASC") {
|
|
t.Fatalf("expected single-library episode added_at sort to use first_seen_at without NULLS LAST, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_AddedAtAggregatesEpisodeLibrariesForMultiLibraryScope(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithMediaScope("episode").
|
|
WithLibraryScope([]int{6, 7}).
|
|
BuildSortPlan(QuerySort{Field: "added_at", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Args) != 2 || plan.Args[0] != 6 || plan.Args[1] != 7 {
|
|
t.Fatalf("expected scoped library args [6 7], got %v", plan.Args)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "FROM episode_libraries el") {
|
|
t.Fatalf("expected episode added_at aggregate to use episode_libraries, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "GROUP BY el.episode_id") {
|
|
t.Fatalf("expected multi-library episode added_at join to group by episode_id, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "sort_added.added_at DESC NULLS LAST") {
|
|
t.Fatalf("expected multi-library episode added_at sort to keep NULLS LAST, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_FileSortUsesEpisodeIDsForEpisodeScope(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithMediaScope("episode").
|
|
BuildSortPlan(QuerySort{Field: "resolution", Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected one join, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "SELECT mf.episode_id AS content_id") {
|
|
t.Fatalf("expected episode file sort join to group by episode_id, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "GROUP BY mf.episode_id") {
|
|
t.Fatalf("expected episode file sort join to aggregate by episode_id, got %q", plan.Joins[0])
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_PersonalizedComputedSorts(t *testing.T) {
|
|
builder := NewQueryBuilder("mi").WithUserScope(42, "profile-1")
|
|
tests := []struct {
|
|
field string
|
|
expectJoin []string
|
|
expectExpr []string
|
|
expectArgN int
|
|
}{
|
|
{
|
|
field: "progress",
|
|
expectJoin: []string{"FROM user_watch_progress uwp", "uwp.position_seconds > 0", "uwp.position_seconds::double precision / NULLIF(uwp.duration_seconds, 0)"},
|
|
expectExpr: []string{"sort_progress.progress_ratio"},
|
|
expectArgN: 2,
|
|
},
|
|
{
|
|
field: "date_viewed",
|
|
expectJoin: []string{"FROM user_watch_history uwh", "uwh.completed = TRUE", "FROM user_watch_progress uwp", "uwp.completed = TRUE"},
|
|
expectExpr: []string{"sort_history_viewed.viewed_at", "sort_progress_viewed.viewed_at"},
|
|
expectArgN: 2,
|
|
},
|
|
{
|
|
field: "plays",
|
|
expectJoin: []string{"COUNT(*) AS play_count", "FROM user_watch_history uwh", "FROM user_watch_progress uwp", "completed_play_count"},
|
|
expectExpr: []string{"sort_history_plays.play_count", "sort_progress_plays.completed_play_count"},
|
|
expectArgN: 2,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
plan, err := builder.BuildSortPlan(QuerySort{Field: tt.field, Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("%s: BuildSortPlan returned error: %v", tt.field, err)
|
|
}
|
|
if len(plan.Args) != tt.expectArgN {
|
|
t.Fatalf("%s: expected %d args, got %v", tt.field, tt.expectArgN, plan.Args)
|
|
}
|
|
if plan.Args[0] != 42 || plan.Args[1] != "profile-1" {
|
|
t.Fatalf("%s: expected user scope args, got %v", tt.field, plan.Args)
|
|
}
|
|
joined := strings.Join(plan.Joins, "\n")
|
|
for _, fragment := range tt.expectJoin {
|
|
if !strings.Contains(joined, fragment) {
|
|
t.Fatalf("%s: expected joins to contain %q, got %q", tt.field, fragment, joined)
|
|
}
|
|
}
|
|
for _, fragment := range tt.expectExpr {
|
|
if !strings.Contains(plan.OrderBy, fragment) {
|
|
t.Fatalf("%s: expected order by to contain %q, got %q", tt.field, fragment, plan.OrderBy)
|
|
}
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "LOWER(COALESCE(NULLIF(BTRIM(mi.sort_title), ''), mi.title)) ASC") {
|
|
t.Fatalf("%s: expected title tie-breaker, got %q", tt.field, plan.OrderBy)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBuildSortClause_EbookPersonalizedComputedSortsUseReaderProgress(t *testing.T) {
|
|
builder := NewQueryBuilder("mi").WithMediaScope("ebook").WithUserScope(42, "profile-1")
|
|
tests := []struct {
|
|
field string
|
|
expectJoin []string
|
|
expectExpr []string
|
|
}{
|
|
{
|
|
field: "progress",
|
|
expectJoin: []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress > 0",
|
|
"erp.progress < 0.9",
|
|
"LEFT JOIN user_history_hidden_items hhi",
|
|
"hhi.media_item_id IS NULL OR erp.updated_at > hhi.hidden_before",
|
|
},
|
|
expectExpr: []string{"sort_progress.progress_ratio"},
|
|
},
|
|
{
|
|
field: "date_viewed",
|
|
expectJoin: []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress >= 0.9",
|
|
"LEFT JOIN user_history_hidden_items hhi",
|
|
"hhi.media_item_id IS NULL OR erp.updated_at > hhi.hidden_before",
|
|
},
|
|
expectExpr: []string{"sort_ebook_viewed.viewed_at"},
|
|
},
|
|
{
|
|
field: "plays",
|
|
expectJoin: []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress >= 0.9",
|
|
"completed_play_count",
|
|
"LEFT JOIN user_history_hidden_items hhi",
|
|
"hhi.media_item_id IS NULL OR erp.updated_at > hhi.hidden_before",
|
|
},
|
|
expectExpr: []string{"sort_ebook_plays.completed_play_count"},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
plan, err := builder.BuildSortPlan(QuerySort{Field: tt.field, Order: "desc"})
|
|
if err != nil {
|
|
t.Fatalf("%s: BuildSortPlan returned error: %v", tt.field, err)
|
|
}
|
|
if len(plan.Args) != 2 || plan.Args[0] != 42 || plan.Args[1] != "profile-1" {
|
|
t.Fatalf("%s: expected user scope args, got %v", tt.field, plan.Args)
|
|
}
|
|
joined := strings.Join(plan.Joins, "\n")
|
|
for _, fragment := range tt.expectJoin {
|
|
if !strings.Contains(joined, fragment) {
|
|
t.Fatalf("%s: expected joins to contain %q, got %q", tt.field, fragment, joined)
|
|
}
|
|
}
|
|
for _, fragment := range tt.expectExpr {
|
|
if !strings.Contains(plan.OrderBy, fragment) {
|
|
t.Fatalf("%s: expected order by to contain %q, got %q", tt.field, fragment, plan.OrderBy)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBuild_EbookUserStateRulesUseReaderProgress(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
rule QueryRule
|
|
expectSQL []string
|
|
unexpectSQL []string
|
|
}{
|
|
{
|
|
name: "watched",
|
|
rule: QueryRule{Field: "watched", Op: "is", Value: true},
|
|
expectSQL: []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress >= 0.9",
|
|
"FROM user_history_hidden_items hhi",
|
|
"hhi.media_item_id = erp.content_id",
|
|
"erp.updated_at <= hhi.hidden_before",
|
|
},
|
|
unexpectSQL: []string{"FROM user_watch_progress uwp", "FROM user_watch_history uwh"},
|
|
},
|
|
{
|
|
name: "unread",
|
|
rule: QueryRule{Field: "watched", Op: "is", Value: false},
|
|
expectSQL: []string{
|
|
"NOT (EXISTS",
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress >= 0.9",
|
|
"FROM user_history_hidden_items hhi",
|
|
"hhi.media_item_id = erp.content_id",
|
|
"erp.updated_at <= hhi.hidden_before",
|
|
},
|
|
unexpectSQL: []string{"FROM user_watch_progress uwp", "FROM user_watch_history uwh"},
|
|
},
|
|
{
|
|
name: "in progress",
|
|
rule: QueryRule{Field: "in_progress", Op: "is", Value: true},
|
|
expectSQL: []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress > 0",
|
|
"erp.progress < 0.9",
|
|
"FROM user_history_hidden_items hhi",
|
|
"hhi.media_item_id = erp.content_id",
|
|
"erp.updated_at <= hhi.hidden_before",
|
|
},
|
|
unexpectSQL: []string{"FROM user_watch_progress uwp"},
|
|
},
|
|
{
|
|
name: "not in progress",
|
|
rule: QueryRule{Field: "in_progress", Op: "is", Value: false},
|
|
expectSQL: []string{
|
|
"NOT (EXISTS",
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress > 0",
|
|
"erp.progress < 0.9",
|
|
"FROM user_history_hidden_items hhi",
|
|
"hhi.media_item_id = erp.content_id",
|
|
"erp.updated_at <= hhi.hidden_before",
|
|
},
|
|
unexpectSQL: []string{"FROM user_watch_progress uwp"},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
clause, args, err := NewQueryBuilder("mi").
|
|
WithMediaScope("ebook").
|
|
WithUserScope(42, "profile-1").
|
|
Build(QueryDefinition{
|
|
MediaScope: "ebook",
|
|
Match: "all",
|
|
Groups: []QueryGroup{{
|
|
Match: "all",
|
|
Rules: []QueryRule{tt.rule},
|
|
}},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("%s: Build returned error: %v", tt.name, err)
|
|
}
|
|
if len(args) != 2 || args[0] != 42 || args[1] != "profile-1" {
|
|
t.Fatalf("%s: expected user scope args, got %v", tt.name, args)
|
|
}
|
|
for _, fragment := range tt.expectSQL {
|
|
if !strings.Contains(clause, fragment) {
|
|
t.Fatalf("%s: expected clause to contain %q, got %q", tt.name, fragment, clause)
|
|
}
|
|
}
|
|
for _, fragment := range tt.unexpectSQL {
|
|
if strings.Contains(clause, fragment) {
|
|
t.Fatalf("%s: did not expect clause to contain %q, got %q", tt.name, fragment, clause)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBuild_ResolutionNormalizes4KAndScopesMediaFiles(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").
|
|
WithLibraryScope([]int{3}).
|
|
Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{
|
|
Match: "all",
|
|
Rules: []QueryRule{
|
|
{Field: "resolution", Op: "is", Value: "4K"},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 2 || args[0] != 3 || args[1] != "2160p" {
|
|
t.Fatalf("expected args [3 2160p], got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "WHEN '4k' THEN '2160p'") || !strings.Contains(clause, "WHEN 'uhd' THEN '2160p'") {
|
|
t.Fatalf("expected normalized resolution CASE expression, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "mf.media_folder_id IN ($1)") {
|
|
t.Fatalf("expected scoped media-file clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_GroupAllCombinesPositiveTechnicalFiltersOnSameFile(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{
|
|
Match: "all",
|
|
Rules: []QueryRule{
|
|
{Field: "resolution", Op: "is", Value: "2160p"},
|
|
{Field: "hdr", Op: "is", Value: true},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 2 || args[0] != "2160p" || args[1] != true {
|
|
t.Fatalf("expected args [2160p true], got %v", args)
|
|
}
|
|
if strings.Count(clause, "FROM media_files mf") != 1 {
|
|
t.Fatalf("expected one shared media_files EXISTS clause, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "mf.hdr = $2") {
|
|
t.Fatalf("expected hdr predicate in shared clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_GroupAllCombinesHDRAndDolbyVisionOnSameFile(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{
|
|
Match: "all",
|
|
Rules: []QueryRule{
|
|
{Field: "hdr", Op: "is", Value: true},
|
|
{Field: "dolby_vision", Op: "is", Value: true},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 1 || args[0] != true {
|
|
t.Fatalf("expected args [true], got %v", args)
|
|
}
|
|
if strings.Count(clause, "FROM media_files mf") != 1 {
|
|
t.Fatalf("expected one shared media_files EXISTS clause, got %q", clause)
|
|
}
|
|
if !strings.Contains(clause, "mf.hdr = $1") || !strings.Contains(clause, "vt->>'dolby_vision'") {
|
|
t.Fatalf("expected HDR and Dolby Vision predicates in shared clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_AuthorClauseUsesPersonKindAuthor(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{Match: "all", Rules: []QueryRule{{Field: "author", Op: "is", Value: "Brandon Sanderson"}}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 1 || args[0] != "Brandon Sanderson" {
|
|
t.Fatalf("expected author arg, got %v", args)
|
|
}
|
|
// PersonKindAuthor == 7. We compare against the integer constant so an
|
|
// accidental kind drift breaks the test rather than silently hitting
|
|
// the wrong table partition.
|
|
if !strings.Contains(clause, "ip.kind = 7") {
|
|
t.Fatalf("expected ip.kind = 7 (PersonKindAuthor) in clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_NarratorClauseUsesPersonKindNarrator(t *testing.T) {
|
|
clause, _, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{Match: "all", Rules: []QueryRule{{Field: "narrator", Op: "is", Value: "Michael Kramer"}}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if !strings.Contains(clause, "ip.kind = 8") {
|
|
t.Fatalf("expected ip.kind = 8 (PersonKindNarrator) in clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_SeriesClauseJoinsAudiobookSeries(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{Match: "all", Rules: []QueryRule{{Field: "series", Op: "is", Value: "Mistborn"}}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 1 || args[0] != "Mistborn" {
|
|
t.Fatalf("expected series arg, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "FROM audiobook_series s") {
|
|
t.Fatalf("expected audiobook_series join in series clause, got %q", clause)
|
|
}
|
|
// Both sides trimmed + case-folded so user-typed input matches stored
|
|
// values written by the scanner regardless of incidental whitespace.
|
|
if !strings.Contains(clause, "LOWER(BTRIM(s.series_name))") || !strings.Contains(clause, "LOWER(BTRIM($1))") {
|
|
t.Fatalf("expected case+whitespace-insensitive series match, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_SeriesClauseJoinsEbookSeriesForEbookScope(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").
|
|
WithMediaScope("ebook").
|
|
Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{Match: "all", Rules: []QueryRule{{Field: "series", Op: "is", Value: "Wayfarers"}}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 1 || args[0] != "Wayfarers" {
|
|
t.Fatalf("expected series arg, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "FROM ebook_series s") {
|
|
t.Fatalf("expected ebook_series join in series clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_AuthorJoinsLateralOnPersonKindAuthor(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{Field: "author", Order: "asc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan(author) returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 {
|
|
t.Fatalf("expected exactly one join, got %d: %v", len(plan.Joins), plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.Joins[0], "LEFT JOIN LATERAL") || !strings.Contains(plan.Joins[0], "ip.kind = 7") {
|
|
t.Fatalf("expected LATERAL on item_people with kind=7, got %q", plan.Joins[0])
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "sort_author.name") {
|
|
t.Fatalf("expected ORDER BY on sort_author.name, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_NarratorJoinsLateralOnPersonKindNarrator(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{Field: "narrator", Order: "asc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan(narrator) returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 || !strings.Contains(plan.Joins[0], "ip.kind = 8") {
|
|
t.Fatalf("expected LATERAL on item_people with kind=8, got %v", plan.Joins)
|
|
}
|
|
if !strings.Contains(plan.OrderBy, "sort_narrator.name") {
|
|
t.Fatalf("expected ORDER BY on sort_narrator.name, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_SeriesOrdersByNameThenIndex(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").BuildSortPlan(QuerySort{Field: "series", Order: "asc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan(series) returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 || !strings.Contains(plan.Joins[0], "audiobook_series sort_series") {
|
|
t.Fatalf("expected LEFT JOIN audiobook_series, got %v", plan.Joins)
|
|
}
|
|
// Series name primary, series_index secondary; both nulls last so
|
|
// books without a series_index still appear under their series.
|
|
if !strings.Contains(plan.OrderBy, "sort_series.series_name ASC NULLS LAST") ||
|
|
!strings.Contains(plan.OrderBy, "sort_series.series_index ASC NULLS LAST") {
|
|
t.Fatalf("expected name+index ordering with NULLS LAST, got %q", plan.OrderBy)
|
|
}
|
|
}
|
|
|
|
func TestBuildSortPlan_SeriesUsesEbookSeriesForEbookScope(t *testing.T) {
|
|
plan, err := NewQueryBuilder("mi").
|
|
WithMediaScope("ebook").
|
|
BuildSortPlan(QuerySort{Field: "series", Order: "asc"})
|
|
if err != nil {
|
|
t.Fatalf("BuildSortPlan(series) returned error: %v", err)
|
|
}
|
|
if len(plan.Joins) != 1 || !strings.Contains(plan.Joins[0], "ebook_series sort_series") {
|
|
t.Fatalf("expected LEFT JOIN ebook_series, got %v", plan.Joins)
|
|
}
|
|
}
|
|
|
|
func TestBuild_SeriesClauseNegationWrapsInNOT(t *testing.T) {
|
|
clause, _, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{Match: "all", Rules: []QueryRule{{Field: "series", Op: "is_not", Value: "Mistborn"}}},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if !strings.HasPrefix(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(clause), "WHERE")), "NOT (") &&
|
|
!strings.Contains(clause, "NOT (") {
|
|
t.Fatalf("expected is_not to wrap the EXISTS in NOT(...), got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestBuild_PersonClauseMatchesByResolvedPersonID(t *testing.T) {
|
|
clause, args, err := NewQueryBuilder("mi").Build(QueryDefinition{
|
|
Match: "all",
|
|
Groups: []QueryGroup{
|
|
{
|
|
Match: "all",
|
|
Rules: []QueryRule{
|
|
{Field: "actor", Op: "is", Value: "Sigourney Weaver"},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Build returned error: %v", err)
|
|
}
|
|
if len(args) != 1 || args[0] != "Sigourney Weaver" {
|
|
t.Fatalf("expected actor arg, got %v", args)
|
|
}
|
|
if !strings.Contains(clause, "ip.person_id IN (") || !strings.Contains(clause, "FROM people p") {
|
|
t.Fatalf("expected person id resolution subquery, got %q", clause)
|
|
}
|
|
if strings.Contains(clause, "JOIN people") {
|
|
t.Fatalf("expected no join against people table in person clause, got %q", clause)
|
|
}
|
|
}
|
|
|
|
func TestQueryBuilder_AudioLanguageFilter_UsesGeneratedColumn(t *testing.T) {
|
|
// Migration 104 added a STORED text[] generated column for audio
|
|
// language codes. The audio_language filter should use GIN-indexed
|
|
// array containment instead of unnesting JSONB per row
|
|
// (audit 2026-05-01 §2.5b).
|
|
qb := NewQueryBuilder("mi")
|
|
clause, err := qb.buildAudioLanguageClause(QueryRule{
|
|
Field: "audio_language", Op: "is", Value: "ja",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("buildAudioLanguageClause error: %v", err)
|
|
}
|
|
if !strings.Contains(clause, "audio_language_codes @>") {
|
|
t.Fatalf("expected GIN containment on audio_language_codes; got %s", clause)
|
|
}
|
|
if strings.Contains(clause, "jsonb_array_elements(COALESCE(mf.audio_tracks") {
|
|
t.Fatalf("audio_language filter must not unnest audio_tracks JSONB anymore; got %s", clause)
|
|
}
|
|
}
|
|
|
|
func TestQueryBuilder_SubtitleLanguageFilter_UsesGeneratedColumn(t *testing.T) {
|
|
qb := NewQueryBuilder("mi")
|
|
clause, err := qb.buildSubtitleLanguageClause(QueryRule{
|
|
Field: "subtitle_language", Op: "is", Value: "en",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("buildSubtitleLanguageClause error: %v", err)
|
|
}
|
|
if !strings.Contains(clause, "subtitle_language_codes @>") {
|
|
t.Fatalf("expected GIN containment on subtitle_language_codes; got %s", clause)
|
|
}
|
|
// Option A: external_subtitles still need a JSONB unnest because the
|
|
// generated column only covers embedded subtitle_tracks.
|
|
if strings.Contains(clause, "jsonb_array_elements(COALESCE(mf.subtitle_tracks") {
|
|
t.Fatalf("subtitle_language filter must not unnest subtitle_tracks JSONB anymore; got %s", clause)
|
|
}
|
|
}
|
|
|
|
func TestQueryBuilder_SameFileAudioLanguagePredicate_UsesGeneratedColumn(t *testing.T) {
|
|
qb := NewQueryBuilder("mi")
|
|
predicate, err := qb.buildTechnicalMediaFilePredicate(QueryRule{
|
|
Field: "audio_language", Op: "is", Value: "ja",
|
|
}, "mf")
|
|
if err != nil {
|
|
t.Fatalf("buildTechnicalMediaFilePredicate error: %v", err)
|
|
}
|
|
if !strings.Contains(predicate, "audio_language_codes @>") {
|
|
t.Fatalf("expected GIN containment on audio_language_codes; got %s", predicate)
|
|
}
|
|
if strings.Contains(predicate, "jsonb_array_elements(COALESCE(mf.audio_tracks") {
|
|
t.Fatalf("same-file audio_language predicate must not unnest audio_tracks JSONB anymore; got %s", predicate)
|
|
}
|
|
}
|
|
|
|
func TestQueryBuilder_SameFileSubtitleLanguagePredicate_UsesGeneratedColumn(t *testing.T) {
|
|
qb := NewQueryBuilder("mi")
|
|
predicate, err := qb.buildTechnicalMediaFilePredicate(QueryRule{
|
|
Field: "subtitle_language", Op: "is", Value: "en",
|
|
}, "mf")
|
|
if err != nil {
|
|
t.Fatalf("buildTechnicalMediaFilePredicate error: %v", err)
|
|
}
|
|
if !strings.Contains(predicate, "subtitle_language_codes @>") {
|
|
t.Fatalf("expected GIN containment on subtitle_language_codes; got %s", predicate)
|
|
}
|
|
if strings.Contains(predicate, "jsonb_array_elements(COALESCE(mf.subtitle_tracks") {
|
|
t.Fatalf("same-file subtitle_language predicate must not unnest subtitle_tracks JSONB anymore; got %s", predicate)
|
|
}
|
|
}
|
|
|
|
// TestLastWatchedExpr_UsesDerivedTableJoin asserts that lastWatchedExpr no
|
|
// longer emits the two correlated MAX subqueries (audit 2026-05-01 §3.1 Pattern
|
|
// B). The expression should reference the user_last_watched derived-table CTE
|
|
// the executor injects when the builder requires it.
|
|
func TestLastWatchedExpr_UsesDerivedTableJoin(t *testing.T) {
|
|
qb := NewQueryBuilder("mi").WithUserScope(1, "p1")
|
|
expr := qb.lastWatchedExpr("last_watched")
|
|
if strings.Contains(expr, "SELECT MAX(uwh.watched_at)") {
|
|
t.Fatalf("last_watched must not use correlated MAX subquery; got %s", expr)
|
|
}
|
|
if !strings.Contains(expr, "uhist.last_watched") {
|
|
t.Fatalf("expected derived-table join alias uhist.last_watched; got %s", expr)
|
|
}
|
|
}
|
|
|
|
// TestQueryBuilder_LastWatched_RequiresCTE asserts that referencing
|
|
// last_watched flips the builder flag the executor checks before injecting the
|
|
// user_last_watched CTE.
|
|
func TestQueryBuilder_LastWatched_RequiresCTE(t *testing.T) {
|
|
qb := NewQueryBuilder("mi").WithUserScope(1, "p1")
|
|
_ = qb.lastWatchedExpr("last_watched")
|
|
if !qb.RequiresUserHistoryCTE() {
|
|
t.Fatalf("after lastWatchedExpr, builder should require CTE")
|
|
}
|
|
}
|
|
|
|
func TestUserHistoryCTESQLIncludesCompletedEbookReaderProgress(t *testing.T) {
|
|
sql := UserHistoryCTESQL(1)
|
|
expectedFragments := []string{
|
|
"FROM ebook_reader_progress erp",
|
|
"erp.progress >= 0.9",
|
|
"erp.content_id",
|
|
"erp.updated_at",
|
|
}
|
|
for _, fragment := range expectedFragments {
|
|
if !strings.Contains(sql, fragment) {
|
|
t.Fatalf("expected CTE to contain %q, got:\n%s", fragment, sql)
|
|
}
|
|
}
|
|
}
|