### LevelUp Style Get with LMDB-JS Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Shows how to use the `levelup` export to create a database instance that mimics the LevelUp API style for the `get` operation, even though LMDB-JS's native `get` is synchronous. This example illustrates both callback and Promise-based usage for `get`. ```javascript let dbLevel = levelup(db) dbLevel.get(id, (error, value) => { }) // or dbLevel.get(id).then(...) ``` -------------------------------- ### LZ4 CLI Usage Example Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/dll/example/README.md Basic usage syntax for the LZ4 command-line utility. Use -h or -H for a full list of commands. ```bash Usage: lz4 [arg] [input] [output] ``` -------------------------------- ### Key Ordering Example Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates the default ordering of various JavaScript primitives and arrays when used as keys in LMDB-JS. ```javascript null; Symbol.for('even symbols'); false; true - 10 - // negative supported 1.1; // decimals supported 400; 3e10; 'Hello'[ ('Hello', 'World') ]; ('World'); 'hello'[ ('hello', 1, 'world') ][ ('hello', 'world') ]; Buffer.from([255]); // buffers are used directly, 255 is higher than any byte produced by primitives ``` -------------------------------- ### Install lmdb-js Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Install the lmdb-js package using npm. This command installs the latest version for use in your project. ```bash npm install lmdb ``` -------------------------------- ### Start and Use a Read Transaction Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Explicitly start a read transaction to ensure a consistent snapshot of the database for retrieval operations. Remember to call `transaction.done()` when finished to avoid resource exhaustion and enable free space reclamation. ```javascript let transaction = myDb.useReadTransaction(); let data = myDb.get('my-key', { transaction }); // ... operations using the same transaction ... data = myDb.get('my-key', { transaction }); transaction.done(); ``` -------------------------------- ### Compiling with LZ4 DLL using gcc/MinGW Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/dll/example/README.md Example command to compile a C file using the LZ4 dynamic library with gcc/MinGW. Ensure include paths and library paths are correctly set. ```bash gcc $(CFLAGS) -Iinclude\ test-dll.c -o test-dll dll\msys-lz4-1.dll ``` -------------------------------- ### BerkeleyDB Operations Example in C Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lmdb/libraries/liblmdb/sample-bdb.txt This C code demonstrates creating a BerkeleyDB environment, opening a database, performing a transaction to insert a key-value pair, and then retrieving all entries using a cursor. Error checking is minimal for brevity. ```c #include #include #include int main(int argc,char * argv[]) { int rc; DB_ENV *env; DB *dbi; DBT key, data; DB_TXN *txn; DBC *cursor; char sval[32], kval[32]; /* Note: Most error checking omitted for simplicity */ #define FLAGS (DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_INIT_MPOOL|DB_CREATE|DB_THREAD) rc = db_env_create(&env, 0); rc = env->open(env, "./testdb", FLAGS, 0664); rc = db_create(&dbi, env, 0); rc = env->txn_begin(env, NULL, &txn, 0); rc = dbi->open(dbi, txn, "test.bdb", NULL, DB_BTREE, DB_CREATE, 0664); memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); key.size = sizeof(int); key.data = sval; data.size = sizeof(sval); data.data = sval; sprintf(sval, "%03x %d foo bar", 32, 3141592); rc = dbi->put(dbi, txn, &key, &data, 0); rc = txn->commit(txn, 0); if (rc) { fprintf(stderr, "txn->commit: (%d) %s\n", rc, db_strerror(rc)); goto leave; } rc = env->txn_begin(env, NULL, &txn, 0); rc = dbi->cursor(dbi, txn, &cursor, 0); key.flags = DB_DBT_USERMEM; key.data = kval; key.ulen = sizeof(kval); data.flags = DB_DBT_USERMEM; data.data = sval; data.ulen = sizeof(sval); while ((rc = cursor->c_get(cursor, &key, &data, DB_NEXT)) == 0) { printf("key: %p %.*s, data: %p %.*s\n", key.data, (int) key.size, (char *) key.data, data.data, (int) data.size, (char *) data.data); } rc = cursor->c_close(cursor); rc = txn->abort(txn); leave: rc = dbi->close(dbi, 0); rc = env->close(env, 0); return rc; } ``` -------------------------------- ### Open LMDB Database and Basic Operations Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates how to open an LMDB database with compression enabled, and perform basic put and get operations. This snippet shows both direct put/get and transactional usage. ```javascript import { open } from 'lmdb'; // or require let myDB = open('my-db', { // any options go here, we can turn on compression like this: compression: true, }); await myDB.put('greeting', { someText: 'Hello, World!' }); myDB.get('greeting').someText; // 'Hello, World!' // or myDB.transaction(() => { myDB.put('greeting', { someText: 'Hello, World!' }); myDB.get('greeting').someText; // 'Hello, World!' }); ``` -------------------------------- ### Using Overlapping Sync Options Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates how to use the `overlappingSync` option for improved performance by deferring disk flushing. This example shows opening a database with the option enabled, performing a write, awaiting its commit, retrieving the value, and then awaiting the full disk flush. ```javascript let db = open('my-db', { overlappingSync: true }); let written = db.put(key, value); await written; // wait for it to be committed let v = db.get(key); // this value now be retrieved from the db await db.flushed; // wait for last commit to be fully flushed to disk ``` -------------------------------- ### Building LMDB-JS with Legacy Data Format Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Install lmdb-js from source with the '--use_data_v1=true' flag to build with the legacy data format version 1. This is useful for data format portability but may exclude features like encryption. ```bash npm install lmdb --build-from-source --use_data_v1=true ``` -------------------------------- ### LMDB-JS NPM Package JSON Configuration Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Configure your package.json to automatically download prebuilds for lmdb-js. This requires the 'prebuildify-ci' package to be installed globally. ```json { "dependencies": { "lmdb": "2.6.0" }, "scripts": { "download-lmdb-prebuilds": "download-lmdb-prebuilds" } } ``` -------------------------------- ### db.getBinaryFast(key): Buffer Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves binary data using a reusable buffer for performance. The buffer's contents are only valid until the next `get` operation. ```APIDOC ## `db.getBinaryFast(key): Buffer` ### Description This will retrieve the binary data at the specified key, like `getBinary`, except it uses reusable buffers, which is faster, but means the data in the buffer is only valid until the next get operation (including cursor operations). Since this is a reusable buffer it also slightly differs from a typical buffer: the `length` property is set to the length of the value (what you typically want for normal usage), but the `byteLength` will be the size of the full allocated memory area for the buffer (usually much larger). ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters - **key** (any) - The key of the binary data to retrieve. ### Request Example ```javascript let fastBuffer = db.getBinaryFast('my-fast-key'); // Use fastBuffer immediately, as its contents may change. ``` ### Response #### Success Response - **Buffer** - The binary data as a reusable Buffer. Note: `length` is the value length, `byteLength` is the allocated memory size. ``` -------------------------------- ### Immediate Get After Put with Caching Enabled Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates synchronous retrieval of a value immediately after a 'put' operation when caching is enabled. This bypasses the need to await the 'put' promise resolution for immediate access. ```javascript db.put('hi', 'there'); db.get('hi'); // can immediately access value without having to await the promise ``` -------------------------------- ### Synchronous Transaction Execution Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `transactionSync` to begin and commit a synchronous transaction. The callback can perform `get`, `put`, and `remove` operations. Abort the transaction by returning `ABORT` or throwing an error. ```javascript db.transactionSync(callback: Function) ``` -------------------------------- ### Get Multiple Values Asynchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `getMany` to asynchronously retrieve values for a list of IDs. It first prefetches the data and then performs synchronous gets for each entry. ```javascript db.getMany(ids, callback); ``` -------------------------------- ### Retrieve Binary Data Efficiently Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `getBinaryFast` for faster retrieval of binary data using reusable buffers. Note that the buffer's content is only valid until the next get operation, and `byteLength` differs from `length`. ```javascript let fastBinaryData = db.getBinaryFast(key); ``` -------------------------------- ### Range Options for Value Retrieval Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Optionally specify `start` and `end` values to filter the range of values returned for a key. This feature requires `ordered-binary` encoding. ```javascript for (let value of db.getValues('key1', { start: 'value1', end: 'value3'})) ... ``` -------------------------------- ### db.useReadTransaction(): Transaction Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Explicitly starts a read transaction, providing a consistent snapshot of the database for retrieval operations. The transaction must be marked as done using `transaction.done()` when no longer needed. ```APIDOC ## `db.useReadTransaction(): Transaction` ### Description This allows you to explicitly start a read transaction, which holds a consistent snapshot of the database, and use it for subsequent retrieval operations. This will mark the read transaction as in use until `transaction.done()` is called. It is critical that you mark read transactions as done when you no longer need it or you will exhaust the read transactions that are available. Long-lived read transactions also prevent free space reclamation. This can be used with `get`, `getEntry` and range/query methods. ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript let transaction = myDb.useReadTransaction(); let data = myDb.get('my-key', { transaction }); // ... transaction.done(); // make sure you mark the transaction as done ``` ### Response #### Success Response - **Transaction** - An object representing the read transaction. ``` -------------------------------- ### db.getMany(ids: K[], callback?): Promise Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Asynchronously retrieves values for a given array of IDs. It first prefetches the data and then performs individual `get` operations for each entry. ```APIDOC ## `db.getMany(ids: K[], callback?): Promise` ### Description Asynchronously gets the values stored by the given ids and return the values in array corresponding to the array of ids. This uses `prefetch` followed by `get`s for each entry once the data is prefetched. ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters - **ids** (Array) - An array of IDs for which to retrieve values. - **callback** (function, optional) - A callback function to be executed upon completion. ### Request Example ```javascript db.getMany(['key1', 'key2']).then(values => { console.log(values); }); ``` ### Response #### Success Response - **Promise** - A promise that resolves with an array of values corresponding to the input IDs. ``` -------------------------------- ### getLastVersion(): number Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves the version number of the last entry retrieved with `get`. This is applicable to versioned databases. For databases with caching enabled, `getEntry` should be used instead. ```APIDOC ## `getLastVersion(): number` ### Description Retrieves the version number of the last entry retrieved with `get` (assuming it was a versioned database). If you are using a database with `cache` enabled, use `getEntry` instead. ### Method N/A (Function call) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response - **version** (number) - The version number of the last retrieved entry. ``` -------------------------------- ### db.prefetch(ids, callback?): Promise Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Asynchronously fetches data for specified IDs in a separate thread to ensure data is in memory, optimizing subsequent synchronous `get` operations and avoiding main thread page faults. ```APIDOC ## `db.prefetch(ids, callback?): Promise` ### Description With larger databases and situations where the data in the database may not be cached in memory, it may be advisable to use asynchronous methods to fetch data to avoid slow/expensive hard-page faults on the main thread. This method provides a means of asynchronously fetching data in separate thread/asynchronously to ensure data is in memory. This fetches the data for given ids and accesses all pages to ensure that any hard page faults are done asynchronously. Once completed, synchronous gets to the same entries will most likely be in memory and fast. The `prefetch` can also be run in parallel with sync `get`s (for the same entries) in situations where the main thread be busy with deserialization and other work at roughly the same rate as the prefetch page faults might occur. ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters - **ids** (Array) - An array of IDs for which to prefetch data. - **callback** (function, optional) - A callback function to be executed upon completion. ### Request Example ```javascript db.prefetch(['id1', 'id2']).then(() => { console.log('Data prefetched'); }); ``` ### Response #### Success Response - **Promise** - A promise that resolves when the data has been prefetched. ``` -------------------------------- ### db.putSync Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Synchronously sets a value at a specified key. If called within a transaction, the put operation is part of that transaction. Otherwise, it starts, commits, and returns a new transaction. ```APIDOC ## db.putSync(key, value, versionOrOptions?: number | PutOptions): boolean ### Description Synchronously sets the value for the given key. If executed within a transaction, the operation is added to the current transaction. If not within a transaction, a new transaction is initiated, the operation is performed, and the transaction is committed before returning. This method can be significantly slower than asynchronous `put` operations. ### Method `putSync` ### Parameters - **key** (any) - Required - The key to associate with the value. - **value** (any) - Required - The value to store. - **versionOrOptions** (number | PutOptions) - Optional - A version number or an options object. Options can include `append`, `appendDup`, `noOverwrite`, `noDupData`, and `version`. ### Return Value - **boolean** - Returns `true` if the operation was successful. ### Example ```javascript // Inside a transaction products.putSync('myKey', 'myValue'); // Outside a transaction products.putSync('anotherKey', 'anotherValue'); ``` ``` -------------------------------- ### Disabling LMDB Robust Mutex Option Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Install lmdb-js from source with the '--use_robust=false' flag to disable LMDB's robust mutex option. This can improve performance but is not recommended if using multiple processes. ```bash npm install lmdb --build-from-source --use_robust=false ``` -------------------------------- ### Prefetch Data Asynchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `prefetch` to asynchronously fetch data in a separate thread, ensuring data is in memory and avoiding hard page faults on the main thread. This can improve performance for subsequent synchronous `get` operations. ```javascript db.prefetch(ids, callback); ``` -------------------------------- ### Open Database with Custom Encoder Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates how to specify a custom encoder, such as CBOR, when opening a database. Ensure the encoder library is imported. ```javascript import * as cbor from 'cbor-x'; let db = open({ encoder: cbor }); ``` -------------------------------- ### Open Multiple Databases in an Environment Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Demonstrates how to open multiple named databases within a single LMDB environment using the `open` function and `openDB` method. Ensure `maxDbs` is set if opening many databases. ```javascript import { open } from 'lmdb'; let rootDB = open('all-my-data'); let usersDB = rootDB.openDB('users'); let groupsDB = rootDB.openDB('groups'); let productsDB = rootDB.openDB('products'); ``` -------------------------------- ### Get All Values for a Key with Duplicate Entries Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `getValues` to retrieve all associated values for a given key when `dupSort` is enabled. This method returns an iterator for the values. ```javascript let db = db.openDB('my-index', { dupSort: true, encoding: 'ordered-binary', }); await db.put('key1', 'value1'); await db.put('key1', 'value2'); for (let value of db.getValues('key1')) { // iterate values 'value1', 'value2' } await db.remove('key', 'value1'); // only remove the second value under key1 for (let value of db.getValues('key1')) { // just iterate value 'value1' } ``` -------------------------------- ### Linking a C project with LZ4 DLL using GCC/MinGW Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/README.md Compile a C source file (e.g., test-dll.c) and link it with the LZ4 dynamic library (dll\liblz4.dll) using GCC or MinGW. Ensure the include path and library path are correctly specified. ```bash $(CC) $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\liblz4.dll ``` -------------------------------- ### Open Database with Versioning Enabled Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use this option when opening a database to enable version tracking for conditional writes. ```javascript let myDB = open('my-db', { useVersions: true }); ``` -------------------------------- ### Basic LMDB Operations in C Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lmdb/libraries/liblmdb/sample-mdb.txt This C code demonstrates essential LMDB operations including environment creation, transaction handling, data insertion, and reading data using a cursor. Error checking is minimal for brevity. ```c #include #include "lmdb.h" int main(int argc,char * argv[]) { int rc; MDB_env *env; MDB_dbi dbi; MDB_val key, data; MDB_txn *txn; MDB_cursor *cursor; char sval[32]; /* Note: Most error checking omitted for simplicity */ rc = mdb_env_create(&env); rc = mdb_env_open(env, "./testdb", 0, 0664); rc = mdb_txn_begin(env, NULL, 0, &txn); rc = mdb_dbi_open(txn, NULL, 0, &dbi); key.mv_size = sizeof(int); key.mv_data = sval; data.mv_size = sizeof(sval); data.mv_data = sval; sprintf(sval, "%03x %d foo bar", 32, 3141592); rc = mdb_put(txn, dbi, &key, &data, 0); rc = mdb_txn_commit(txn); if (rc) { fprintf(stderr, "mdb_txn_commit: (%d) %s\n", rc, mdb_strerror(rc)); goto leave; } rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn); rc = mdb_cursor_open(txn, dbi, &cursor); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { printf("key: %p %.*s, data: %p %.*s\n", key.mv_data, (int) key.mv_size, (char *) key.mv_data, data.mv_data, (int) data.mv_size, (char *) data.mv_data); } mdb_cursor_close(cursor); mdb_txn_abort(txn); leave: mdb_dbi_close(env, dbi); mdb_env_close(env); return 0; } ``` -------------------------------- ### Enable LZ4 Compression with Custom Settings Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Turn on off-thread LZ4 compression when opening a database. Configure compression threshold and a custom dictionary for optimized compression of specific data types. ```javascript let myDB = open('my-db', { compression: { threshold: 500, // compress any entry larger than 500 bytes dictionary: fs.readFileSync('dict.txt'), // use your own shared dictionary }, }); ``` -------------------------------- ### db.backup(path): Promise Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Safely makes a snapshot backup copy of the database at the specified target path. This operation is asynchronous and returns a Promise. ```APIDOC ## db.backup(path): Promise ### Description Safely makes a snapshot backup copy of the database at the specified target path. ### Method Asynchronous (returns a Promise) ### Parameters #### Path Parameters - **path** (string) - Required - The target path for the backup copy. ``` -------------------------------- ### Transaction Across Multiple Databases Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Initiate a transaction from any database within an environment, and perform writes to any other database in that same environment. All operations within the transaction will be committed together. ```javascript rootDB.transaction(() => { usersDB.put('some-user', { data: userInfo }); groupsDB.put('some-group', { groupData: moreData }); }); ``` -------------------------------- ### put(key, value, [version], [ifVersion]) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Puts a key-value pair into the database. Optionally supports versioning for conditional writes. ```APIDOC ## put(key, value, [version], [ifVersion]) ### Description Puts a key-value pair into the database. Supports versioning for conditional writes. ### Parameters #### Path Parameters - **key** (string) - Required - The key to store the value under. - **value** (any) - Required - The value to store. - **version** (number) - Optional - The new version to assign to the entry. - **ifVersion** (number) - Optional - If provided, the put operation will only succeed if the current version of the key matches this value. ``` -------------------------------- ### db.get(key, options?) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves the value associated with a given key from the database. The key can be any supported JavaScript primitive or array, and the return value depends on the database's encoding. If the key does not exist, `undefined` is returned. An optional `options` argument can be provided to specify a read transaction. ```APIDOC ## db.get(key, options?) ### Description Retrieves the value at the specified key from the database. The `key` must be a JS value/primitive as described in the Keys section, and the return value will be the stored data (dependent on the encoding), or `undefined` if the entry does not exist. ### Method `get(key, options?): any` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript db.get('myKey'); ``` ### Response #### Success Response (200) - **value** (any) - The stored data, deserialized according to the database encoding, or `undefined` if the key is not found. #### Response Example ```json { "example": "retrievedValue" } ``` ``` -------------------------------- ### Open Database with Shared Structures Enabled Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Enable the shared structures feature by specifying a key (e.g., a Symbol) where structural information will be stored. ```javascript let myDB = open('my-db', { sharedStructuresKey: Symbol.for('structures'), }); ``` -------------------------------- ### Cross-compiling LZ4 DLL on Linux with MinGW-w64 Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/README.md Use this command to cross-compile the LZ4 DLL on Linux using MinGW-w64, specifying the build type, compiler, DLL tool, and operating system. ```bash make BUILD_STATIC=no CC=x86_64-w64-mingw32-gcc DLLTOOL=x86_64-w64-mingw32-dlltool OS=Windows_NT ``` -------------------------------- ### Drop Database Synchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `dropSync` to remove all entries from the database and delete the database itself synchronously. ```javascript db.dropSync(); ``` -------------------------------- ### db.getKeys(options: RangeOptions) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Behaves like `getRange`, but only returns the keys. If this is a duplicate key database, each key is only returned once. ```APIDOC ## db.getKeys(options: RangeOptions) ### Description This method behaves like `getRange` but exclusively returns the keys. In a duplicate key database, each key is returned only once, regardless of the number of associated values. ### Method `getKeys` ### Parameters #### Query Parameters - **options** (RangeOptions) - Optional - Options to configure the range of keys to return. - **start** (any) - Optional - Starting key for the range. - **end** (any) - Optional - Ending key for the range. - **reverse** (boolean) - Optional - Whether to traverse keys in reverse order. - **limit** (number) - Optional - Maximum number of entries to read. - **offset** (number) - Optional - Number of entries to skip before starting iteration. - **versions** (boolean) - Optional - Whether to include versions in returned entries. - **snapshot** (boolean) - Optional - Whether to use a database snapshot for iteration (defaults to true). ### Request Example ```javascript for (let key of db.getKeys({ reverse: true, limit: 10 })) { // iterate through the first 10 keys in reverse order } ``` ### Response #### Success Response - **Iterable** - An iterator yielding keys from the database. ``` -------------------------------- ### db.drop(): Promise and db.dropSync() Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Removes all entries from the database and deletes the database itself. `drop` performs the operation asynchronously, while `dropSync` performs it synchronously. ```APIDOC ## `db.drop(): Promise` and `db.dropSync()` ### Description These methods remove all the entries from a database and delete that database (asynchronously or synchronously, respectively). ### Method N/A (Method calls on DB object) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript // Asynchronous drop db.drop().then(() => console.log('Database dropped asynchronously')); // Synchronous drop db.dropSync(); console.log('Database dropped synchronously'); ``` ### Response #### Success Response - **`drop`**: **Promise** - Resolves when the database is dropped. - **`dropSync`**: **void** - Returns immediately after dropping the database. ``` -------------------------------- ### db.openDB(database: string|{name:string,...}) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Opens a specific database within an LMDB environment. Supports multiple databases per environment. ```APIDOC ## db.openDB(database: string|{name:string,...}) ### Description LMDB supports multiple databases within a single environment (a single memory-mapped file). This method allows you to open a specific database. If you plan to open many databases, ensure `maxDbs` is set appropriately. ### Method `openDB` ### Parameters #### Path Parameters - **database** (string | {name: string, ...}) - Required - The name or configuration object for the database to open. ### Request Example ```javascript import { open } from 'lmdb'; let rootDB = open('all-my-data'); let usersDB = rootDB.openDB('users'); let groupsDB = rootDB.openDB('groups'); ``` ### Response #### Success Response - **Database** - An object representing the opened database, with the same API as the default database. ``` -------------------------------- ### db.doesExist(key, valueOrVersion): boolean Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Checks for the existence of an entry by key, with optional verification of a specific value or version. For `dupSort` databases, it can check for a specific key/value pair. ```APIDOC ## `db.doesExist(key, valueOrVersion): boolean` ### Description This checks if an entry exists for the given key, and optionally verifies that the version or value exists. If this is a `dupSort` enabled database, you can provide the key and value to check if that key/value entry exists. If you are using a versioned database, you can provide a version number to verify if the entry for the provided key has the specific version number. This returns true if the entry does exist. ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters - **key** (any) - The key to check for. - **valueOrVersion** (any | number) - Optional. The value or version number to verify. ### Request Example ```javascript let exists = db.doesExist('my-key'); let existsWithValue = db.doesExist('my-key', 'my-value'); let existsWithVersion = db.doesExist('my-key', 123); ``` ### Response #### Success Response - **exists** (boolean) - True if the entry exists (and optionally matches the value/version), false otherwise. ``` -------------------------------- ### Enabling LZ4_FAST_DEC_LOOP with Make Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/README.md Manually enable the speed-optimized decompression loop when using Make by adding the LZ4_FAST_DEC_LOOP=1 flag to CPPFLAGS. ```bash CPPFLAGS+=-DLZ4_FAST_DEC_LOOP=1 make lz4 ``` -------------------------------- ### db.getBinary(key): Buffer Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves the raw binary data for a given key as a Buffer, bypassing any database encoding. Returns `undefined` if no entry is found. ```APIDOC ## `db.getBinary(key): Buffer` ### Description This will retrieve the binary data at the specified key. This is just like `get`, except it will always return the value's binary representation as a buffer, rather than decoding with the db's encoding format (if there is no entry, `undefined` will still be returned). ### Method N/A (Method call on DB object) ### Endpoint N/A ### Parameters - **key** (any) - The key of the binary data to retrieve. ### Request Example ```javascript let binaryData = db.getBinary('my-binary-key'); ``` ### Response #### Success Response - **Buffer** - The binary data as a Buffer, or `undefined` if the key does not exist. ``` -------------------------------- ### Query Range with Offset and Limit Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Specify `offset` and `limit` in `getRange` options to skip entries and control the number of entries iterated. ```javascript db.getRange({ start, end, offset: 10, limit: 10 }); // skip first 10 and get next 10 ``` -------------------------------- ### ifVersion(key, expectedVersion, callback) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Performs a conditional operation based on the version of a key. The callback function is executed only if the key's current version matches the expected version. ```APIDOC ## ifVersion(key, expectedVersion, callback) ### Description Performs a conditional operation based on the version of a key. The callback function is executed only if the key's current version matches the expected version. ### Parameters #### Path Parameters - **key** (string) - Required - The key to check the version against. - **expectedVersion** (number) - Required - The version that the key is expected to have. - **callback** (function) - Required - The function to execute if the version matches. This callback can contain multiple `put` operations. ``` -------------------------------- ### Conditional Write if Key Does Not Exist Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `ifNoExists` to execute a callback function only if the specified key does not already exist in the database. Puts or removes within the callback are conditional. ```javascript db.ifNoExists(key, callback): Promise ``` -------------------------------- ### Amalgamating LZ4 Source Code Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/README.md Combine all LZ4 source files into a single C file for compilation. The order of concatenation is important. ```bash cat lz4.c lz4hc.c lz4frame.c > lz4_all.c ``` -------------------------------- ### Drop Database Asynchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `drop` to remove all entries from the database and delete the database itself asynchronously. ```javascript db.drop(); ``` -------------------------------- ### Import lmdb-js in Deno Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Import the 'open' function from the lmdb package in Deno using the NPM module identifier. This allows direct use of the library's features within Deno projects. ```javascript import { open } from 'npm:lmdb'; ``` -------------------------------- ### db.getEntry Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves an entry from the database by its key. Supports optional read transactions and returns the entry's value and version if available. ```APIDOC ## `db.getEntry(key, options?)` ### Description Retrieves the entry at the specified key. The `key` must be a JS value/primitive. The return value will be the stored entry, or `undefined` if the entry does not exist. An entry is an object with a `value` property for the value in the database and a `version` property for the version number of the entry (if `useVersions` is enabled). ### Parameters #### Path Parameters - **key** (any) - Required - The key of the entry to retrieve. - **options** (object) - Optional - An object to specify an explicit read transaction. ### Response #### Success Response (200) - **value** (any) - The stored value for the key. - **version** (number) - The version number of the entry (if `useVersions` is enabled). ``` -------------------------------- ### db.clearAsync() and db.clearSync() Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Removes all entries from the database. `clearAsync` performs the operation asynchronously, while `clearSync` performs it synchronously. ```APIDOC ## `db.clearAsync(): Promise` and `db.clearSync()` ### Description These methods remove all the entries from a database (asynchronously or synchronously, respectively). ### Method N/A (Method calls on DB object) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript // Asynchronous clear db.clearAsync().then(() => console.log('Database cleared asynchronously')); // Synchronous clear db.clearSync(); console.log('Database cleared synchronously'); ``` ### Response #### Success Response - **`clearAsync`**: **Promise** - Resolves when the database is cleared. - **`clearSync`**: **void** - Returns immediately after clearing the database. ``` -------------------------------- ### Clear All Entries Synchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `clearSync` to remove all entries from the database synchronously. ```javascript db.clearSync(); ``` -------------------------------- ### asBinary(buffer): Binary Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Allows direct storage of a buffer or Uint8Array as a value, bypassing any encoding. This is useful when a value has already been encoded and you wish to store it directly. ```APIDOC ## `asBinary(buffer): Binary` ### Description This can be used to directly store a buffer or Uint8Array as a value, bypassing any encoding. If you are using a database with an encoding that isn't `binary`, setting a value with a Uint8Array will typically be encoded with the db's encoding. However, if you want to bypass encoding, for example, if you have already encoded a value, you can use `asBinary`. ### Method N/A (Function call) ### Endpoint N/A ### Parameters - **buffer** (Buffer | Uint8Array) - The buffer or Uint8Array to store as binary data. ### Request Example ```js let buffer = encode(myValue); // we can directly store the encoded value db.put(key, asBinary(buffer)); ``` ### Response #### Success Response - **Binary** - A representation of the binary data suitable for storage. ``` -------------------------------- ### Conditional Write Based on Key Version Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `ifVersion` to execute a callback function only if the specified key's entry matches the provided version. Puts or removes within the callback are conditional. ```javascript db.ifVersion(key, ifVersion: number, callback): Promise ``` -------------------------------- ### Enabling LZ4_FAST_DEC_LOOP with GCC Source: https://github.com/kriszyp/lmdb-js/blob/master/dependencies/lz4/lib/README.md Manually enable the speed-optimized decompression loop for GCC by passing the LZ4_FAST_DEC_LOOP=1 macro to the preprocessor. ```bash gcc -DLZ4_FAST_DEC_LOOP=1 ``` -------------------------------- ### Retrieve Binary Data Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `getBinary` to retrieve the raw binary representation of a value as a buffer, without applying the database's encoding. Returns `undefined` if the key does not exist. ```javascript let binaryData = db.getBinary(key); ``` -------------------------------- ### db.getValues(key, options?: RangeOptions) Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Retrieves all values for a given key when using a database with duplicate entries per key. Returns an iterator of values. ```APIDOC ## db.getValues(key, options?: RangeOptions) ### Description When using a database with duplicate entries per key (with `dupSort` flag), this method retrieves all the values for a given key. It returns an iterator of values. ### Method `getValues` ### Parameters #### Path Parameters - **key** (any) - Required - The key to retrieve values for. #### Query Parameters - **options** (RangeOptions) - Optional - Options to configure the range of values to return. - **start** (any) - Optional - Starting value for the range. - **end** (any) - Optional - Ending value for the range. - **snapshot** (boolean) - Optional - Whether to use a database snapshot for iteration (defaults to true). ### Request Example ```javascript for (let value of db.getValues('key1')) { // iterate values } for (let value of db.getValues('key1', { start: 'value1', end: 'value3'})) { // iterate values within the specified range } ``` ### Response #### Success Response - **Iterable** - An iterator yielding values associated with the key. ``` -------------------------------- ### db.put Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Stores a value at a specified key. Supports versioning and conditional puts based on the existing entry's version. Operations are batched into transactions. ```APIDOC ## `db.put(key, value, version?, ifVersion?)` ### Description Stores the provided value/data at the specified key. If versioning is enabled, the `version` parameter sets the entry's version. If `ifVersion` is set, the put only occurs if the existing entry's version matches `ifVersion` at commit time. Operations are enqueued for batched transactions and return a promise indicating success. ### Parameters #### Path Parameters - **key** (any) - Required - The key at which to store the value. - **value** (any) - Required - The data to store. - **version** (number) - Optional - The version number to set for the entry if versioning is enabled. - **ifVersion** (number) - Optional - If set, the put only occurs if the existing entry's version matches this value. ### Response #### Success Response (200) - **Promise** - Resolves to `true` if the put was successful, `false` if it did not occur due to `ifVersion` mismatch. ### Request Example ```json { "key": "myKey", "value": "myValue", "version": 1, "ifVersion": 0 } ``` ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### db.ifVersion Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Executes a block of conditional writes. Puts or removes within the callback are only performed if the specified key's entry matches the provided version. ```APIDOC ## `db.ifVersion(key, ifVersion: number, callback): Promise` ### Description Executes a block of conditional writes. Operations within the callback (puts or removes) are conditionally executed based on the provided version of the specified key. ### Method `ifVersion` ### Parameters #### Path Parameters - **key** (any) - Required - The key to check the version against. - **ifVersion** (number) - Required - The version number that the key's entry must match. - **callback** (Function) - Required - A function containing the put or remove operations to perform if the version matches. ``` -------------------------------- ### Clear All Entries Asynchronously Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `clearAsync` to remove all entries from the database asynchronously. ```javascript db.clearAsync(); ``` -------------------------------- ### db.transactionSync Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Begins and commits a synchronous transaction. Operations within the callback are executed within the transaction's scope. ```APIDOC ## `db.transactionSync(callback: Function)` ### Description Begins a synchronous transaction, executes the provided callback function, and then commits the transaction. Operations like `get`, `put`, and `remove` can be performed within the callback. The callback can return a promise for ongoing asynchronous transactions, but minimizing transaction duration on the main thread is recommended, especially in multi-process scenarios. ### Method `transactionSync` ### Parameters #### Path Parameters - **callback** (Function) - Required - The function to execute within the transaction. It can perform database operations and may return a promise or the `ABORT` constant to abort the transaction. Throwing an error from the callback also aborts the transaction. ### Notes - If called within an existing transaction and child transactions are supported, it executes as a child transaction. - Otherwise, it executes as part of the existing transaction and cannot be aborted independently. ``` -------------------------------- ### Batched Writes Across Multiple Databases Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Writes to different databases within the same environment are automatically batched together in the same transaction. This ensures atomicity for operations across databases. ```javascript usersDB.put('some-user', { data: userInfo }); groupsDB.put('some-group', { groupData: moreData }); ``` -------------------------------- ### db.removeSync Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Synchronously deletes an entry from the database. It returns true if an entry was deleted, and false otherwise. ```APIDOC ## `db.removeSync(key, valueOrIfVersion?: number): boolean` ### Description Synchronously deletes an entry from the database. This function is analogous to `putSync` in its synchronous nature and argument usage for deletion. ### Method `removeSync` ### Parameters #### Path Parameters - **key** (any) - Required - The key of the entry to delete. - **valueOrIfVersion** (number) - Optional - If provided, the entry is only deleted if its current version matches this number. ### Return Value - **boolean** - `true` if an existing entry was deleted, `false` if no matching entry was found. ``` -------------------------------- ### Store Encoded Buffer Directly Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `asBinary` to store a pre-encoded buffer or Uint8Array directly, bypassing the database's default encoding. ```javascript let buffer = encode(myValue); db.put(key, asBinary(buffer)); ``` -------------------------------- ### Synchronously Remove an Entry Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Use `removeSync` to delete an entry by key. It returns true if an entry was deleted, false otherwise. This is the synchronous counterpart to `remove`. ```javascript db.removeSync(key, valueOrIfVersion?: number): boolean ``` -------------------------------- ### db.ifNoExists Source: https://github.com/kriszyp/lmdb-js/blob/master/README.md Executes a block of conditional writes. Puts or removes within the callback are only performed if the specified key's entry does not already exist. ```APIDOC ## `db.ifNoExists(key, callback): Promise` ### Description Executes a block of conditional writes. Operations within the callback (puts or removes) are conditionally executed only if the specified key does not exist in the database. ### Method `ifNoExists` ### Parameters #### Path Parameters - **key** (any) - Required - The key to check for existence. - **callback** (Function) - Required - A function containing the put or remove operations to perform if the key does not exist. ```