idb: make unique cursor work

This commit is contained in:
Florian Dold 2019-06-25 13:18:09 +02:00
parent c84361d3cb
commit b3fc710d9a
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 51 additions and 12 deletions

View File

@ -188,6 +188,32 @@ test("Spec: Example 1 Part 3", async t => {
t.is(cursor.value.author, "Fred");
cursor.continue();
await promiseFromRequest(request5);
cursor = request5.result;
t.is(cursor.value.author, "Fred");
cursor.continue();
await promiseFromRequest(request5);
cursor = request5.result;
t.is(cursor, null);
const request6 = index5.openCursor(null, "nextunique");
await promiseFromRequest(request6);
cursor = request6.result;
t.is(cursor.value.author, "Barney");
cursor.continue();
await promiseFromRequest(request6);
cursor = request6.result;
t.is(cursor.value.author, "Fred");
t.is(cursor.value.isbn, 123456);
cursor.continue();
await promiseFromRequest(request6);
cursor = request6.result;
t.is(cursor, null);
db.close();
t.pass();

View File

@ -832,19 +832,32 @@ export class MemoryBackend implements Backend {
break;
}
}
if (
unique &&
indexKeys.length > 0 &&
compareKeys(indexEntry.indexKey, indexKeys[indexKeys.length - 1]) ===
0
) {
// We only return the first result if subsequent index keys are the same.
continue;
// Skip repeated index keys if unique results are requested.
let skip = false;
if (unique) {
if (
indexKeys.length > 0 &&
compareKeys(
indexEntry.indexKey,
indexKeys[indexKeys.length - 1],
) === 0
) {
skip = true;
}
if (
req.lastIndexPosition !== undefined &&
compareKeys(indexPos, req.lastIndexPosition) === 0
) {
skip = true;
}
}
indexKeys.push(indexEntry.indexKey);
primaryKeys.push(indexEntry.primaryKeys[primkeySubPos]);
numResults++;
primkeySubPos = forward ? 0 : indexEntry.primaryKeys.length - 1;
if (!skip) {
indexKeys.push(indexEntry.indexKey);
primaryKeys.push(indexEntry.primaryKeys[primkeySubPos]);
numResults++;
}
primkeySubPos += forward ? 1 : -1;
}
// Now we can collect the values based on the primary keys,