kriszyp / lmdb-js

Simple, efficient, ultra-fast, scalable data store wrapper for LMDB
Other
520 stars 44 forks source link

Shared structures are not used when `sharedStructuresKey` is set to `0` #270

Closed kajkal closed 7 months ago

kajkal commented 10 months ago

It looks like the sharedStructuresKey does not work if it is set to 0. I would like to use keyEncoding: 'uint32' combined with shared structures thus sharedStructuresKey set to 0 seems to me the optimal choice (in the case in which, due to the key encoding, js Symbols can not be used).

import assert from 'node:assert/strict';
import { open } from 'lmdb';

async function populate(db, idOffset) {
    await db.transaction(() => {
        for (let id = 0; id < 100_000; id++) {
            db.put(id + idOffset, { some: 'structure' });
        }
    });
}

{
    let db = open({
        path: 'shared-structures-are-not-used-when-key-is-0',
        sharedStructuresKey: 0,
        keyEncoding: 'uint32',
    });

    await populate(db, 1); // 0 - sharedStructuresKey; 1,2,3,... - ids

    assert.deepEqual(db.get(0), undefined);
    assert.equal(db.getCount(), 100_000);

    await db.close();
}

{
    let db = open({
        path: 'shared-structures-are-used-when-key-is-1',
        sharedStructuresKey: 1,
        keyEncoding: 'uint32',
    });

    await populate(db, 2); // 1 - sharedStructuresKey; 2,3,4,... - ids

    assert.deepEqual(db.get(1), [ [ 'some' ] ]);
    assert.equal(db.getCount(), 100_001);

    await db.close();
}

0 is a falsy value so condition below will not see the passed key and will conclude that sharedStructuresKey was not defined. https://github.com/kriszyp/lmdb-js/blob/35e37a2cb4efaaeae496a38cdc857e9d5014c83b/open.js#L252-L254 Is this intentional?

kriszyp commented 10 months ago

No, not intentional, thank you for the clear issue report. I will get this fix published soon.