diff --git a/backend/src/connection.ts b/backend/src/connection.ts index c812556..c9dfc5d 100644 --- a/backend/src/connection.ts +++ b/backend/src/connection.ts @@ -39,7 +39,7 @@ export function toConnection({ */ /** The largest value of a PostgreSQL `integer`. A larger id cannot exist, and the query would fail. */ -const MAX_INTEGER = 2_147_483_647; +export const MAX_INTEGER = 2_147_483_647; export function encodeIdCursor(id: number): string { return Buffer.from(`id:${id}`).toString('base64'); diff --git a/backend/src/lists/list-query.test.ts b/backend/src/lists/list-query.test.ts new file mode 100644 index 0000000..40e73b9 --- /dev/null +++ b/backend/src/lists/list-query.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it } from 'vitest'; +import { encodeIdCursor } from '../connection'; +import { + buildListPageQuery, + decodeListCursor, + encodeListCursor, + WINE_LIST_SORTS, + type ListedWineRow, + type WineListSort, +} from './list-query'; + +// The order itself is tested against PostgreSQL in lists-api.db.test.ts. These tests cover what +// can be checked without a database: which SQL can be built, and the cursors. + +const base = { userId: 7, list: 'TRIED' as const, first: 2 }; +const row = (entry_id: number, sort_key: string | null) => + ({ entry_id, sort_key }) as ListedWineRow; +const cursor = (text: string) => Buffer.from(text).toString('base64'); +const badInput = expect.objectContaining({ extensions: { code: 'BAD_USER_INPUT' } }); + +describe('buildListPageQuery', () => { + it('sorts by newest added when no sort is given, as before the sort orders existed', () => { + const query = buildListPageQuery(base); + expect(query.sort).toBe('NEWEST'); + expect(query.listSql).toContain('ORDER BY user_wine.id DESC'); + expect(query.listSql).not.toContain('review'); + expect(query.listParams).toEqual([7, 'TRIED', 3]); + }); + + it.each(WINE_LIST_SORTS)( + 'ends the order for %s with the row id, so it is always the same', + (sort) => { + expect(buildListPageQuery({ ...base, sort }).listSql).toMatch( + /ORDER BY [^\n]*user_wine\.id DESC\nLIMIT/, + ); + }, + ); + + it('sorts by the rating of the user who owns the list, not by anyone else', () => { + const { listSql } = buildListPageQuery({ ...base, sort: 'OWN_RATING' }); + expect(listSql).toContain( + 'LEFT JOIN review ON review.user_id = user_wine.user_id AND review.wine_id = user_wine.wine_id', + ); + expect(listSql).toContain('ORDER BY COALESCE(review.rating, 0) DESC'); + }); + + it('puts wines without a rating last, and sorts names A to Z', () => { + expect(buildListPageQuery({ ...base, sort: 'COMMUNITY_RATING' }).listSql).toContain( + 'ORDER BY COALESCE(wine.community_avg, 0) DESC', + ); + expect(buildListPageQuery({ ...base, sort: 'NAME' }).listSql).toContain( + 'ORDER BY wine.name ASC', + ); + }); + + it('filters on the shared rating in both the page and the count', () => { + const query = buildListPageQuery({ ...base, sort: 'NAME', minRating: 4 }); + expect(query.listSql).toContain('wine.community_avg >= $3'); + expect(query.countSql).toContain('wine.community_avg >= $3'); + expect(query.countParams).toEqual([7, 'TRIED', 4]); + // Without minRating, the count needs only user_wine. + expect(buildListPageQuery(base).countSql).not.toContain('JOIN'); + }); + + it('accepts minRating from 0 to 5, and refuses anything else', () => { + for (const minRating of [0, 2.5, 5]) { + expect(() => buildListPageQuery({ ...base, minRating })).not.toThrow(); + } + for (const minRating of [-0.5, 5.5, Number.NaN]) { + expect(() => buildListPageQuery({ ...base, minRating })).toThrow(badInput); + } + }); + + it('refuses a sort order that is not in the list', () => { + const sort = 'wine.name; DROP TABLE wine' as WineListSort; + expect(() => buildListPageQuery({ ...base, sort })).toThrow('Invalid sort.'); + }); + + it('pages after the cursor with keyset conditions, and the count ignores the cursor', () => { + const after = encodeListCursor('COMMUNITY_RATING', row(40, '4.50')); + const query = buildListPageQuery({ ...base, sort: 'COMMUNITY_RATING', after }); + expect(query.listSql).toContain( + '(COALESCE(wine.community_avg, 0) < $4::numeric OR (COALESCE(wine.community_avg, 0) = $4::numeric AND user_wine.id < $3))', + ); + expect(query.listParams).toEqual([7, 'TRIED', 40, '4.50', 3]); + expect(query.countSql).not.toContain('$3'); + + const byName = buildListPageQuery({ + ...base, + sort: 'NAME', + after: encodeListCursor('NAME', row(40, 'Bravo')), + }); + expect(byName.listSql).toContain('wine.name > $4::text'); + }); + + it('never puts a value from the cursor in the SQL itself', () => { + const name = "Bravo'; DROP TABLE wine; --"; + const query = buildListPageQuery({ + ...base, + sort: 'NAME', + after: encodeListCursor('NAME', row(40, name)), + }); + expect(query.listSql).not.toContain('DROP TABLE'); + expect(query.listParams).toContain(name); + }); +}); + +describe('list cursors', () => { + it('uses the plain id cursor for NEWEST, so pages loaded before the sort orders still work', () => { + expect(encodeListCursor('NEWEST', row(12, null))).toBe(encodeIdCursor(12)); + expect(decodeListCursor('NEWEST', encodeIdCursor(12))).toEqual({ id: 12, value: null }); + }); + + it.each([ + ['OWN_RATING', '4.5'], + ['OWN_RATING', '0'], + ['COMMUNITY_RATING', '3.75'], + ['NAME', 'Château: Øst, «Réserve»'], + ['NAME', ''], + ] as const)('round-trips %s with the value %j', (sort, value) => { + expect(decodeListCursor(sort, encodeListCursor(sort, row(2_147_483_647, value)))).toEqual({ + id: 2_147_483_647, + value, + }); + }); + + it('is null without a cursor', () => { + expect(decodeListCursor('NAME', null)).toBeNull(); + expect(decodeListCursor('NEWEST', undefined)).toBeNull(); + }); + + it.each([ + ['a cursor from another sort order', 'OWN_RATING', encodeListCursor('NAME', row(1, 'A'))], + ['a sorted cursor with NEWEST', 'NEWEST', encodeListCursor('NAME', row(1, 'A'))], + ['an id cursor with NAME', 'NAME', encodeIdCursor(1)], + ['an offset cursor from the wine search', 'NAME', cursor('offset:24')], + ['not base64 at all', 'COMMUNITY_RATING', 'not-a-cursor'], + ['a rating that is not a number', 'OWN_RATING', cursor('sort:OWN_RATING:1:4; DROP')], + [ + 'a rating with too many decimals', + 'COMMUNITY_RATING', + cursor('sort:COMMUNITY_RATING:1:4.555'), + ], + ['id 0', 'NAME', cursor('sort:NAME:0:A')], + ['an id above the largest database integer', 'NAME', cursor('sort:NAME:2147483648:A')], + ['a name longer than any wine name', 'NAME', cursor(`sort:NAME:1:${'a'.repeat(1001)}`)], + ['a name with a zero byte', 'NAME', cursor('sort:NAME:1:A\0B')], + ] as const)('rejects %s with BAD_USER_INPUT', (_name, sort, text) => { + expect(() => decodeListCursor(sort, text)).toThrow(badInput); + }); +}); diff --git a/backend/src/lists/list-query.ts b/backend/src/lists/list-query.ts new file mode 100644 index 0000000..ecc070c --- /dev/null +++ b/backend/src/lists/list-query.ts @@ -0,0 +1,174 @@ +// Builds the SQL for one page of a user's wine list (User.wines). Kept apart from the database, +// like wine-query.ts, so the sort orders and the cursor can be tested without PostgreSQL. +import { GraphQLError } from 'graphql'; +import { decodeIdCursor, encodeIdCursor, MAX_INTEGER } from '../connection'; +import type { WineRow } from '../loaders'; +import type { WineList } from './wine-lists'; + +/** The same values as the GraphQL enum WineListSort. */ +export const WINE_LIST_SORTS = ['NEWEST', 'OWN_RATING', 'COMMUNITY_RATING', 'NAME'] as const; +export type WineListSort = (typeof WINE_LIST_SORTS)[number]; + +/** How a sort order other than NEWEST compares two wines. NEWEST needs only the row id. */ +interface SortKey { + /** The SQL to sort by. Never null, so a cursor can always be compared with it. */ + sql: string; + /** What the value in the cursor is cast to in the query. */ + type: 'numeric' | 'text'; + descending: boolean; +} + +/* + * Only these expressions can ever reach the database: the sort order picks one by name, and + * nothing from the request is put in the SQL. A wine without a rating counts as 0, below the + * lowest possible rating (0.5), so it comes last. Every order ends with the row id, newest + * added first, so two wines with the same value always come in the same order. + */ +const SORT_KEYS: Record, SortKey> = { + // The rating of the user who owns the list, not of the one asking, so it means the same on + // every profile. + OWN_RATING: { sql: 'COALESCE(review.rating, 0)', type: 'numeric', descending: true }, + COMMUNITY_RATING: { sql: 'COALESCE(wine.community_avg, 0)', type: 'numeric', descending: true }, + NAME: { sql: 'wine.name', type: 'text', descending: false }, +}; + +const JOIN_WINE = 'JOIN wine ON wine.id = user_wine.wine_id'; + +/** The owner's review of each wine, for OWN_RATING. At most one per user and wine (review_wine_user_key). */ +const JOIN_OWN_REVIEW = + 'LEFT JOIN review ON review.user_id = user_wine.user_id AND review.wine_id = user_wine.wine_id'; + +const badInput = (message: string) => + new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); + +/** A row of the wine table, plus the id of its row in the list and the value it was sorted by. */ +export interface ListedWineRow extends WineRow { + entry_id: number; + /** The sort value as text, for the cursor. Null for NEWEST, which needs only entry_id. */ + sort_key: string | null; +} + +/* + * Cursors. NEWEST keeps the plain id cursor from connection.ts, so pages loaded before the sort + * orders existed still work. The other orders also need the value of the last wine on the page, + * and the name of the order, so a cursor is never used with an order it was not made for: + * "sort:NAME:42:Château Margaux", base64-encoded. The value is last, as a name can hold a colon. + */ + +/** No wine name in X-Wines comes close. Anything longer is not a cursor the API made. */ +const MAX_CURSOR_VALUE_LENGTH = 1000; +const NUMERIC_VALUE = /^\d(\.\d{1,2})?$/; + +/** The cursor that points just after this row, in this order. */ +export function encodeListCursor(sort: WineListSort, row: ListedWineRow): string { + if (sort === 'NEWEST') return encodeIdCursor(row.entry_id); + return Buffer.from(`sort:${sort}:${row.entry_id}:${row.sort_key}`).toString('base64'); +} + +interface ListCursor { + id: number; + /** The sort value of the last wine on the page. Null for NEWEST. */ + value: string | null; +} + +/** The cursor's position, or null without one. A cursor for another order gives BAD_USER_INPUT. */ +export function decodeListCursor( + sort: WineListSort, + cursor: string | null | undefined, +): ListCursor | null { + if (!cursor) return null; + if (sort === 'NEWEST') { + const id = decodeIdCursor(cursor); + return id === null ? null : { id, value: null }; + } + + const match = /^sort:([A-Z_]+):(\d{1,10}):(.*)$/s.exec( + Buffer.from(cursor, 'base64').toString('utf8'), + ); + if (!match) throw badInput('Invalid cursor.'); + const [, cursorSort, idText, value] = match; + if (cursorSort !== sort) throw badInput('The cursor belongs to another sort order.'); + + // The id and the value must be ones the query can compare with, or PostgreSQL would fail. + const id = Number(idText); + const validId = id > 0 && id <= MAX_INTEGER; + const validValue = + SORT_KEYS[sort].type === 'numeric' + ? NUMERIC_VALUE.test(value) + : value.length <= MAX_CURSOR_VALUE_LENGTH && !value.includes('\0'); + if (!validId || !validValue) throw badInput('Invalid cursor.'); + return { id, value }; +} + +/** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */ +function addParam(params: unknown[], value: unknown): string { + params.push(value); + return `$${params.length}`; +} + +/** The parts of a query on their own lines, leaving out the ones that are false. */ +const lines = (...parts: (string | false)[]) => parts.filter(Boolean).join('\n'); + +export interface ListPageArgs { + userId: number; + list: WineList; + sort?: WineListSort | null; + /** Only wines whose shared rating is at least this, 0 to 5. Leaves out wines without ratings. */ + minRating?: number | null; + first: number; + after?: string | null; +} + +/** + * The SQL for one page of the list (one row more than `first`, to know if there is a next + * page), and for the number of wines on it in all. Only the page depends on the cursor. + */ +export function buildListPageQuery({ userId, list, sort, minRating, first, after }: ListPageArgs) { + const order: WineListSort = sort ?? 'NEWEST'; + if (!WINE_LIST_SORTS.includes(order)) throw new Error('Invalid sort.'); + if (minRating != null && !(minRating >= 0 && minRating <= 5)) { + throw badInput('minRating must be between 0 and 5.'); + } + const cursor = decodeListCursor(order, after); + const key = order === 'NEWEST' ? null : SORT_KEYS[order]; + + const params: unknown[] = []; + const where = [ + `user_wine.user_id = ${addParam(params, userId)}`, + `user_wine.list = ${addParam(params, list)}`, + ]; + if (minRating != null) where.push(`wine.community_avg >= ${addParam(params, minRating)}`); + const countSql = lines( + 'SELECT count(*)::int AS total FROM user_wine', + minRating != null && JOIN_WINE, + `WHERE ${where.join(' AND ')}`, + ); + const countParams = [...params]; + + // Keyset pagination: the rows after the cursor in the same order, so a wine added to or + // taken off the list meanwhile neither skips nor repeats a wine on the next page. + if (cursor) { + const id = addParam(params, cursor.id); + if (key) { + const value = `${addParam(params, cursor.value)}::${key.type}`; + const beyond = key.descending ? '<' : '>'; + where.push( + `(${key.sql} ${beyond} ${value} OR (${key.sql} = ${value} AND user_wine.id < ${id}))`, + ); + } else { + where.push(`user_wine.id < ${id}`); + } + } + + const listSql = lines( + `SELECT wine.*, user_wine.id AS entry_id, ${key ? `(${key.sql})::text` : 'NULL'} AS sort_key`, + 'FROM user_wine', + JOIN_WINE, + order === 'OWN_RATING' && JOIN_OWN_REVIEW, + `WHERE ${where.join(' AND ')}`, + `ORDER BY ${key ? `${key.sql} ${key.descending ? 'DESC' : 'ASC'}, ` : ''}user_wine.id DESC`, + `LIMIT ${addParam(params, first + 1)}`, + ); + + return { listSql, listParams: params, countSql, countParams, sort: order }; +} diff --git a/backend/src/lists/lists-api.db.test.ts b/backend/src/lists/lists-api.db.test.ts index aaa0b72..e296c82 100644 --- a/backend/src/lists/lists-api.db.test.ts +++ b/backend/src/lists/lists-api.db.test.ts @@ -10,8 +10,14 @@ const SET = `mutation Set($wineId: ID!, $list: WineList!, $inList: Boolean!) { setWineInList(wineId: $wineId, list: $list, inList: $inList) { id myLists } }`; const MY_LISTS = `query MyLists($id: ID!) { wine(id: $id) { id myLists } }`; -const LIST = `query List($list: WineList!, $first: Int, $after: String) { - me { wines(list: $list, first: $first, after: $after) { +const LIST = `query List( + $list: WineList! + $sort: WineListSort + $minRating: Float + $first: Int + $after: String +) { + me { wines(list: $list, sort: $sort, minRating: $minRating, first: $first, after: $after) { totalCount edges { node { id } } pageInfo { hasNextPage endCursor } @@ -145,6 +151,139 @@ describe.skipIf(!url)('wine lists API (PostgreSQL)', () => { expect(second.pageInfo.hasNextPage).toBe(false); }); + /** Every wine on a list in the given order, read one page of `first` at a time. */ + async function readAll( + browser: { + request: (query: string, variables?: Record) => Promise; + }, + variables: { list: string; sort?: string; minRating?: number }, + first = 1, + ) { + const ids: string[] = []; + let after: string | null = null; + for (;;) { + const result = await browser.request(LIST, { ...variables, first, after }); + expect(result.errors).toBeUndefined(); + const page = pageOf(result); + ids.push(...idsOf(page)); + if (!page.pageInfo.hasNextPage) return { ids, totalCount: page.totalCount }; + after = page.pageInfo.endCursor; + } + } + + /** + * Four favourites with names and shared ratings set on purpose, with two wines that are + * equal on both. Sol has reviewed two of them, and Tom (another user) one of the others. + */ + async function sortableList() { + const [a, b, c, d] = await api.createWines(4); + const sol = await api.createBrowser('sol'); + const tom = await api.createBrowser('tom'); + for (const wine of [a, b, c, d]) await sol.request(SET, set(wine, 'FAVOURITE')); + const review = (wineId: string, rating: number) => ({ input: { wineId, rating } }); + await sol.request(SAVE_REVIEW, review(a, 5)); + await sol.request(SAVE_REVIEW, review(c, 4)); + await tom.request(SAVE_REVIEW, review(b, 5)); + // Set after the reviews, which recalculate the shared rating. + for (const [id, name, rating] of [ + [a, 'Cava', 3], + [b, 'Barolo', 4.5], + [c, 'Amarone', null], + [d, 'Barolo', 4.5], + ] as const) { + await pool.query('UPDATE wine SET name = $2, community_avg = $3 WHERE id = $1', [ + Number(id), + name, + rating, + ]); + } + return { sol, wines: { a, b, c, d } }; + } + + it('sorts by newest, own rating, shared rating and name, with the newest first on a tie', async () => { + const { sol, wines } = await sortableList(); + const { a, b, c, d } = wines; + const expected = { + NEWEST: [d, c, b, a], + // Only Sol's own reviews count: Tom's 5 for «b» does not. Unreviewed wines come last. + OWN_RATING: [a, c, d, b], + // «b» and «d» are equal, so the newest added comes first. No rating comes last. + COMMUNITY_RATING: [d, b, a, c], + // The two «Barolo» are equal, so the newest added comes first. + NAME: [c, d, b, a], + }; + + for (const [sort, order] of Object.entries(expected)) { + // One wine per page uses a cursor after every wine; 50 gets the whole list at once. + expect(await readAll(sol, { list: 'FAVOURITE', sort }, 1)).toEqual({ + ids: order, + totalCount: 4, + }); + expect(await readAll(sol, { list: 'FAVOURITE', sort }, 50)).toEqual({ + ids: order, + totalCount: 4, + }); + } + // Without a sort, the list is newest first, as before. + expect((await readAll(sol, { list: 'FAVOURITE' })).ids).toEqual(expected.NEWEST); + }); + + it('keeps only wines with at least minRating, also in totalCount, in any order', async () => { + const { sol, wines } = await sortableList(); + const { a, b, d } = wines; + + expect(await readAll(sol, { list: 'FAVOURITE', minRating: 4 })).toEqual({ + ids: [d, b], + totalCount: 2, + }); + expect(await readAll(sol, { list: 'FAVOURITE', sort: 'NAME', minRating: 3 })).toEqual({ + ids: [d, b, a], + totalCount: 3, + }); + // Wines without a shared rating are left out, also with 0. + expect((await readAll(sol, { list: 'FAVOURITE', minRating: 0 })).totalCount).toBe(3); + + for (const minRating of [-1, 5.5]) { + expect(codeOf(await sol.request(LIST, { list: 'FAVOURITE', minRating }))).toBe( + 'BAD_USER_INPUT', + ); + } + }); + + it('does not skip a wine when one is taken off the list while paging in a sorted order', async () => { + const { sol, wines } = await sortableList(); + const { a, b, c, d } = wines; + + const first = pageOf(await sol.request(LIST, { list: 'FAVOURITE', sort: 'NAME', first: 2 })); + expect(idsOf(first)).toEqual([c, d]); + await sol.request(SET, set(d, 'FAVOURITE', false)); + + const second = pageOf( + await sol.request(LIST, { + list: 'FAVOURITE', + sort: 'NAME', + first: 2, + after: first.pageInfo.endCursor, + }), + ); + expect(idsOf(second)).toEqual([b, a]); + expect(second.pageInfo.hasNextPage).toBe(false); + }); + + it('rejects a cursor from another sort order', async () => { + const { sol } = await sortableList(); + const byName = pageOf(await sol.request(LIST, { list: 'FAVOURITE', sort: 'NAME', first: 1 })); + + for (const sort of ['OWN_RATING', 'NEWEST']) { + const result = await sol.request(LIST, { + list: 'FAVOURITE', + sort, + after: byName.pageInfo.endCursor, + }); + expect(codeOf(result)).toBe('BAD_USER_INPUT'); + } + }); + it('rejects a cursor that was not made by the API', async () => { const lise = await api.createBrowser('lise'); expect(codeOf(await lise.request(LIST, { list: 'TRIED', after: 'not-a-cursor' }))).toBe( diff --git a/backend/src/lists/resolvers.ts b/backend/src/lists/resolvers.ts index 3e4ff40..efc6275 100644 --- a/backend/src/lists/resolvers.ts +++ b/backend/src/lists/resolvers.ts @@ -2,7 +2,7 @@ import { GraphQLError } from 'graphql'; import { AuthErrorCode, authError } from '../auth/errors'; import { toGraphQLUser } from '../auth/resolvers'; -import { encodeIdCursor, toConnection } from '../connection'; +import { toConnection } from '../connection'; import type { Context } from '../context'; import { isForeignKeyViolation } from '../db-errors'; import { withTransaction } from '../db'; @@ -16,6 +16,7 @@ import { TopFavouritesError, type WineList, } from './wine-lists'; +import { encodeListCursor, type WineListSort } from './list-query'; /** The most wines one page of a list can have. */ const MAX_PAGE_SIZE = 50; @@ -70,12 +71,21 @@ export const listResolvers = { User: { async wines( user: { id: string }, - args: { list: WineList; first?: number | null; after?: string | null }, + args: { + list: WineList; + sort?: WineListSort | null; + minRating?: number | null; + first?: number | null; + after?: string | null; + }, ) { const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); - const { rows, totalCount } = await findListPage({ + // Only the user whose list it is: OWN_RATING is their rating, never the session's. + const { rows, totalCount, sort } = await findListPage({ userId: Number(user.id), list: args.list, + sort: args.sort, + minRating: args.minRating, first, after: args.after, }); @@ -84,7 +94,7 @@ export const listResolvers = { first, totalCount, toNode: toWine, - cursorFor: (row) => encodeIdCursor(row.entry_id), + cursorFor: (row) => encodeListCursor(sort, row), }); }, diff --git a/backend/src/lists/schema.ts b/backend/src/lists/schema.ts index 97c28fa..52763f6 100644 --- a/backend/src/lists/schema.ts +++ b/backend/src/lists/schema.ts @@ -9,9 +9,32 @@ export const listTypeDefs = `#graphql TRIED } + "How a list of wines is sorted. Wines with the same value come newest added first." + enum WineListSort { + "Newest added first." + NEWEST + "The list owner's own review, highest first. Wines the owner has not reviewed come last." + OWN_RATING + "The shared rating (Wine.communityRating), highest first. Wines without ratings come last." + COMMUNITY_RATING + "The wine's name, A to Z." + NAME + } + extend type User { - "The wines on one of the user's lists, newest first. Use pageInfo.endCursor as 'after' to load more." - wines(list: WineList!, first: Int = 24, after: String): WineConnection! + """ + The wines on one of the user's lists, newest added first unless 'sort' says otherwise. + 'minRating' (0 to 5) keeps only wines with at least that shared rating, and leaves out wines + without ratings; totalCount follows it. Use pageInfo.endCursor as 'after' to load more, with + the same sort. A cursor from another sort gives BAD_USER_INPUT. + """ + wines( + list: WineList! + sort: WineListSort = NEWEST + minRating: Float + first: Int = 24 + after: String + ): WineConnection! "Up to four of the user's favourites, in the order the user chose." topFavourites: [Wine!]! diff --git a/backend/src/lists/wine-lists.ts b/backend/src/lists/wine-lists.ts index 630364d..f671fb0 100644 --- a/backend/src/lists/wine-lists.ts +++ b/backend/src/lists/wine-lists.ts @@ -3,9 +3,9 @@ // lists are here, and run in one transaction. The frontend repeats them in // frontend/src/lib/wineLists.ts, so a button can change before the answer: change both together. import type { PoolClient } from 'pg'; -import { decodeIdCursor } from '../connection'; import { pool } from '../db'; import type { WineRow } from '../loaders'; +import { buildListPageQuery, type ListedWineRow, type ListPageArgs } from './list-query'; /** The same values as the GraphQL enum WineList and the CHECK on user_wine.list. */ export const WINE_LISTS = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED'] as const; @@ -109,40 +109,17 @@ export async function findTopFavourites(userId: number) { return rows; } -/** A row of the wine table, plus the id of its row in the list (for the cursor). */ -export interface ListedWineRow extends WineRow { - entry_id: number; -} - -/** One page of a list, newest first, and how many wines the list has in all. */ -export async function findListPage({ - userId, - list, - first, - after, -}: { - userId: number; - list: WineList; - first: number; - after?: string | null; -}) { - const before = decodeIdCursor(after); - // The index user_wine_list_newest covers both queries. +/** + * One page of a list in the chosen order, and how many wines match in all. The SQL is built in + * list-query.ts. The index user_wine_list_newest finds the user's list for every order; NEWEST + * also reads it in order. The other orders sort the user's list in memory, which is fast for + * lists of a few hundred wines. + */ +export async function findListPage(args: ListPageArgs) { + const query = buildListPageQuery(args); const [page, count] = await Promise.all([ - pool.query( - `SELECT wine.*, user_wine.id AS entry_id - FROM user_wine - JOIN wine ON wine.id = user_wine.wine_id - WHERE user_wine.user_id = $1 AND user_wine.list = $2 - AND ($3::integer IS NULL OR user_wine.id < $3) - ORDER BY user_wine.id DESC - LIMIT $4`, - [userId, list, before, first + 1], - ), - pool.query<{ total: number }>( - 'SELECT count(*)::int AS total FROM user_wine WHERE user_id = $1 AND list = $2', - [userId, list], - ), + pool.query(query.listSql, query.listParams), + pool.query<{ total: number }>(query.countSql, query.countParams), ]); - return { rows: page.rows, totalCount: count.rows[0].total }; + return { rows: page.rows, totalCount: count.rows[0].total, sort: query.sort }; } diff --git a/docs/api.md b/docs/api.md index d4556bc..886d3a0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -249,9 +249,16 @@ The table `user_wine` has one row per user, list and wine: `id`, `user_id`, `win ```graphql enum WineList { FAVOURITE WANT_TO_TRY TRIED } +enum WineListSort { NEWEST OWN_RATING COMMUNITY_RATING NAME } extend type User { - wines(list: WineList!, first: Int = 24, after: String): WineConnection! # newest first, first <= 50 + wines( # first <= 50 + list: WineList! + sort: WineListSort = NEWEST + minRating: Float # 0 to 5, on the shared rating + first: Int = 24 + after: String + ): WineConnection! topFavourites: [Wine!]! # in the chosen order } extend type Wine { myLists: [WineList!]! } # [] when logged out @@ -267,7 +274,7 @@ top 4 at once: send the wines in the new order, or `[]` to clear it. | Error code | When | |---|---| | `UNAUTHENTICATED` | Either mutation without a logged-in user | -| `BAD_USER_INPUT` | An invalid or unknown wine id, an unknown list, an invalid cursor, or a top 4 that breaks the rules above. A refused top 4 keeps the old one | +| `BAD_USER_INPUT` | An invalid or unknown wine id, an unknown list, an invalid cursor or one from another sort order, a `minRating` outside 0 to 5, or a top 4 that breaks the rules above. A refused top 4 keeps the old one | Choices and why: @@ -280,11 +287,64 @@ Choices and why: | `Wine.myLists` with a DataLoader per user | A page of 24 wines asks for the lists in one query | One query per wine | | Changes to the top 4 lock the user's row (`FOR NO KEY UPDATE`) | Two changes at the same time are done one after the other instead of colliding on the unique index | Retrying on a unique violation | +### Sorting and filtering a list + +`User.wines` takes a sort order and an optional lowest shared rating. The SQL is built in +`backend/src/lists/list-query.ts`, in the same way as the wine search in `wine-query.ts`. + +| `sort` | Order | Ties and missing values | +|---|---|---| +| `NEWEST` (default) | Newest added first | No ties: every row has its own id | +| `OWN_RATING` | The list owner's own review, highest first | Wines the owner has not reviewed come last | +| `COMMUNITY_RATING` | The shared rating (`Wine.communityRating`), highest first | Wines without ratings come last | +| `NAME` | The wine's name, A to Z, in the database's collation | | + +Every order ends with the row id, so wines with the same value come newest added first, and the +order is the same every time. `minRating` keeps only wines whose shared rating is at least that +value, in any order. Wines without ratings are left out, also with `minRating: 0`. `totalCount` counts +only the wines that match, across all pages. + +```graphql +query { + me { + wines(list: TRIED, sort: COMMUNITY_RATING, minRating: 4, first: 24) { + totalCount + edges { node { id name communityRating } } + pageInfo { hasNextPage endCursor } + } + } +} +``` + +Load the next page with the same `list`, `sort` and `minRating`, and `pageInfo.endCursor` as +`after`. A cursor from another sort order gives `BAD_USER_INPUT`, so a page can never continue +from the wrong place. + +Choices and why: + +| Choice | Why | Alternatives considered | +|---|---|---| +| Keyset pages for every order: the cursor holds the sort value and the row id of the last wine | A wine taken off the list while the user pages neither skips nor repeats a wine. That matters here, as the list pages remove a wine at once | Offset, as for the wine search | +| `NEWEST` keeps the plain id cursor | Pages loaded by a frontend from before the sort orders still work after a deploy | One cursor format for all orders | +| The other cursors name their order (`sort:NAME:42:Château …`, base64) | A cursor used with another order is refused instead of giving a wrong page | Trusting the frontend to send the right one | +| A missing rating sorts as 0 (`COALESCE`), below the lowest real rating (0.5) | Wines without ratings come last, and the cursor never has to compare with null | `NULLS LAST`, which a keyset condition cannot compare | +| `OWN_RATING` uses the review of the user who owns the list | It means the same on every profile, and never depends on who is asking | The rating of the logged-in user | +| Only fixed `ORDER BY` clauses, chosen by the enum value | Nothing from the request reaches the SQL. The cursor's value is a parameter, and it is checked before use | | +| No new index | The index `user_wine_list_newest` finds the user's list for every order. The orders other than `NEWEST` then sort that list in memory, which is fast for lists of a few hundred wines | An index per order, which `OWN_RATING` and `COMMUNITY_RATING` cannot use, as the values are in other tables | + +Known limit: a rating can change while someone pages (a new review changes the shared rating). +The wine then moves in the order, and the next page can miss it or have it again. The frontend +leaves out a wine it already has when a page is added (`mergeWineConnection` in +`frontend/src/lib/apollo.ts`), so it is never shown twice, and a reload gives the right order. The list pages on «Min +side» do not use `sort` yet. When they do, add `sort` and `minRating` to `keyArgs` for +`User.wines` in `frontend/src/lib/apollo.ts`, so each order is kept apart in the cache. + ### Tests | File | Tests | |---|---| -| `lists/lists-api.db.test.ts` | Through Apollo Server against PostgreSQL: login required, adding and removing twice, several lists, «Har prøvd» takes the wine off «Vil prøve», users kept apart, unknown wines and lists, pages that do not skip, one query for `myLists` on a page of 24, the top 4 rules and order, two changes at once, the database constraints, and that a saved review marks the wine as tried | +| `lists/list-query.test.ts` | Without a database: the default order, the row id last in every order, the owner's rating, `minRating` in both the page and the count and its limits, an unknown order, keyset conditions with the cursor's value as a parameter, and the cursors: the plain id cursor for `NEWEST`, round trips with names that hold colons and accents, and refused cursors from another order, with invalid values or ids | +| `lists/lists-api.db.test.ts` | Through Apollo Server against PostgreSQL: login required, adding and removing twice, several lists, «Har prøvd» takes the wine off «Vil prøve», users kept apart, unknown wines and lists, pages that do not skip, each sort order one wine per page and all at once (with ties and wines without ratings, and only the owner's own reviews), `minRating` and `totalCount`, a wine taken off while paging by name, a cursor from another order, one query for `myLists` on a page of 24, the top 4 rules and order, two changes at once, the database constraints, and that a saved review marks the wine as tried | | `demo/demo-user.db.test.ts` | The demo user: the documented password works, the data follows the rules, the averages are updated, and running it again gives the same state | ### In the frontend