diff --git a/README.md b/README.md index 06cb817..18654e9 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ Repository for team IT2810-H26-T19 in IT2810-H26. -**Crate** is an album catalog where users can search for music. The GraphQL API -already supports filtering, sorting and cursor-based pagination, while the -frontend controls for these features are planned for later milestones. Album -details, ratings, reviews and a personal wantlist ("crate") are also planned. +**Crate** is an album catalog where users can search for music, sort and page +through the results, open an album for detail, rate and review it, and add it to +a personal wantlist ("crate"). The GraphQL API also supports genre and decade +filters; the frontend filter controls are planned. IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`. @@ -228,15 +228,15 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai | `schema.graphql` | GraphQL schema | | `docs/` | Architecture, data model, UI, workflow, AI log and VM guide | -**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`. `AVERAGE_RATING_DESC` is defined in the schema but currently returns an error because reviews are not implemented yet. +**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre and decade filters, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results. -The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. +The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page. -**Planned:** Frontend filters and sorting controls; album details; reviews, ratings and wantlist functionality; and Playwright end-to-end tests (M4). The database tables for reviews and crate items exist, but their GraphQL functionality is still planned. `X-User-Id` is also defined but not yet handled at runtime. Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. +**Planned:** Frontend filter controls (#13), a page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. ### Backend search behavior -The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. +The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. Everything except the filters and facet counts is exposed in the frontend. ## Try the application diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index eb0ddec..02eed69 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -6,6 +6,7 @@ import { GraphQLError } from 'graphql'; import App from './App.js'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; import type { + AlbumSort, AlbumSummary, SearchAlbumsData, SearchAlbumsVariables, @@ -25,11 +26,12 @@ const album: AlbumSummary = { function mockSearch( query: string, albums: AlbumSummary[] = [album], + sort: AlbumSort = 'RELEVANCE', ): MockLink.MockedResponse { return { request: { query: SEARCH_ALBUMS, - variables: { input: { query, sort: 'RELEVANCE' }, first: 20, after: null }, + variables: { input: { query, sort }, first: 20, after: null }, }, result: { data: { @@ -281,6 +283,39 @@ describe('App search', () => { expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 1 albums.'); }); + it('re-queries the server when the sort changes and keeps it in the URL', async () => { + const lowRated = { ...album, id: '2', title: 'Abbey Lane', averageRating: 2.1 }; + renderApp([ + mockSearch('Abbey', [lowRated, album]), + mockSearch('Abbey', [album, lowRated], 'AVERAGE_RATING_DESC'), + ]); + submitSearch('Abbey'); + await screen.findByRole('article', { name: 'Abbey Lane' }); + const sort = screen.getByRole('combobox', { name: 'Sort by' }); + expect(sort).toHaveValue('RELEVANCE'); + + fireEvent.change(sort, { target: { value: 'AVERAGE_RATING_DESC' } }); + + expect(window.location.search).toBe('?q=Abbey&sort=AVERAGE_RATING_DESC'); + // The order is whatever the server returned, not a client-side re-sort. + await waitFor(() => + expect( + screen + .getAllByRole('article') + .map((card) => within(card).getByRole('heading').textContent), + ).toEqual(['Abbey Road', 'Abbey Lane']), + ); + }); + + it('restores the sort from a shared link', async () => { + window.history.replaceState({}, '', '/?q=Abbey&sort=RELEASE_YEAR_ASC'); + renderApp([mockSearch('Abbey', [album], 'RELEASE_YEAR_ASC')]); + await screen.findByRole('article', { name: 'Abbey Road' }); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue( + 'RELEASE_YEAR_ASC', + ); + }); + it('replaces results for a new query rather than retaining the previous search', async () => { renderApp([mockSearch('Abbey'), mockSearch('missing', [])]); submitSearch('Abbey'); diff --git a/client/src/App.tsx b/client/src/App.tsx index fde583b..b94be3c 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -64,6 +64,8 @@ function DiscoveryPage() { albums={search.albums} totalCount={search.totalCount} hasQuery={search.hasQuery} + sort={search.sort} + onSortChange={search.setSort} loading={search.loading} loadingMore={search.loadingMore} pageError={search.pageError} diff --git a/client/src/api/searchAlbums.ts b/client/src/api/searchAlbums.ts index cbb08db..c0b9966 100644 --- a/client/src/api/searchAlbums.ts +++ b/client/src/api/searchAlbums.ts @@ -6,7 +6,10 @@ import type { TypedDocumentNode } from '@apollo/client'; export const ALBUM_SORTS = [ 'RELEVANCE', 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_ASC', 'RELEASE_YEAR_DESC', + 'AVERAGE_RATING_ASC', 'AVERAGE_RATING_DESC', ] as const; diff --git a/client/src/components/ResultsLayout.css b/client/src/components/ResultsLayout.css index 0b85f27..2ebbdfd 100644 --- a/client/src/components/ResultsLayout.css +++ b/client/src/components/ResultsLayout.css @@ -1,6 +1,13 @@ .results { padding-bottom: 2.5rem; } +.results-header { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 0.5rem 1rem; +} .pagination { text-align: center; diff --git a/client/src/components/ResultsLayout.tsx b/client/src/components/ResultsLayout.tsx index 4b13cfe..9449c99 100644 --- a/client/src/components/ResultsLayout.tsx +++ b/client/src/components/ResultsLayout.tsx @@ -2,12 +2,15 @@ import { useEffect, useRef } from 'react'; import AlbumCard from './AlbumCard.js'; -import type { AlbumSummary } from '../api/searchAlbums.js'; +import SortSelect from './SortSelect.js'; +import type { AlbumSort, AlbumSummary } from '../api/searchAlbums.js'; interface Props { albums: AlbumSummary[]; totalCount: number; hasQuery: boolean; + sort: AlbumSort; + onSortChange: (sort: AlbumSort) => void; loading: boolean; loadingMore: boolean; pageError: boolean; @@ -80,7 +83,12 @@ export default function ResultsLayout(props: Props) { aria-labelledby="results-heading" aria-busy={props.loading || props.loadingMore} > -

Search results

+
+

Search results

+ {props.hasQuery && ( + + )} +

{!props.hasQuery ? 'Search for an album or artist to get started.' diff --git a/client/src/components/SortSelect.css b/client/src/components/SortSelect.css new file mode 100644 index 0000000..0264698 --- /dev/null +++ b/client/src/components/SortSelect.css @@ -0,0 +1,17 @@ +.sort-select { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.9rem; +} +.sort-select label { + color: var(--muted); +} +.sort-select select { + padding: 0.45rem 0.6rem; + border: 1px solid var(--border-strong); + border-radius: 6px; + background: var(--surface); + color: var(--text); + font: inherit; +} diff --git a/client/src/components/SortSelect.test.tsx b/client/src/components/SortSelect.test.tsx new file mode 100644 index 0000000..7022c7e --- /dev/null +++ b/client/src/components/SortSelect.test.tsx @@ -0,0 +1,24 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, within } from '@testing-library/react'; +import SortSelect from './SortSelect.js'; +import { ALBUM_SORTS } from '../api/searchAlbums.js'; + +describe('SortSelect', () => { + it('is labelled and offers every sort the schema accepts', () => { + render(); + const select = screen.getByRole('combobox', { name: 'Sort by' }); + const values = within(select) + .getAllByRole('option') + .map((option) => (option as HTMLOptionElement).value); + expect([...values].sort()).toEqual([...ALBUM_SORTS].sort()); + }); + + it('shows the current sort and reports a change', () => { + const onSortChange = vi.fn(); + render(); + const select = screen.getByRole('combobox', { name: 'Sort by' }); + expect(select).toHaveValue('TITLE_ASC'); + fireEvent.change(select, { target: { value: 'AVERAGE_RATING_DESC' } }); + expect(onSortChange).toHaveBeenCalledExactlyOnceWith('AVERAGE_RATING_DESC'); + }); +}); diff --git a/client/src/components/SortSelect.tsx b/client/src/components/SortSelect.tsx new file mode 100644 index 0000000..476f29a --- /dev/null +++ b/client/src/components/SortSelect.tsx @@ -0,0 +1,60 @@ +import './SortSelect.css'; + +import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js'; + +const LABELS: Record = { + RELEVANCE: 'Best match', + TITLE_ASC: 'Title A–Z', + TITLE_DESC: 'Title Z–A', + RELEASE_YEAR_DESC: 'Newest first', + RELEASE_YEAR_ASC: 'Oldest first', + AVERAGE_RATING_DESC: 'Highest rated', + AVERAGE_RATING_ASC: 'Lowest rated', +}; + +// Grouped by what is being sorted rather than in enum order. +const OPTIONS: readonly AlbumSort[] = [ + 'RELEVANCE', + 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_DESC', + 'RELEASE_YEAR_ASC', + 'AVERAGE_RATING_DESC', + 'AVERAGE_RATING_ASC', +]; + +interface Props { + sort: AlbumSort; + onSortChange: (sort: AlbumSort) => void; +} + +function isAlbumSort(value: string): value is AlbumSort { + return (ALBUM_SORTS as readonly string[]).includes(value); +} + +/** + * A native select, so keyboard and screen reader support come from the + * browser. Changing it only writes the URL: the order itself comes from the + * server, over the whole result set, never from rearranging loaded cards. + */ +export default function SortSelect({ sort, onSortChange }: Props) { + return ( +

+ + +
+ ); +} diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index e1e0a7c..b9d4716 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -9,7 +9,7 @@ const PAGE_SIZE = 20; const AUTOMATIC_PAGE_LIMIT = 2; export function useAlbumSearch() { - const { state, setQuery } = useSearchState(); + const { state, setQuery, setSort } = useSearchState(); const query = state.q; const hasQuery = query.length > 0; const retryInFlight = useRef(false); @@ -174,6 +174,8 @@ export function useAlbumSearch() { return { query, + sort: state.sort, + setSort, search, hasQuery, albums: hasQuery diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts index 561d365..7cb1e12 100644 --- a/client/src/hooks/useSearchState.test.ts +++ b/client/src/hooks/useSearchState.test.ts @@ -34,7 +34,7 @@ describe('parseSearchState', () => { }); it('falls back to the default sort for a value the schema does not accept', () => { - expect(parseSearchState('?sort=TITLE_DESC').sort).toBe(DEFAULT_SORT); + expect(parseSearchState('?sort=YEAR_DESC').sort).toBe(DEFAULT_SORT); expect(parseSearchState('?sort=').sort).toBe(DEFAULT_SORT); expect(parseSearchState('?').sort).toBe(DEFAULT_SORT); }); diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index 9a1b4ae..bb262a2 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -270,6 +270,9 @@ describe('cursor pagination', () => { const user = userEvent.setup(); screen.getByRole('button', { name: 'Search' }).focus(); + await user.tab(); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveFocus(); + await user.tab(); expect(screen.getByRole('link', { name: 'Album 1' })).toHaveFocus(); diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 6a985ae..70438c8 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -69,7 +69,9 @@ the part that matters most. | 2026-10-24 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing cursor pagination, infinite scroll, Load more, Apollo cache handling, and accessibility improvements (#14). | | 2026-10-25 | rachelks | ChatGPT | Assisted with researching real album datasets, evaluating which data source best fit the project, and planning issues #63 and #64 to implement real data. | | 2026-10-26 | robertky | Codex (ChatGPT) | Assisted me when I implemented #16: idempotent add/remove mutations, per-request crate-state loading, and accessible list/detail toggles. I reviewed the implementation and test results before using it. | +| 2026-10-26 | evenkkl | Claude | #12, server-side sorting. Read the issue first; it settles the names (`RELEASE_YEAR`, `AVERAGE_RATING`) and that the rating sorts need a stored column, not a live `AVG()`. Claude added the five missing sorts with keyset cursors, `album.average_rating` kept current by a trigger on `review`, the sort control above the results via `setSort`, and tests. I had the trigger and paging across rating ties checked against a real PostgreSQL instance, not only the generated SQL. | | 2026-10-27 | robertky | Codex (ChatGPT) | Assisted me with #63's MusicBrainz snapshot fetcher, non-destructive catalog import and documentation. | +| 2026-10-28 | evenkkl | Claude | #12, review fixes on #66. Robert asked for an up-to-date branch, a correct README and green CI. Claude merged main, renumbered our migration to `0003` after #63's `0002`, kept both sides of the other conflicts, fixed a duplicate import from the merge, updated the README status sections and added the sort control to the Load more keyboard test. I checked the diff against main contains only our sorting work and these fixes. | ## Notes diff --git a/docs/architecture.md b/docs/architecture.md index 91b744d..a4a1982 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ resolver loads every match into memory. builder is the most complex server code, so it needs tests against a real database. -The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. The supported sort options are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`; rating-based sorting is not yet implemented. +The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. Sorting covers relevance, title, release year and average rating, the last three in both directions. Every sort ends with an `album.id` tiebreak and puts NULLs last, so the keyset cursor stays stable. The rating sorts read `album.average_rating`, a column a trigger on `review` keeps current, because a live `AVG()` would be recomputed for the whole result set and would move under a cursor whenever someone saved a review. ## 4. DataLoaders against N+1 diff --git a/docs/data-model.md b/docs/data-model.md index 1590e45..5e0d84e 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -34,6 +34,12 @@ details. artist terms when titles, artist names or artist links change. Migration `0001` also backfills existing albums. +`album.average_rating` is the mean of the album's review ratings, or NULL without +reviews. A trigger on `review` recomputes it for the one album a review write +touches, so its cost does not grow with the catalog. The rating sorts and +`Album.averageRating` both read it. Migration `0003` adds it and backfills +existing reviews. + ## User-generated data - A **user** is a simulated identity: a UUID the client keeps in `localStorage` diff --git a/schema.graphql b/schema.graphql index d7d1719..e15f0f6 100644 --- a/schema.graphql +++ b/schema.graphql @@ -150,6 +150,9 @@ input UpsertReviewInput { enum AlbumSort { RELEVANCE TITLE_ASC + TITLE_DESC + RELEASE_YEAR_ASC RELEASE_YEAR_DESC + AVERAGE_RATING_ASC AVERAGE_RATING_DESC } diff --git a/server/drizzle/0003_album-average-rating.sql b/server/drizzle/0003_album-average-rating.sql new file mode 100644 index 0000000..1623e27 --- /dev/null +++ b/server/drizzle/0003_album-average-rating.sql @@ -0,0 +1,48 @@ +ALTER TABLE "album" ADD COLUMN "average_rating" double precision; +--> statement-breakpoint +CREATE FUNCTION refresh_album_average_rating(target_album_id integer) +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + -- Lock the album row first. Two reviews saved at once for the same album + -- then run one after the other, and the second average is computed in a new + -- statement that already sees the first review. + PERFORM 1 FROM album WHERE id = target_album_id FOR UPDATE; + + UPDATE album + SET average_rating = ( + SELECT avg(rating) FROM review WHERE review.album_id = target_album_id + ) + WHERE id = target_album_id; +END; +$$; +--> statement-breakpoint +CREATE FUNCTION refresh_album_average_rating_from_review() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP <> 'DELETE' THEN + PERFORM refresh_album_average_rating(NEW.album_id); + END IF; + + IF TG_OP <> 'INSERT' AND OLD.album_id IS DISTINCT FROM NEW.album_id THEN + PERFORM refresh_album_average_rating(OLD.album_id); + END IF; + RETURN NULL; +END; +$$; +--> statement-breakpoint +CREATE TRIGGER review_refresh_album_average_rating +AFTER INSERT OR UPDATE OF rating, album_id OR DELETE ON review +FOR EACH ROW EXECUTE FUNCTION refresh_album_average_rating_from_review(); +--> statement-breakpoint +UPDATE album +SET average_rating = rated.average_rating +FROM ( + SELECT album_id, avg(rating) AS average_rating + FROM review + GROUP BY album_id +) AS rated +WHERE album.id = rated.album_id; diff --git a/server/drizzle/meta/0003_snapshot.json b/server/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..8b2422a --- /dev/null +++ b/server/drizzle/meta/0003_snapshot.json @@ -0,0 +1,597 @@ +{ + "id": "82666a74-d81e-4ae3-85d0-a0ff16223746", + "prevId": "4498ebd9-d731-420a-825a-7eb22c50a3e4", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album": { + "name": "album", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "release_year": { + "name": "release_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "musicbrainz_release_group_id": { + "name": "musicbrainz_release_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_search_vector_idx": { + "name": "album_search_vector_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "album_musicbrainz_release_group_id_unique": { + "name": "album_musicbrainz_release_group_id_unique", + "nullsNotDistinct": false, + "columns": ["musicbrainz_release_group_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_artist": { + "name": "album_artist", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artist_id": { + "name": "artist_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_artist_album_id_album_id_fk": { + "name": "album_artist_album_id_album_id_fk", + "tableFrom": "album_artist", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_artist_artist_id_artist_id_fk": { + "name": "album_artist_artist_id_artist_id_fk", + "tableFrom": "album_artist", + "tableTo": "artist", + "columnsFrom": ["artist_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_artist_album_id_artist_id_pk": { + "name": "album_artist_album_id_artist_id_pk", + "columns": ["album_id", "artist_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_genre": { + "name": "album_genre", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "genre_id": { + "name": "genre_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_genre_album_id_album_id_fk": { + "name": "album_genre_album_id_album_id_fk", + "tableFrom": "album_genre", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_genre_genre_id_genre_id_fk": { + "name": "album_genre_genre_id_genre_id_fk", + "tableFrom": "album_genre", + "tableTo": "genre", + "columnsFrom": ["genre_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_genre_album_id_genre_id_pk": { + "name": "album_genre_album_id_genre_id_pk", + "columns": ["album_id", "genre_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_user": { + "name": "app_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.artist": { + "name": "artist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.crate_item": { + "name": "crate_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "crate_item_user_album_unique": { + "name": "crate_item_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "crate_item_user_added_at_idx": { + "name": "crate_item_user_added_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "added_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "crate_item_user_id_app_user_id_fk": { + "name": "crate_item_user_id_app_user_id_fk", + "tableFrom": "crate_item", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "crate_item_album_id_album_id_fk": { + "name": "crate_item_album_id_album_id_fk", + "tableFrom": "crate_item", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.genre": { + "name": "genre", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "genre_name_unique": { + "name": "genre_name_unique", + "nullsNotDistinct": false, + "columns": ["name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.review": { + "name": "review", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "review_user_album_unique": { + "name": "review_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "review_album_idx": { + "name": "review_album_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "review_user_id_app_user_id_fk": { + "name": "review_user_id_app_user_id_fk", + "tableFrom": "review", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "review_album_id_album_id_fk": { + "name": "review_album_id_album_id_fk", + "tableFrom": "review", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "review_rating_range": { + "name": "review_rating_range", + "value": "\"review\".\"rating\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "public.track": { + "name": "track", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "track_number": { + "name": "track_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "track_album_track_number_unique": { + "name": "track_album_track_number_unique", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "track_album_track_number_idx": { + "name": "track_album_track_number_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "track_album_id_album_id_fk": { + "name": "track_album_id_album_id_fk", + "tableFrom": "track", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index c2d5fad..4eb27ca 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1793110958654, "tag": "0002_musicbrainz-catalog", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1793199189807, + "tag": "0003_album-average-rating", + "breakpoints": true } ] } diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 9823838..b3f30f3 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -2,6 +2,7 @@ import { sql } from 'drizzle-orm'; import { check, customType, + doublePrecision, index, integer, pgTable, @@ -28,6 +29,9 @@ export const album = pgTable( // The words a search matches: the title plus artist names. The database // trigger keeps this up to date when catalog data changes. searchVector: tsvector('search_vector'), + // Mean of the album's review ratings, NULL with no reviews. A trigger on + // review keeps it current, so the rating sorts page on a stored column. + averageRating: doublePrecision('average_rating'), }, // GIN is the index type for tsvector, so a word lookup does not scan the table. (t) => [index('album_search_vector_idx').using('gin', t.searchVector)], diff --git a/server/src/loaders/index.ts b/server/src/loaders/index.ts index 9de2f09..8e0756c 100644 --- a/server/src/loaders/index.ts +++ b/server/src/loaders/index.ts @@ -1,10 +1,10 @@ import DataLoader from 'dataloader'; -import { and, asc, avg, count, eq, inArray } from 'drizzle-orm'; +import { and, asc, count, eq, inArray } from 'drizzle-orm'; import type { Db } from '../db/client.js'; import { + album, albumArtist, albumGenre, - album, appUser, crateItem, artist, @@ -73,18 +73,15 @@ export function createLoaders(db: Db, userId: string | null) { return albumIds.map((id) => counts.get(id) ?? 0); }), + // Reads the stored column the rating sorts use, so the number shown on a + // card is the same one the results were ordered by. It is loaded at + // resolve time, so a review mutation's payload sees the updated value. averageRatingByAlbum: new DataLoader(async (albumIds) => { const rows = await db - .select({ albumId: review.albumId, averageRating: avg(review.rating) }) - .from(review) - .where(inArray(review.albumId, [...albumIds])) - .groupBy(review.albumId); - const averages = new Map( - rows.map((row) => [ - row.albumId, - row.averageRating === null ? null : Number(row.averageRating), - ]), - ); + .select({ id: album.id, averageRating: album.averageRating }) + .from(album) + .where(inArray(album.id, [...albumIds])); + const averages = new Map(rows.map((row) => [row.id, row.averageRating])); return albumIds.map((id) => averages.get(id) ?? null); }), diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index c295052..1856a6b 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -5,6 +5,7 @@ import { afterCursor, decodeCursor, encodeCursor, + orderBy, pageSize, searchFilter, sortKey, @@ -70,6 +71,83 @@ describe('afterCursor', () => { }); }); +describe('sortKey for every sort', () => { + it.each([ + ['TITLE_ASC', 'lower(album.title)', 'ASC', false], + ['TITLE_DESC', 'lower(album.title)', 'DESC', false], + ['RELEASE_YEAR_ASC', 'album.release_year', 'ASC', true], + ['RELEASE_YEAR_DESC', 'album.release_year', 'DESC', true], + ['AVERAGE_RATING_ASC', 'album.average_rating', 'ASC', true], + ['AVERAGE_RATING_DESC', 'album.average_rating', 'DESC', true], + ] as const)('%s sorts on %s %s', (sort, expr, direction, nullable) => { + const key = sortKey(input({ sort })); + expect(render(key.expr).sql).toBe(expr); + expect(key.direction).toBe(direction); + expect(key.nullable).toBe(nullable); + // NULLs last in both directions, then the id tiebreak. + expect(render(orderBy(key)).sql).toBe( + `${expr} ${direction} NULLS LAST, album.id ASC`, + ); + }); + + it('sorts by rating on the stored column, not a live aggregate', () => { + const { sql } = render(sortKey(input({ sort: 'AVERAGE_RATING_DESC' })).expr); + expect(sql).not.toMatch(/avg|review/i); + }); +}); + +describe('afterCursor for the descending and rating sorts', () => { + it('continues below the cursor for a descending title sort', () => { + const key = sortKey(input({ sort: 'TITLE_DESC' })); + const { sql, params } = render( + afterCursor(key, { sort: 'TITLE_DESC', value: 'blue', id: 5 }), + ); + expect(sql).toBe( + '(lower(album.title) < $1 OR (lower(album.title) = $2 AND album.id > $3))', + ); + expect(params).toEqual(['blue', 'blue', 5]); + }); + + it('keeps unknown years last when sorting oldest first', () => { + const key = sortKey(input({ sort: 'RELEASE_YEAR_ASC' })); + const { sql } = render( + afterCursor(key, { sort: 'RELEASE_YEAR_ASC', value: 1990, id: 3 }), + ); + expect(sql).toContain('album.release_year > $1'); + expect(sql).toContain('album.release_year IS NULL'); + }); + + // Ratings repeat far more than titles do, so on a tie the id decides which + // rows are left. Without it a page boundary inside a run of 4.5s would skip + // or repeat albums. + it.each(['AVERAGE_RATING_ASC', 'AVERAGE_RATING_DESC'] as const)( + 'breaks %s ties on id', + (sort) => { + const key = sortKey(input({ sort })); + const beyond = sort === 'AVERAGE_RATING_ASC' ? '>' : '<'; + const { sql, params } = render(afterCursor(key, { sort, value: 4.5, id: 12 })); + expect(sql).toBe( + `(album.average_rating ${beyond} $1 OR (album.average_rating = $2 AND album.id > $3) OR album.average_rating IS NULL)`, + ); + expect(params).toEqual([4.5, 4.5, 12]); + }, + ); + + it('pages through unrated albums by id once the cursor reaches them', () => { + const key = sortKey(input({ sort: 'AVERAGE_RATING_DESC' })); + const { sql, params } = render( + afterCursor(key, { sort: 'AVERAGE_RATING_DESC', value: null, id: 9 }), + ); + expect(sql).toBe('(album.average_rating IS NULL AND album.id > $1)'); + expect(params).toEqual([9]); + }); + + it('rejects a cursor from the opposite direction of the same column', () => { + const cursor = encodeCursor({ sort: 'TITLE_ASC', value: 'blue', id: 1 }); + expect(() => decodeCursor(cursor, 'TITLE_DESC')).toThrow('different sort'); + }); +}); + describe('cursor value validation', () => { it('rejects a value of the wrong type for the sort', () => { const yearKey = sortKey(input({ sort: 'RELEASE_YEAR_DESC' })); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 1ae09c9..9195cdf 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -8,7 +8,13 @@ import { GraphQLError } from 'graphql'; */ export type AlbumSort = - 'RELEVANCE' | 'TITLE_ASC' | 'RELEASE_YEAR_DESC' | 'AVERAGE_RATING_DESC'; + | 'RELEVANCE' + | 'TITLE_ASC' + | 'TITLE_DESC' + | 'RELEASE_YEAR_ASC' + | 'RELEASE_YEAR_DESC' + | 'AVERAGE_RATING_ASC' + | 'AVERAGE_RATING_DESC'; export type AlbumSearchInput = { query: string; @@ -88,7 +94,8 @@ export function searchFilter(input: AlbumSearchInput, omit?: 'decades'): SQL { export type SortKey = { expr: SQL; direction: 'ASC' | 'DESC'; - // Nullable keys (release year) put NULLs last and need extra cursor logic. + // Nullable keys (release year, rating) put NULLs last in both directions and + // need extra cursor logic. nullable: boolean; // What a cursor's value must be for this sort, checked before it reaches SQL. valueType: 'string' | 'number'; @@ -114,23 +121,32 @@ export function sortKey(input: AlbumSearchInput): SortKey { valueType: 'string', }; case 'TITLE_ASC': + case 'TITLE_DESC': return { expr: sql`lower(album.title)`, - direction: 'ASC', + direction: input.sort === 'TITLE_ASC' ? 'ASC' : 'DESC', nullable: false, valueType: 'string', }; + case 'RELEASE_YEAR_ASC': case 'RELEASE_YEAR_DESC': return { expr: sql`album.release_year`, - direction: 'DESC', + direction: input.sort === 'RELEASE_YEAR_ASC' ? 'ASC' : 'DESC', nullable: true, valueType: 'number', }; + // A stored column kept current by a trigger on review, not a live AVG(): + // the cursor needs a value that does not move with every other review. + // Albums without reviews are NULL and come last. + case 'AVERAGE_RATING_ASC': case 'AVERAGE_RATING_DESC': - throw new GraphQLError( - 'Sorting by rating is not available until reviews are stored.', - ); + return { + expr: sql`album.average_rating`, + direction: input.sort === 'AVERAGE_RATING_ASC' ? 'ASC' : 'DESC', + nullable: true, + valueType: 'number', + }; } } diff --git a/server/src/search/sort.postgres.test.ts b/server/src/search/sort.postgres.test.ts new file mode 100644 index 0000000..4b9919b --- /dev/null +++ b/server/src/search/sort.postgres.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from 'node:crypto'; +import { PgDialect } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; +import { Pool } from 'pg'; +import { afterAll, describe, expect, it } from 'vitest'; +import { + afterCursor, + decodeCursor, + encodeCursor, + orderBy, + sortKey, + type AlbumSort, +} from './search.js'; + +// Set TEST_DATABASE_URL to run these tests. The paging test reads VALUES rows +// only; the trigger test writes inside a transaction it rolls back. +describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL sorting', () => { + const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }); + const dialect = new PgDialect(); + + afterAll(() => pool.end()); + + // Repeated titles, years and ratings, and NULLs, so every page boundary of + // two rows lands inside a run of ties at least once. + const fixture = sql`(VALUES + (1, 'Blue', 1971, 4.5::float8), + (2, 'blue', 1971, 4.5::float8), + (3, 'Abbey Road', NULL, 4.5::float8), + (4, 'Kid A', 2000, NULL), + (5, 'Blue', 1997, 3::float8), + (6, 'Kid A', NULL, NULL), + (7, 'Abbey Road', 1969, 4.5::float8) + ) AS album(id, title, release_year, average_rating)`; + + async function page(sort: AlbumSort, after: string | null) { + const key = sortKey({ query: '', sort }); + const where = after ? afterCursor(key, decodeCursor(after, sort)) : sql`TRUE`; + const query = dialect.sqlToQuery(sql` + SELECT album.id, ${key.expr} AS "sortValue" + FROM ${fixture} + WHERE ${where} + ORDER BY ${orderBy(key)} + LIMIT 2 + `); + const result = await pool.query<{ id: number; sortValue: string | number | null }>( + query.sql, + query.params, + ); + return result.rows; + } + + it.each([ + 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_ASC', + 'RELEASE_YEAR_DESC', + 'AVERAGE_RATING_ASC', + 'AVERAGE_RATING_DESC', + ] as const)('pages %s in the same order as one unpaged query', async (sort) => { + const key = sortKey({ query: '', sort }); + const all = dialect.sqlToQuery( + sql`SELECT album.id FROM ${fixture} ORDER BY ${orderBy(key)}`, + ); + const expected = (await pool.query<{ id: number }>(all.sql, all.params)).rows.map( + (row) => row.id, + ); + + const paged: number[] = []; + let after: string | null = null; + for (;;) { + const rows = await page(sort, after); + const last = rows.at(-1); + if (!last) break; + paged.push(...rows.map((row) => row.id)); + after = encodeCursor({ sort, value: last.sortValue, id: last.id }); + } + + expect(paged).toEqual(expected); + expect(new Set(paged).size).toBe(7); + }); + + it('orders ratings with ties on id and unrated albums last', async () => { + const key = sortKey({ query: '', sort: 'AVERAGE_RATING_DESC' }); + const query = dialect.sqlToQuery( + sql`SELECT album.id FROM ${fixture} ORDER BY ${orderBy(key)}`, + ); + const rows = (await pool.query<{ id: number }>(query.sql, query.params)).rows; + expect(rows.map((row) => row.id)).toEqual([1, 2, 3, 7, 5, 4, 6]); + }); + + it('keeps album.average_rating in step with reviews', async () => { + const client = await pool.connect(); + const rating = async (albumId: number) => + ( + await client.query<{ average_rating: number | null }>( + 'SELECT average_rating FROM album WHERE id = $1', + [albumId], + ) + ).rows[0]?.average_rating; + + try { + await client.query('BEGIN'); + const albums = await client.query<{ id: number }>( + `INSERT INTO album (title) VALUES ('Trigger test A'), ('Trigger test B') RETURNING id`, + ); + const [a, b] = albums.rows.map((row) => row.id) as [number, number]; + const [u1, u2] = [randomUUID(), randomUUID()]; + await client.query( + `INSERT INTO app_user (id, display_name) VALUES ($1, 'one'), ($2, 'two')`, + [u1, u2], + ); + + expect(await rating(a)).toBeNull(); + + await client.query( + 'INSERT INTO review (user_id, album_id, rating) VALUES ($1, $3, 5), ($2, $3, 2)', + [u1, u2, a], + ); + expect(await rating(a)).toBe(3.5); + + await client.query('UPDATE review SET rating = 4 WHERE user_id = $1', [u2]); + expect(await rating(a)).toBe(4.5); + + // Moving a review refreshes both albums. + await client.query('UPDATE review SET album_id = $2 WHERE user_id = $1', [u2, b]); + expect(await rating(a)).toBe(5); + expect(await rating(b)).toBe(4); + + await client.query('DELETE FROM review WHERE user_id = $1', [u1]); + expect(await rating(a)).toBeNull(); + } finally { + await client.query('ROLLBACK'); + client.release(); + } + }); +});