* docs(audiobooks): design spec for plugin absorption Plan to absorb silo-plugin-audiobooks into silo-server as a first-party feature. Audiobooks land in silo's existing SPA; ABS clients connect directly. Hard constraints: reuse existing tables (media_items, media_files, user_watch_progress, user_playback_sessions, people, item_people, library_collections); only two new tables (abs_sessions, podcast_feeds) and at most one column add (media_libraries.kind); silo's main :8080 listener handles ABS Socket.io natively. Out of scope: audiobook requests flow, smart collections, share links, external recommender, custom metadata providers, separate audiobook SPA. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(audiobooks): implementation plan sub-plan 1 (discovery + schema) First of six sub-plans for the absorption. Six tasks: a discovery audit that resolves the spec's Risk questions, four idempotent SQL migrations (abs_sessions, podcast_feeds, media_libraries.kind, audiobooks.enabled feature flag), and an empty-but-compiling internal/audiobooks package scaffolded into cmd/silo. Lands as a strict no-op for users (feature flag defaults to false). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(audiobooks): discovery findings for absorption sub-plan 1 Locks schema/code decisions for migrations 139-142 and downstream sub-plans. Resolves open Risk questions from the absorption design spec. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): migration 139 add abs_sessions table Parallel of jellycompat_sessions for Audiobookshelf-compatible clients. Lets ABS mobile/desktop apps maintain a device-bound session that silo's audiobooks/abs handlers will validate. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style(audiobooks): match codebase conventions in migration 139 Lowercases type keywords in the abs_sessions CREATE TABLE body to match neighboring migrations, fixes the client_version column alignment, and replaces the misleading "parallel to jellycompat_sessions" header comment with a more accurate description of the table's role. Cosmetic only — the running schema is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): migration 140 add podcast_feeds table Side table on media_items for RSS-subscribed podcasts. Holds feed URL, ETag/Last-Modified for conditional fetches, last-refresh timestamp, and the per-feed refresh interval consumed by the upcoming podcastfeed.Refresher scheduled task. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style(audiobooks): uppercase PRIMARY KEY in migration 140 Aligns with the codebase convention (type keywords lowercase, constraint keywords uppercase) established in migration 139's post-style-fix form. Cosmetic only — running schema is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(audiobooks): migration 141 no-op for media_folders.type Sub-plan 1 originally reserved migration 141 to add a 'kind' column to media_libraries discriminating audiobook/podcast libraries. Discovery audit (sub-plan 1 Task 1) found that the actual table is media_folders and it already has a type text NOT NULL column with no CHECK constraint or enum, so 'audiobooks' and 'podcasts' can be added as future values without DDL. Landing this migration as a documented no-op preserves the version numbering audit trail and pins the decision in git history. The matching down migration is also a no-op. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): migration 142 add audiobooks.enabled flag Server-settings row that gates the absorbed audiobooks feature. Defaults to 'false' so sub-plan 1 lands as a strict no-op; subsequent sub-plans branch on this flag and operators flip it to 'true' at cutover. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): scaffold internal/audiobooks package Empty-but-compiling Service that reads the audiobooks.enabled feature flag from server_settings. Wired into cmd/silo so the package is referenced from the binary; no routes mounted, no scheduled tasks registered, no DB writes. Subsequent sub-plans hang scanner branches, ABS handlers, Socket.io, podcast refresher, and SPA pages off this Service. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style(audiobooks): cosmetic cleanups in scaffolded package Two pre-emptive cleanups flagged by code review before sub-plan 2 copies the patterns: 1. Sort the internal/audiobooks import after internal/adminjob in cmd/silo/main.go (alphabetical). 2. Drop the redundant "audiobooks: " prefix from the Enabled() error wrap; matches how every other top-level service package (watchstate, scanqueue, metadata, etc.) formats errors. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(audiobooks): implementation plan sub-plan 2 (scanner) Second of six sub-plans. 10 tasks: PersonKind constants for Author and Narrator, audio-extension recognizer, library-type helpers, a walkLogicalTree refactor (movieLibrary bool -> typed walkMode), chapter extraction via ffprobe, single-file and multi-file audiobook parsers, scanner write path producing media_items.type='audiobook', and a filesystem podcast parser (RSS deferred to sub-plan 5). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): add Author and Narrator PersonKind constants Discovery audit confirmed item_people.kind is unconstrained smallint with values 1-6 in use. Reserve 7 = Author, 8 = Narrator for audiobook people-links written by the upcoming scanner branches. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): add audio-extension recognizer for scanner Mirrors the existing videoExtensions/SupportsVideoFile pair. Used by upcoming audiobook and podcast scanner branches to filter directory walks. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): library-type recognizers for scanner dispatch isAudiobookLibraryType and isPodcastLibraryType match singular and plural forms case-insensitively, mirroring isMovieLibraryType. Used by upcoming scanner walk branches (Task 4) that filter audio files into audiobook and podcast libraries. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(scanner): replace movieLibrary bool with typed walkMode Lets walkLogicalTree dispatch on multiple library shapes (video, movie, audiobook, podcast) without proliferating boolean flags. Behavior for existing video and movie libraries is unchanged; audiobook and podcast modes will be consumed by the upcoming audiobook.go and podcast.go parsers in later tasks of this sub-plan. walkModeFor() derives the mode from a media_folders.type string; unknown types default to walkModeVideo to preserve prior behavior for any caller still passing a raw type. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): expose ffprobe format tags on ProbeData The audiobook scanner needs format-level tags (title, artist, album, date) for media_items metadata; ffprobe already parses them in ffprobeFormat.Tags but ProbeData previously discarded them. Add FormatTags map[string]string to ProbeData, populate it in convertProbeData via a new normalizeFormatTags helper that lowercases keys and trims values. Adds a fixture audiobook .m4b with embedded chapters (Intro/Outro) and format tags, and a test that verifies ProbeFile() returns both correctly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): parser for single-file audiobook folders parseAudiobookFolder reads tags + chapters via the existing ProbeFile (now that Task 5 exposes FormatTags on ProbeData) and produces a parsedAudiobook struct. Title falls back from "title" tag to "album"; author from "artist" -> "album_artist" -> "composer"; series from "album" -> "series" -> "mvnm" (Movement Name, used by some MP4 tools). Year parsed from "date" or "year" tags, tolerating ISO dates and parenthesized forms. Single-file case only; multi-file folders (one audio file per chapter) return a placeholder error and arrive in Task 7. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): multi-file audiobook folder support Folders containing N audio files (one per chapter/part) get one parsedAudiobookFile per file; each file's chapter list is synthesized as a single chapter with title = filename stem. Title/author/series/ year come from the first file's tags. Also drops the duplicate pickFirstNonEmpty helper added in Task 6 in favor of the existing firstNonEmpty already in probe.go. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): scanner write path produces audiobook media_items ScanAudiobookFolder walks an audiobooks-typed media folder and treats each immediate subdirectory as one audiobook. For each parsed audiobook it upserts: - one media_items row with type='audiobook' - one media_files row per audio file (with chapters JSONB) - author/narrator links in item_people (kind=7, kind=8) Adds itemRepo and personRepo to the Scanner struct, wired from fileRepo.Pool() in NewScanner — no constructor signature change needed. ScanFolder dispatches to this path when folder.Type='audiobooks', bypassing the per-file movie/TV pipeline because audiobooks are folder-scoped entities. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): filesystem podcast scanner ScanPodcastFolder walks a podcasts-typed media folder, treating each subdirectory as a podcast show and each audio file inside as an episode. Writes media_items.type='podcast' + episodes rows + media_files rows. RSS-subscribed feeds (podcast_feeds table) arrive in sub-plan 5; this task covers filesystem-only ingestion. ScanFolder dispatches to this path when folder.Type='podcasts'. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(audiobooks): implementation plan sub-plan 5 (podcasts) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): expose audiobooks/podcasts library types in admin UI Adds 'Audiobooks' and 'Podcasts' options to the library-type dropdown in the admin libraries page so operators can flag a folder as an audiobook or podcast library. Extends contentLevelsForType() so the admin UI's downstream filtering treats those types correctly (audiobook -> ['audiobook'], podcasts -> ['podcast', 'podcast_episode']). Backend scanner branches for these types were already wired in sub-plan 2. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(migrations): renumber 139_abs_sessions to 147 for origin/main merge origin/main adds 139_media_requests at the same number our local audiobook branch had used for abs_sessions. Renumber ours to 147 to free up 139 for the upstream migration. The schema_versions row is updated in lockstep on the running database so the migrator sees the abs_sessions migration as already applied at its new version. Migrations 140-146 (podcast feeds, media_folders kind noop, audiobook feature flag, abs playback sessions, podcast episode guid, audiobook series, audiobook title cleanup) stay where they are — they don't collide with anything on origin/main. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(migrations): renumber 140_podcast_feeds to 157 for origin/main merge origin/main added 140_user_permissions at the same version this branch had used for podcast_feeds. Renumber ours to 157 (next free above the collections-unify migration at 156) so 140 is free for the upstream migration. schema_versions on the running database is updated in lockstep so the migrator sees podcast_feeds as already applied at its new version. Same pattern asd59c1cb(renumber 139_abs_sessions to 147 for the prior main merge). Pending migrations after this rename: 132 (downloaded subtitles admin index, main), 140 (user_permissions, main), and 156 (unify_user_collections, this branch). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(migrations): renumber 141_media_folders_kind_noop to 159 for origin/main merge Same shape aseb8f67d(the 140→157 renumber from the previous main merge). origin/main added 141_episode_title_sort_index at the same version this branch had used for media_folders_kind_noop. Renumber ours to 159 (next free above the audiobook_series truncate at 158) so 141 is open for the upstream migration. schema_versions on the running database is updated in lockstep so the migrator sees media_folders_kind_noop as already applied at its new version. Pending migrations on silo-prod after this rename: 141 (episode_title_sort_index, main) and any other newer ones from main that the branch hasn't picked up yet. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(migrations): renumber 142_audiobooks_feature_flag to 160 for origin/main merge Companion to 3c6f062's 141 renumber — origin/main also added 142_episode_catalog_entries (alongside 141_episode_title_sort_index) at a version this branch had used for the audiobooks feature flag. Renumber ours to 160 so 142 is open for the upstream migration; schema_versions on silo-prod is updated in lockstep so the migrator sees audiobooks_feature_flag as already applied at its new version. This was the only remaining collision (verified by checking for duplicate version prefixes across migrations/). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(audiobooks): address foundation review comments * fix(audiobooks): tighten scanner identity handling * fix(audiobooks): propagate scanner cancellation * chore(audiobooks): adopt goose migration layout * docs(audiobooks): implementation plan sub-plan 3 (API + frontend MVP) Third of six sub-plans. 9 tasks: three REST endpoints (list/detail/ progress), TanStack Query hooks + types, three React pages (Library/Detail/Player), and navigation integration. Scoped to MVP — author/series indices, smart collections, share links, and other nice-to-haves from the spec are deferred. Streaming reuses silo's existing /api/v1/stream/{session_id}; no new transcode code. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): list endpoint at GET /api/v1/audiobooks Paginated list of media_items with type='audiobook' scoped to the caller's accessible libraries via the existing access filter. Mirrors silo's existing list-style handlers for movies and series. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): detail endpoint at GET /api/v1/audiobooks/{id} Returns the media_items row, its media_files (with chapters JSONB), author/narrator extracted from item_people (kinds 7/8), and the caller's per-profile listening progress from user_watch_progress. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): progress endpoint at POST /api/v1/audiobooks/{id}/progress UPSERTs user_watch_progress for the caller's (user_id, profile_id, content_id). Body carries position_seconds; clients are expected to post every 5-10s during playback plus on pause/seek (matching silo's existing video progress cadence). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): frontend types and TanStack Query hooks TypeScript types match the JSON shapes from the new /api/v1/audiobooks endpoints (list, detail, progress). Three hooks: useAudiobookLibrary (list), useAudiobook (detail), and useReportAudiobookProgress (mutation that invalidates the detail query on success so progress updates reflect immediately). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): library grid page at /audiobooks Renders a paginated grid of audiobook cards using the useAudiobookLibrary hook. Each card links to /audiobooks/book/{id}. Cards show poster, title, and year; falls back to a "No cover" placeholder when the audiobook has no poster_url. Empty state hints to operators that they need to set a library's type to 'audiobooks'. Routes themselves are wired in Task 8 (navigation integration). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): detail page with chapter list Renders cover, title, author, narrator, year, and overview alongside a chapter list. Clicking a chapter opens an inline sticky AudiobookPlayer at that chapter's start. A "Resume" button restarts playback at the saved progress position if present. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): HTML5 audio player with chapter navigation Single-file audiobook playback for MVP. Multi-file queuing arrives in a follow-up. Streams via the existing /api/v1/direct-download GET endpoint. Position is reported to /api/v1/audiobooks/{id}/progress every 10s while playing plus on pause/seek/end. Skip-30s, playback rate select, chapter list panel. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(audiobooks): wire navigation and routes Adds an Audiobooks entry to the sidebar and registers the two new routes (/audiobooks for the library grid, /audiobooks/book/:id for detail). The player renders inline inside the detail page; no dedicated player route is required for MVP. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(audiobooks): address native API review comments * feat(audiobooks): add ABS compatibility and polish * fix(audiobooks): stabilize ABS playback progress reporting * fix(audiobooks): clean up ABS branch review fixes * chore(audiobooks): adopt goose layout for ABS migrations * fix(audiobooks): align player seek bar props * feat(audiobooks): make libraries first-class catalog items * feat(admin): add server restart endpoint * fix(audiobooks): address review comment findings --------- Co-authored-by: RXWatcher <14085001+RXWatcher@users.noreply.github.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
716 lines
26 KiB
Go
716 lines
26 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.completed = FALSE", "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 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 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 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")
|
|
}
|
|
}
|