lex-gql-sqlite 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +9 -0
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/package.json +11 -11
- package/src/lex-gql-sqlite.js +132 -24
- package/test/lex-gql-sqlite.test.js +221 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 074d06f: Fix cursor pagination with custom sort fields
|
|
8
|
+
|
|
9
|
+
Previously, cursor pagination used only the record ID which caused duplicate records when paginating with custom sort fields. Cursors now encode actual sort field values for correct pagination.
|
|
10
|
+
|
|
11
|
+
- Encode sort field values + URI tiebreaker in JSON cursor format
|
|
12
|
+
- Add progressive WHERE clauses for multi-field sorts
|
|
13
|
+
- Add field name validation to prevent SQL injection
|
|
14
|
+
- Export centralized DEFAULT_SORT constant from lex-gql
|
|
15
|
+
|
|
16
|
+
**Note:** Existing cursors from previous versions will be invalid and pagination will restart from the beginning.
|
|
17
|
+
|
|
18
|
+
- Updated dependencies [074d06f]
|
|
19
|
+
- lex-gql@0.2.1
|
|
20
|
+
|
|
3
21
|
## 0.2.0
|
|
4
22
|
|
|
5
23
|
### Minor Changes
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chad Miller
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lex-gql-sqlite",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "SQLite adapter for lex-gql",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/lex-gql-sqlite.js",
|
|
@@ -11,12 +11,6 @@
|
|
|
11
11
|
"default": "./src/lex-gql-sqlite.js"
|
|
12
12
|
}
|
|
13
13
|
},
|
|
14
|
-
"scripts": {
|
|
15
|
-
"build": "tsc",
|
|
16
|
-
"test": "vitest run",
|
|
17
|
-
"test:watch": "vitest",
|
|
18
|
-
"typecheck": "tsc --noEmit"
|
|
19
|
-
},
|
|
20
14
|
"keywords": [
|
|
21
15
|
"graphql",
|
|
22
16
|
"atproto",
|
|
@@ -27,14 +21,20 @@
|
|
|
27
21
|
"license": "MIT",
|
|
28
22
|
"peerDependencies": {
|
|
29
23
|
"better-sqlite3": ">=11.0.0",
|
|
30
|
-
"lex-gql": ">=0.2.
|
|
24
|
+
"lex-gql": ">=0.2.1"
|
|
31
25
|
},
|
|
32
26
|
"devDependencies": {
|
|
33
27
|
"@types/better-sqlite3": "^7.6.12",
|
|
34
28
|
"@types/node": "^22.10.0",
|
|
35
29
|
"better-sqlite3": "^12.6.0",
|
|
36
|
-
"lex-gql": "workspace:*",
|
|
37
30
|
"typescript": "^5.7.2",
|
|
38
|
-
"vitest": "^1.6.1"
|
|
31
|
+
"vitest": "^1.6.1",
|
|
32
|
+
"lex-gql": "0.2.1"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsc",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"test:watch": "vitest",
|
|
38
|
+
"typecheck": "tsc --noEmit"
|
|
39
39
|
}
|
|
40
|
-
}
|
|
40
|
+
}
|
package/src/lex-gql-sqlite.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* SQLite adapter for lex-gql
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { hydrateRecord } from 'lex-gql';
|
|
5
|
+
import { hydrateRecord, DEFAULT_SORT } from 'lex-gql';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* SQL schema for lex-gql records
|
|
@@ -110,6 +110,118 @@ const SYSTEM_FIELDS = {
|
|
|
110
110
|
actorHandle: 'a.handle',
|
|
111
111
|
};
|
|
112
112
|
|
|
113
|
+
/**
|
|
114
|
+
* Decode a sort-field-aware cursor
|
|
115
|
+
* @param {string} cursor - Base64 encoded cursor
|
|
116
|
+
* @param {Array<{field: string, dir?: string}>} sortFields - Sort configuration
|
|
117
|
+
* @returns {{ fieldValues: any[], uri: string } | null}
|
|
118
|
+
*/
|
|
119
|
+
function decodeCursor(cursor, sortFields) {
|
|
120
|
+
try {
|
|
121
|
+
const decoded = Buffer.from(cursor, 'base64').toString();
|
|
122
|
+
const parsed = JSON.parse(decoded);
|
|
123
|
+
|
|
124
|
+
// Validate cursor structure
|
|
125
|
+
if (!parsed.v || !Array.isArray(parsed.v) || !parsed.u) {
|
|
126
|
+
console.debug('lex-gql-sqlite: Invalid cursor structure');
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Validate field count matches sort configuration
|
|
131
|
+
const expectedCount = sortFields?.length || 1;
|
|
132
|
+
if (parsed.v.length !== expectedCount) {
|
|
133
|
+
console.debug(
|
|
134
|
+
`lex-gql-sqlite: Cursor field count mismatch (got ${parsed.v.length}, expected ${expectedCount})`
|
|
135
|
+
);
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return { fieldValues: parsed.v, uri: parsed.u };
|
|
140
|
+
} catch (err) {
|
|
141
|
+
console.debug('lex-gql-sqlite: Failed to decode cursor:', /** @type {Error} */ (err).message);
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Get SQL comparison operator based on sort direction and cursor type
|
|
148
|
+
* @param {string | undefined} direction - Sort direction ('asc' or 'desc')
|
|
149
|
+
* @param {boolean} isBefore - Whether this is a 'before' cursor
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
function getComparisonOp(direction, isBefore) {
|
|
153
|
+
const isDesc = direction?.toLowerCase() === 'desc';
|
|
154
|
+
return isBefore ? (isDesc ? '>' : '<') : (isDesc ? '<' : '>');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Get SQL expression for a field, handling system vs record fields
|
|
159
|
+
* @param {string} field - Field name
|
|
160
|
+
* @returns {string}
|
|
161
|
+
*/
|
|
162
|
+
function fieldToSqlExpr(field) {
|
|
163
|
+
// Validate field name to prevent SQL injection (defense-in-depth)
|
|
164
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(field)) {
|
|
165
|
+
throw new Error(`Invalid field name: ${field}`);
|
|
166
|
+
}
|
|
167
|
+
return SYSTEM_FIELDS[field] || `json_extract(r.record, '$.${field}')`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Build WHERE clause for cursor pagination with sort field awareness
|
|
172
|
+
* @param {string} cursor - Base64 encoded cursor
|
|
173
|
+
* @param {Array<{field: string, dir?: string}>} sortFields - Sort configuration
|
|
174
|
+
* @param {boolean} isBefore - Whether this is a 'before' cursor
|
|
175
|
+
* @returns {{ sql: string, params: any[] }}
|
|
176
|
+
*/
|
|
177
|
+
function buildCursorWhere(cursor, sortFields, isBefore) {
|
|
178
|
+
// Default to indexedAt DESC if no sort fields specified
|
|
179
|
+
const effectiveSort = sortFields && sortFields.length > 0 ? sortFields : DEFAULT_SORT;
|
|
180
|
+
|
|
181
|
+
const decoded = decodeCursor(cursor, effectiveSort);
|
|
182
|
+
if (!decoded || decoded.fieldValues.length === 0) {
|
|
183
|
+
return { sql: '1=1', params: [] };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const clauses = [];
|
|
187
|
+
const params = [];
|
|
188
|
+
|
|
189
|
+
// Build progressive OR clauses for multi-field sort
|
|
190
|
+
// For sort [A DESC, B ASC], after cursor [a_val, b_val, uri]:
|
|
191
|
+
// (A < a_val) OR (A = a_val AND B > b_val) OR (A = a_val AND B = b_val AND uri < uri_val)
|
|
192
|
+
for (let i = 0; i < effectiveSort.length; i++) {
|
|
193
|
+
const clauseParts = [];
|
|
194
|
+
const clauseParams = [];
|
|
195
|
+
|
|
196
|
+
// Add equality for all prior fields
|
|
197
|
+
for (let j = 0; j < i; j++) {
|
|
198
|
+
clauseParts.push(`${fieldToSqlExpr(effectiveSort[j].field)} = ?`);
|
|
199
|
+
clauseParams.push(decoded.fieldValues[j]);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Add comparison for current field
|
|
203
|
+
const op = getComparisonOp(effectiveSort[i].dir, isBefore);
|
|
204
|
+
clauseParts.push(`${fieldToSqlExpr(effectiveSort[i].field)} ${op} ?`);
|
|
205
|
+
clauseParams.push(decoded.fieldValues[i]);
|
|
206
|
+
|
|
207
|
+
clauses.push(`(${clauseParts.join(' AND ')})`);
|
|
208
|
+
params.push(...clauseParams);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Final clause: all sort fields equal, compare by URI (tiebreaker)
|
|
212
|
+
const allEqualParts = effectiveSort.map((s) => {
|
|
213
|
+
return `${fieldToSqlExpr(s.field)} = ?`;
|
|
214
|
+
});
|
|
215
|
+
const lastDir = effectiveSort[effectiveSort.length - 1]?.dir || 'desc';
|
|
216
|
+
const uriOp = getComparisonOp(lastDir, isBefore);
|
|
217
|
+
allEqualParts.push(`r.uri ${uriOp} ?`);
|
|
218
|
+
|
|
219
|
+
clauses.push(`(${allEqualParts.join(' AND ')})`);
|
|
220
|
+
params.push(...decoded.fieldValues, decoded.uri);
|
|
221
|
+
|
|
222
|
+
return { sql: `(${clauses.join(' OR ')})`, params };
|
|
223
|
+
}
|
|
224
|
+
|
|
113
225
|
/**
|
|
114
226
|
* Build SQL WHERE clause from lex-gql where conditions
|
|
115
227
|
* @param {import('lex-gql').WhereClause[]} where
|
|
@@ -204,15 +316,19 @@ export function buildWhere(where) {
|
|
|
204
316
|
*/
|
|
205
317
|
export function buildOrderBy(sort) {
|
|
206
318
|
if (!sort || sort.length === 0) {
|
|
207
|
-
return 'r.
|
|
319
|
+
return 'r.indexed_at DESC, r.uri DESC';
|
|
208
320
|
}
|
|
209
321
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
322
|
+
const sortClauses = sort.map(({ field, dir = 'asc' }) => {
|
|
323
|
+
const fieldPath = SYSTEM_FIELDS[field] || `json_extract(r.record, '$.${field}')`;
|
|
324
|
+
return `${fieldPath} ${dir.toUpperCase()}`;
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// Add URI as tiebreaker using direction of last sort field
|
|
328
|
+
const lastDir = sort[sort.length - 1]?.dir || 'asc';
|
|
329
|
+
sortClauses.push(`r.uri ${lastDir.toUpperCase()}`);
|
|
330
|
+
|
|
331
|
+
return sortClauses.join(', ');
|
|
216
332
|
}
|
|
217
333
|
|
|
218
334
|
/**
|
|
@@ -251,26 +367,18 @@ function findMany(db, op) {
|
|
|
251
367
|
const cursorParams = [];
|
|
252
368
|
|
|
253
369
|
if (after) {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
cursorParams.push(cursor.id);
|
|
259
|
-
}
|
|
260
|
-
} catch (err) {
|
|
261
|
-
console.warn('lex-gql-sqlite: Malformed cursor (after), ignoring:', /** @type {Error} */ (err).message);
|
|
370
|
+
const cursorWhere = buildCursorWhere(after, sort, false);
|
|
371
|
+
if (cursorWhere.sql !== '1=1') {
|
|
372
|
+
cursorConditions.push(cursorWhere.sql);
|
|
373
|
+
cursorParams.push(...cursorWhere.params);
|
|
262
374
|
}
|
|
263
375
|
}
|
|
264
376
|
|
|
265
377
|
if (before) {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
cursorParams.push(cursor.id);
|
|
271
|
-
}
|
|
272
|
-
} catch (err) {
|
|
273
|
-
console.warn('lex-gql-sqlite: Malformed cursor (before), ignoring:', /** @type {Error} */ (err).message);
|
|
378
|
+
const cursorWhere = buildCursorWhere(before, sort, true);
|
|
379
|
+
if (cursorWhere.sql !== '1=1') {
|
|
380
|
+
cursorConditions.push(cursorWhere.sql);
|
|
381
|
+
cursorParams.push(...cursorWhere.params);
|
|
274
382
|
}
|
|
275
383
|
}
|
|
276
384
|
|
|
@@ -222,32 +222,32 @@ describe('buildWhere', () => {
|
|
|
222
222
|
describe('buildOrderBy', () => {
|
|
223
223
|
it('returns default order when no sort', () => {
|
|
224
224
|
const sql = buildOrderBy([]);
|
|
225
|
-
expect(sql).toBe('r.
|
|
225
|
+
expect(sql).toBe('r.indexed_at DESC, r.uri DESC');
|
|
226
226
|
});
|
|
227
227
|
|
|
228
|
-
it('handles single sort field', () => {
|
|
228
|
+
it('handles single sort field with uri tiebreaker', () => {
|
|
229
229
|
const sql = buildOrderBy([{ field: 'createdAt', dir: 'asc' }]);
|
|
230
|
-
expect(sql).toBe("json_extract(r.record, '$.createdAt') ASC");
|
|
230
|
+
expect(sql).toBe("json_extract(r.record, '$.createdAt') ASC, r.uri ASC");
|
|
231
231
|
});
|
|
232
232
|
|
|
233
|
-
it('handles system field sort', () => {
|
|
233
|
+
it('handles system field sort with uri tiebreaker', () => {
|
|
234
234
|
const sql = buildOrderBy([{ field: 'indexedAt', dir: 'desc' }]);
|
|
235
|
-
expect(sql).toBe('r.indexed_at DESC');
|
|
235
|
+
expect(sql).toBe('r.indexed_at DESC, r.uri DESC');
|
|
236
236
|
});
|
|
237
237
|
|
|
238
|
-
it('handles multi-field sort', () => {
|
|
238
|
+
it('handles multi-field sort with uri tiebreaker', () => {
|
|
239
239
|
const sql = buildOrderBy([
|
|
240
240
|
{ field: 'status', dir: 'asc' },
|
|
241
241
|
{ field: 'createdAt', dir: 'desc' },
|
|
242
242
|
]);
|
|
243
243
|
expect(sql).toBe(
|
|
244
|
-
"json_extract(r.record, '$.status') ASC, json_extract(r.record, '$.createdAt') DESC",
|
|
244
|
+
"json_extract(r.record, '$.status') ASC, json_extract(r.record, '$.createdAt') DESC, r.uri DESC",
|
|
245
245
|
);
|
|
246
246
|
});
|
|
247
247
|
|
|
248
248
|
it('defaults to asc when dir not specified', () => {
|
|
249
249
|
const sql = buildOrderBy([{ field: 'name' }]);
|
|
250
|
-
expect(sql).toBe("json_extract(r.record, '$.name') ASC");
|
|
250
|
+
expect(sql).toBe("json_extract(r.record, '$.name') ASC, r.uri ASC");
|
|
251
251
|
});
|
|
252
252
|
});
|
|
253
253
|
|
|
@@ -334,7 +334,9 @@ describe('findMany', () => {
|
|
|
334
334
|
pagination: { first: 2 },
|
|
335
335
|
});
|
|
336
336
|
|
|
337
|
-
|
|
337
|
+
// Cursor format: JSON { v: [sortValues], u: uri } (default sort is indexedAt DESC)
|
|
338
|
+
const lastRow = first.rows[1];
|
|
339
|
+
const cursor = Buffer.from(JSON.stringify({ v: [lastRow.indexedAt], u: lastRow.uri })).toString('base64');
|
|
338
340
|
|
|
339
341
|
const second = await query({
|
|
340
342
|
type: 'findMany',
|
|
@@ -347,6 +349,216 @@ describe('findMany', () => {
|
|
|
347
349
|
expect(second.hasPrev).toBe(true);
|
|
348
350
|
});
|
|
349
351
|
|
|
352
|
+
it('handles cursor pagination with custom sort field', async () => {
|
|
353
|
+
// Insert records with different playedTime values (out of insertion order)
|
|
354
|
+
writer.insertRecord({
|
|
355
|
+
uri: 'at://did:plc:abc/col/1',
|
|
356
|
+
record: { playedTime: '2024-01-03T00:00:00Z', name: 'third' },
|
|
357
|
+
});
|
|
358
|
+
writer.insertRecord({
|
|
359
|
+
uri: 'at://did:plc:abc/col/2',
|
|
360
|
+
record: { playedTime: '2024-01-01T00:00:00Z', name: 'first' },
|
|
361
|
+
});
|
|
362
|
+
writer.insertRecord({
|
|
363
|
+
uri: 'at://did:plc:abc/col/3',
|
|
364
|
+
record: { playedTime: '2024-01-05T00:00:00Z', name: 'fifth' },
|
|
365
|
+
});
|
|
366
|
+
writer.insertRecord({
|
|
367
|
+
uri: 'at://did:plc:abc/col/4',
|
|
368
|
+
record: { playedTime: '2024-01-02T00:00:00Z', name: 'second' },
|
|
369
|
+
});
|
|
370
|
+
writer.insertRecord({
|
|
371
|
+
uri: 'at://did:plc:abc/col/5',
|
|
372
|
+
record: { playedTime: '2024-01-04T00:00:00Z', name: 'fourth' },
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// Get first page sorted by playedTime DESC
|
|
376
|
+
const first = await query({
|
|
377
|
+
type: 'findMany',
|
|
378
|
+
collection: 'col',
|
|
379
|
+
where: [],
|
|
380
|
+
sort: [{ field: 'playedTime', dir: 'desc' }],
|
|
381
|
+
pagination: { first: 2 },
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
expect(first.rows).toHaveLength(2);
|
|
385
|
+
expect(first.rows[0].name).toBe('fifth'); // 2024-01-05
|
|
386
|
+
expect(first.rows[1].name).toBe('fourth'); // 2024-01-04
|
|
387
|
+
expect(first.hasNext).toBe(true);
|
|
388
|
+
|
|
389
|
+
// Build cursor from last row
|
|
390
|
+
const lastRow = first.rows[1];
|
|
391
|
+
const cursor = Buffer.from(JSON.stringify({ v: [lastRow.playedTime], u: lastRow.uri })).toString('base64');
|
|
392
|
+
|
|
393
|
+
// Get second page
|
|
394
|
+
const second = await query({
|
|
395
|
+
type: 'findMany',
|
|
396
|
+
collection: 'col',
|
|
397
|
+
where: [],
|
|
398
|
+
sort: [{ field: 'playedTime', dir: 'desc' }],
|
|
399
|
+
pagination: { first: 2, after: cursor },
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
expect(second.rows).toHaveLength(2);
|
|
403
|
+
expect(second.rows[0].name).toBe('third'); // 2024-01-03
|
|
404
|
+
expect(second.rows[1].name).toBe('second'); // 2024-01-02
|
|
405
|
+
expect(second.hasNext).toBe(true);
|
|
406
|
+
|
|
407
|
+
// Get third page
|
|
408
|
+
const lastRow2 = second.rows[1];
|
|
409
|
+
const cursor2 = Buffer.from(JSON.stringify({ v: [lastRow2.playedTime], u: lastRow2.uri })).toString('base64');
|
|
410
|
+
|
|
411
|
+
const third = await query({
|
|
412
|
+
type: 'findMany',
|
|
413
|
+
collection: 'col',
|
|
414
|
+
where: [],
|
|
415
|
+
sort: [{ field: 'playedTime', dir: 'desc' }],
|
|
416
|
+
pagination: { first: 2, after: cursor2 },
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
expect(third.rows).toHaveLength(1);
|
|
420
|
+
expect(third.rows[0].name).toBe('first'); // 2024-01-01
|
|
421
|
+
expect(third.hasNext).toBe(false);
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
it('does not produce duplicate records when paginating with custom sort', async () => {
|
|
425
|
+
// Insert 10 records with varying timestamps
|
|
426
|
+
const timestamps = [
|
|
427
|
+
'2024-01-10T00:00:00Z',
|
|
428
|
+
'2024-01-09T00:00:00Z',
|
|
429
|
+
'2024-01-08T00:00:00Z',
|
|
430
|
+
'2024-01-07T00:00:00Z',
|
|
431
|
+
'2024-01-06T00:00:00Z',
|
|
432
|
+
'2024-01-05T00:00:00Z',
|
|
433
|
+
'2024-01-04T00:00:00Z',
|
|
434
|
+
'2024-01-03T00:00:00Z',
|
|
435
|
+
'2024-01-02T00:00:00Z',
|
|
436
|
+
'2024-01-01T00:00:00Z',
|
|
437
|
+
];
|
|
438
|
+
|
|
439
|
+
// Insert in random order
|
|
440
|
+
const insertOrder = [4, 7, 1, 9, 2, 5, 0, 8, 3, 6];
|
|
441
|
+
for (const i of insertOrder) {
|
|
442
|
+
writer.insertRecord({
|
|
443
|
+
uri: `at://did:plc:abc/col/${i}`,
|
|
444
|
+
record: { playedTime: timestamps[i], index: i },
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const allUris = new Set();
|
|
449
|
+
let cursor = null;
|
|
450
|
+
|
|
451
|
+
// Paginate through all records
|
|
452
|
+
for (let page = 0; page < 5; page++) {
|
|
453
|
+
const result = await query({
|
|
454
|
+
type: 'findMany',
|
|
455
|
+
collection: 'col',
|
|
456
|
+
where: [],
|
|
457
|
+
sort: [{ field: 'playedTime', dir: 'desc' }],
|
|
458
|
+
pagination: { first: 3, after: cursor },
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
// Check for duplicates
|
|
462
|
+
for (const row of result.rows) {
|
|
463
|
+
expect(allUris.has(row.uri)).toBe(false);
|
|
464
|
+
allUris.add(row.uri);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (!result.hasNext) break;
|
|
468
|
+
|
|
469
|
+
// Build cursor for next page
|
|
470
|
+
const lastRow = result.rows[result.rows.length - 1];
|
|
471
|
+
cursor = Buffer.from(JSON.stringify({ v: [lastRow.playedTime], u: lastRow.uri })).toString('base64');
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Verify we got all records
|
|
475
|
+
expect(allUris.size).toBe(10);
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
it('handles before cursor with custom sort field', async () => {
|
|
479
|
+
// Insert records
|
|
480
|
+
for (let i = 1; i <= 5; i++) {
|
|
481
|
+
writer.insertRecord({
|
|
482
|
+
uri: `at://did:plc:abc/col/${i}`,
|
|
483
|
+
record: { playedTime: `2024-01-0${i}T00:00:00Z`, name: `item${i}` },
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Start from the middle: item3 (2024-01-03)
|
|
488
|
+
const cursor = Buffer.from(JSON.stringify({ v: ['2024-01-03T00:00:00Z'], u: 'at://did:plc:abc/col/3' })).toString('base64');
|
|
489
|
+
|
|
490
|
+
// Get records BEFORE item3 (should be item4, item5 in DESC order)
|
|
491
|
+
const result = await query({
|
|
492
|
+
type: 'findMany',
|
|
493
|
+
collection: 'col',
|
|
494
|
+
where: [],
|
|
495
|
+
sort: [{ field: 'playedTime', dir: 'desc' }],
|
|
496
|
+
pagination: { last: 2, before: cursor },
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
expect(result.rows).toHaveLength(2);
|
|
500
|
+
expect(result.rows[0].name).toBe('item5'); // 2024-01-05
|
|
501
|
+
expect(result.rows[1].name).toBe('item4'); // 2024-01-04
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
it('handles cursor pagination with multi-field sort', async () => {
|
|
505
|
+
// Insert records with two sort fields: category and playedTime
|
|
506
|
+
const records = [
|
|
507
|
+
{ uri: 'at://did:plc:abc/col/1', category: 'A', playedTime: '2024-01-03T00:00:00Z' },
|
|
508
|
+
{ uri: 'at://did:plc:abc/col/2', category: 'A', playedTime: '2024-01-01T00:00:00Z' },
|
|
509
|
+
{ uri: 'at://did:plc:abc/col/3', category: 'B', playedTime: '2024-01-05T00:00:00Z' },
|
|
510
|
+
{ uri: 'at://did:plc:abc/col/4', category: 'A', playedTime: '2024-01-02T00:00:00Z' },
|
|
511
|
+
{ uri: 'at://did:plc:abc/col/5', category: 'B', playedTime: '2024-01-04T00:00:00Z' },
|
|
512
|
+
{ uri: 'at://did:plc:abc/col/6', category: 'C', playedTime: '2024-01-01T00:00:00Z' },
|
|
513
|
+
];
|
|
514
|
+
|
|
515
|
+
for (const r of records) {
|
|
516
|
+
writer.insertRecord({
|
|
517
|
+
uri: r.uri,
|
|
518
|
+
record: { category: r.category, playedTime: r.playedTime },
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Sort by category ASC, then playedTime DESC
|
|
523
|
+
// Expected order: A(01-03), A(01-02), A(01-01), B(01-05), B(01-04), C(01-01)
|
|
524
|
+
const allUris = [];
|
|
525
|
+
let cursor = null;
|
|
526
|
+
|
|
527
|
+
// Paginate through all records with page size 2
|
|
528
|
+
for (let page = 0; page < 4; page++) {
|
|
529
|
+
const result = await query({
|
|
530
|
+
type: 'findMany',
|
|
531
|
+
collection: 'col',
|
|
532
|
+
where: [],
|
|
533
|
+
sort: [{ field: 'category', dir: 'asc' }, { field: 'playedTime', dir: 'desc' }],
|
|
534
|
+
pagination: { first: 2, after: cursor },
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
for (const row of result.rows) {
|
|
538
|
+
allUris.push(row.uri);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
if (!result.hasNext) break;
|
|
542
|
+
|
|
543
|
+
// Build cursor with both sort field values
|
|
544
|
+
const lastRow = result.rows[result.rows.length - 1];
|
|
545
|
+
cursor = Buffer.from(JSON.stringify({
|
|
546
|
+
v: [lastRow.category, lastRow.playedTime],
|
|
547
|
+
u: lastRow.uri,
|
|
548
|
+
})).toString('base64');
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// Verify correct order
|
|
552
|
+
expect(allUris).toEqual([
|
|
553
|
+
'at://did:plc:abc/col/1', // A, 01-03
|
|
554
|
+
'at://did:plc:abc/col/4', // A, 01-02
|
|
555
|
+
'at://did:plc:abc/col/2', // A, 01-01
|
|
556
|
+
'at://did:plc:abc/col/3', // B, 01-05
|
|
557
|
+
'at://did:plc:abc/col/5', // B, 01-04
|
|
558
|
+
'at://did:plc:abc/col/6', // C, 01-01
|
|
559
|
+
]);
|
|
560
|
+
});
|
|
561
|
+
|
|
350
562
|
it('filters with where clause', async () => {
|
|
351
563
|
writer.insertRecord({
|
|
352
564
|
uri: 'at://did:plc:abc/col/1',
|