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