Fix after handling

This commit is contained in:
Zoe Roux
2025-01-12 15:55:02 +01:00
parent f490faa796
commit 86d37514dc
2 changed files with 18 additions and 39 deletions
+17 -18
View File
@@ -29,33 +29,33 @@ export const keysetPaginate = <
sort: Sort<T, Remap>;
}) => {
if (!after) return undefined;
let cursor: After = JSON.parse(
const cursor: After = JSON.parse(
Buffer.from(after, "base64").toString("utf-8"),
);
const pkSort = { key: "pk" as const, desc: false };
if (sort.random) {
return or(
gt(
sql`md5(${sort.random.seed} || ${table[pkSort.key]})`,
sql`md5(${sort.random.seed} || ${cursor[0]})`,
),
and(
eq(
sql`md5(${sort.random.seed} || ${table[pkSort.key]})`,
sql`md5(${sort.random.seed} || ${cursor[0]})`,
),
gt(table[pkSort.key], cursor[0]),
),
);
}
// TODO: Add an outer query >= for perf
// PERF: See https://use-the-index-luke.com/sql/partial-results/fetch-next-page#sb-equivalent-logic
let where = undefined;
let previous = undefined;
if (sort.random) {
const lastCursor = cursor.slice(-1)[0];
where = or(
where,
and(
previous,
gt(
sql`md5(${sort.random.seed} || ${table[pkSort.key]})`,
sql`md5(${sort.random.seed} || ${lastCursor})`,
),
),
);
previous = and(previous, eq(table[pkSort.key], lastCursor));
cursor = cursor.slice(1);
}
for (const [i, by] of [...sort.sort, pkSort].entries()) {
const cmp = by.desc ? lt : gt;
where = or(
@@ -79,7 +79,6 @@ export const keysetPaginate = <
export const generateAfter = (cursor: any, sort: Sort<any, any>) => {
const ret = [
...(sort.random ? [`random:${sort.random.seed}`] : []),
...sort.sort.map((by) => cursor[by.remmapedKey ?? by.key]),
cursor.pk,
];