@powersync/web 1.35.0 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/index.umd.js +1126 -1231
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +599 -3086
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +860 -868
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +2 -3
  8. package/lib/src/db/PowerSyncDatabase.d.ts +1 -2
  9. package/lib/src/db/PowerSyncDatabase.js +3 -4
  10. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +40 -0
  11. package/lib/src/db/adapters/AsyncWebAdapter.js +69 -0
  12. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  13. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  14. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  15. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  16. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  17. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  18. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  19. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +146 -0
  20. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  21. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  22. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +14 -6
  23. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +66 -39
  24. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +61 -0
  25. package/lib/src/db/adapters/wa-sqlite/vfs.js +91 -0
  26. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  27. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +1 -2
  28. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +2 -3
  29. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  30. package/lib/src/index.d.ts +1 -4
  31. package/lib/src/index.js +1 -4
  32. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  33. package/lib/src/shared/tab_close_signal.js +26 -0
  34. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  35. package/lib/src/worker/db/MultiDatabaseServer.js +86 -0
  36. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  37. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  38. package/lib/src/worker/db/open-worker-database.js +1 -1
  39. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  40. package/lib/src/worker/sync/SharedSyncImplementation.js +92 -54
  41. package/lib/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +3 -4
  43. package/src/db/PowerSyncDatabase.ts +3 -3
  44. package/src/db/adapters/AsyncWebAdapter.ts +91 -0
  45. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  46. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  47. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  48. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +201 -0
  49. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +191 -0
  50. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +87 -43
  51. package/src/db/adapters/wa-sqlite/vfs.ts +112 -0
  52. package/src/db/adapters/web-sql-flags.ts +6 -0
  53. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +2 -3
  54. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  55. package/src/index.ts +1 -4
  56. package/src/shared/tab_close_signal.ts +28 -0
  57. package/src/worker/db/MultiDatabaseServer.ts +104 -0
  58. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  59. package/src/worker/db/open-worker-database.ts +3 -3
  60. package/src/worker/sync/SharedSyncImplementation.ts +118 -58
  61. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1878
  62. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  63. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  64. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  65. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  66. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  67. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  68. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  69. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  70. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -401
  71. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  72. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  73. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  74. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  75. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  76. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  77. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  78. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  79. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  80. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  81. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  82. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  83. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  84. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  85. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -490
  86. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  87. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  88. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  89. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  90. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  91. package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
