@happyvertical/sql 0.116.0 → 0.116.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.
@@ -0,0 +1,415 @@
1
+ import { n as ReopenNotSupportedError } from "./types-DihIt7ez.js";
2
+ import { DatabaseError } from "@happyvertical/utils";
3
+ //#region src/shared/connection-cache.ts
4
+ var CACHED_VALIDATION_CAPABILITY = Symbol.for("@happyvertical/sql/connection-cache-cached-validation/v1");
5
+ /** Race-safe async resource cache used by database adapters. */
6
+ var ConnectionCache = class {
7
+ [CACHED_VALIDATION_CAPABILITY] = true;
8
+ #connections = /* @__PURE__ */ new Map();
9
+ #pending = /* @__PURE__ */ new Map();
10
+ #evictions = /* @__PURE__ */ new Map();
11
+ #requests = /* @__PURE__ */ new Map();
12
+ #clearing = /* @__PURE__ */ new Map();
13
+ #failedClosures = /* @__PURE__ */ new Map();
14
+ async getOrCreate(key, options, create, close, validateCached) {
15
+ validateDatabaseCacheOptions(options);
16
+ const request = key && options.cache !== false ? this.#registerRequest(key) : void 0;
17
+ try {
18
+ this.#throwIfCancelled(request);
19
+ if (key && options.clearCache) {
20
+ await this.evict(key, close);
21
+ this.#throwIfCancelled(request);
22
+ }
23
+ if (key) this.#throwIfFailedClosure(key);
24
+ if (!key || options.cache === false) return create();
25
+ while (true) {
26
+ if (this.#evictions.has(key)) {
27
+ await this.#waitForEviction(key);
28
+ this.#throwIfCancelled(request);
29
+ }
30
+ this.#throwIfFailedClosure(key);
31
+ const cached = this.#connections.get(key);
32
+ if (cached !== void 0) {
33
+ if (!validateCached) return cached;
34
+ const isValid = await validateCached(cached);
35
+ this.#throwIfCancelled(request);
36
+ if (isValid && this.#connections.get(key) === cached && !this.#evictions.has(key)) return cached;
37
+ if (!isValid && this.#connections.get(key) === cached && !this.#evictions.has(key)) {
38
+ await this.evict(key, close);
39
+ this.#throwIfCancelled(request);
40
+ }
41
+ continue;
42
+ }
43
+ let pending = this.#pending.get(key);
44
+ if (!pending) {
45
+ this.#throwIfCancelled(request);
46
+ pending = {
47
+ invalidated: false,
48
+ promise: create()
49
+ };
50
+ this.#pending.set(key, pending);
51
+ }
52
+ let connection;
53
+ try {
54
+ connection = await pending.promise;
55
+ } catch (error) {
56
+ if (this.#pending.get(key) === pending) this.#pending.delete(key);
57
+ throw error;
58
+ }
59
+ if (pending.invalidated || this.#evictions.has(key)) {
60
+ if (this.#evictions.has(key)) await this.#waitForEviction(key);
61
+ this.#throwIfCancelled(request);
62
+ if (pending.invalidated === "clear") throw this.#clearError();
63
+ continue;
64
+ }
65
+ this.#throwIfCancelled(request);
66
+ if (this.#pending.get(key) === pending) this.#pending.delete(key);
67
+ this.#connections.set(key, connection);
68
+ return connection;
69
+ }
70
+ } finally {
71
+ if (request && key) this.#finishRequest(key, request);
72
+ }
73
+ }
74
+ async evict(key, close, invalidation = "evict") {
75
+ const previous = this.#evictions.get(key);
76
+ const state = previous?.state ?? {
77
+ invalidated: /* @__PURE__ */ new Set(),
78
+ invalidation
79
+ };
80
+ if (invalidation === "clear") {
81
+ state.invalidation = "clear";
82
+ for (const pending of state.invalidated) pending.invalidated = "clear";
83
+ }
84
+ const eviction = (previous?.promise ?? Promise.resolve()).then(async () => {
85
+ const resources = new Set(this.#failedClosures.get(key)?.resources ?? []);
86
+ this.#failedClosures.delete(key);
87
+ const cached = this.#connections.get(key);
88
+ this.#connections.delete(key);
89
+ if (cached) resources.add(cached);
90
+ const pending = this.#pending.get(key);
91
+ this.#pending.delete(key);
92
+ if (pending) {
93
+ state.invalidated.add(pending);
94
+ pending.invalidated = state.invalidation;
95
+ const initialized = await pending.promise.catch(() => void 0);
96
+ if (initialized !== void 0) resources.add(initialized);
97
+ }
98
+ const closeResults = await Promise.allSettled([...resources].map(async (resource) => {
99
+ await close(resource);
100
+ return resource;
101
+ }));
102
+ const failures = closeResults.filter((result) => result.status === "rejected");
103
+ if (failures.length) {
104
+ const resourceList = [...resources];
105
+ const failedResources = /* @__PURE__ */ new Set();
106
+ closeResults.forEach((result, index) => {
107
+ if (result.status === "rejected") failedResources.add(resourceList[index]);
108
+ });
109
+ const error = failures.length === 1 ? failures[0].reason : new AggregateError(failures.map((failure) => failure.reason), "Multiple database connections failed to close");
110
+ this.#failedClosures.set(key, {
111
+ error,
112
+ resources: failedResources
113
+ });
114
+ throw error;
115
+ }
116
+ });
117
+ const chain = {
118
+ promise: eviction,
119
+ state
120
+ };
121
+ this.#evictions.set(key, chain);
122
+ try {
123
+ await eviction;
124
+ } finally {
125
+ if (this.#evictions.get(key) === chain) this.#evictions.delete(key);
126
+ }
127
+ }
128
+ async clear(close) {
129
+ const keys = /* @__PURE__ */ new Set([
130
+ ...this.#connections.keys(),
131
+ ...this.#pending.keys(),
132
+ ...this.#evictions.keys(),
133
+ ...this.#requests.keys(),
134
+ ...this.#clearing.keys(),
135
+ ...this.#failedClosures.keys()
136
+ ]);
137
+ const failures = (await Promise.allSettled([...keys].map((key) => this.#clearKey(key, close)))).filter((result) => result.status === "rejected");
138
+ if (failures.length === 1) throw failures[0].reason;
139
+ if (failures.length > 1) throw new AggregateError(failures.map((failure) => failure.reason), "Multiple database connection cache entries failed to clear");
140
+ }
141
+ forget(connection) {
142
+ for (const [key, cached] of this.#connections) if (cached === connection) this.#connections.delete(key);
143
+ }
144
+ /** @internal Test-only visibility; includes every retained namespace. */
145
+ get size() {
146
+ return this.#connections.size + this.#pending.size + this.#evictions.size + this.#requests.size + this.#clearing.size + this.#failedClosures.size;
147
+ }
148
+ async #clearKey(key, close) {
149
+ this.#clearing.set(key, (this.#clearing.get(key) ?? 0) + 1);
150
+ try {
151
+ this.#cancelRequests(key);
152
+ await this.evict(key, close, "clear");
153
+ while (this.#requests.get(key)?.size) {
154
+ this.#cancelRequests(key);
155
+ await Promise.all([...this.#requests.get(key) ?? []].map((request) => request.done));
156
+ }
157
+ } finally {
158
+ const remaining = (this.#clearing.get(key) ?? 1) - 1;
159
+ if (remaining === 0) this.#clearing.delete(key);
160
+ else this.#clearing.set(key, remaining);
161
+ }
162
+ }
163
+ #cancelRequests(key) {
164
+ for (const request of this.#requests.get(key) ?? []) request.cancelled = true;
165
+ }
166
+ #clearError() {
167
+ return /* @__PURE__ */ new Error("Database connection initialization was cancelled by cache clear");
168
+ }
169
+ #finishRequest(key, request) {
170
+ const requests = this.#requests.get(key);
171
+ requests?.delete(request);
172
+ if (requests?.size === 0) this.#requests.delete(key);
173
+ request.finish();
174
+ }
175
+ #registerRequest(key) {
176
+ let finish = () => {};
177
+ const done = new Promise((resolve) => {
178
+ finish = resolve;
179
+ });
180
+ const request = {
181
+ cancelled: this.#clearing.has(key),
182
+ done,
183
+ finish
184
+ };
185
+ const requests = this.#requests.get(key) ?? /* @__PURE__ */ new Set();
186
+ requests.add(request);
187
+ this.#requests.set(key, requests);
188
+ return request;
189
+ }
190
+ #throwIfCancelled(request) {
191
+ if (request?.cancelled) throw this.#clearError();
192
+ }
193
+ #throwIfFailedClosure(key) {
194
+ const failure = this.#failedClosures.get(key);
195
+ if (failure) throw failure.error;
196
+ }
197
+ async #waitForEviction(key) {
198
+ while (true) {
199
+ const eviction = this.#evictions.get(key);
200
+ if (!eviction) return;
201
+ await eviction.promise;
202
+ }
203
+ }
204
+ };
205
+ /**
206
+ * Adds cached-resource validation to a shared cache created by an older module.
207
+ *
208
+ * JSON connection caches live on `globalThis`, so a compatible older SDK copy
209
+ * can create the shared object before this module loads. Mutating that object
210
+ * preserves one cache for both module copies while upgrading its four-argument
211
+ * `getOrCreate` method to the current validation contract.
212
+ */
213
+ function enableCachedValidation(cache) {
214
+ if (cache[CACHED_VALIDATION_CAPABILITY]) return cache;
215
+ const legacyGetOrCreate = cache.getOrCreate.bind(cache);
216
+ const legacyClear = cache.clear.bind(cache);
217
+ const locks = /* @__PURE__ */ new Map();
218
+ let clearGeneration = 0;
219
+ let activeClear;
220
+ const runLocked = async (key, work) => {
221
+ const previous = locks.get(key) ?? Promise.resolve();
222
+ let release;
223
+ const current = new Promise((resolve) => {
224
+ release = resolve;
225
+ });
226
+ const chain = previous.then(() => current, () => current);
227
+ locks.set(key, chain);
228
+ await previous.catch(() => {});
229
+ try {
230
+ return await work();
231
+ } finally {
232
+ release();
233
+ if (locks.get(key) === chain) locks.delete(key);
234
+ }
235
+ };
236
+ Object.defineProperty(cache, "getOrCreate", {
237
+ configurable: true,
238
+ value: async (key, options, create, close, validateCached) => {
239
+ if (!key || options.cache === false) return legacyGetOrCreate(key, options, create, close);
240
+ const requestGeneration = clearGeneration;
241
+ const throwIfCleared = () => {
242
+ if (activeClear || requestGeneration !== clearGeneration) throw new Error("Database connection initialization was cancelled by cache clear");
243
+ };
244
+ return runLocked(key, async () => {
245
+ throwIfCleared();
246
+ let requestOptions = options;
247
+ while (true) {
248
+ throwIfCleared();
249
+ const candidate = await legacyGetOrCreate(key, requestOptions, create, close);
250
+ throwIfCleared();
251
+ if (!validateCached) return candidate;
252
+ const isValid = await validateCached(candidate);
253
+ throwIfCleared();
254
+ if (isValid) {
255
+ const confirmed = await legacyGetOrCreate(key, {
256
+ ...requestOptions,
257
+ clearCache: false
258
+ }, create, close);
259
+ throwIfCleared();
260
+ if (confirmed === candidate) return candidate;
261
+ } else await cache.evict(key, close);
262
+ requestOptions = {
263
+ ...options,
264
+ clearCache: false
265
+ };
266
+ }
267
+ });
268
+ },
269
+ writable: true
270
+ });
271
+ Object.defineProperty(cache, "clear", {
272
+ configurable: true,
273
+ value: async (close) => {
274
+ if (activeClear) return activeClear;
275
+ clearGeneration += 1;
276
+ const clearing = (async () => {
277
+ let clearError;
278
+ let clearFailed = false;
279
+ try {
280
+ await legacyClear(close);
281
+ } catch (error) {
282
+ clearFailed = true;
283
+ clearError = error;
284
+ }
285
+ while (locks.size > 0) await Promise.allSettled([...locks.values()]);
286
+ if (clearFailed) throw clearError;
287
+ })();
288
+ activeClear = clearing;
289
+ try {
290
+ await clearing;
291
+ } finally {
292
+ if (activeClear === clearing) activeClear = void 0;
293
+ }
294
+ },
295
+ writable: true
296
+ });
297
+ Object.defineProperty(cache, CACHED_VALIDATION_CAPABILITY, {
298
+ configurable: false,
299
+ enumerable: false,
300
+ value: true,
301
+ writable: false
302
+ });
303
+ return cache;
304
+ }
305
+ function validateDatabaseCacheOptions(options) {
306
+ if (options.dbid === "") throw new Error("Database cache dbid must be a non-empty string");
307
+ }
308
+ //#endregion
309
+ //#region src/shared/reopen.ts
310
+ /**
311
+ * A `reopenOptions` for engines that allow one owner per database: it refuses
312
+ * with {@link ReopenNotSupportedError}.
313
+ */
314
+ function refuseReopen(engine, reason) {
315
+ return () => {
316
+ throw new ReopenNotSupportedError(engine, reason);
317
+ };
318
+ }
319
+ //#endregion
320
+ //#region src/shared/transaction-lock.ts
321
+ /**
322
+ * How long a queued transaction waits for the connection before giving up.
323
+ *
324
+ * A transaction that legitimately runs longer than this will make the ones
325
+ * behind it fail rather than stall indefinitely. Raise it with the adapter's
326
+ * `transactionQueueTimeout` option if that is the wrong trade for a workload.
327
+ */
328
+ var DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS = 3e4;
329
+ /**
330
+ * Creates a lock that serializes transactions on one connection.
331
+ *
332
+ * SQLite, DuckDB and the JSON adapter each drive a single connection, and a
333
+ * connection can only be in one transaction at a time. `transaction()` used to
334
+ * issue `BEGIN` on that shared connection with no serialization and no record
335
+ * of whether one was already open, so two overlapping calls corrupted each
336
+ * other: the second `BEGIN` threw, its `catch` ran `ROLLBACK`, and that
337
+ * rollback landed on the *first* transaction — committing part of its work,
338
+ * discarding the rest, and rejecting its promise. Nesting was not required;
339
+ * two concurrent requests were enough, which made it reachable from any server
340
+ * handling more than one at a time.
341
+ *
342
+ * The lock spans the whole `BEGIN` … `COMMIT`/`ROLLBACK` sequence, so a queued
343
+ * transaction starts only once the previous one has ended. It is a
344
+ * promise-chain mutex, the same shape as the `withNullAwareUpsertLock` the
345
+ * SQLite adapter already used for the narrower upsert case.
346
+ *
347
+ * Re-entrant calls must not come through here. A nested `tx.transaction()`
348
+ * arrives via the transaction-scoped interface, which re-enters under a
349
+ * `SAVEPOINT` (SQLite) or refuses (DuckDB, JSON) without ever reaching the
350
+ * top-level `transaction()`; routing one here instead would make it wait on a
351
+ * lock its own caller is holding.
352
+ *
353
+ * @param adapter - Adapter name, for the timeout error
354
+ * @param timeoutMs - Ceiling on how long to wait for a turn
355
+ */
356
+ function createTransactionLock(adapter, timeoutMs = DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS) {
357
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new DatabaseError("transactionQueueTimeout must be a positive, finite number of milliseconds", {
358
+ adapter,
359
+ timeoutMs
360
+ });
361
+ let tail = Promise.resolve();
362
+ let held = false;
363
+ const acquire = async () => {
364
+ const previous = tail;
365
+ let release = () => {};
366
+ const current = new Promise((resolve) => {
367
+ release = resolve;
368
+ });
369
+ tail = previous.then(() => current, () => current);
370
+ let timer;
371
+ try {
372
+ await new Promise((resolve, reject) => {
373
+ timer = setTimeout(() => {
374
+ reject(new DatabaseError(`Timed out after ${timeoutMs}ms waiting for the ${adapter} connection's current transaction to finish. This connection runs one transaction at a time. Usually one of: a beginTransaction() handle that was never committed or rolled back; a top-level db.* call that opens its own transaction being made inside a transaction callback, which waits on the connection its own caller holds (use the tx-scoped method instead); or simply more queued transactions than transactionQueueTimeout allows for.`, {
375
+ adapter,
376
+ timeoutMs
377
+ }));
378
+ }, timeoutMs);
379
+ previous.then(resolve, resolve);
380
+ });
381
+ } catch (error) {
382
+ release();
383
+ throw error;
384
+ } finally {
385
+ if (timer) clearTimeout(timer);
386
+ }
387
+ let released = false;
388
+ held = true;
389
+ return () => {
390
+ if (released) return;
391
+ released = true;
392
+ held = false;
393
+ release();
394
+ };
395
+ };
396
+ const run = async (work) => {
397
+ const release = await acquire();
398
+ try {
399
+ return await work();
400
+ } finally {
401
+ release();
402
+ }
403
+ };
404
+ return {
405
+ acquire,
406
+ get held() {
407
+ return held;
408
+ },
409
+ run
410
+ };
411
+ }
412
+ //#endregion
413
+ export { enableCachedValidation as a, ConnectionCache as i, createTransactionLock as n, validateDatabaseCacheOptions as o, refuseReopen as r, DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS as t };
414
+
415
+ //# sourceMappingURL=transaction-lock-BX2GJ4ei.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction-lock-BX2GJ4ei.js","names":["#connections","#pending","#evictions","#requests","#clearing","#failedClosures","#registerRequest","#throwIfCancelled","#throwIfFailedClosure","#waitForEviction","#clearError","#finishRequest","#clearKey","#cancelRequests"],"sources":["../../src/shared/connection-cache.ts","../../src/shared/reopen.ts","../../src/shared/transaction-lock.ts"],"sourcesContent":["import type { DatabaseCacheOptions } from './types';\n\nconst CACHED_VALIDATION_CAPABILITY = Symbol.for(\n '@happyvertical/sql/connection-cache-cached-validation/v1',\n);\n\ntype PendingConnection<T> = {\n invalidated: false | 'clear' | 'evict';\n promise: Promise<T>;\n};\n\ntype EvictionChain<T> = {\n promise: Promise<void>;\n state: {\n invalidated: Set<PendingConnection<T>>;\n invalidation: 'clear' | 'evict';\n };\n};\n\ntype CacheRequest = {\n cancelled: boolean;\n done: Promise<void>;\n finish: () => void;\n};\n\n/** Race-safe async resource cache used by database adapters. */\nexport class ConnectionCache<T> {\n readonly [CACHED_VALIDATION_CAPABILITY] = true;\n readonly #connections = new Map<string, T>();\n readonly #pending = new Map<string, PendingConnection<T>>();\n readonly #evictions = new Map<string, EvictionChain<T>>();\n readonly #requests = new Map<string, Set<CacheRequest>>();\n readonly #clearing = new Map<string, number>();\n readonly #failedClosures = new Map<\n string,\n { error: unknown; resources: Set<T> }\n >();\n\n async getOrCreate(\n key: string | undefined,\n options: DatabaseCacheOptions,\n create: () => Promise<T>,\n close: (connection: T) => Promise<void>,\n validateCached?: (connection: T) => Promise<boolean>,\n ): Promise<T> {\n validateDatabaseCacheOptions(options);\n const request =\n key && options.cache !== false ? this.#registerRequest(key) : undefined;\n try {\n this.#throwIfCancelled(request);\n if (key && options.clearCache) {\n await this.evict(key, close);\n this.#throwIfCancelled(request);\n }\n if (key) this.#throwIfFailedClosure(key);\n\n if (!key || options.cache === false) {\n return create();\n }\n\n while (true) {\n if (this.#evictions.has(key)) {\n await this.#waitForEviction(key);\n this.#throwIfCancelled(request);\n }\n this.#throwIfFailedClosure(key);\n\n const cached = this.#connections.get(key);\n if (cached !== undefined) {\n if (!validateCached) return cached;\n\n // Validation may yield while another caller evicts this entry. Only\n // return the resource when it remains this key's live cache entry.\n const isValid = await validateCached(cached);\n this.#throwIfCancelled(request);\n if (\n isValid &&\n this.#connections.get(key) === cached &&\n !this.#evictions.has(key)\n ) {\n return cached;\n }\n if (\n !isValid &&\n this.#connections.get(key) === cached &&\n !this.#evictions.has(key)\n ) {\n await this.evict(key, close);\n this.#throwIfCancelled(request);\n }\n continue;\n }\n\n let pending = this.#pending.get(key);\n if (!pending) {\n this.#throwIfCancelled(request);\n pending = { invalidated: false, promise: create() };\n this.#pending.set(key, pending);\n }\n\n let connection: T;\n try {\n connection = await pending.promise;\n } catch (error) {\n if (this.#pending.get(key) === pending) {\n this.#pending.delete(key);\n }\n throw error;\n }\n\n if (pending.invalidated || this.#evictions.has(key)) {\n if (this.#evictions.has(key)) {\n await this.#waitForEviction(key);\n }\n this.#throwIfCancelled(request);\n if (pending.invalidated === 'clear') {\n throw this.#clearError();\n }\n continue;\n }\n\n this.#throwIfCancelled(request);\n if (this.#pending.get(key) === pending) {\n this.#pending.delete(key);\n }\n this.#connections.set(key, connection);\n return connection;\n }\n } finally {\n if (request && key) {\n this.#finishRequest(key, request);\n }\n }\n }\n\n async evict(\n key: string,\n close: (connection: T) => Promise<void>,\n invalidation: 'clear' | 'evict' = 'evict',\n ) {\n const previous = this.#evictions.get(key);\n const state = previous?.state ?? {\n invalidated: new Set<PendingConnection<T>>(),\n invalidation,\n };\n if (invalidation === 'clear') {\n state.invalidation = 'clear';\n for (const pending of state.invalidated) {\n pending.invalidated = 'clear';\n }\n }\n\n const eviction = (previous?.promise ?? Promise.resolve()).then(async () => {\n const resources = new Set<T>(\n this.#failedClosures.get(key)?.resources ?? [],\n );\n this.#failedClosures.delete(key);\n const cached = this.#connections.get(key);\n this.#connections.delete(key);\n if (cached) resources.add(cached);\n\n const pending = this.#pending.get(key);\n this.#pending.delete(key);\n if (pending) {\n state.invalidated.add(pending);\n pending.invalidated = state.invalidation;\n // The original initializer caller still observes its rejection. For\n // eviction, a stale failure means there is simply no resource to close.\n const initialized = await pending.promise.catch(() => undefined);\n if (initialized !== undefined) resources.add(initialized);\n }\n\n const closeResults = await Promise.allSettled(\n [...resources].map(async (resource) => {\n await close(resource);\n return resource;\n }),\n );\n const failures = closeResults.filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n );\n if (failures.length) {\n const resourceList = [...resources];\n const failedResources = new Set<T>();\n closeResults.forEach((result, index) => {\n if (result.status === 'rejected') {\n failedResources.add(resourceList[index]);\n }\n });\n const error =\n failures.length === 1\n ? failures[0].reason\n : new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple database connections failed to close',\n );\n this.#failedClosures.set(key, {\n error,\n resources: failedResources,\n });\n throw error;\n }\n });\n\n const chain = { promise: eviction, state };\n this.#evictions.set(key, chain);\n try {\n await eviction;\n } finally {\n if (this.#evictions.get(key) === chain) {\n this.#evictions.delete(key);\n }\n }\n }\n\n async clear(close: (connection: T) => Promise<void>) {\n const keys = new Set([\n ...this.#connections.keys(),\n ...this.#pending.keys(),\n ...this.#evictions.keys(),\n ...this.#requests.keys(),\n ...this.#clearing.keys(),\n ...this.#failedClosures.keys(),\n ]);\n const results = await Promise.allSettled(\n [...keys].map((key) => this.#clearKey(key, close)),\n );\n const failures = results.filter(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n if (failures.length === 1) throw failures[0].reason;\n if (failures.length > 1) {\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n 'Multiple database connection cache entries failed to clear',\n );\n }\n }\n\n forget(connection: T): void {\n for (const [key, cached] of this.#connections) {\n if (cached === connection) {\n this.#connections.delete(key);\n }\n }\n }\n\n /** @internal Test-only visibility; includes every retained namespace. */\n get size(): number {\n return (\n this.#connections.size +\n this.#pending.size +\n this.#evictions.size +\n this.#requests.size +\n this.#clearing.size +\n this.#failedClosures.size\n );\n }\n\n async #clearKey(key: string, close: (connection: T) => Promise<void>) {\n this.#clearing.set(key, (this.#clearing.get(key) ?? 0) + 1);\n try {\n this.#cancelRequests(key);\n await this.evict(key, close, 'clear');\n while (this.#requests.get(key)?.size) {\n this.#cancelRequests(key);\n await Promise.all(\n [...(this.#requests.get(key) ?? [])].map((request) => request.done),\n );\n }\n } finally {\n const remaining = (this.#clearing.get(key) ?? 1) - 1;\n if (remaining === 0) this.#clearing.delete(key);\n else this.#clearing.set(key, remaining);\n }\n }\n\n #cancelRequests(key: string): void {\n for (const request of this.#requests.get(key) ?? []) {\n request.cancelled = true;\n }\n }\n\n #clearError(): Error {\n return new Error(\n 'Database connection initialization was cancelled by cache clear',\n );\n }\n\n #finishRequest(key: string, request: CacheRequest): void {\n const requests = this.#requests.get(key);\n requests?.delete(request);\n if (requests?.size === 0) this.#requests.delete(key);\n request.finish();\n }\n\n #registerRequest(key: string): CacheRequest {\n let finish = () => {};\n const done = new Promise<void>((resolve) => {\n finish = resolve;\n });\n const request = {\n cancelled: this.#clearing.has(key),\n done,\n finish,\n };\n const requests = this.#requests.get(key) ?? new Set<CacheRequest>();\n requests.add(request);\n this.#requests.set(key, requests);\n return request;\n }\n\n #throwIfCancelled(request: CacheRequest | undefined): void {\n if (request?.cancelled) throw this.#clearError();\n }\n\n #throwIfFailedClosure(key: string): void {\n const failure = this.#failedClosures.get(key);\n if (failure) throw failure.error;\n }\n\n async #waitForEviction(key: string): Promise<void> {\n while (true) {\n const eviction = this.#evictions.get(key);\n if (!eviction) return;\n await eviction.promise;\n }\n }\n}\n\n/**\n * Adds cached-resource validation to a shared cache created by an older module.\n *\n * JSON connection caches live on `globalThis`, so a compatible older SDK copy\n * can create the shared object before this module loads. Mutating that object\n * preserves one cache for both module copies while upgrading its four-argument\n * `getOrCreate` method to the current validation contract.\n */\nexport function enableCachedValidation<T>(\n cache: ConnectionCache<T>,\n): ConnectionCache<T> {\n const compatible = cache as ConnectionCache<T> &\n Record<symbol, boolean | undefined>;\n if (compatible[CACHED_VALIDATION_CAPABILITY]) return cache;\n\n const legacyGetOrCreate = cache.getOrCreate.bind(cache) as (\n key: string | undefined,\n options: DatabaseCacheOptions,\n create: () => Promise<T>,\n close: (connection: T) => Promise<void>,\n ) => Promise<T>;\n const legacyClear = cache.clear.bind(cache);\n const locks = new Map<string, Promise<void>>();\n let clearGeneration = 0;\n let activeClear: Promise<void> | undefined;\n\n const runLocked = async <R>(key: string, work: () => Promise<R>) => {\n const previous = locks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const chain = previous.then(\n () => current,\n () => current,\n );\n locks.set(key, chain);\n await previous.catch(() => {});\n try {\n return await work();\n } finally {\n release();\n if (locks.get(key) === chain) locks.delete(key);\n }\n };\n\n Object.defineProperty(cache, 'getOrCreate', {\n configurable: true,\n value: async (\n key: string | undefined,\n options: DatabaseCacheOptions,\n create: () => Promise<T>,\n close: (connection: T) => Promise<void>,\n validateCached?: (connection: T) => Promise<boolean>,\n ): Promise<T> => {\n if (!key || options.cache === false) {\n return legacyGetOrCreate(key, options, create, close);\n }\n const requestGeneration = clearGeneration;\n const throwIfCleared = () => {\n if (activeClear || requestGeneration !== clearGeneration) {\n throw new Error(\n 'Database connection initialization was cancelled by cache clear',\n );\n }\n };\n\n return runLocked(key, async () => {\n throwIfCleared();\n let requestOptions = options;\n while (true) {\n throwIfCleared();\n const candidate = await legacyGetOrCreate(\n key,\n requestOptions,\n create,\n close,\n );\n throwIfCleared();\n if (!validateCached) return candidate;\n\n const isValid = await validateCached(candidate);\n throwIfCleared();\n if (isValid) {\n // Reacquire under the compatibility lock so an explicit eviction\n // that completed during validation cannot make us return its old\n // resource.\n const confirmed = await legacyGetOrCreate(\n key,\n { ...requestOptions, clearCache: false },\n create,\n close,\n );\n throwIfCleared();\n if (confirmed === candidate) return candidate;\n } else {\n await cache.evict(key, close);\n }\n requestOptions = { ...options, clearCache: false };\n }\n });\n },\n writable: true,\n });\n Object.defineProperty(cache, 'clear', {\n configurable: true,\n value: async (close: (connection: T) => Promise<void>): Promise<void> => {\n if (activeClear) return activeClear;\n\n clearGeneration += 1;\n const clearing = (async () => {\n let clearError: unknown;\n let clearFailed = false;\n try {\n await legacyClear(close);\n } catch (error) {\n clearFailed = true;\n clearError = error;\n }\n while (locks.size > 0) {\n await Promise.allSettled([...locks.values()]);\n }\n if (clearFailed) throw clearError;\n })();\n activeClear = clearing;\n try {\n await clearing;\n } finally {\n if (activeClear === clearing) activeClear = undefined;\n }\n },\n writable: true,\n });\n Object.defineProperty(cache, CACHED_VALIDATION_CAPABILITY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return cache;\n}\n\nexport function validateDatabaseCacheOptions(options: DatabaseCacheOptions) {\n if (options.dbid === '') {\n throw new Error('Database cache dbid must be a non-empty string');\n }\n}\n","import { type DatabaseEngine, ReopenNotSupportedError } from './types';\n\n/**\n * A `reopenOptions` for engines that allow one owner per database: it refuses\n * with {@link ReopenNotSupportedError}.\n */\nexport function refuseReopen(\n engine: DatabaseEngine,\n reason: string,\n): () => never {\n return () => {\n throw new ReopenNotSupportedError(engine, reason);\n };\n}\n","import { DatabaseError } from '@happyvertical/utils';\n\n/**\n * How long a queued transaction waits for the connection before giving up.\n *\n * A transaction that legitimately runs longer than this will make the ones\n * behind it fail rather than stall indefinitely. Raise it with the adapter's\n * `transactionQueueTimeout` option if that is the wrong trade for a workload.\n */\nexport const DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS = 30_000;\n\n/**\n * Serializes transactions on a connection that cannot hold more than one.\n */\nexport interface TransactionLock {\n /** Whether one caller currently owns the connection. */\n readonly held: boolean;\n\n /**\n * Takes the connection and returns the function that gives it back.\n *\n * Calling the returned function more than once is a no-op, so a teardown\n * path that runs twice cannot hand the connection to two callers at once.\n */\n acquire(): Promise<() => void>;\n\n /**\n * Runs `work` with exclusive use of the connection, releasing it however\n * `work` finishes.\n */\n run<T>(work: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Creates a lock that serializes transactions on one connection.\n *\n * SQLite, DuckDB and the JSON adapter each drive a single connection, and a\n * connection can only be in one transaction at a time. `transaction()` used to\n * issue `BEGIN` on that shared connection with no serialization and no record\n * of whether one was already open, so two overlapping calls corrupted each\n * other: the second `BEGIN` threw, its `catch` ran `ROLLBACK`, and that\n * rollback landed on the *first* transaction — committing part of its work,\n * discarding the rest, and rejecting its promise. Nesting was not required;\n * two concurrent requests were enough, which made it reachable from any server\n * handling more than one at a time.\n *\n * The lock spans the whole `BEGIN` … `COMMIT`/`ROLLBACK` sequence, so a queued\n * transaction starts only once the previous one has ended. It is a\n * promise-chain mutex, the same shape as the `withNullAwareUpsertLock` the\n * SQLite adapter already used for the narrower upsert case.\n *\n * Re-entrant calls must not come through here. A nested `tx.transaction()`\n * arrives via the transaction-scoped interface, which re-enters under a\n * `SAVEPOINT` (SQLite) or refuses (DuckDB, JSON) without ever reaching the\n * top-level `transaction()`; routing one here instead would make it wait on a\n * lock its own caller is holding.\n *\n * @param adapter - Adapter name, for the timeout error\n * @param timeoutMs - Ceiling on how long to wait for a turn\n */\nexport function createTransactionLock(\n adapter: string,\n timeoutMs: number = DEFAULT_TRANSACTION_QUEUE_TIMEOUT_MS,\n): TransactionLock {\n // The timer is measured from enqueue, not from when the lock frees, so this\n // bounds the total wait rather than any one holder. A caller that expects\n // sustained bursts on one connection should raise it: a hundred queued\n // 400ms transactions exceed 30s even though none of them is stuck.\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new DatabaseError(\n 'transactionQueueTimeout must be a positive, finite number of milliseconds',\n { adapter, timeoutMs },\n );\n }\n // Resolves when the transaction currently holding the connection ends.\n let tail: Promise<void> = Promise.resolve();\n let held = false;\n\n const acquire = async (): Promise<() => void> => {\n const previous = tail;\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n // Publish our turn before awaiting, so a caller that arrives while we are\n // suspended queues behind us rather than racing us for the connection.\n tail = previous.then(\n () => current,\n () => current,\n );\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await new Promise<void>((resolve, reject) => {\n timer = setTimeout(() => {\n reject(\n new DatabaseError(\n `Timed out after ${timeoutMs}ms waiting for the ${adapter} connection's current transaction to finish. This connection runs one transaction at a time. Usually one of: a beginTransaction() handle that was never committed or rolled back; a top-level db.* call that opens its own transaction being made inside a transaction callback, which waits on the connection its own caller holds (use the tx-scoped method instead); or simply more queued transactions than transactionQueueTimeout allows for.`,\n { adapter, timeoutMs },\n ),\n );\n }, timeoutMs);\n previous.then(resolve, resolve);\n });\n } catch (error) {\n // Drop out of the queue rather than wedge it: `tail` still chains through\n // `current`, so resolving it lets the callers behind us take their turn.\n release();\n throw error;\n } finally {\n if (timer) clearTimeout(timer);\n }\n\n let released = false;\n held = true;\n return () => {\n if (released) return;\n released = true;\n held = false;\n release();\n };\n };\n\n const run = async <T>(work: () => Promise<T>): Promise<T> => {\n const release = await acquire();\n try {\n return await work();\n } finally {\n release();\n }\n };\n\n return {\n acquire,\n get held() {\n return held;\n },\n run,\n };\n}\n"],"mappings":";;;AAEA,IAAM,+BAA+B,OAAO,IAC1C,0DACF;;AAsBA,IAAa,kBAAb,MAAgC;CAC9B,CAAU,gCAAgC;CAC1C,+BAAwB,IAAI,IAAe;CAC3C,2BAAoB,IAAI,IAAkC;CAC1D,6BAAsB,IAAI,IAA8B;CACxD,4BAAqB,IAAI,IAA+B;CACxD,4BAAqB,IAAI,IAAoB;CAC7C,kCAA2B,IAAI,IAG7B;CAEF,MAAM,YACJ,KACA,SACA,QACA,OACA,gBACY;EACZ,6BAA6B,OAAO;EACpC,MAAM,UACJ,OAAO,QAAQ,UAAU,QAAQ,KAAKM,iBAAiB,GAAG,IAA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GACd,WAAW;GACX,OAAO;GACP,QAAQ;EACV;CACF;CAEA,MAAM,MAAM,OAAU,SAAuC;EAC3D,MAAM,UAAU,MAAM,QAAQ;EAC9B,IAAI;GACF,OAAO,MAAM,KAAK;EACpB,UAAU;GACR,QAAQ;EACV;CACF;CAEA,OAAO;EACL;EACA,IAAI,OAAO;GACT,OAAO;EACT;EACA;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -54,7 +54,14 @@ export type { AggregateArithmeticOp, AggregateComparisonOp, AggregateExpression,
54
54
  export { checkExpectedTables, checkRelationship, checkUniqueColumn, type DoctorCheck, type DoctorContext, type DoctorIssue, type DoctorLevel, type DoctorResult, type RelationshipSpec, type RunDoctorOptions, runDoctor, type UniqueColumnSpec, } from "./doctor.js";
55
55
  export { clearConnectionCache } from './json.js';
56
56
  export type { PGliteLike, PGliteOptions } from "./pglite.js";
57
- export { clearPostgresConnectionCache } from './postgres.js';
57
+ /**
58
+ * Clears the PostgreSQL connection cache.
59
+ * Useful for test isolation and reconnection scenarios.
60
+ *
61
+ * The PostgreSQL adapter (and its `pg` driver) loads on first call, so the
62
+ * root entry does not pull the driver in for callers that never use it.
63
+ */
64
+ export declare function clearPostgresConnectionCache(): Promise<void>;
58
65
  export { assertCanExportDatabase, assertCanImportDatabase, type CreateDropOptions, createPostgresDatabase, type DumpOptions, databaseNameFromUrl, dropPostgresDatabase, dumpPostgresDatabase, isLocalDatabaseUrl, type PostgresImportLocalityOptions, type PostgresLocalityOptions, postgresEnvFromUrl, type RestoreOptions, redactDatabaseUrl, restorePostgresDatabase, } from "./postgres-cli.js";
59
66
  export { type AggregateBuildResult, type AggregateFunction, type AggregateSelectExpr, type AggregateSpec, type AggregateTimeBucketUnit, bucketExpr, buildAggregate, buildWhere, convertUniqueIndexesToInlineConstraints, DatabaseSchemaManager, ExpressionError, type ExpressionErrorCode, type ExpressionResultType, escapeSqlValue, formatDbError, type PortableExpression, type RawSqlKey, type RenderExpressionOptions, type RenderExpressionResult, raw, renderExpression, type SchemaInitializationResult, type SqlAdapterType, syncSchema, type TypedDateLiteral, tableExists, validateColumnName, } from './query.js';
60
67
  export type { SecureSqliteWindowsCustody } from './secure-sqlite-client.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAU,CAAC;AAC9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAY,CAAC;AAClD,OAAO,KAAK,EACV,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,aAAa,EACd,MAAM,mBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAU,CAAC;AAE9C;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAC1B,CAAC,eAAe,GAAG;IAAE,IAAI,CAAC,EAAE,UAAU,CAAA;CAAE,CAAC,GACzC,CAAC,aAAa,GAAG;IAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;CAAE,CAAC,GACrC,CAAC,aAAa,GAAG;IAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;CAAE,CAAC,GACrC,CAAC,aAAa,GAAG;IAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;CAAE,CAAC,GACrC,WAAW,CAAC;AAmBhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAsB,WAAW,CAC/B,OAAO,GAAE,kBAAkB,GAAG,aAAa,GAAG,iBAAsB,GACnE,OAAO,CAAC,iBAAiB,CAAC,CAqD5B;AAcD,OAAO,EAAc,GAAG,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtE,YAAY,EACV,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,2BAAwB,CAAC;AAEhC,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,KA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