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