@marianmeres/kv 3.1.1 → 4.1.0
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/AGENTS.md +134 -31
- package/API.md +190 -24
- package/README.md +225 -32
- package/dist/adapter/postgres.d.ts +6 -3
- package/dist/adapter/postgres.js +94 -126
- package/dist/adapter/sqlite.d.ts +23 -7
- package/dist/adapter/sqlite.js +231 -106
- package/dist/kv.d.ts +12 -2
- package/dist/kv.js +10 -2
- package/dist/utils/driver.d.ts +26 -0
- package/dist/utils/driver.js +54 -0
- package/dist/utils/sqlite-driver.d.ts +37 -0
- package/dist/utils/sqlite-driver.js +67 -0
- package/package.json +13 -15
package/dist/adapter/postgres.js
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* PostgreSQL key-value storage adapter implementation.
|
|
5
5
|
*/
|
|
6
6
|
import { createClog } from "@marianmeres/clog";
|
|
7
|
+
import { toPgDriver } from "../utils/driver.js";
|
|
7
8
|
import { AdapterAbstract, } from "./abstract.js";
|
|
9
|
+
/** Rows fetched per page by {@link AdapterPostgres.keysIter}. */
|
|
10
|
+
const KEYS_ITER_PAGE = 500;
|
|
8
11
|
/**
|
|
9
12
|
* PostgreSQL key-value storage adapter.
|
|
10
13
|
*
|
|
@@ -22,6 +25,8 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
22
25
|
validateKeys: true,
|
|
23
26
|
};
|
|
24
27
|
#cleanupTimer;
|
|
28
|
+
/** What every statement runs on: built from `options.db` by {@link toPgDriver}. */
|
|
29
|
+
#db;
|
|
25
30
|
constructor(namespace = "", options = {}) {
|
|
26
31
|
super(namespace);
|
|
27
32
|
this.options = Object.freeze({ ...this.options, ...(options || {}) });
|
|
@@ -33,6 +38,8 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
33
38
|
if (!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(this.options.tableName)) {
|
|
34
39
|
throw new Error(`Invalid tableName "${this.options.tableName}". Only word characters and a single "schema." prefix are allowed.`);
|
|
35
40
|
}
|
|
41
|
+
// last, so a constructor that throws leaves no driver (and no listener) behind
|
|
42
|
+
this.#db = toPgDriver(this.options.db);
|
|
36
43
|
}
|
|
37
44
|
/** Safe slug derived from tableName for use inside other identifiers (e.g. index names). */
|
|
38
45
|
get #safeSlug() {
|
|
@@ -40,8 +47,8 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
40
47
|
}
|
|
41
48
|
/** @inheritdoc */
|
|
42
49
|
async initialize() {
|
|
43
|
-
const {
|
|
44
|
-
await db.query(`
|
|
50
|
+
const { tableName } = this.options;
|
|
51
|
+
await this.#db.query(`
|
|
45
52
|
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
46
53
|
key VARCHAR(512) PRIMARY KEY,
|
|
47
54
|
value JSONB NOT NULL,
|
|
@@ -50,13 +57,13 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
50
57
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
|
51
58
|
)
|
|
52
59
|
`);
|
|
53
|
-
await db.query(`
|
|
60
|
+
await this.#db.query(`
|
|
54
61
|
CREATE INDEX IF NOT EXISTS idx_${this.#safeSlug}_expires_at
|
|
55
62
|
ON ${tableName} (expires_at)
|
|
56
63
|
WHERE expires_at IS NOT NULL
|
|
57
64
|
`);
|
|
58
65
|
// Index for efficient prefix lookups with LIKE 'prefix%' queries
|
|
59
|
-
await db.query(`
|
|
66
|
+
await this.#db.query(`
|
|
60
67
|
CREATE INDEX IF NOT EXISTS idx_${this.#safeSlug}_key_prefix
|
|
61
68
|
ON ${tableName} (key text_pattern_ops)
|
|
62
69
|
`);
|
|
@@ -71,17 +78,17 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
71
78
|
this.#cleanupTimer = undefined;
|
|
72
79
|
this._initialized = false;
|
|
73
80
|
if (hard) {
|
|
74
|
-
const {
|
|
75
|
-
await db.query(`DROP TABLE IF EXISTS ${tableName}`);
|
|
81
|
+
const { tableName } = this.options;
|
|
82
|
+
await this.#db.query(`DROP TABLE IF EXISTS ${tableName}`);
|
|
76
83
|
}
|
|
77
84
|
}
|
|
78
85
|
async #maybeTTLCleanup() {
|
|
79
86
|
clearTimeout(this.#cleanupTimer); // safety
|
|
80
87
|
if (this.options.ttlCleanupIntervalSec) {
|
|
81
|
-
const {
|
|
88
|
+
const { tableName, logger } = this.options;
|
|
82
89
|
// do the cleanup now
|
|
83
90
|
try {
|
|
84
|
-
await db.query(`
|
|
91
|
+
await this.#db.query(`
|
|
85
92
|
DELETE FROM ${tableName}
|
|
86
93
|
WHERE expires_at IS NOT NULL AND expires_at <= NOW()`);
|
|
87
94
|
}
|
|
@@ -118,7 +125,7 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
118
125
|
}
|
|
119
126
|
/** @inheritdoc */
|
|
120
127
|
set(key, value, options = {}) {
|
|
121
|
-
return this.#setOn(this
|
|
128
|
+
return this.#setOn(this.#db, key, value, options);
|
|
122
129
|
}
|
|
123
130
|
async #setOn(exec, key, value, options = {}) {
|
|
124
131
|
this._assertInitialized();
|
|
@@ -138,12 +145,12 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
138
145
|
async setIfAbsent(key, value, options = {}) {
|
|
139
146
|
this._assertInitialized();
|
|
140
147
|
const nsKey = this._withNs(key);
|
|
141
|
-
const {
|
|
148
|
+
const { tableName } = this.options;
|
|
142
149
|
const ttl = this._resolveTtl(options);
|
|
143
150
|
const expiresAt = ttl ? new Date(Date.now() + ttl * 1000) : null;
|
|
144
151
|
// INSERT on new keys; UPDATE only when the existing row is expired.
|
|
145
152
|
// (Live keys stay untouched — the hallmark of setIfAbsent.)
|
|
146
|
-
const { rowCount } = await db.query(`INSERT INTO ${tableName} (key, value, expires_at, updated_at)
|
|
153
|
+
const { rowCount } = await this.#db.query(`INSERT INTO ${tableName} (key, value, expires_at, updated_at)
|
|
147
154
|
VALUES ($1, $2, $3, NOW())
|
|
148
155
|
ON CONFLICT (key) DO UPDATE SET
|
|
149
156
|
value = EXCLUDED.value,
|
|
@@ -156,11 +163,11 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
156
163
|
async getSet(key, value, options = {}) {
|
|
157
164
|
this._assertInitialized();
|
|
158
165
|
const nsKey = this._withNs(key);
|
|
159
|
-
const {
|
|
166
|
+
const { tableName } = this.options;
|
|
160
167
|
const ttl = this._resolveTtl(options);
|
|
161
168
|
const expiresAt = ttl ? new Date(Date.now() + ttl * 1000) : null;
|
|
162
169
|
// CTE captures pre-write state; UPSERT writes; RETURNING surfaces the prev.
|
|
163
|
-
const { rows } = await db.query(`WITH prev AS (
|
|
170
|
+
const { rows } = await this.#db.query(`WITH prev AS (
|
|
164
171
|
SELECT value FROM ${tableName}
|
|
165
172
|
WHERE key = $1 AND (expires_at IS NULL OR expires_at > NOW())
|
|
166
173
|
), upserted AS (
|
|
@@ -178,15 +185,17 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
178
185
|
async #incrBy(key, delta, options = {}) {
|
|
179
186
|
this._assertInitialized();
|
|
180
187
|
const nsKey = this._withNs(key);
|
|
181
|
-
const {
|
|
188
|
+
const { tableName } = this.options;
|
|
182
189
|
const ttl = this._resolveTtl(options);
|
|
183
190
|
const expiresAt = ttl ? new Date(Date.now() + ttl * 1000) : null;
|
|
184
191
|
// - New key OR expired key: value = delta, expires_at = $ttl
|
|
185
192
|
// - Live key: value = old + delta, preserve existing expires_at
|
|
186
|
-
//
|
|
187
|
-
//
|
|
193
|
+
// - Live key that is not a JSON number: the WHERE of DO UPDATE skips it,
|
|
194
|
+
// so the statement updates nothing and returns no row. It raises nothing,
|
|
195
|
+
// so a transaction the host opened on the same Driver is not aborted.
|
|
196
|
+
// The 22P02 catch is a backstop: a delta PostgreSQL cannot cast as numeric.
|
|
188
197
|
try {
|
|
189
|
-
const { rows } = await db.query(`INSERT INTO ${tableName} (key, value, expires_at, updated_at)
|
|
198
|
+
const { rows } = await this.#db.query(`INSERT INTO ${tableName} (key, value, expires_at, updated_at)
|
|
190
199
|
VALUES ($1, to_jsonb($2::numeric), $3, NOW())
|
|
191
200
|
ON CONFLICT (key) DO UPDATE SET
|
|
192
201
|
value = CASE
|
|
@@ -200,7 +209,11 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
200
209
|
ELSE ${tableName}.expires_at
|
|
201
210
|
END,
|
|
202
211
|
updated_at = NOW()
|
|
212
|
+
WHERE (${tableName}.expires_at IS NOT NULL AND ${tableName}.expires_at <= NOW())
|
|
213
|
+
OR jsonb_typeof(${tableName}.value) = 'number'
|
|
203
214
|
RETURNING value`, [nsKey, delta, expiresAt]);
|
|
215
|
+
if (!rows.length)
|
|
216
|
+
throw new TypeError("KV value is not a number");
|
|
204
217
|
return Number(rows[0].value);
|
|
205
218
|
}
|
|
206
219
|
catch (err) {
|
|
@@ -223,7 +236,7 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
223
236
|
async cas(key, expected, next, options = {}) {
|
|
224
237
|
this._assertInitialized();
|
|
225
238
|
const nsKey = this._withNs(key);
|
|
226
|
-
const {
|
|
239
|
+
const { tableName } = this.options;
|
|
227
240
|
const hasTtl = options.ttl !== undefined;
|
|
228
241
|
const ttl = hasTtl ? this._resolveTtl(options) : undefined;
|
|
229
242
|
const expiresAt = ttl ? new Date(Date.now() + ttl * 1000) : null;
|
|
@@ -243,12 +256,12 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
243
256
|
const params = [nsKey, nextJson, expectedJson];
|
|
244
257
|
if (hasTtl)
|
|
245
258
|
params.push(expiresAt);
|
|
246
|
-
const { rowCount } = await db.query(sql, params);
|
|
259
|
+
const { rowCount } = await this.#db.query(sql, params);
|
|
247
260
|
return (rowCount ?? 0) > 0;
|
|
248
261
|
}
|
|
249
262
|
/** @inheritdoc */
|
|
250
263
|
get(key) {
|
|
251
|
-
return this.#getOn(this
|
|
264
|
+
return this.#getOn(this.#db, key);
|
|
252
265
|
}
|
|
253
266
|
async #getOn(exec, key) {
|
|
254
267
|
this._assertInitialized();
|
|
@@ -263,7 +276,7 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
263
276
|
}
|
|
264
277
|
/** @inheritdoc */
|
|
265
278
|
delete(key) {
|
|
266
|
-
return this.#deleteOn(this
|
|
279
|
+
return this.#deleteOn(this.#db, key);
|
|
267
280
|
}
|
|
268
281
|
async #deleteOn(exec, key) {
|
|
269
282
|
this._assertInitialized();
|
|
@@ -278,81 +291,58 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
278
291
|
async exists(key) {
|
|
279
292
|
this._assertInitialized();
|
|
280
293
|
key = this._withNs(key);
|
|
281
|
-
const {
|
|
282
|
-
const { rows } = await db.query(`SELECT 1 FROM ${tableName}
|
|
294
|
+
const { tableName } = this.options;
|
|
295
|
+
const { rows } = await this.#db.query(`SELECT 1 FROM ${tableName}
|
|
283
296
|
WHERE key = $1 AND (expires_at IS NULL OR expires_at > NOW())`, [key]);
|
|
284
297
|
return rows.length > 0;
|
|
285
298
|
}
|
|
286
299
|
/** @inheritdoc */
|
|
287
300
|
async keys(pattern) {
|
|
288
301
|
this._assertInitialized();
|
|
289
|
-
const {
|
|
290
|
-
const { rows } = await db.query(`SELECT key FROM ${tableName}
|
|
302
|
+
const { tableName } = this.options;
|
|
303
|
+
const { rows } = await this.#db.query(`SELECT key FROM ${tableName}
|
|
291
304
|
WHERE key LIKE $1${this.#likeEscape}
|
|
292
|
-
AND (expires_at IS NULL OR expires_at > NOW())
|
|
293
|
-
ORDER BY key`, [this.#withNsLike(pattern)]);
|
|
305
|
+
AND (expires_at IS NULL OR expires_at > NOW())`, [this.#withNsLike(pattern)]);
|
|
294
306
|
return rows.map((row) => this._withoutNs(row.key)).toSorted();
|
|
295
307
|
}
|
|
296
308
|
/** @inheritdoc */
|
|
297
309
|
async *keysIter(pattern) {
|
|
298
310
|
this._assertInitialized();
|
|
299
311
|
const { tableName } = this.options;
|
|
300
|
-
const
|
|
301
|
-
//
|
|
302
|
-
//
|
|
303
|
-
|
|
304
|
-
let
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
for (const row of rows) {
|
|
318
|
-
yield this._withoutNs(row.key);
|
|
319
|
-
}
|
|
312
|
+
const like = this.#withNsLike(pattern);
|
|
313
|
+
// Keyset pages in byte order, which is the order of the text_pattern_ops index
|
|
314
|
+
// initialize() creates: each page is one range scan of it. Nothing stays open
|
|
315
|
+
// between yields, so an early break leaves nothing to release.
|
|
316
|
+
let after;
|
|
317
|
+
while (true) {
|
|
318
|
+
const { rows } = after === undefined
|
|
319
|
+
? await this.#db.query(`SELECT key FROM ${tableName}
|
|
320
|
+
WHERE key LIKE $1${this.#likeEscape}
|
|
321
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
322
|
+
ORDER BY key USING ~<~ LIMIT ${KEYS_ITER_PAGE}`, [like])
|
|
323
|
+
: await this.#db.query(`SELECT key FROM ${tableName}
|
|
324
|
+
WHERE key LIKE $1${this.#likeEscape} AND key ~>~ $2
|
|
325
|
+
AND (expires_at IS NULL OR expires_at > NOW())
|
|
326
|
+
ORDER BY key USING ~<~ LIMIT ${KEYS_ITER_PAGE}`, [like, after]);
|
|
327
|
+
for (const row of rows) {
|
|
328
|
+
yield this._withoutNs(row.key);
|
|
320
329
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
try {
|
|
325
|
-
await client.query(`CLOSE ${cursorName}`);
|
|
326
|
-
}
|
|
327
|
-
catch {
|
|
328
|
-
// cursor may already be gone if the txn aborted
|
|
329
|
-
}
|
|
330
|
-
try {
|
|
331
|
-
await client.query("COMMIT");
|
|
332
|
-
}
|
|
333
|
-
catch {
|
|
334
|
-
try {
|
|
335
|
-
await client.query("ROLLBACK");
|
|
336
|
-
}
|
|
337
|
-
catch {
|
|
338
|
-
// ignore — caller will see the original error
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
release();
|
|
330
|
+
if (rows.length < KEYS_ITER_PAGE)
|
|
331
|
+
return;
|
|
332
|
+
after = rows[rows.length - 1].key;
|
|
343
333
|
}
|
|
344
334
|
}
|
|
345
335
|
/** @inheritdoc */
|
|
346
336
|
async clear(pattern) {
|
|
347
337
|
this._assertInitialized();
|
|
348
|
-
const {
|
|
338
|
+
const { tableName } = this.options;
|
|
349
339
|
const likePattern = this.#withNsLike(pattern);
|
|
350
340
|
// Batch large deletions to prevent long-running transactions
|
|
351
341
|
const batchSize = 10000;
|
|
352
342
|
let totalDeleted = 0;
|
|
353
343
|
let deleted;
|
|
354
344
|
do {
|
|
355
|
-
const { rowCount } = await db.query(`DELETE FROM ${tableName} WHERE key IN (
|
|
345
|
+
const { rowCount } = await this.#db.query(`DELETE FROM ${tableName} WHERE key IN (
|
|
356
346
|
SELECT key FROM ${tableName} WHERE key LIKE $1${this.#likeEscape} LIMIT $2
|
|
357
347
|
)`, [likePattern, batchSize]);
|
|
358
348
|
deleted = rowCount ?? 0;
|
|
@@ -366,7 +356,7 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
366
356
|
if (entries.length === 0)
|
|
367
357
|
return [];
|
|
368
358
|
const normalized = this._normalizePairs(entries);
|
|
369
|
-
const {
|
|
359
|
+
const { tableName } = this.options;
|
|
370
360
|
const placeholders = [];
|
|
371
361
|
const params = [];
|
|
372
362
|
let idx = 1;
|
|
@@ -384,7 +374,7 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
384
374
|
expires_at = EXCLUDED.expires_at,
|
|
385
375
|
updated_at = NOW()
|
|
386
376
|
`;
|
|
387
|
-
await db.query(sql, params);
|
|
377
|
+
await this.#db.query(sql, params);
|
|
388
378
|
return normalized.map(() => true);
|
|
389
379
|
}
|
|
390
380
|
/** @inheritdoc */
|
|
@@ -393,14 +383,14 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
393
383
|
if (keys.length === 0)
|
|
394
384
|
return {};
|
|
395
385
|
const placeholders = keys.map((_, i) => `$${i + 1}`).join(", ");
|
|
396
|
-
const {
|
|
386
|
+
const { tableName } = this.options;
|
|
397
387
|
const sql = `
|
|
398
388
|
SELECT key, value
|
|
399
389
|
FROM ${tableName}
|
|
400
390
|
WHERE key IN (${placeholders}) AND (expires_at IS NULL OR expires_at > NOW())
|
|
401
391
|
`;
|
|
402
392
|
const params = keys.map((k) => this._withNs(k));
|
|
403
|
-
const { rows } = await db.query(sql, params);
|
|
393
|
+
const { rows } = await this.#db.query(sql, params);
|
|
404
394
|
const found = Object.create(null);
|
|
405
395
|
for (const row of rows) {
|
|
406
396
|
found[this._withoutNs(row.key)] = row.value;
|
|
@@ -416,9 +406,9 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
416
406
|
async expire(key, ttl) {
|
|
417
407
|
this._assertInitialized();
|
|
418
408
|
key = this._withNs(key);
|
|
419
|
-
const {
|
|
409
|
+
const { tableName } = this.options;
|
|
420
410
|
const expiresAt = new Date(Date.now() + ttl * 1000);
|
|
421
|
-
const { rowCount } = await db.query(`UPDATE ${tableName}
|
|
411
|
+
const { rowCount } = await this.#db.query(`UPDATE ${tableName}
|
|
422
412
|
SET expires_at = $2, updated_at = NOW()
|
|
423
413
|
WHERE key = $1 AND (expires_at IS NULL OR expires_at > NOW())`, [key, expiresAt]);
|
|
424
414
|
return rowCount > 0;
|
|
@@ -427,8 +417,8 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
427
417
|
async ttl(key) {
|
|
428
418
|
this._assertInitialized();
|
|
429
419
|
key = this._withNs(key);
|
|
430
|
-
const {
|
|
431
|
-
const { rows } = await db.query(`SELECT expires_at FROM ${tableName} WHERE key = $1`, [key]);
|
|
420
|
+
const { tableName } = this.options;
|
|
421
|
+
const { rows } = await this.#db.query(`SELECT expires_at FROM ${tableName} WHERE key = $1`, [key]);
|
|
432
422
|
if (rows.length === 0)
|
|
433
423
|
return { state: "missing" };
|
|
434
424
|
const expiresAt = rows[0].expires_at;
|
|
@@ -440,60 +430,38 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
440
430
|
return { state: "missing" };
|
|
441
431
|
return { state: "expires", at };
|
|
442
432
|
}
|
|
443
|
-
/**
|
|
444
|
-
* Acquire a single pinned connection for a transaction.
|
|
445
|
-
*/
|
|
446
|
-
async #acquireClient() {
|
|
447
|
-
const { db } = this.options;
|
|
448
|
-
if (typeof db.totalCount === "number" && typeof db.connect === "function") {
|
|
449
|
-
const client = await db.connect();
|
|
450
|
-
return { client, release: () => client.release() };
|
|
451
|
-
}
|
|
452
|
-
return { client: db, release: () => { } };
|
|
453
|
-
}
|
|
454
433
|
/** @inheritdoc */
|
|
455
434
|
async transaction(operations) {
|
|
456
|
-
this._assertInitialized();
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
435
|
+
this._assertInitialized(); // `async` keeps this a rejection
|
|
436
|
+
// `savepoint()`, not `transaction()`: outside a transaction the two are the same
|
|
437
|
+
// call, and the driver pins one connection (or, on one client, holds every other
|
|
438
|
+
// caller back), checks the COMMIT, and rolls back when the callback rejects.
|
|
439
|
+
// Inside a transaction the host opened on the same driver, the unit is a
|
|
440
|
+
// savepoint of it: undone alone when it fails, while the host's transaction goes
|
|
441
|
+
// on and decides the rest. A joined `transaction()` would leave the operations
|
|
442
|
+
// before the failure in the host's transaction.
|
|
443
|
+
return this.#db.savepoint(async (tx) => {
|
|
444
|
+
const results = [];
|
|
445
|
+
for (const op of operations) {
|
|
446
|
+
switch (op.type) {
|
|
447
|
+
case "set":
|
|
448
|
+
results.push(await this.#setOn(tx, op.key, op.value, op.options || {}));
|
|
449
|
+
break;
|
|
450
|
+
case "get":
|
|
451
|
+
results.push(await this.#getOn(tx, op.key));
|
|
452
|
+
break;
|
|
453
|
+
case "delete":
|
|
454
|
+
results.push(await this.#deleteOn(tx, op.key));
|
|
455
|
+
break;
|
|
475
456
|
}
|
|
476
|
-
await client.query("COMMIT");
|
|
477
457
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
await client.query("ROLLBACK");
|
|
481
|
-
}
|
|
482
|
-
catch (rollbackErr) {
|
|
483
|
-
logger?.error?.(`Rollback failed: ${rollbackErr}`);
|
|
484
|
-
}
|
|
485
|
-
throw err;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
finally {
|
|
489
|
-
release();
|
|
490
|
-
}
|
|
491
|
-
return results;
|
|
458
|
+
return results;
|
|
459
|
+
});
|
|
492
460
|
}
|
|
493
461
|
async __debug_dump() {
|
|
494
462
|
this._assertInitialized();
|
|
495
|
-
const {
|
|
496
|
-
const { rows } = await db.query(`SELECT key, value, expires_at FROM ${tableName} WHERE key LIKE $1${this.#likeEscape}`, [this.#withNsLike("*")]);
|
|
463
|
+
const { tableName } = this.options;
|
|
464
|
+
const { rows } = await this.#db.query(`SELECT key, value, expires_at FROM ${tableName} WHERE key LIKE $1${this.#likeEscape}`, [this.#withNsLike("*")]);
|
|
497
465
|
return rows.reduce((m, row) => {
|
|
498
466
|
m[this._withoutNs(row.key)] = {
|
|
499
467
|
value: row.value,
|
package/dist/adapter/sqlite.d.ts
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @module
|
|
3
3
|
*
|
|
4
|
-
* SQLite key-value storage adapter implementation (`node:sqlite
|
|
4
|
+
* SQLite key-value storage adapter implementation (`node:sqlite`, through a sqlkit
|
|
5
|
+
* driver: kv's own over a handle, or the host's).
|
|
5
6
|
*/
|
|
6
|
-
import type
|
|
7
|
+
import { type SqliteDb } from "../utils/sqlite-driver.ts";
|
|
7
8
|
import { AdapterAbstract, type AdapterAbstractOptions, type Operation, type SetMultipleEntry, type SetOptions, type TtlResult } from "./abstract.ts";
|
|
8
9
|
/**
|
|
9
10
|
* Configuration options for the SQLite KV adapter.
|
|
10
11
|
*/
|
|
11
12
|
export interface AdapterSqliteOptions extends AdapterAbstractOptions {
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
14
|
+
* The database: an open `node:sqlite` handle, e.g. `new DatabaseSync("kv.db")`, or a
|
|
15
|
+
* sqlkit `Driver` of the `sqlite` dialect with a sync tier, e.g. `openSqlite("kv.db")`.
|
|
16
|
+
* The caller owns it: `destroy()` never closes it, so one can be shared across
|
|
17
|
+
* adapters.
|
|
15
18
|
*/
|
|
16
|
-
db:
|
|
19
|
+
db: SqliteDb;
|
|
17
20
|
/**
|
|
18
21
|
* Name of the table to use for storing key-value pairs.
|
|
19
22
|
* The table will be created automatically if it doesn't exist.
|
|
@@ -36,11 +39,20 @@ export interface AdapterSqliteOptions extends AdapterAbstractOptions {
|
|
|
36
39
|
* and index on initialization.
|
|
37
40
|
*
|
|
38
41
|
* @remarks
|
|
42
|
+
* - Over a `DatabaseSync`, every statement goes through kv's own sqlkit driver over the
|
|
43
|
+
* handle, on its synchronous tier: one driver per handle, imported on first use. A
|
|
44
|
+
* statement runs inside the call, and nothing else on the handle interleaves.
|
|
45
|
+
* - Over a sqlkit `Driver` the host passed, a statement takes its turn on the driver's
|
|
46
|
+
* async tier: it waits for a transaction the host has open elsewhere, and joins one
|
|
47
|
+
* it was issued inside.
|
|
39
48
|
* - `node:sqlite` is synchronous, so every operation blocks the event loop for its
|
|
40
|
-
* duration (typically microseconds)
|
|
49
|
+
* duration (typically microseconds).
|
|
41
50
|
* - Multi-statement operations run in `BEGIN IMMEDIATE`, so they stay atomic against
|
|
42
51
|
* other connections and processes on the same file. Inside a transaction the caller
|
|
43
|
-
* already opened on the same handle, they use a
|
|
52
|
+
* already opened (on the same handle, or through the same `Driver`), they use a
|
|
53
|
+
* savepoint instead.
|
|
54
|
+
* - A statement SQLite refused rejects with sqlkit's `SqlError`, node:sqlite's error as
|
|
55
|
+
* its `cause`.
|
|
44
56
|
*
|
|
45
57
|
* @example
|
|
46
58
|
* ```typescript
|
|
@@ -51,6 +63,10 @@ export interface AdapterSqliteOptions extends AdapterAbstractOptions {
|
|
|
51
63
|
* });
|
|
52
64
|
* await client.initialize();
|
|
53
65
|
* await client.set("session:abc", { userId: 123 }, { ttl: 3600 });
|
|
66
|
+
*
|
|
67
|
+
* // or on a sqlkit Driver
|
|
68
|
+
* import { openSqlite } from "@marianmeres/sqlkit/sqlite";
|
|
69
|
+
* const onDriver = createKVClient("myapp:", "sqlite", { db: openSqlite("kv.db") });
|
|
54
70
|
* ```
|
|
55
71
|
*/
|
|
56
72
|
export declare class AdapterSqlite extends AdapterAbstract {
|