@keyv/postgres 2.2.3 → 6.0.0-alpha.1
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/README.md +434 -23
- package/dist/index.cjs +571 -100
- package/dist/index.d.cts +275 -15
- package/dist/index.d.ts +275 -15
- package/dist/index.js +571 -100
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,146 +1,476 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import
|
|
2
|
+
import { Hookified } from "hookified";
|
|
3
3
|
import Keyv from "keyv";
|
|
4
4
|
|
|
5
5
|
// src/pool.ts
|
|
6
6
|
import pg from "pg";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
7
|
+
function getCacheKey(uri, options) {
|
|
8
|
+
const sortedKeys = Object.keys(options).sort();
|
|
9
|
+
const sorted = {};
|
|
10
|
+
for (const key of sortedKeys) {
|
|
11
|
+
sorted[key] = options[key];
|
|
12
|
+
}
|
|
13
|
+
return `${uri}::${JSON.stringify(sorted)}`;
|
|
14
|
+
}
|
|
15
|
+
var createPoolManager = () => {
|
|
16
|
+
const pools = /* @__PURE__ */ new Map();
|
|
17
|
+
return {
|
|
18
|
+
getPool(uri, options = {}) {
|
|
19
|
+
const key = getCacheKey(uri, options);
|
|
20
|
+
let existingPool = pools.get(key);
|
|
21
|
+
if (!existingPool) {
|
|
22
|
+
existingPool = new pg.Pool({ connectionString: uri, ...options });
|
|
23
|
+
pools.set(key, existingPool);
|
|
24
|
+
}
|
|
25
|
+
return existingPool;
|
|
26
|
+
},
|
|
27
|
+
async endPool(uri, options = {}) {
|
|
28
|
+
const key = getCacheKey(uri, options);
|
|
29
|
+
const existingPool = pools.get(key);
|
|
30
|
+
if (existingPool) {
|
|
31
|
+
await existingPool.end();
|
|
32
|
+
pools.delete(key);
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
async endAllPools() {
|
|
36
|
+
const endings = [];
|
|
37
|
+
for (const [, p] of pools) {
|
|
38
|
+
endings.push(p.end());
|
|
39
|
+
}
|
|
40
|
+
await Promise.all(endings);
|
|
41
|
+
pools.clear();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
20
44
|
};
|
|
45
|
+
var poolManager = createPoolManager();
|
|
46
|
+
var pool = (uri, options = {}) => poolManager.getPool(uri, options);
|
|
47
|
+
var endPool = async (uri, options = {}) => poolManager.endPool(uri, options);
|
|
21
48
|
|
|
22
49
|
// src/index.ts
|
|
23
50
|
function escapeIdentifier(identifier) {
|
|
24
51
|
return `"${identifier.replace(/"/g, '""')}"`;
|
|
25
52
|
}
|
|
26
|
-
var KeyvPostgres = class extends
|
|
27
|
-
|
|
28
|
-
opts;
|
|
53
|
+
var KeyvPostgres = class extends Hookified {
|
|
54
|
+
/** Function for executing SQL queries against the PostgreSQL database. */
|
|
29
55
|
query;
|
|
30
|
-
|
|
56
|
+
/** Promise that resolves to the query function once initialization completes. */
|
|
57
|
+
_connected;
|
|
58
|
+
/** The namespace used to prefix keys for multi-tenant separation. */
|
|
59
|
+
_namespace;
|
|
60
|
+
/**
|
|
61
|
+
* The PostgreSQL connection URI.
|
|
62
|
+
* @default 'postgresql://localhost:5432'
|
|
63
|
+
*/
|
|
64
|
+
_uri = "postgresql://localhost:5432";
|
|
65
|
+
/**
|
|
66
|
+
* The table name used for storage.
|
|
67
|
+
* @default 'keyv'
|
|
68
|
+
*/
|
|
69
|
+
_table = "keyv";
|
|
70
|
+
/**
|
|
71
|
+
* The maximum key length (VARCHAR length) for the key column.
|
|
72
|
+
* @default 255
|
|
73
|
+
*/
|
|
74
|
+
_keyLength = 255;
|
|
75
|
+
/**
|
|
76
|
+
* The maximum namespace length (VARCHAR length) for the namespace column.
|
|
77
|
+
* @default 255
|
|
78
|
+
*/
|
|
79
|
+
_namespaceLength = 255;
|
|
80
|
+
/**
|
|
81
|
+
* The PostgreSQL schema name.
|
|
82
|
+
* @default 'public'
|
|
83
|
+
*/
|
|
84
|
+
_schema = "public";
|
|
85
|
+
/**
|
|
86
|
+
* The SSL configuration for the PostgreSQL connection.
|
|
87
|
+
* @default undefined
|
|
88
|
+
*/
|
|
89
|
+
_ssl;
|
|
90
|
+
/**
|
|
91
|
+
* The number of rows to fetch per iteration batch.
|
|
92
|
+
* @default 10
|
|
93
|
+
*/
|
|
94
|
+
_iterationLimit = 10;
|
|
95
|
+
/**
|
|
96
|
+
* Whether to use a PostgreSQL unlogged table (faster writes, no WAL, data lost on crash).
|
|
97
|
+
* @default false
|
|
98
|
+
*/
|
|
99
|
+
_useUnloggedTable = false;
|
|
100
|
+
/**
|
|
101
|
+
* The interval in milliseconds between automatic expired-entry cleanup runs.
|
|
102
|
+
* A value of 0 (default) disables the automatic cleanup.
|
|
103
|
+
* @default 0
|
|
104
|
+
*/
|
|
105
|
+
_clearExpiredInterval = 0;
|
|
106
|
+
/**
|
|
107
|
+
* The timer reference for the automatic expired-entry cleanup interval.
|
|
108
|
+
*/
|
|
109
|
+
_clearExpiredTimer;
|
|
110
|
+
/**
|
|
111
|
+
* Additional PoolConfig properties passed through to the pg connection pool.
|
|
112
|
+
*/
|
|
113
|
+
_poolConfig = {};
|
|
114
|
+
/**
|
|
115
|
+
* Creates a new KeyvPostgres instance.
|
|
116
|
+
* @param options - A PostgreSQL connection URI string or a {@link KeyvPostgresOptions} configuration object.
|
|
117
|
+
*/
|
|
31
118
|
constructor(options) {
|
|
32
119
|
super();
|
|
33
|
-
this.ttlSupport = false;
|
|
34
120
|
if (typeof options === "string") {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
uri
|
|
39
|
-
};
|
|
40
|
-
} else {
|
|
41
|
-
options = {
|
|
42
|
-
dialect: "postgres",
|
|
43
|
-
uri: "postgresql://localhost:5432",
|
|
44
|
-
...options
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
this.opts = {
|
|
48
|
-
table: "keyv",
|
|
49
|
-
schema: "public",
|
|
50
|
-
keySize: 255,
|
|
51
|
-
...options
|
|
52
|
-
};
|
|
53
|
-
let createTable = `CREATE${this.opts.useUnloggedTable ? " UNLOGGED " : " "}TABLE IF NOT EXISTS ${this.opts.schema}.${this.opts.table}(key VARCHAR(${Number(this.opts.keySize)}) PRIMARY KEY, value TEXT )`;
|
|
54
|
-
if (this.opts.schema !== "public") {
|
|
55
|
-
createTable = `CREATE SCHEMA IF NOT EXISTS ${this.opts.schema}; ${createTable}`;
|
|
121
|
+
this._uri = options;
|
|
122
|
+
} else if (options) {
|
|
123
|
+
this.setOptions(options);
|
|
56
124
|
}
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
125
|
+
const schemaEsc = escapeIdentifier(this._schema);
|
|
126
|
+
const tableEsc = escapeIdentifier(this._table);
|
|
127
|
+
let createTable = `CREATE${this._useUnloggedTable ? " UNLOGGED " : " "}TABLE IF NOT EXISTS ${schemaEsc}.${tableEsc}(key VARCHAR(${Number(this._keyLength)}) NOT NULL, value TEXT, namespace VARCHAR(${Number(this._namespaceLength)}) DEFAULT NULL, expires BIGINT DEFAULT NULL)`;
|
|
128
|
+
if (this._schema !== "public") {
|
|
129
|
+
createTable = `CREATE SCHEMA IF NOT EXISTS ${schemaEsc}; ${createTable}`;
|
|
130
|
+
}
|
|
131
|
+
const migration = `ALTER TABLE ${schemaEsc}.${tableEsc} ADD COLUMN IF NOT EXISTS namespace VARCHAR(${Number(this._namespaceLength)}) DEFAULT NULL`;
|
|
132
|
+
const migrationExpires = `ALTER TABLE ${schemaEsc}.${tableEsc} ADD COLUMN IF NOT EXISTS expires BIGINT DEFAULT NULL`;
|
|
133
|
+
const dropOldPk = `ALTER TABLE ${schemaEsc}.${tableEsc} DROP CONSTRAINT IF EXISTS ${escapeIdentifier(`${this._table}_pkey`)}`;
|
|
134
|
+
const createIndex = `CREATE UNIQUE INDEX IF NOT EXISTS ${escapeIdentifier(`${this._table}_key_namespace_idx`)} ON ${schemaEsc}.${tableEsc} (key, COALESCE(namespace, ''))`;
|
|
135
|
+
const createExpiresIndex = `CREATE INDEX IF NOT EXISTS ${escapeIdentifier(`${this._table}_expires_idx`)} ON ${schemaEsc}.${tableEsc} (expires) WHERE expires IS NOT NULL`;
|
|
136
|
+
this._connected = this.init(
|
|
137
|
+
createTable,
|
|
138
|
+
migration,
|
|
139
|
+
migrationExpires,
|
|
140
|
+
dropOldPk,
|
|
141
|
+
createIndex,
|
|
142
|
+
createExpiresIndex
|
|
143
|
+
).catch((error) => {
|
|
144
|
+
this.emit("error", error);
|
|
145
|
+
throw error;
|
|
146
|
+
});
|
|
147
|
+
this.query = async (sqlString, values) => {
|
|
148
|
+
const query = await this._connected;
|
|
149
|
+
return query(sqlString, values);
|
|
150
|
+
};
|
|
151
|
+
this.startClearExpiredTimer();
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Initializes the database connection and ensures the table schema exists.
|
|
155
|
+
* Called from the constructor; errors are emitted rather than thrown.
|
|
156
|
+
*/
|
|
157
|
+
async init(createTable, migration, migrationExpires, dropOldPk, createIndex, createExpiresIndex) {
|
|
158
|
+
const query = await this.connect();
|
|
159
|
+
try {
|
|
160
|
+
await query(createTable);
|
|
161
|
+
await query(migration);
|
|
162
|
+
await query(migrationExpires);
|
|
163
|
+
await query(dropOldPk);
|
|
164
|
+
await query(createIndex);
|
|
165
|
+
await query(createExpiresIndex);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
if (error.code !== "23505") {
|
|
168
|
+
this.emit("error", error);
|
|
65
169
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
170
|
+
}
|
|
171
|
+
return query;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Get the namespace for the adapter. If undefined, no namespace prefix is applied.
|
|
175
|
+
*/
|
|
176
|
+
get namespace() {
|
|
177
|
+
return this._namespace;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Set the namespace for the adapter. Used for key prefixing and scoping operations like `clear()`.
|
|
181
|
+
*/
|
|
182
|
+
set namespace(value) {
|
|
183
|
+
this._namespace = value;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Get the PostgreSQL connection URI.
|
|
187
|
+
* @default 'postgresql://localhost:5432'
|
|
188
|
+
*/
|
|
189
|
+
get uri() {
|
|
190
|
+
return this._uri;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Set the PostgreSQL connection URI.
|
|
194
|
+
*/
|
|
195
|
+
set uri(value) {
|
|
196
|
+
this._uri = value;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Get the table name used for storage.
|
|
200
|
+
* @default 'keyv'
|
|
201
|
+
*/
|
|
202
|
+
get table() {
|
|
203
|
+
return this._table;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Set the table name used for storage.
|
|
207
|
+
*/
|
|
208
|
+
set table(value) {
|
|
209
|
+
this._table = value;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Get the maximum key length (VARCHAR length) for the key column.
|
|
213
|
+
* @default 255
|
|
214
|
+
*/
|
|
215
|
+
get keyLength() {
|
|
216
|
+
return this._keyLength;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Set the maximum key length (VARCHAR length) for the key column.
|
|
220
|
+
*/
|
|
221
|
+
set keyLength(value) {
|
|
222
|
+
this._keyLength = value;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Get the maximum namespace length (VARCHAR length) for the namespace column.
|
|
226
|
+
* @default 255
|
|
227
|
+
*/
|
|
228
|
+
get namespaceLength() {
|
|
229
|
+
return this._namespaceLength;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Set the maximum namespace length (VARCHAR length) for the namespace column.
|
|
233
|
+
*/
|
|
234
|
+
set namespaceLength(value) {
|
|
235
|
+
this._namespaceLength = value;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Get the PostgreSQL schema name.
|
|
239
|
+
* @default 'public'
|
|
240
|
+
*/
|
|
241
|
+
get schema() {
|
|
242
|
+
return this._schema;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Set the PostgreSQL schema name.
|
|
246
|
+
*/
|
|
247
|
+
set schema(value) {
|
|
248
|
+
this._schema = value;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Get the SSL configuration for the PostgreSQL connection.
|
|
252
|
+
* @default undefined
|
|
253
|
+
*/
|
|
254
|
+
get ssl() {
|
|
255
|
+
return this._ssl;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Set the SSL configuration for the PostgreSQL connection.
|
|
259
|
+
*/
|
|
260
|
+
set ssl(value) {
|
|
261
|
+
this._ssl = value;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get the number of rows to fetch per iteration batch.
|
|
265
|
+
* @default 10
|
|
266
|
+
*/
|
|
267
|
+
get iterationLimit() {
|
|
268
|
+
return this._iterationLimit;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Set the number of rows to fetch per iteration batch.
|
|
272
|
+
*/
|
|
273
|
+
set iterationLimit(value) {
|
|
274
|
+
this._iterationLimit = value;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Get whether to use a PostgreSQL unlogged table (faster writes, no WAL, data lost on crash).
|
|
278
|
+
* @default false
|
|
279
|
+
*/
|
|
280
|
+
get useUnloggedTable() {
|
|
281
|
+
return this._useUnloggedTable;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Set whether to use a PostgreSQL unlogged table.
|
|
285
|
+
*/
|
|
286
|
+
set useUnloggedTable(value) {
|
|
287
|
+
this._useUnloggedTable = value;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Get the interval in milliseconds between automatic expired-entry cleanup runs.
|
|
291
|
+
* A value of 0 means the automatic cleanup is disabled.
|
|
292
|
+
* @default 0
|
|
293
|
+
*/
|
|
294
|
+
get clearExpiredInterval() {
|
|
295
|
+
return this._clearExpiredInterval;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Set the interval in milliseconds between automatic expired-entry cleanup runs.
|
|
299
|
+
* Setting to 0 disables the automatic cleanup.
|
|
300
|
+
*/
|
|
301
|
+
set clearExpiredInterval(value) {
|
|
302
|
+
this._clearExpiredInterval = value;
|
|
303
|
+
this.startClearExpiredTimer();
|
|
69
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* Get the options for the adapter. This is required by the KeyvStoreAdapter interface.
|
|
307
|
+
*/
|
|
308
|
+
// biome-ignore lint/suspicious/noExplicitAny: type format
|
|
309
|
+
get opts() {
|
|
310
|
+
return {
|
|
311
|
+
uri: this._uri,
|
|
312
|
+
table: this._table,
|
|
313
|
+
keyLength: this._keyLength,
|
|
314
|
+
namespaceLength: this._namespaceLength,
|
|
315
|
+
schema: this._schema,
|
|
316
|
+
ssl: this._ssl,
|
|
317
|
+
dialect: "postgres",
|
|
318
|
+
iterationLimit: this._iterationLimit,
|
|
319
|
+
useUnloggedTable: this._useUnloggedTable,
|
|
320
|
+
clearExpiredInterval: this._clearExpiredInterval,
|
|
321
|
+
...this._poolConfig
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Set the options for the adapter.
|
|
326
|
+
*/
|
|
327
|
+
set opts(options) {
|
|
328
|
+
this.setOptions(options);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Gets a value by key.
|
|
332
|
+
* @param key - The key to retrieve.
|
|
333
|
+
* @returns The value associated with the key, or `undefined` if not found.
|
|
334
|
+
*/
|
|
70
335
|
async get(key) {
|
|
71
|
-
const
|
|
72
|
-
const
|
|
336
|
+
const strippedKey = this.removeKeyPrefix(key);
|
|
337
|
+
const select = `SELECT * FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = $1 AND COALESCE(namespace, '') = COALESCE($2, '')`;
|
|
338
|
+
const rows = await this.query(select, [
|
|
339
|
+
strippedKey,
|
|
340
|
+
this.getNamespaceValue()
|
|
341
|
+
]);
|
|
73
342
|
const row = rows[0];
|
|
74
343
|
return row === void 0 ? void 0 : row.value;
|
|
75
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Gets multiple values by their keys.
|
|
347
|
+
* @param keys - An array of keys to retrieve.
|
|
348
|
+
* @returns An array of values in the same order as the keys, with `undefined` for missing keys.
|
|
349
|
+
*/
|
|
76
350
|
async getMany(keys) {
|
|
77
|
-
const
|
|
78
|
-
const
|
|
351
|
+
const strippedKeys = keys.map((k) => this.removeKeyPrefix(k));
|
|
352
|
+
const getMany = `SELECT * FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = ANY($1) AND COALESCE(namespace, '') = COALESCE($2, '')`;
|
|
353
|
+
const rows = await this.query(getMany, [
|
|
354
|
+
strippedKeys,
|
|
355
|
+
this.getNamespaceValue()
|
|
356
|
+
]);
|
|
79
357
|
const rowsMap = new Map(rows.map((row) => [row.key, row]));
|
|
80
|
-
return
|
|
358
|
+
return strippedKeys.map((key) => rowsMap.get(key)?.value);
|
|
81
359
|
}
|
|
360
|
+
/**
|
|
361
|
+
* Sets a key-value pair. Uses an upsert operation via `ON CONFLICT` to insert or update.
|
|
362
|
+
* @param key - The key to set.
|
|
363
|
+
* @param value - The value to store.
|
|
364
|
+
*/
|
|
82
365
|
// biome-ignore lint/suspicious/noExplicitAny: type format
|
|
83
366
|
async set(key, value) {
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
367
|
+
const strippedKey = this.removeKeyPrefix(key);
|
|
368
|
+
const expires = this.getExpiresFromValue(value);
|
|
369
|
+
const upsert = `INSERT INTO ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} (key, value, namespace, expires)
|
|
370
|
+
VALUES($1, $2, $3, $4)
|
|
371
|
+
ON CONFLICT(key, COALESCE(namespace, ''))
|
|
372
|
+
DO UPDATE SET value=excluded.value, expires=excluded.expires;`;
|
|
373
|
+
await this.query(upsert, [
|
|
374
|
+
strippedKey,
|
|
375
|
+
value,
|
|
376
|
+
this.getNamespaceValue(),
|
|
377
|
+
expires
|
|
378
|
+
]);
|
|
89
379
|
}
|
|
380
|
+
/**
|
|
381
|
+
* Sets multiple key-value pairs at once using PostgreSQL `UNNEST` for efficient bulk operations.
|
|
382
|
+
* @param entries - An array of key-value entry objects.
|
|
383
|
+
*/
|
|
90
384
|
async setMany(entries) {
|
|
91
385
|
const keys = [];
|
|
92
386
|
const values = [];
|
|
387
|
+
const expiresArray = [];
|
|
93
388
|
for (const { key, value } of entries) {
|
|
94
|
-
keys.push(key);
|
|
389
|
+
keys.push(this.removeKeyPrefix(key));
|
|
95
390
|
values.push(value);
|
|
391
|
+
expiresArray.push(this.getExpiresFromValue(value));
|
|
96
392
|
}
|
|
97
|
-
const upsert = `INSERT INTO ${this.
|
|
98
|
-
SELECT
|
|
99
|
-
ON CONFLICT(key)
|
|
100
|
-
DO UPDATE SET value=excluded.value;`;
|
|
101
|
-
await this.query(upsert, [
|
|
393
|
+
const upsert = `INSERT INTO ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} (key, value, namespace, expires)
|
|
394
|
+
SELECT k, v, $3, e FROM UNNEST($1::text[], $2::text[], $4::bigint[]) AS t(k, v, e)
|
|
395
|
+
ON CONFLICT(key, COALESCE(namespace, ''))
|
|
396
|
+
DO UPDATE SET value=excluded.value, expires=excluded.expires;`;
|
|
397
|
+
await this.query(upsert, [
|
|
398
|
+
keys,
|
|
399
|
+
values,
|
|
400
|
+
this.getNamespaceValue(),
|
|
401
|
+
expiresArray
|
|
402
|
+
]);
|
|
102
403
|
}
|
|
404
|
+
/**
|
|
405
|
+
* Deletes a key from the store.
|
|
406
|
+
* @param key - The key to delete.
|
|
407
|
+
* @returns `true` if the key existed and was deleted, `false` otherwise.
|
|
408
|
+
*/
|
|
103
409
|
async delete(key) {
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
await this.query(del, [key]);
|
|
111
|
-
return true;
|
|
410
|
+
const strippedKey = this.removeKeyPrefix(key);
|
|
411
|
+
const ns = this.getNamespaceValue();
|
|
412
|
+
const del = `DELETE FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = $1 AND COALESCE(namespace, '') = COALESCE($2, '') RETURNING 1`;
|
|
413
|
+
const rows = await this.query(del, [strippedKey, ns]);
|
|
414
|
+
return rows.length > 0;
|
|
112
415
|
}
|
|
416
|
+
/**
|
|
417
|
+
* Deletes multiple keys from the store at once.
|
|
418
|
+
* @param keys - An array of keys to delete.
|
|
419
|
+
* @returns `true` if any of the keys existed and were deleted, `false` otherwise.
|
|
420
|
+
*/
|
|
113
421
|
async deleteMany(keys) {
|
|
114
|
-
const
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
120
|
-
await this.query(del, [keys]);
|
|
121
|
-
return true;
|
|
422
|
+
const strippedKeys = keys.map((k) => this.removeKeyPrefix(k));
|
|
423
|
+
const ns = this.getNamespaceValue();
|
|
424
|
+
const del = `DELETE FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = ANY($1) AND COALESCE(namespace, '') = COALESCE($2, '') RETURNING 1`;
|
|
425
|
+
const rows = await this.query(del, [strippedKeys, ns]);
|
|
426
|
+
return rows.length > 0;
|
|
122
427
|
}
|
|
428
|
+
/**
|
|
429
|
+
* Clears all keys in the current namespace. If no namespace is set, all keys are removed.
|
|
430
|
+
*/
|
|
123
431
|
async clear() {
|
|
124
|
-
|
|
125
|
-
|
|
432
|
+
if (this._namespace) {
|
|
433
|
+
const del = `DELETE FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE namespace = $1`;
|
|
434
|
+
await this.query(del, [this._namespace]);
|
|
435
|
+
} else {
|
|
436
|
+
const del = `DELETE FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE namespace IS NULL`;
|
|
437
|
+
await this.query(del);
|
|
438
|
+
}
|
|
126
439
|
}
|
|
440
|
+
/**
|
|
441
|
+
* Utility helper method to delete all expired entries from the store where the `expires` column is less than the current timestamp.
|
|
442
|
+
*/
|
|
443
|
+
async clearExpired() {
|
|
444
|
+
const del = `DELETE FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE expires IS NOT NULL AND expires < $1`;
|
|
445
|
+
await this.query(del, [Date.now()]);
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Iterates over all key-value pairs, optionally filtered by namespace.
|
|
449
|
+
* Uses cursor-based (keyset) pagination with batch size controlled by `iterationLimit`.
|
|
450
|
+
* @param namespace - Optional namespace to filter keys by.
|
|
451
|
+
* @yields A `[key, value]` tuple for each entry.
|
|
452
|
+
*/
|
|
127
453
|
async *iterator(namespace) {
|
|
128
|
-
const limit = Number.parseInt(String(this.
|
|
129
|
-
const
|
|
130
|
-
const pattern = `${escapedNamespace}%`;
|
|
454
|
+
const limit = Number.parseInt(String(this._iterationLimit), 10) || 10;
|
|
455
|
+
const namespaceValue = namespace ?? null;
|
|
131
456
|
let lastKey = null;
|
|
132
457
|
while (true) {
|
|
133
458
|
let entries;
|
|
134
459
|
try {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if (
|
|
138
|
-
|
|
139
|
-
params
|
|
460
|
+
const where = [];
|
|
461
|
+
const params = [];
|
|
462
|
+
if (namespaceValue !== null) {
|
|
463
|
+
where.push(`namespace = $${params.length + 1}`);
|
|
464
|
+
params.push(namespaceValue);
|
|
140
465
|
} else {
|
|
141
|
-
|
|
142
|
-
|
|
466
|
+
where.push("namespace IS NULL");
|
|
467
|
+
}
|
|
468
|
+
if (lastKey !== null) {
|
|
469
|
+
where.push(`key > $${params.length + 1}`);
|
|
470
|
+
params.push(lastKey);
|
|
143
471
|
}
|
|
472
|
+
const select = `SELECT * FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE ${where.join(" AND ")} ORDER BY key LIMIT $${params.length + 1}`;
|
|
473
|
+
params.push(limit);
|
|
144
474
|
entries = await this.query(select, params);
|
|
145
475
|
} catch (error) {
|
|
146
476
|
this.emit(
|
|
@@ -156,7 +486,8 @@ var KeyvPostgres = class extends EventEmitter {
|
|
|
156
486
|
}
|
|
157
487
|
for (const entry of entries) {
|
|
158
488
|
if (entry.key !== void 0 && entry.key !== null) {
|
|
159
|
-
|
|
489
|
+
const prefixedKey = namespace ? `${namespace}:${entry.key}` : entry.key;
|
|
490
|
+
yield [prefixedKey, entry.value];
|
|
160
491
|
}
|
|
161
492
|
}
|
|
162
493
|
lastKey = entries[entries.length - 1].key;
|
|
@@ -165,20 +496,159 @@ var KeyvPostgres = class extends EventEmitter {
|
|
|
165
496
|
}
|
|
166
497
|
}
|
|
167
498
|
}
|
|
499
|
+
/**
|
|
500
|
+
* Checks whether a key exists in the store.
|
|
501
|
+
* @param key - The key to check.
|
|
502
|
+
* @returns `true` if the key exists, `false` otherwise.
|
|
503
|
+
*/
|
|
168
504
|
async has(key) {
|
|
169
|
-
const
|
|
170
|
-
const
|
|
505
|
+
const strippedKey = this.removeKeyPrefix(key);
|
|
506
|
+
const exists = `SELECT EXISTS ( SELECT * FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = $1 AND COALESCE(namespace, '') = COALESCE($2, '') )`;
|
|
507
|
+
const rows = await this.query(exists, [
|
|
508
|
+
strippedKey,
|
|
509
|
+
this.getNamespaceValue()
|
|
510
|
+
]);
|
|
171
511
|
return rows[0].exists;
|
|
172
512
|
}
|
|
513
|
+
/**
|
|
514
|
+
* Checks whether multiple keys exist in the store.
|
|
515
|
+
* @param keys - An array of keys to check.
|
|
516
|
+
* @returns An array of booleans in the same order as the input keys.
|
|
517
|
+
*/
|
|
518
|
+
async hasMany(keys) {
|
|
519
|
+
const strippedKeys = keys.map((k) => this.removeKeyPrefix(k));
|
|
520
|
+
const select = `SELECT key FROM ${escapeIdentifier(this._schema)}.${escapeIdentifier(this._table)} WHERE key = ANY($1) AND COALESCE(namespace, '') = COALESCE($2, '')`;
|
|
521
|
+
const rows = await this.query(select, [
|
|
522
|
+
strippedKeys,
|
|
523
|
+
this.getNamespaceValue()
|
|
524
|
+
]);
|
|
525
|
+
const existingKeys = new Set(rows.map((row) => row.key));
|
|
526
|
+
return strippedKeys.map((key) => existingKeys.has(key));
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Establishes a connection to the PostgreSQL database via the connection pool.
|
|
530
|
+
* @returns A query function that executes SQL statements and returns result rows.
|
|
531
|
+
*/
|
|
173
532
|
async connect() {
|
|
174
|
-
const conn = pool(this.
|
|
533
|
+
const conn = pool(this._uri, { ...this._poolConfig, ssl: this._ssl });
|
|
175
534
|
return async (sql, values) => {
|
|
176
535
|
const data = await conn.query(sql, values);
|
|
177
536
|
return data.rows;
|
|
178
537
|
};
|
|
179
538
|
}
|
|
539
|
+
/**
|
|
540
|
+
* Disconnects from the PostgreSQL database and releases the connection pool.
|
|
541
|
+
* Also stops the automatic expired-entry cleanup interval if running.
|
|
542
|
+
*/
|
|
180
543
|
async disconnect() {
|
|
181
|
-
|
|
544
|
+
this.stopClearExpiredTimer();
|
|
545
|
+
await endPool(this._uri, { ...this._poolConfig, ssl: this._ssl });
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Strips the namespace prefix from a key that was added by the Keyv core.
|
|
549
|
+
* For example, if namespace is "ns" and key is "ns:foo", returns "foo".
|
|
550
|
+
*/
|
|
551
|
+
removeKeyPrefix(key) {
|
|
552
|
+
if (this._namespace && key.startsWith(`${this._namespace}:`)) {
|
|
553
|
+
return key.slice(this._namespace.length + 1);
|
|
554
|
+
}
|
|
555
|
+
return key;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Returns the namespace value for SQL parameters. Returns null when no namespace is set.
|
|
559
|
+
*/
|
|
560
|
+
getNamespaceValue() {
|
|
561
|
+
return this._namespace ?? null;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Extracts the `expires` timestamp from a serialized value.
|
|
565
|
+
* The Keyv core serializes data as JSON like `{"value":"...","expires":1234567890}`.
|
|
566
|
+
* Returns the expires value as a number, or null if not present or not parseable.
|
|
567
|
+
*/
|
|
568
|
+
// biome-ignore lint/suspicious/noExplicitAny: type format
|
|
569
|
+
getExpiresFromValue(value) {
|
|
570
|
+
let data;
|
|
571
|
+
if (typeof value === "string") {
|
|
572
|
+
try {
|
|
573
|
+
data = JSON.parse(value);
|
|
574
|
+
} catch {
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
} else {
|
|
578
|
+
data = value;
|
|
579
|
+
}
|
|
580
|
+
if (data && typeof data === "object" && typeof data.expires === "number") {
|
|
581
|
+
return data.expires;
|
|
582
|
+
}
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Starts (or restarts) the automatic expired-entry cleanup interval.
|
|
587
|
+
* If the interval is 0 or negative, any existing timer is stopped.
|
|
588
|
+
*/
|
|
589
|
+
startClearExpiredTimer() {
|
|
590
|
+
this.stopClearExpiredTimer();
|
|
591
|
+
if (this._clearExpiredInterval > 0) {
|
|
592
|
+
this._clearExpiredTimer = setInterval(async () => {
|
|
593
|
+
try {
|
|
594
|
+
await this.clearExpired();
|
|
595
|
+
} catch (error) {
|
|
596
|
+
this.emit("error", error);
|
|
597
|
+
}
|
|
598
|
+
}, this._clearExpiredInterval);
|
|
599
|
+
this._clearExpiredTimer.unref();
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Stops the automatic expired-entry cleanup interval if running.
|
|
604
|
+
*/
|
|
605
|
+
stopClearExpiredTimer() {
|
|
606
|
+
if (this._clearExpiredTimer) {
|
|
607
|
+
clearInterval(this._clearExpiredTimer);
|
|
608
|
+
this._clearExpiredTimer = void 0;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
setOptions(options) {
|
|
612
|
+
if (options.uri !== void 0) {
|
|
613
|
+
this._uri = options.uri;
|
|
614
|
+
}
|
|
615
|
+
if (options.table !== void 0) {
|
|
616
|
+
this._table = options.table;
|
|
617
|
+
}
|
|
618
|
+
if (options.keyLength !== void 0) {
|
|
619
|
+
this._keyLength = options.keyLength;
|
|
620
|
+
}
|
|
621
|
+
if (options.namespaceLength !== void 0) {
|
|
622
|
+
this._namespaceLength = options.namespaceLength;
|
|
623
|
+
}
|
|
624
|
+
if (options.schema !== void 0) {
|
|
625
|
+
this._schema = options.schema;
|
|
626
|
+
}
|
|
627
|
+
if (options.ssl !== void 0) {
|
|
628
|
+
this._ssl = options.ssl;
|
|
629
|
+
}
|
|
630
|
+
if (options.iterationLimit !== void 0) {
|
|
631
|
+
this._iterationLimit = options.iterationLimit;
|
|
632
|
+
}
|
|
633
|
+
if (options.useUnloggedTable !== void 0) {
|
|
634
|
+
this._useUnloggedTable = options.useUnloggedTable;
|
|
635
|
+
}
|
|
636
|
+
if (options.clearExpiredInterval !== void 0) {
|
|
637
|
+
this._clearExpiredInterval = options.clearExpiredInterval;
|
|
638
|
+
}
|
|
639
|
+
const {
|
|
640
|
+
uri,
|
|
641
|
+
table,
|
|
642
|
+
keyLength,
|
|
643
|
+
namespaceLength,
|
|
644
|
+
schema,
|
|
645
|
+
ssl,
|
|
646
|
+
iterationLimit,
|
|
647
|
+
useUnloggedTable,
|
|
648
|
+
clearExpiredInterval,
|
|
649
|
+
...poolConfigRest
|
|
650
|
+
} = options;
|
|
651
|
+
this._poolConfig = { ...this._poolConfig, ...poolConfigRest };
|
|
182
652
|
}
|
|
183
653
|
};
|
|
184
654
|
var createKeyv = (options) => new Keyv({ store: new KeyvPostgres(options) });
|
|
@@ -189,3 +659,4 @@ export {
|
|
|
189
659
|
index_default as default
|
|
190
660
|
};
|
|
191
661
|
/* v8 ignore next -- @preserve */
|
|
662
|
+
/* v8 ignore start -- @preserve */
|