@@ -1,55 +0,0 @@
1
- import { BatchedUpdateNotification, QueryResult } from '@powersync/common';
2
- import { ResolvedWebSQLOpenOptions } from './web-sql-flags.js';
3
-
4
- /**
5
- * @internal
6
- * Proxied query result does not contain a function for accessing row values
7
- */
8
- export type ProxiedQueryResult = Omit<QueryResult, 'rows'> & {
9
- rows: {
10
- _array: any[];
11
- length: number;
12
- };
13
- };
14
-
15
- /**
16
- * @internal
17
- */
18
- export type OnTableChangeCallback = (event: BatchedUpdateNotification) => void;
19
-
20
- /**
21
- * @internal
22
- * An async Database connection which provides basic async SQL methods.
23
- * This is usually a proxied through a web worker.
24
- */
25
- export interface AsyncDatabaseConnection<Config extends ResolvedWebSQLOpenOptions = ResolvedWebSQLOpenOptions> {
26
- init(): Promise<void>;
27
- close(): Promise<void>;
28
- /**
29
- * Marks the connection as in-use by a certain actor.
30
- * @returns A hold ID which can be used to release the hold.
31
- */
32
- markHold(): Promise<string>;
33
- /**
34
- * Releases a hold on the connection.
35
- * @param holdId The hold ID to release.
36
- */
37
- releaseHold(holdId: string): Promise<void>;
38
- /**
39
- * Checks if the database connection is in autocommit mode.
40
- * @returns true if in autocommit mode, false if in a transaction
41
- */
42
- isAutoCommit(): Promise<boolean>;
43
- execute(sql: string, params?: any[]): Promise<ProxiedQueryResult>;
44
- executeRaw(sql: string, params?: any[]): Promise<any[][]>;
45
- executeBatch(sql: string, params?: any[]): Promise<ProxiedQueryResult>;
46
- registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void>;
47
- getConfig(): Promise<Config>;
48
- }
49
-
50
- /**
51
- * @internal
52
- */
53
- export type OpenAsyncDatabaseConnection<Config extends ResolvedWebSQLOpenOptions = ResolvedWebSQLOpenOptions> = (
54
- config: Config
55
- ) => AsyncDatabaseConnection;
@@ -1,490 +0,0 @@
1
- import {
2
- BaseObserver,
3
- ConnectionClosedError,
4
- DBAdapter,
5
- DBAdapterListener,
6
- DBGetUtils,
7
- DBLockOptions,
8
- LockContext,
9
- QueryResult,
10
- Transaction,
11
- createLogger,
12
- type ILogger
13
- } from '@powersync/common';
14
- import { getNavigatorLocks } from '../../shared/navigator.js';
15
- import { AsyncDatabaseConnection } from './AsyncDatabaseConnection.js';
16
- import { SharedConnectionWorker, WebDBAdapter, WebDBAdapterConfiguration } from './WebDBAdapter.js';
17
- import { WorkerWrappedAsyncDatabaseConnection } from './WorkerWrappedAsyncDatabaseConnection.js';
18
- import { WASQLiteVFS } from './wa-sqlite/WASQLiteConnection.js';
19
- import { ResolvedWASQLiteOpenFactoryOptions } from './wa-sqlite/WASQLiteOpenFactory.js';
20
- import { ResolvedWebSQLOpenOptions } from './web-sql-flags.js';
21
-
22
- /**
23
- * @internal
24
- */
25
- export interface LockedAsyncDatabaseAdapterOptions {
26
- name: string;
27
- openConnection: () => Promise<AsyncDatabaseConnection>;
28
- debugMode?: boolean;
29
- logger?: ILogger;
30
- defaultLockTimeoutMs?: number;
31
- reOpenOnConnectionClosed?: boolean;
32
- }
33
-
34
- export type LockedAsyncDatabaseAdapterListener = DBAdapterListener & {
35
- initialized?: () => void;
36
- /**
37
- * Fired when the database is re-opened after being closed.
38
- */
39
- databaseReOpened?: () => void;
40
- };
41
-
42
- /**
43
- * @internal
44
- * Wraps a {@link AsyncDatabaseConnection} and provides exclusive locking functions in
45
- * order to implement {@link DBAdapter}.
46
- */
47
- export class LockedAsyncDatabaseAdapter
48
- extends BaseObserver<LockedAsyncDatabaseAdapterListener>
49
- implements WebDBAdapter
50
- {
51
- private logger: ILogger;
52
- private dbGetHelpers: DBGetUtils | null;
53
- private debugMode: boolean;
54
- private _dbIdentifier: string;
55
- protected initPromise: Promise<void>;
56
- private _db: AsyncDatabaseConnection | null = null;
57
- protected _disposeTableChangeListener: (() => void) | null = null;
58
- private _config: ResolvedWebSQLOpenOptions | null = null;
59
- protected pendingAbortControllers: Set<AbortController>;
60
- protected requiresHolds: boolean | null;
61
- protected databaseOpenPromise: Promise<void> | null = null;
62
-
63
- closing: boolean;
64
- closed: boolean;
65
-
66
- constructor(protected options: LockedAsyncDatabaseAdapterOptions) {
67
- super();
68
- this._dbIdentifier = options.name;
69
- this.logger = options.logger ?? createLogger(`LockedAsyncDatabaseAdapter - ${this._dbIdentifier}`);
70
- this.pendingAbortControllers = new Set<AbortController>();
71
- this.closed = false;
72
- this.closing = false;
73
- this.requiresHolds = null;
74
- // Set the name if provided. We can query for the name if not available yet
75
- this.debugMode = options.debugMode ?? false;
76
- if (this.debugMode) {
77
- const originalExecute = this._execute.bind(this);
78
- this._execute = async (sql, bindings) => {
79
- const start = performance.now();
80
- try {
81
- const r = await originalExecute(sql, bindings);
82
- performance.measure(`[SQL] ${sql}`, { start });
83
- return r;
84
- } catch (e: any) {
85
- performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });
86
- throw e;
87
- }
88
- };
89
- }
90
-
91
- this.dbGetHelpers = this.generateDBHelpers({
92
- execute: (query, params) => this.acquireLock(() => this._execute(query, params)),
93
- executeRaw: (query, params) => this.acquireLock(() => this._executeRaw(query, params))
94
- });
95
- this.initPromise = this._init();
96
- }
97
-
98
- protected get baseDB() {
99
- if (!this._db) {
100
- throw new Error(`Initialization has not completed yet. Cannot access base db`);
101
- }
102
- return this._db;
103
- }
104
-
105
- get name() {
106
- return this._dbIdentifier;
107
- }
108
-
109
- /**
110
- * Init is automatic, this helps catch errors or explicitly await initialization
111
- */
112
- async init() {
113
- return this.initPromise;
114
- }
115
-
116
- protected async openInternalDB() {
117
- /**
118
- * Execute opening of the db in a lock in order not to interfere with other operations.
119
- */
120
- return this._acquireLock(async () => {
121
- // Dispose any previous table change listener.
122
- this._disposeTableChangeListener?.();
123
- this._disposeTableChangeListener = null;
124
- this._db?.close().catch((ex) => this.logger.warn(`Error closing database before opening new instance`, ex));
125
- const isReOpen = !!this._db;
126
- this._db = null;
127
-
128
- this._db = await this.options.openConnection();
129
- await this._db.init();
130
- this._config = await this._db.getConfig();
131
- await this.registerOnChangeListener(this._db);
132
- if (isReOpen) {
133
- this.iterateListeners((cb) => cb.databaseReOpened?.());
134
- }
135
- /**
136
- * This is only required for the long-lived shared IndexedDB connections.
137
- */
138
- this.requiresHolds = (this._config as ResolvedWASQLiteOpenFactoryOptions).vfs == WASQLiteVFS.IDBBatchAtomicVFS;
139
- });
140
- }
141
-
142
- protected _reOpen() {
143
- this.databaseOpenPromise = this.openInternalDB().finally(() => {
144
- this.databaseOpenPromise = null;
145
- });
146
- return this.databaseOpenPromise;
147
- }
148
-
149
- /**
150
- * Re-opens the underlying database.
151
- * Returns a pending operation if one is already in progress.
152
- */
153
- async reOpenInternalDB(): Promise<void> {
154
- if (this.closing || !this.options.reOpenOnConnectionClosed) {
155
- // No-op
156
- return;
157
- } else if (this.databaseOpenPromise) {
158
- // Already busy opening
159
- return this.databaseOpenPromise;
160
- } else {
161
- return this._reOpen();
162
- }
163
- }
164
-
165
- protected async _init() {
166
- /**
167
- * For OPFS, we can see this open call sometimes fail due to NoModificationAllowedError.
168
- * We should be able to recover from this by re-opening the database.
169
- */
170
- const maxAttempts = 3;
171
- for (let count = 0; count < maxAttempts; count++) {
172
- try {
173
- await this.openInternalDB();
174
- break;
175
- } catch (ex) {
176
- if (count == maxAttempts - 1) {
177
- throw ex;
178
- }
179
- this.logger.warn(`Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`, ex);
180
- await new Promise((resolve) => setTimeout(resolve, 1000));
181
- }
182
- }
183
- this.iterateListeners((cb) => cb.initialized?.());
184
- }
185
-
186
- getConfiguration(): WebDBAdapterConfiguration {
187
- if (!this._config) {
188
- throw new Error(`Cannot get config before initialization is completed`);
189
- }
190
- return {
191
- ...this._config,
192
- // This can be overridden by the adapter later
193
- requiresPersistentTriggers: false
194
- };
195
- }
196
-
197
- protected async waitForInitialized() {
198
- // Awaiting this will expose errors on function calls like .execute etc
199
- await this.initPromise;
200
- }
201
-
202
- async shareConnection(): Promise<SharedConnectionWorker> {
203
- if (false == this._db instanceof WorkerWrappedAsyncDatabaseConnection) {
204
- throw new Error(`Only worker connections can be shared`);
205
- }
206
- return (this._db as WorkerWrappedAsyncDatabaseConnection).shareConnection();
207
- }
208
-
209
- /**
210
- * Registers a table change notification callback with the base database.
211
- * This can be extended by custom implementations in order to handle proxy events.
212
- */
213
- protected async registerOnChangeListener(db: AsyncDatabaseConnection) {
214
- this._disposeTableChangeListener = await db.registerOnTableChange((event) => {
215
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
216
- });
217
- }
218
-
219
- /**
220
- * This is currently a no-op on web
221
- */
222
- async refreshSchema(): Promise<void> {}
223
-
224
- async execute(query: string, params?: any[] | undefined): Promise<QueryResult> {
225
- return this.writeLock((ctx) => ctx.execute(query, params));
226
- }
227
-
228
- async executeRaw(query: string, params?: any[] | undefined): Promise<any[][]> {
229
- return this.writeLock((ctx) => ctx.executeRaw(query, params));
230
- }
231
-
232
- async executeBatch(query: string, params?: any[][]): Promise<QueryResult> {
233
- return this.writeLock((ctx) => this._executeBatch(query, params));
234
- }
235
-
236
- /**
237
- * Attempts to close the connection.
238
- * Shared workers might not actually close the connection if other
239
- * tabs are still using it.
240
- */
241
- async close() {
242
- this.closing = true;
243
- /**
244
- * Note that we obtain a reference to the callback to avoid calling the callback with `this` as the context.
245
- * This is to avoid Comlink attempting to clone `this` when calling the method.
246
- */
247
- const dispose = this._disposeTableChangeListener;
248
- if (dispose) {
249
- dispose();
250
- }
251
- this.pendingAbortControllers.forEach((controller) => controller.abort('Closed'));
252
- await this.baseDB?.close?.();
253
- this.closed = true;
254
- }
255
-
256
- async getAll<T>(sql: string, parameters?: any[] | undefined): Promise<T[]> {
257
- await this.waitForInitialized();
258
- return this.dbGetHelpers!.getAll(sql, parameters);
259
- }
260
-
261
- async getOptional<T>(sql: string, parameters?: any[] | undefined): Promise<T | null> {
262
- await this.waitForInitialized();
263
- return this.dbGetHelpers!.getOptional(sql, parameters);
264
- }
265
-
266
- async get<T>(sql: string, parameters?: any[] | undefined): Promise<T> {
267
- await this.waitForInitialized();
268
- return this.dbGetHelpers!.get(sql, parameters);
269
- }
270
-
271
- async readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
272
- await this.waitForInitialized();
273
- return this.acquireLock(
274
- async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })),
275
- {
276
- timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
277
- }
278
- );
279
- }
280
-
281
- async writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
282
- await this.waitForInitialized();
283
- return this.acquireLock(
284
- async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })),
285
- {
286
- timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
287
- }
288
- );
289
- }
290
-
291
- protected async _acquireLock(callback: () => Promise<any>, options?: { timeoutMs?: number }): Promise<any> {
292
- if (this.closing) {
293
- throw new Error(`Cannot acquire lock, the database is closing`);
294
- }
295
- const abortController = new AbortController();
296
- this.pendingAbortControllers.add(abortController);
297
- const { timeoutMs } = options ?? {};
298
-
299
- const timeoutId = timeoutMs
300
- ? setTimeout(() => {
301
- abortController.abort(`Timeout after ${timeoutMs}ms`);
302
- this.pendingAbortControllers.delete(abortController);
303
- }, timeoutMs)
304
- : null;
305
-
306
- return getNavigatorLocks().request(
307
- `db-lock-${this._dbIdentifier}`,
308
- { signal: abortController.signal },
309
- async () => {
310
- this.pendingAbortControllers.delete(abortController);
311
- if (timeoutId) {
312
- clearTimeout(timeoutId);
313
- }
314
- return await callback();
315
- }
316
- );
317
- }
318
-
319
- protected async acquireLock(callback: () => Promise<any>, options?: { timeoutMs?: number }): Promise<any> {
320
- await this.waitForInitialized();
321
-
322
- // The database is being (re)opened in the background. Wait for it here.
323
- if (this.databaseOpenPromise) {
324
- await this.databaseOpenPromise;
325
- } else if (!this._db) {
326
- /**
327
- * The database is not open anymore, we might need to re-open it.
328
- * Typically, _db, can be `null` if we tried to reOpen the database, but failed to succeed in re-opening.
329
- * This can happen when disconnecting the client.
330
- * Note: It is safe to re-enter this method multiple times.
331
- */
332
- await this.reOpenInternalDB();
333
- }
334
-
335
- return this._acquireLock(async () => {
336
- let holdId: string | null = null;
337
- try {
338
- /**
339
- * We can't await this since it uses the same lock as we're in now.
340
- * If there is a pending open, this call will throw.
341
- * If there is no pending open, but there is also no database - the open
342
- * might have failed. We need to re-open the database.
343
- */
344
- if (this.databaseOpenPromise || !this._db) {
345
- throw new ConnectionClosedError('Connection is busy re-opening');
346
- }
347
-
348
- holdId = this.requiresHolds ? await this.baseDB.markHold() : null;
349
- return await callback();
350
- } catch (ex) {
351
- if (ConnectionClosedError.MATCHES(ex)) {
352
- // Immediately re-open the database. We need to miss as little table updates as possible.
353
- // Note, don't await this since it uses the same lock as we're in now.
354
- this.reOpenInternalDB();
355
- }
356
- throw ex;
357
- } finally {
358
- if (holdId) {
359
- await this.baseDB.releaseHold(holdId);
360
- }
361
- }
362
- }, options);
363
- }
364
-
365
- async readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
366
- return this.readLock(this.wrapTransaction(fn));
367
- }
368
-
369
- writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
370
- return this.writeLock(this.wrapTransaction(fn, true));
371
- }
372
-
373
- private generateDBHelpers<
374
- T extends {
375
- execute: (sql: string, params?: any[]) => Promise<QueryResult>;
376
- executeRaw: (sql: string, params?: any[]) => Promise<any[][]>;
377
- }
378
- >(tx: T): T & DBGetUtils {
379
- return {
380
- ...tx,
381
- /**
382
- * Execute a read-only query and return results
383
- */
384
- async getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
385
- const res = await tx.execute(sql, parameters);
386
- return res.rows?._array ?? [];
387
- },
388
-
389
- /**
390
- * Execute a read-only query and return the first result, or null if the ResultSet is empty.
391
- */
392
- async getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
393
- const res = await tx.execute(sql, parameters);
394
- return res.rows?.item(0) ?? null;
395
- },
396
-
397
- /**
398
- * Execute a read-only query and return the first result, error if the ResultSet is empty.
399
- */
400
- async get<T>(sql: string, parameters?: any[]): Promise<T> {
401
- const res = await tx.execute(sql, parameters);
402
- const first = res.rows?.item(0);
403
- if (!first) {
404
- throw new Error('Result set is empty');
405
- }
406
- return first;
407
- }
408
- };
409
- }
410
-
411
- /**
412
- * Wraps a lock context into a transaction context
413
- */
414
- private wrapTransaction<T>(cb: (tx: Transaction) => Promise<T>, write = false) {
415
- return async (tx: LockContext): Promise<T> => {
416
- await this._execute(write ? 'BEGIN EXCLUSIVE' : 'BEGIN');
417
- let finalized = false;
418
- const commit = async (): Promise<QueryResult> => {
419
- if (finalized) {
420
- return { rowsAffected: 0 };
421
- }
422
- finalized = true;
423
- return this._execute('COMMIT');
424
- };
425
-
426
- const rollback = () => {
427
- finalized = true;
428
- return this._execute('ROLLBACK');
429
- };
430
-
431
- try {
432
- const result = await cb({
433
- ...tx,
434
- commit,
435
- rollback
436
- });
437
-
438
- if (!finalized) {
439
- await commit();
440
- }
441
- return result;
442
- } catch (ex) {
443
- this.logger.debug('Caught ex in transaction', ex);
444
- try {
445
- await rollback();
446
- } catch (ex2) {
447
- // In rare cases, a rollback may fail.
448
- // Safe to ignore.
449
- }
450
- throw ex;
451
- }
452
- };
453
- }
454
-
455
- /**
456
- * Wraps the worker execute function, awaiting for it to be available
457
- */
458
- private _execute = async (sql: string, bindings?: any[]): Promise<QueryResult> => {
459
- await this.waitForInitialized();
460
-
461
- const result = await this.baseDB.execute(sql, bindings);
462
- return {
463
- ...result,
464
- rows: {
465
- ...result.rows,
466
- item: (idx: number) => result.rows._array[idx]
467
- }
468
- };
469
- };
470
-
471
- /**
472
- * Wraps the worker executeRaw function, awaiting for it to be available
473
- */
474
- private _executeRaw = async (sql: string, bindings?: any[]): Promise<any[][]> => {
475
- await this.waitForInitialized();
476
- return await this.baseDB.executeRaw(sql, bindings);
477
- };
478
-
479
- /**
480
- * Wraps the worker executeBatch function, awaiting for it to be available
481
- */
482
- private _executeBatch = async (query: string, params?: any[]): Promise<QueryResult> => {
483
- await this.waitForInitialized();
484
- const result = await this.baseDB.executeBatch(query, params);
485
- return {
486
- ...result,
487
- rows: undefined
488
- };
489
- };
490
- }