Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function toConnection<Row, Node>({
*/

/** 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');
Expand Down
151 changes: 151 additions & 0 deletions backend/src/lists/list-query.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
174 changes: 174 additions & 0 deletions backend/src/lists/list-query.ts
Original file line number Diff line number Diff line change
@@ -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<Exclude<WineListSort, 'NEWEST'>, 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 };
}
Loading