@happyvertical/sql 0.115.1 → 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.
- package/README.md +38 -0
- package/dist/chunks/{duckdb-aMJ05d68.js → duckdb-ddmnqn5l.js} +9 -3
- package/dist/chunks/duckdb-ddmnqn5l.js.map +1 -0
- package/dist/chunks/postgres-dbGVT9aR.js +610 -0
- package/dist/chunks/postgres-dbGVT9aR.js.map +1 -0
- package/dist/chunks/{postgres-dialect-C8GwYO-9.js → postgres-dialect-uyqX-KB-.js} +76 -458
- package/dist/chunks/postgres-dialect-uyqX-KB-.js.map +1 -0
- package/dist/chunks/{query-CcLSVKOo.js → query-DFAYXNk-.js} +47 -2
- package/dist/chunks/{query-CcLSVKOo.js.map → query-DFAYXNk-.js.map} +1 -1
- package/dist/chunks/{sqlite-DAzuB3Hb.js → sqlite-DQXS8fAo.js} +12 -11
- package/dist/chunks/sqlite-DQXS8fAo.js.map +1 -0
- package/dist/chunks/{sqlite-engine-ByvkAlrK.js → sqlite-engine-DpcUbF-P.js} +2 -2
- package/dist/chunks/{sqlite-engine-ByvkAlrK.js.map → sqlite-engine-DpcUbF-P.js.map} +1 -1
- package/dist/chunks/{sqlite-native-Dj0hF4qn.js → sqlite-native-BJcrl8b4.js} +7 -5
- package/dist/chunks/sqlite-native-BJcrl8b4.js.map +1 -0
- package/dist/chunks/transaction-lock-BX2GJ4ei.js +415 -0
- package/dist/chunks/transaction-lock-BX2GJ4ei.js.map +1 -0
- package/dist/chunks/types-DihIt7ez.js.map +1 -1
- package/dist/doctor.d.ts +30 -5
- package/dist/doctor.d.ts.map +1 -1
- package/dist/duckdb.d.ts.map +1 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +67 -632
- package/dist/index.js.map +1 -1
- package/dist/pglite.d.ts.map +1 -1
- package/dist/pglite.js +4 -6
- package/dist/pglite.js.map +1 -1
- package/dist/postgres.d.ts.map +1 -1
- package/dist/query.js +1 -1
- package/dist/shared/duckdb-schema-utils.d.ts +13 -0
- package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
- package/dist/shared/postgres-dialect.d.ts +16 -1
- package/dist/shared/postgres-dialect.d.ts.map +1 -1
- package/dist/shared/types.d.ts +35 -4
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/sqlite-native.d.ts.map +1 -1
- package/dist/sqlite.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/duckdb-aMJ05d68.js.map +0 -1
- package/dist/chunks/postgres-dialect-C8GwYO-9.js.map +0 -1
- package/dist/chunks/sqlite-DAzuB3Hb.js.map +0 -1
- package/dist/chunks/sqlite-native-Dj0hF4qn.js.map +0 -1
|
@@ -1,415 +1,5 @@
|
|
|
1
|
-
import { D as validateIndexName, E as validateColumnNames, O as validatePlainColumnName, T as validateColumnName, a as buildAdapterWhere, b as quoteLiteralIdentifier, d as rewriteSqlParameters, g as generateCreateIndexStatement, h as generateAddColumnStatement, k as validateTableName,
|
|
1
|
+
import { D as validateIndexName, E as validateColumnNames, O as validatePlainColumnName, T as validateColumnName, a as buildAdapterWhere, b as quoteLiteralIdentifier, d as rewriteSqlParameters, g as generateCreateIndexStatement, h as generateAddColumnStatement, k as validateTableName, p as wrapDatabaseError, s as formatDbError, u as resolveInsertColumns, w as renderIdentifier, x as quotePostgresColumnName } from "./types-DihIt7ez.js";
|
|
2
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
3
|
//#region src/shared/postgres-dialect.ts
|
|
414
4
|
/**
|
|
415
5
|
* PostgreSQL dialect logic shared by every adapter that speaks to a Postgres
|
|
@@ -1247,22 +837,22 @@ function createPostgresDialect(host) {
|
|
|
1247
837
|
/**
|
|
1248
838
|
* Checks if a table exists in the database
|
|
1249
839
|
*
|
|
1250
|
-
* @param tableName - Name of the table to check
|
|
840
|
+
* @param tableName - Name of the table to check; `schema.table` checks that
|
|
841
|
+
* schema, a bare name resolves through the session's `search_path`
|
|
1251
842
|
* @returns Promise resolving to boolean indicating if the table exists
|
|
1252
843
|
*/
|
|
1253
844
|
const tableExists = async (tableName) => {
|
|
845
|
+
const { literal, qualified } = parseRelationName(tableName);
|
|
1254
846
|
return (await executor.query(`SELECT EXISTS (
|
|
1255
847
|
SELECT 1
|
|
1256
|
-
FROM information_schema.tables
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
)
|
|
1265
|
-
)`, [tableName])).rows[0].exists;
|
|
848
|
+
FROM information_schema.tables AS listed
|
|
849
|
+
JOIN pg_catalog.pg_namespace AS namespace
|
|
850
|
+
ON namespace.nspname = listed.table_schema
|
|
851
|
+
JOIN pg_catalog.pg_class AS relation
|
|
852
|
+
ON relation.relnamespace = namespace.oid
|
|
853
|
+
AND relation.relname = listed.table_name
|
|
854
|
+
WHERE relation.oid = ${resolveRegclass("$1", "$2")}
|
|
855
|
+
)`, [literal, qualified])).rows[0].exists;
|
|
1266
856
|
};
|
|
1267
857
|
/**
|
|
1268
858
|
* Synchronizes database schema with provided SQL DDL
|
|
@@ -1410,6 +1000,10 @@ function createPostgresDialect(host) {
|
|
|
1410
1000
|
ox: pluck,
|
|
1411
1001
|
xx: execute,
|
|
1412
1002
|
tableExists,
|
|
1003
|
+
getTableSchema: createGetTableSchema({
|
|
1004
|
+
many,
|
|
1005
|
+
tableExists
|
|
1006
|
+
}),
|
|
1413
1007
|
syncSchema
|
|
1414
1008
|
};
|
|
1415
1009
|
};
|
|
@@ -1470,6 +1064,26 @@ function createPostgresDialect(host) {
|
|
|
1470
1064
|
};
|
|
1471
1065
|
}
|
|
1472
1066
|
/**
|
|
1067
|
+
* Candidate `regclass` texts for a table name that may be schema-qualified.
|
|
1068
|
+
*
|
|
1069
|
+
* `literal` is the whole name as one quoted identifier, which is how a bare
|
|
1070
|
+
* name has always been resolved (through the session's `search_path`) and how a
|
|
1071
|
+
* table whose own name contains a dot is still found. `qualified` is set only
|
|
1072
|
+
* when the name is exactly two plain identifiers joined by a dot
|
|
1073
|
+
* (`schema.table`); it is tried after `literal`, so a literal dotted table wins
|
|
1074
|
+
* over a same-spelled schema-qualified one.
|
|
1075
|
+
*/
|
|
1076
|
+
function parseRelationName(name) {
|
|
1077
|
+
const quote = (identifier) => `"${identifier.replaceAll("\"", "\"\"")}"`;
|
|
1078
|
+
const match = typeof name === "string" ? /^([a-zA-Z_][a-zA-Z0-9_]*)\.([a-zA-Z_][a-zA-Z0-9_]*)$/.exec(name) : null;
|
|
1079
|
+
return {
|
|
1080
|
+
literal: quote(name),
|
|
1081
|
+
qualified: match ? `${quote(match[1])}.${quote(match[2])}` : null
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
/** SQL resolving the two `parseRelationName` candidates bound at `$a`/`$b`. */
|
|
1085
|
+
var resolveRegclass = (a, b) => `COALESCE(pg_catalog.to_regclass(${a}), pg_catalog.to_regclass(${b}))`;
|
|
1086
|
+
/**
|
|
1473
1087
|
* Builds `getTableSchema` on top of a dialect's statement methods.
|
|
1474
1088
|
*/
|
|
1475
1089
|
function createGetTableSchema(methods) {
|
|
@@ -1477,14 +1091,28 @@ function createGetTableSchema(methods) {
|
|
|
1477
1091
|
/**
|
|
1478
1092
|
* Retrieves the schema information for a table
|
|
1479
1093
|
*
|
|
1480
|
-
* @param
|
|
1094
|
+
* @param requested - Table name, optionally `schema.table` qualified
|
|
1481
1095
|
* @returns Promise resolving to table schema info or null if table doesn't exist
|
|
1482
1096
|
* @throws Error if the query fails
|
|
1483
1097
|
*/
|
|
1484
|
-
const getTableSchema = async (
|
|
1485
|
-
|
|
1098
|
+
const getTableSchema = async (requested) => {
|
|
1099
|
+
const relation = parseRelationName(requested);
|
|
1100
|
+
if (relation.qualified === null) validateTableName(requested);
|
|
1486
1101
|
try {
|
|
1487
|
-
if (!await tableExists(
|
|
1102
|
+
if (!await tableExists(requested)) return null;
|
|
1103
|
+
const resolved = await many`
|
|
1104
|
+
SELECT namespace.nspname AS schema_name, relation.relname AS table_name
|
|
1105
|
+
FROM pg_catalog.pg_class AS relation
|
|
1106
|
+
JOIN pg_catalog.pg_namespace AS namespace
|
|
1107
|
+
ON namespace.oid = relation.relnamespace
|
|
1108
|
+
WHERE relation.oid = COALESCE(
|
|
1109
|
+
pg_catalog.to_regclass(${relation.literal}),
|
|
1110
|
+
pg_catalog.to_regclass(${relation.qualified})
|
|
1111
|
+
)
|
|
1112
|
+
`;
|
|
1113
|
+
if (resolved.length === 0) return null;
|
|
1114
|
+
const schemaName = resolved[0].schema_name;
|
|
1115
|
+
const table = resolved[0].table_name;
|
|
1488
1116
|
const columnRows = await many`
|
|
1489
1117
|
SELECT
|
|
1490
1118
|
column_name,
|
|
@@ -1493,13 +1121,7 @@ function createGetTableSchema(methods) {
|
|
|
1493
1121
|
column_default
|
|
1494
1122
|
FROM information_schema.columns
|
|
1495
1123
|
WHERE table_name = ${table}
|
|
1496
|
-
AND table_schema =
|
|
1497
|
-
SELECT namespace.nspname
|
|
1498
|
-
FROM pg_catalog.pg_class AS relation
|
|
1499
|
-
JOIN pg_catalog.pg_namespace AS namespace
|
|
1500
|
-
ON namespace.oid = relation.relnamespace
|
|
1501
|
-
WHERE relation.oid = pg_catalog.to_regclass(pg_catalog.quote_ident(${table}))
|
|
1502
|
-
)
|
|
1124
|
+
AND table_schema = ${schemaName}
|
|
1503
1125
|
ORDER BY ordinal_position
|
|
1504
1126
|
`;
|
|
1505
1127
|
const pkRows = await many`
|
|
@@ -1509,20 +1131,28 @@ function createGetTableSchema(methods) {
|
|
|
1509
1131
|
ON tc.constraint_name = kcu.constraint_name
|
|
1510
1132
|
AND tc.table_schema = kcu.table_schema
|
|
1511
1133
|
WHERE tc.table_name = ${table}
|
|
1512
|
-
AND tc.table_schema =
|
|
1513
|
-
SELECT namespace.nspname
|
|
1514
|
-
FROM pg_catalog.pg_class AS relation
|
|
1515
|
-
JOIN pg_catalog.pg_namespace AS namespace
|
|
1516
|
-
ON namespace.oid = relation.relnamespace
|
|
1517
|
-
WHERE relation.oid = pg_catalog.to_regclass(pg_catalog.quote_ident(${table}))
|
|
1518
|
-
)
|
|
1134
|
+
AND tc.table_schema = ${schemaName}
|
|
1519
1135
|
AND tc.constraint_type = 'PRIMARY KEY'
|
|
1520
1136
|
`;
|
|
1521
1137
|
const pkColumns = new Set(pkRows.map((row) => row.column_name));
|
|
1138
|
+
const generatedRows = await many`
|
|
1139
|
+
SELECT attribute.attname AS column_name
|
|
1140
|
+
FROM pg_catalog.pg_attribute AS attribute
|
|
1141
|
+
WHERE attribute.attrelid = COALESCE(
|
|
1142
|
+
pg_catalog.to_regclass(${relation.literal}),
|
|
1143
|
+
pg_catalog.to_regclass(${relation.qualified})
|
|
1144
|
+
)
|
|
1145
|
+
AND attribute.attnum > 0
|
|
1146
|
+
AND NOT attribute.attisdropped
|
|
1147
|
+
AND attribute.attgenerated::text <> ''
|
|
1148
|
+
`;
|
|
1149
|
+
const generatedColumns = new Set(generatedRows.map((row) => row.column_name));
|
|
1522
1150
|
const columns = {};
|
|
1523
1151
|
for (const row of columnRows) {
|
|
1524
1152
|
const colName = row.column_name;
|
|
1525
1153
|
columns[colName] = {
|
|
1154
|
+
generated: generatedColumns.has(colName),
|
|
1155
|
+
hidden: false,
|
|
1526
1156
|
type: row.data_type,
|
|
1527
1157
|
primaryKey: pkColumns.has(colName),
|
|
1528
1158
|
notNull: row.is_nullable === "NO",
|
|
@@ -1535,13 +1165,7 @@ function createGetTableSchema(methods) {
|
|
|
1535
1165
|
indexdef
|
|
1536
1166
|
FROM pg_indexes
|
|
1537
1167
|
WHERE tablename = ${table}
|
|
1538
|
-
AND schemaname =
|
|
1539
|
-
SELECT namespace.nspname
|
|
1540
|
-
FROM pg_catalog.pg_class AS relation
|
|
1541
|
-
JOIN pg_catalog.pg_namespace AS namespace
|
|
1542
|
-
ON namespace.oid = relation.relnamespace
|
|
1543
|
-
WHERE relation.oid = pg_catalog.to_regclass(pg_catalog.quote_ident(${table}))
|
|
1544
|
-
)
|
|
1168
|
+
AND schemaname = ${schemaName}
|
|
1545
1169
|
AND indexname NOT LIKE '%_pkey'
|
|
1546
1170
|
`;
|
|
1547
1171
|
const indexes = [];
|
|
@@ -1576,13 +1200,7 @@ function createGetTableSchema(methods) {
|
|
|
1576
1200
|
AND rc.constraint_schema = tc.table_schema
|
|
1577
1201
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
1578
1202
|
AND tc.table_name = ${table}
|
|
1579
|
-
AND tc.table_schema =
|
|
1580
|
-
SELECT namespace.nspname
|
|
1581
|
-
FROM pg_catalog.pg_class AS relation
|
|
1582
|
-
JOIN pg_catalog.pg_namespace AS namespace
|
|
1583
|
-
ON namespace.oid = relation.relnamespace
|
|
1584
|
-
WHERE relation.oid = pg_catalog.to_regclass(pg_catalog.quote_ident(${table}))
|
|
1585
|
-
)
|
|
1203
|
+
AND tc.table_schema = ${schemaName}
|
|
1586
1204
|
`;
|
|
1587
1205
|
const foreignKeys = [];
|
|
1588
1206
|
for (const fkRow of fkRows) foreignKeys.push({
|
|
@@ -1593,14 +1211,14 @@ function createGetTableSchema(methods) {
|
|
|
1593
1211
|
onUpdate: fkRow.update_rule
|
|
1594
1212
|
});
|
|
1595
1213
|
return {
|
|
1596
|
-
tableName:
|
|
1214
|
+
tableName: requested,
|
|
1597
1215
|
columns,
|
|
1598
1216
|
indexes,
|
|
1599
1217
|
foreignKeys
|
|
1600
1218
|
};
|
|
1601
1219
|
} catch (e) {
|
|
1602
1220
|
throw new DatabaseError("Failed to retrieve table schema", {
|
|
1603
|
-
table,
|
|
1221
|
+
table: requested,
|
|
1604
1222
|
originalError: formatDbError(e)
|
|
1605
1223
|
});
|
|
1606
1224
|
}
|
|
@@ -1662,6 +1280,6 @@ function createAlterTable(client) {
|
|
|
1662
1280
|
};
|
|
1663
1281
|
}
|
|
1664
1282
|
//#endregion
|
|
1665
|
-
export {
|
|
1283
|
+
export { normalizePostgresRawQuery as a, createVectorCapabilities as i, createPostgresDialect as n, createTransactionErrorTracker as r, createAlterTable as t };
|
|
1666
1284
|
|
|
1667
|
-
//# sourceMappingURL=postgres-dialect-
|
|
1285
|
+
//# sourceMappingURL=postgres-dialect-uyqX-KB-.js.map
|