@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.
- package/dist/index.umd.js +1127 -1235
- package/dist/index.umd.js.map +1 -1
- package/dist/worker/SharedSyncImplementation.umd.js +481 -3111
- package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
- package/dist/worker/WASQLiteDB.umd.js +688 -836
- package/dist/worker/WASQLiteDB.umd.js.map +1 -1
- package/lib/package.json +2 -3
- package/lib/src/db/PowerSyncDatabase.d.ts +1 -2
- package/lib/src/db/PowerSyncDatabase.js +3 -4
- package/lib/src/db/adapters/AsyncWebAdapter.d.ts +40 -0
- package/lib/src/db/adapters/AsyncWebAdapter.js +69 -0
- package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
- package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
- package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
- package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
- package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
- package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
- package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
- package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +146 -0
- package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
- package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +14 -6
- package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +66 -39
- package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +61 -0
- package/lib/src/db/adapters/wa-sqlite/vfs.js +91 -0
- package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
- package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +1 -2
- package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +2 -3
- package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
- package/lib/src/index.d.ts +1 -4
- package/lib/src/index.js +1 -4
- package/lib/src/shared/tab_close_signal.d.ts +11 -0
- package/lib/src/shared/tab_close_signal.js +26 -0
- package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
- package/lib/src/worker/db/MultiDatabaseServer.js +86 -0
- package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
- package/lib/src/worker/db/open-worker-database.d.ts +3 -3
- package/lib/src/worker/db/open-worker-database.js +1 -1
- package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
- package/lib/src/worker/sync/SharedSyncImplementation.js +92 -54
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -4
- package/src/db/PowerSyncDatabase.ts +3 -3
- package/src/db/adapters/AsyncWebAdapter.ts +91 -0
- package/src/db/adapters/SSRDBAdapter.ts +7 -7
- package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
- package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
- package/src/db/adapters/wa-sqlite/DatabaseServer.ts +201 -0
- package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +191 -0
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +87 -43
- package/src/db/adapters/wa-sqlite/vfs.ts +112 -0
- package/src/db/adapters/web-sql-flags.ts +6 -0
- package/src/db/sync/SSRWebStreamingSyncImplementation.ts +2 -3
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
- package/src/index.ts +1 -4
- package/src/shared/tab_close_signal.ts +28 -0
- package/src/worker/db/MultiDatabaseServer.ts +104 -0
- package/src/worker/db/WASQLiteDB.worker.ts +10 -57
- package/src/worker/db/open-worker-database.ts +3 -3
- package/src/worker/sync/SharedSyncImplementation.ts +118 -58
- package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1881
- package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
- package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
- package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
- package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
- package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
- package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
- package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -404
- package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
- package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
- package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
- package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
- package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
- package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
- package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
- package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
- package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
- package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
- package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
- package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
- package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
- package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
- package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -489
- package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
- package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
- package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
- package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
- package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
- package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
|
@@ -1,497 +0,0 @@
|
|
|
1
|
-
import * as SQLite from '@journeyapps/wa-sqlite';
|
|
2
|
-
import { BaseObserver, BatchedUpdateNotification } from '@powersync/common';
|
|
3
|
-
import { Mutex } from 'async-mutex';
|
|
4
|
-
import { AsyncDatabaseConnection, OnTableChangeCallback, ProxiedQueryResult } from '../AsyncDatabaseConnection.js';
|
|
5
|
-
import { ResolvedWASQLiteOpenFactoryOptions } from './WASQLiteOpenFactory.js';
|
|
6
|
-
/**
|
|
7
|
-
* List of currently tested virtual filesystems
|
|
8
|
-
*/
|
|
9
|
-
export enum WASQLiteVFS {
|
|
10
|
-
IDBBatchAtomicVFS = 'IDBBatchAtomicVFS',
|
|
11
|
-
OPFSCoopSyncVFS = 'OPFSCoopSyncVFS',
|
|
12
|
-
AccessHandlePoolVFS = 'AccessHandlePoolVFS'
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* @internal
|
|
17
|
-
*/
|
|
18
|
-
export type WASQLiteBroadCastTableUpdateEvent = {
|
|
19
|
-
changedTables: Set<string>;
|
|
20
|
-
connectionId: number;
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* @internal
|
|
25
|
-
*/
|
|
26
|
-
export type WASQLiteConnectionListener = {
|
|
27
|
-
tablesUpdated: (event: BatchedUpdateNotification) => void;
|
|
28
|
-
/**
|
|
29
|
-
* Triggered when an active hold is overwritten by a new hold.
|
|
30
|
-
* This is most likely to happen when a shared connection has been closed
|
|
31
|
-
* without releasing the hold.
|
|
32
|
-
* This listener can be used to cleanup any resources associated with the previous hold.
|
|
33
|
-
* @param holdId - The id of the hold that has been overwritten.
|
|
34
|
-
*/
|
|
35
|
-
holdOverwritten: (holdId: string) => Promise<void>;
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* @internal
|
|
40
|
-
*/
|
|
41
|
-
export type SQLiteModule = Parameters<typeof SQLite.Factory>[0];
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* @internal
|
|
45
|
-
*/
|
|
46
|
-
export type WASQLiteModuleFactoryOptions = { dbFileName: string; encryptionKey?: string };
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* @internal
|
|
50
|
-
*/
|
|
51
|
-
export type WASQLiteModuleFactory = (
|
|
52
|
-
options: WASQLiteModuleFactoryOptions
|
|
53
|
-
) => Promise<{ module: SQLiteModule; vfs: SQLiteVFS }>;
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* @internal
|
|
57
|
-
*/
|
|
58
|
-
export const AsyncWASQLiteModuleFactory = async () => {
|
|
59
|
-
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
|
|
60
|
-
return factory();
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* @internal
|
|
65
|
-
*/
|
|
66
|
-
export const MultiCipherAsyncWASQLiteModuleFactory = async () => {
|
|
67
|
-
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
|
|
68
|
-
return factory();
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* @internal
|
|
73
|
-
*/
|
|
74
|
-
export const SyncWASQLiteModuleFactory = async () => {
|
|
75
|
-
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');
|
|
76
|
-
return factory();
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* @internal
|
|
81
|
-
*/
|
|
82
|
-
export const MultiCipherSyncWASQLiteModuleFactory = async () => {
|
|
83
|
-
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');
|
|
84
|
-
return factory();
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* @internal
|
|
89
|
-
*/
|
|
90
|
-
export const DEFAULT_MODULE_FACTORIES = {
|
|
91
|
-
[WASQLiteVFS.IDBBatchAtomicVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
92
|
-
let module;
|
|
93
|
-
if (options.encryptionKey) {
|
|
94
|
-
module = await MultiCipherAsyncWASQLiteModuleFactory();
|
|
95
|
-
} else {
|
|
96
|
-
module = await AsyncWASQLiteModuleFactory();
|
|
97
|
-
}
|
|
98
|
-
const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
|
|
99
|
-
return {
|
|
100
|
-
module,
|
|
101
|
-
// @ts-expect-error The types for this static method are missing upstream
|
|
102
|
-
vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
|
|
103
|
-
};
|
|
104
|
-
},
|
|
105
|
-
[WASQLiteVFS.AccessHandlePoolVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
106
|
-
let module;
|
|
107
|
-
if (options.encryptionKey) {
|
|
108
|
-
module = await MultiCipherSyncWASQLiteModuleFactory();
|
|
109
|
-
} else {
|
|
110
|
-
module = await SyncWASQLiteModuleFactory();
|
|
111
|
-
}
|
|
112
|
-
// @ts-expect-error The types for this static method are missing upstream
|
|
113
|
-
const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
|
|
114
|
-
return {
|
|
115
|
-
module,
|
|
116
|
-
vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
|
|
117
|
-
};
|
|
118
|
-
},
|
|
119
|
-
[WASQLiteVFS.OPFSCoopSyncVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
120
|
-
let module;
|
|
121
|
-
if (options.encryptionKey) {
|
|
122
|
-
module = await MultiCipherSyncWASQLiteModuleFactory();
|
|
123
|
-
} else {
|
|
124
|
-
module = await SyncWASQLiteModuleFactory();
|
|
125
|
-
}
|
|
126
|
-
// @ts-expect-error The types for this static method are missing upstream
|
|
127
|
-
const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
|
|
128
|
-
const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
|
|
129
|
-
return {
|
|
130
|
-
module,
|
|
131
|
-
vfs
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* @internal
|
|
138
|
-
* WA-SQLite connection which directly interfaces with WA-SQLite.
|
|
139
|
-
* This is usually instantiated inside a worker.
|
|
140
|
-
*/
|
|
141
|
-
export class WASqliteConnection
|
|
142
|
-
extends BaseObserver<WASQLiteConnectionListener>
|
|
143
|
-
implements AsyncDatabaseConnection<ResolvedWASQLiteOpenFactoryOptions>
|
|
144
|
-
{
|
|
145
|
-
private _sqliteAPI: SQLiteAPI | null = null;
|
|
146
|
-
private _dbP: number | null = null;
|
|
147
|
-
private _moduleFactory: WASQLiteModuleFactory;
|
|
148
|
-
|
|
149
|
-
protected updatedTables: Set<string>;
|
|
150
|
-
protected updateTimer: ReturnType<typeof setTimeout> | null;
|
|
151
|
-
protected statementMutex: Mutex;
|
|
152
|
-
protected broadcastChannel: BroadcastChannel | null;
|
|
153
|
-
/**
|
|
154
|
-
* Unique id for this specific connection. This is used to prevent broadcast table change
|
|
155
|
-
* notification loops.
|
|
156
|
-
*/
|
|
157
|
-
protected connectionId: number;
|
|
158
|
-
|
|
159
|
-
protected _holdCounter: number;
|
|
160
|
-
protected _holdId: string | null;
|
|
161
|
-
|
|
162
|
-
constructor(protected options: ResolvedWASQLiteOpenFactoryOptions) {
|
|
163
|
-
super();
|
|
164
|
-
this.updatedTables = new Set();
|
|
165
|
-
this.updateTimer = null;
|
|
166
|
-
this.broadcastChannel = null;
|
|
167
|
-
this.connectionId = new Date().valueOf() + Math.random();
|
|
168
|
-
this.statementMutex = new Mutex();
|
|
169
|
-
this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
|
|
170
|
-
this._holdCounter = 0;
|
|
171
|
-
this._holdId = null;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Gets the id for the current hold.
|
|
176
|
-
* This can be used to check for invalid states.
|
|
177
|
-
*/
|
|
178
|
-
get currentHoldId() {
|
|
179
|
-
return this._holdId;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
protected get sqliteAPI() {
|
|
183
|
-
if (!this._sqliteAPI) {
|
|
184
|
-
throw new Error(`Initialization has not completed`);
|
|
185
|
-
}
|
|
186
|
-
return this._sqliteAPI;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
protected get dbP() {
|
|
190
|
-
if (!this._dbP) {
|
|
191
|
-
throw new Error(`Initialization has not completed`);
|
|
192
|
-
}
|
|
193
|
-
return this._dbP;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* Checks if the database connection is in autocommit mode.
|
|
198
|
-
* @returns true if in autocommit mode, false if in a transaction
|
|
199
|
-
*/
|
|
200
|
-
async isAutoCommit(): Promise<boolean> {
|
|
201
|
-
return this.sqliteAPI.get_autocommit(this.dbP) != 0;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
async markHold(): Promise<string> {
|
|
205
|
-
const previousHoldId = this._holdId;
|
|
206
|
-
this._holdId = `${++this._holdCounter}`;
|
|
207
|
-
if (previousHoldId) {
|
|
208
|
-
await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));
|
|
209
|
-
}
|
|
210
|
-
return this._holdId;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
async releaseHold(holdId: string): Promise<void> {
|
|
214
|
-
if (holdId != this._holdId) {
|
|
215
|
-
throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
|
|
216
|
-
}
|
|
217
|
-
this._holdId = null;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
protected async openDB() {
|
|
221
|
-
this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
|
|
222
|
-
return this._dbP;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
protected async executeEncryptionPragma(): Promise<void> {
|
|
226
|
-
if (this.options.encryptionKey) {
|
|
227
|
-
await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
|
|
228
|
-
}
|
|
229
|
-
return;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
protected async openSQLiteAPI(): Promise<SQLiteAPI> {
|
|
233
|
-
const { module, vfs } = await this._moduleFactory({
|
|
234
|
-
dbFileName: this.options.dbFilename,
|
|
235
|
-
encryptionKey: this.options.encryptionKey
|
|
236
|
-
});
|
|
237
|
-
const sqlite3 = SQLite.Factory(module);
|
|
238
|
-
sqlite3.vfs_register(vfs, true);
|
|
239
|
-
/**
|
|
240
|
-
* Register the PowerSync core SQLite extension
|
|
241
|
-
*/
|
|
242
|
-
module.ccall('powersync_init_static', 'int', []);
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* Create the multiple cipher vfs if an encryption key is provided
|
|
246
|
-
*/
|
|
247
|
-
if (this.options.encryptionKey) {
|
|
248
|
-
const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
|
|
249
|
-
if (createResult !== 0) {
|
|
250
|
-
throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return sqlite3;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
protected registerBroadcastListeners() {
|
|
258
|
-
this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
|
|
259
|
-
this.broadcastChannel.addEventListener('message', (event) => {
|
|
260
|
-
const data: WASQLiteBroadCastTableUpdateEvent = event.data;
|
|
261
|
-
if (this.connectionId == data.connectionId) {
|
|
262
|
-
// Ignore messages from the same connection
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// Ensuring that we don't rebroadcast the same message
|
|
267
|
-
this.queueTableUpdate(data.changedTables, false);
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
protected queueTableUpdate(tableNames: Set<string>, shouldBroadcast = true) {
|
|
272
|
-
tableNames.forEach((tableName) => this.updatedTables.add(tableName));
|
|
273
|
-
if (this.updateTimer == null) {
|
|
274
|
-
this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
async init() {
|
|
279
|
-
this._sqliteAPI = await this.openSQLiteAPI();
|
|
280
|
-
await this.openDB();
|
|
281
|
-
this.registerBroadcastListeners();
|
|
282
|
-
await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
|
|
283
|
-
await this.executeEncryptionPragma();
|
|
284
|
-
await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
|
|
285
|
-
|
|
286
|
-
this.sqliteAPI.update_hook(this.dbP, (updateType: number, dbName: string | null, tableName: string | null) => {
|
|
287
|
-
if (!tableName) {
|
|
288
|
-
return;
|
|
289
|
-
}
|
|
290
|
-
const changedTables = new Set([tableName]);
|
|
291
|
-
this.queueTableUpdate(changedTables);
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
async getConfig(): Promise<ResolvedWASQLiteOpenFactoryOptions> {
|
|
296
|
-
return this.options;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
fireUpdates(shouldBroadcast = true) {
|
|
300
|
-
this.updateTimer = null;
|
|
301
|
-
const event: BatchedUpdateNotification = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
|
|
302
|
-
// Share to other connections
|
|
303
|
-
if (shouldBroadcast) {
|
|
304
|
-
this.broadcastChannel!.postMessage({
|
|
305
|
-
changedTables: this.updatedTables,
|
|
306
|
-
connectionId: this.connectionId
|
|
307
|
-
} satisfies WASQLiteBroadCastTableUpdateEvent);
|
|
308
|
-
}
|
|
309
|
-
this.updatedTables.clear();
|
|
310
|
-
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* This executes SQL statements in a batch.
|
|
315
|
-
*/
|
|
316
|
-
async executeBatch(sql: string, bindings?: any[][]): Promise<ProxiedQueryResult> {
|
|
317
|
-
return this.acquireExecuteLock(async (): Promise<ProxiedQueryResult> => {
|
|
318
|
-
let affectedRows = 0;
|
|
319
|
-
|
|
320
|
-
try {
|
|
321
|
-
await this.executeSingleStatement('BEGIN TRANSACTION');
|
|
322
|
-
|
|
323
|
-
const wrappedBindings = bindings ? bindings : [];
|
|
324
|
-
for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
|
|
325
|
-
if (stmt === null) {
|
|
326
|
-
return {
|
|
327
|
-
rowsAffected: 0,
|
|
328
|
-
rows: { _array: [], length: 0 }
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
//Prepare statement once
|
|
333
|
-
for (const binding of wrappedBindings) {
|
|
334
|
-
// TODO not sure why this is needed currently, but booleans break
|
|
335
|
-
for (let i = 0; i < binding.length; i++) {
|
|
336
|
-
const b = binding[i];
|
|
337
|
-
if (typeof b == 'boolean') {
|
|
338
|
-
binding[i] = b ? 1 : 0;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
if (bindings) {
|
|
343
|
-
this.sqliteAPI.bind_collection(stmt, binding);
|
|
344
|
-
}
|
|
345
|
-
const result = await this.sqliteAPI.step(stmt);
|
|
346
|
-
if (result === SQLite.SQLITE_DONE) {
|
|
347
|
-
//The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
|
|
348
|
-
affectedRows += this.sqliteAPI.changes(this.dbP);
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
this.sqliteAPI.reset(stmt);
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
await this.executeSingleStatement('COMMIT');
|
|
356
|
-
} catch (err) {
|
|
357
|
-
await this.executeSingleStatement('ROLLBACK');
|
|
358
|
-
return {
|
|
359
|
-
rowsAffected: 0,
|
|
360
|
-
rows: { _array: [], length: 0 }
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
const result = {
|
|
364
|
-
rowsAffected: affectedRows,
|
|
365
|
-
rows: { _array: [], length: 0 }
|
|
366
|
-
};
|
|
367
|
-
|
|
368
|
-
return result;
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* This executes single SQL statements inside a requested lock.
|
|
374
|
-
*/
|
|
375
|
-
async execute(sql: string | TemplateStringsArray, bindings?: any[]): Promise<ProxiedQueryResult> {
|
|
376
|
-
// Running multiple statements on the same connection concurrently should not be allowed
|
|
377
|
-
return this.acquireExecuteLock(async () => {
|
|
378
|
-
return this.executeSingleStatement(sql, bindings);
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
async executeRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]> {
|
|
383
|
-
return this.acquireExecuteLock(async () => {
|
|
384
|
-
return this.executeSingleStatementRaw(sql, bindings);
|
|
385
|
-
});
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
async close() {
|
|
389
|
-
this.broadcastChannel?.close();
|
|
390
|
-
await this.acquireExecuteLock(async () => {
|
|
391
|
-
/**
|
|
392
|
-
* Running the close operation inside the same execute mutex prevents errors like:
|
|
393
|
-
* ```
|
|
394
|
-
* unable to close due to unfinalized statements or unfinished backups
|
|
395
|
-
* ```
|
|
396
|
-
*/
|
|
397
|
-
await this.sqliteAPI.close(this.dbP);
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
async registerOnTableChange(callback: OnTableChangeCallback) {
|
|
402
|
-
return this.registerListener({
|
|
403
|
-
tablesUpdated: (event) => callback(event)
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
/**
|
|
408
|
-
* This requests a lock for executing statements.
|
|
409
|
-
* Should only be used internally.
|
|
410
|
-
*/
|
|
411
|
-
protected acquireExecuteLock = <T>(callback: () => Promise<T>): Promise<T> => {
|
|
412
|
-
return this.statementMutex.runExclusive(callback);
|
|
413
|
-
};
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* This executes a single statement using SQLite3.
|
|
417
|
-
*/
|
|
418
|
-
protected async executeSingleStatement(
|
|
419
|
-
sql: string | TemplateStringsArray,
|
|
420
|
-
bindings?: any[]
|
|
421
|
-
): Promise<ProxiedQueryResult> {
|
|
422
|
-
const results = await this._execute(sql, bindings);
|
|
423
|
-
|
|
424
|
-
const rows: Record<string, any>[] = [];
|
|
425
|
-
for (const resultSet of results) {
|
|
426
|
-
for (const row of resultSet.rows) {
|
|
427
|
-
const outRow: Record<string, any> = {};
|
|
428
|
-
resultSet.columns.forEach((key, index) => {
|
|
429
|
-
outRow[key] = row[index];
|
|
430
|
-
});
|
|
431
|
-
rows.push(outRow);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const result = {
|
|
436
|
-
insertId: this.sqliteAPI.last_insert_id(this.dbP),
|
|
437
|
-
rowsAffected: this.sqliteAPI.changes(this.dbP),
|
|
438
|
-
rows: {
|
|
439
|
-
_array: rows,
|
|
440
|
-
length: rows.length
|
|
441
|
-
}
|
|
442
|
-
};
|
|
443
|
-
|
|
444
|
-
return result;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/**
|
|
448
|
-
* This executes a single statement using SQLite3 and returns the results as an array of arrays.
|
|
449
|
-
*/
|
|
450
|
-
protected async executeSingleStatementRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]> {
|
|
451
|
-
const results = await this._execute(sql, bindings);
|
|
452
|
-
|
|
453
|
-
return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
private async _execute(
|
|
457
|
-
sql: string | TemplateStringsArray,
|
|
458
|
-
bindings?: any[]
|
|
459
|
-
): Promise<{ columns: string[]; rows: SQLiteCompatibleType[][] }[]> {
|
|
460
|
-
const results = [];
|
|
461
|
-
for await (const stmt of this.sqliteAPI.statements(this.dbP, sql as string)) {
|
|
462
|
-
let columns;
|
|
463
|
-
const wrappedBindings = bindings ? [bindings] : [[]];
|
|
464
|
-
for (const binding of wrappedBindings) {
|
|
465
|
-
// TODO not sure why this is needed currently, but booleans break
|
|
466
|
-
binding.forEach((b, index, arr) => {
|
|
467
|
-
if (typeof b == 'boolean') {
|
|
468
|
-
arr[index] = b ? 1 : 0;
|
|
469
|
-
}
|
|
470
|
-
});
|
|
471
|
-
|
|
472
|
-
this.sqliteAPI.reset(stmt);
|
|
473
|
-
if (bindings) {
|
|
474
|
-
this.sqliteAPI.bind_collection(stmt, binding);
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
const rows = [];
|
|
478
|
-
while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {
|
|
479
|
-
const row = this.sqliteAPI.row(stmt);
|
|
480
|
-
rows.push(row);
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
columns = columns ?? this.sqliteAPI.column_names(stmt);
|
|
484
|
-
if (columns.length) {
|
|
485
|
-
results.push({ columns, rows });
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// When binding parameters, only a single statement is executed.
|
|
490
|
-
if (bindings) {
|
|
491
|
-
break;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
return results;
|
|
496
|
-
}
|
|
497
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { type PowerSyncOpenFactoryOptions } from '@powersync/common';
|
|
2
|
-
import * as Comlink from 'comlink';
|
|
3
|
-
import { resolveWebPowerSyncFlags } from '../../PowerSyncDatabase.js';
|
|
4
|
-
import { OpenAsyncDatabaseConnection } from '../AsyncDatabaseConnection.js';
|
|
5
|
-
import {
|
|
6
|
-
DEFAULT_CACHE_SIZE_KB,
|
|
7
|
-
ResolvedWebSQLOpenOptions,
|
|
8
|
-
TemporaryStorageOption,
|
|
9
|
-
WebSQLFlags
|
|
10
|
-
} from '../web-sql-flags.js';
|
|
11
|
-
import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection.js';
|
|
12
|
-
import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
|
|
13
|
-
import { WASQLiteVFS } from './WASQLiteConnection.js';
|
|
14
|
-
import { WASQLiteOpenFactory } from './WASQLiteOpenFactory.js';
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* These flags are the same as {@link WebSQLFlags}.
|
|
18
|
-
* This export is maintained only for API consistency
|
|
19
|
-
*/
|
|
20
|
-
export type WASQLiteFlags = WebSQLFlags;
|
|
21
|
-
|
|
22
|
-
export interface WASQLiteDBAdapterOptions extends Omit<PowerSyncOpenFactoryOptions, 'schema'> {
|
|
23
|
-
flags?: WASQLiteFlags;
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Use an existing port to an initialized worker.
|
|
27
|
-
* A worker will be initialized if none is provided
|
|
28
|
-
*/
|
|
29
|
-
workerPort?: MessagePort;
|
|
30
|
-
|
|
31
|
-
worker?: string | URL | ((options: ResolvedWebSQLOpenOptions) => Worker | SharedWorker);
|
|
32
|
-
|
|
33
|
-
vfs?: WASQLiteVFS;
|
|
34
|
-
temporaryStorage?: TemporaryStorageOption;
|
|
35
|
-
cacheSizeKb?: number;
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Encryption key for the database.
|
|
39
|
-
* If set, the database will be encrypted using multiple-ciphers.
|
|
40
|
-
*/
|
|
41
|
-
encryptionKey?: string;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Adapter for WA-SQLite SQLite connections.
|
|
46
|
-
*/
|
|
47
|
-
export class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
|
|
48
|
-
constructor(options: WASQLiteDBAdapterOptions) {
|
|
49
|
-
super({
|
|
50
|
-
name: options.dbFilename,
|
|
51
|
-
openConnection: async () => {
|
|
52
|
-
const { workerPort, temporaryStorage, cacheSizeKb } = options;
|
|
53
|
-
if (workerPort) {
|
|
54
|
-
const remote = Comlink.wrap<OpenAsyncDatabaseConnection>(workerPort);
|
|
55
|
-
return new WorkerWrappedAsyncDatabaseConnection({
|
|
56
|
-
remote,
|
|
57
|
-
remoteCanCloseUnexpectedly: false,
|
|
58
|
-
identifier: options.dbFilename,
|
|
59
|
-
baseConnection: await remote({
|
|
60
|
-
...options,
|
|
61
|
-
temporaryStorage: temporaryStorage ?? TemporaryStorageOption.MEMORY,
|
|
62
|
-
cacheSizeKb: cacheSizeKb ?? DEFAULT_CACHE_SIZE_KB,
|
|
63
|
-
flags: resolveWebPowerSyncFlags(options.flags),
|
|
64
|
-
encryptionKey: options.encryptionKey
|
|
65
|
-
})
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
const openFactory = new WASQLiteOpenFactory({
|
|
69
|
-
dbFilename: options.dbFilename,
|
|
70
|
-
dbLocation: options.dbLocation,
|
|
71
|
-
debugMode: options.debugMode,
|
|
72
|
-
flags: options.flags,
|
|
73
|
-
temporaryStorage,
|
|
74
|
-
cacheSizeKb,
|
|
75
|
-
logger: options.logger,
|
|
76
|
-
vfs: options.vfs,
|
|
77
|
-
encryptionKey: options.encryptionKey,
|
|
78
|
-
worker: options.worker
|
|
79
|
-
});
|
|
80
|
-
return openFactory.openConnection();
|
|
81
|
-
},
|
|
82
|
-
debugMode: options.debugMode,
|
|
83
|
-
logger: options.logger
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
import { ILogger } from '@powersync/common';
|
|
2
|
-
import {
|
|
3
|
-
AsyncDatabaseConnection,
|
|
4
|
-
OnTableChangeCallback,
|
|
5
|
-
ProxiedQueryResult
|
|
6
|
-
} from '../../db/adapters/AsyncDatabaseConnection.js';
|
|
7
|
-
import { ResolvedWebSQLOpenOptions } from '../../db/adapters/web-sql-flags.js';
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Keeps track of open DB connections and the clients which
|
|
11
|
-
* are using it.
|
|
12
|
-
*/
|
|
13
|
-
export type SharedDBWorkerConnection = {
|
|
14
|
-
clientIds: Set<number>;
|
|
15
|
-
db: AsyncDatabaseConnection;
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
export type SharedWASQLiteConnectionOptions = {
|
|
19
|
-
dbMap: Map<string, SharedDBWorkerConnection>;
|
|
20
|
-
dbFilename: string;
|
|
21
|
-
clientId: number;
|
|
22
|
-
logger: ILogger;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export class SharedWASQLiteConnection implements AsyncDatabaseConnection {
|
|
26
|
-
protected isClosing: boolean;
|
|
27
|
-
// Keeps track if this current hold if the shared connection has a hold
|
|
28
|
-
protected activeHoldId: string | null;
|
|
29
|
-
|
|
30
|
-
constructor(protected options: SharedWASQLiteConnectionOptions) {
|
|
31
|
-
// Add this client ID to the set of known clients
|
|
32
|
-
this.clientIds.add(options.clientId);
|
|
33
|
-
this.isClosing = false;
|
|
34
|
-
this.activeHoldId = null;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
protected get logger() {
|
|
38
|
-
return this.options.logger;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
protected get dbEntry() {
|
|
42
|
-
return this.options.dbMap.get(this.options.dbFilename)!;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
protected get connection() {
|
|
46
|
-
return this.dbEntry.db;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
protected get clientIds() {
|
|
50
|
-
return this.dbEntry.clientIds;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async init(): Promise<void> {
|
|
54
|
-
// No-op since the connection is already initialized when it was created
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async markHold(): Promise<string> {
|
|
58
|
-
this.activeHoldId = await this.connection.markHold();
|
|
59
|
-
return this.activeHoldId;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async releaseHold(id: string): Promise<void> {
|
|
63
|
-
try {
|
|
64
|
-
await this.connection.releaseHold(id);
|
|
65
|
-
} finally {
|
|
66
|
-
this.activeHoldId = null;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async isAutoCommit(): Promise<boolean> {
|
|
71
|
-
return this.connection.isAutoCommit();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Handles closing of a shared connection.
|
|
76
|
-
* The connection is only closed if there are no active clients using it.
|
|
77
|
-
*/
|
|
78
|
-
async close(): Promise<void> {
|
|
79
|
-
// This prevents further statements on this connection from being executed
|
|
80
|
-
this.isClosing = true;
|
|
81
|
-
const { clientIds, logger } = this;
|
|
82
|
-
const { clientId, dbFilename, dbMap } = this.options;
|
|
83
|
-
logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);
|
|
84
|
-
clientIds.delete(clientId);
|
|
85
|
-
|
|
86
|
-
if (this.activeHoldId) {
|
|
87
|
-
// We can't cleanup here since we're not in a lock context.
|
|
88
|
-
// The cleanup will occur once a new hold is acquired.
|
|
89
|
-
this.logger.info(
|
|
90
|
-
`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
if (clientIds.size == 0) {
|
|
95
|
-
logger.debug(`Closing connection to ${this.options}.`);
|
|
96
|
-
const connection = this.connection;
|
|
97
|
-
dbMap.delete(dbFilename);
|
|
98
|
-
await connection.close();
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
protected async withClosing<T>(action: () => Promise<T>) {
|
|
106
|
-
if (this.isClosing) {
|
|
107
|
-
throw new Error('Connection is closing');
|
|
108
|
-
}
|
|
109
|
-
return action();
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async execute(sql: string, params?: any[]): Promise<ProxiedQueryResult> {
|
|
113
|
-
return this.withClosing(() => this.connection.execute(sql, params));
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async executeRaw(sql: string, params?: any[]): Promise<any[][]> {
|
|
117
|
-
return this.withClosing(() => this.connection.executeRaw(sql, params));
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
executeBatch(sql: string, params?: any[] | undefined): Promise<ProxiedQueryResult> {
|
|
121
|
-
return this.withClosing(() => this.connection.executeBatch(sql, params));
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void> {
|
|
125
|
-
return this.connection.registerOnTableChange(callback);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
getConfig(): Promise<ResolvedWebSQLOpenOptions> {
|
|
129
|
-
return this.connection.getConfig();
|
|
130
|
-
}
|
|
131
|
-
}
|