Skip to content

Commit 2b0297e

Browse files
committed
feat: bulk insert records
Expose a method to run an array of prepared queries in a transaction. docs: bulk buffer benches
1 parent d26970f commit 2b0297e

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,33 @@ holder.set('accounts', 'account-123:user-123:name', 'Alice')
145145
console.log(holder.get('accounts', 'account-123:*:name'))
146146
// => [['account-123:user-123:name', 'Alice']]
147147
```
148+
149+
### Bulk Insertion
150+
151+
Bulk insertion leverages transactions to insert a batch of records, prepared ahead of time.
152+
153+
> [!CAUTION]
154+
> When using transactions, if one insert fails, the batch is discarded.
155+
156+
```js
157+
import hold from 'hold-this'
158+
159+
const holder = hold({ turbo: true })
160+
161+
const entries = Array.from(Array(3))
162+
.map((_, i) => holder.prepare('bulk', `key:${i}`, `value${i}`))
163+
164+
holder.setBulk('bulk', 'key', entries)
165+
166+
console.log(holder.get('bulk', 'key:*'))
167+
// => [['key:0', 'value0'], ['key:1', 'value1'], ['key:2', 'value2']]
168+
```
169+
170+
| Run | Time (ms) | Record Count | Records (per ms)|
171+
|-----|-----------|--------------|-----------------|
172+
| 9 | 309.484 | 402861 | 1301.718 |
173+
| 3 | 290.291 | 377501 | 1300.425 |
174+
| 5 | 295.262 | 377501 | 1278.528 |
175+
176+
_Using Turbo Mode_
177+
_Performed on Macbook Pro M1 with 16 GB Memory_

index.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,25 @@ export class KVStore {
160160
}
161161
}
162162

163+
/**
164+
* Set multiple values in the key-value store.
165+
* @param {string} topic The topic to set the values in.
166+
* @param {string} key The key to set the values for.
167+
* @param {Array.<Array.<string, string>>} entries The entries to set. Each entry should be a valid sql query.
168+
* @returns {boolean} True if the values were set.
169+
*/
170+
setBulk (topic = 'topic', key, entries) {
171+
if (!this.#topics[topic]) this.init(topic, key)
172+
173+
this.#connection.tx((transaction) => {
174+
for (const entry of entries) {
175+
transaction.query(entry)
176+
}
177+
})
178+
179+
return true
180+
}
181+
163182
/**
164183
* Get a value from the key-value store.
165184
* @param {string} topic The topic to get the value from.

0 commit comments

Comments
 (0)