@powersync/web 1.28.0 → 1.28.2
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 +64 -26
- package/dist/index.umd.js.map +1 -1
- package/dist/worker/SharedSyncImplementation.umd.js +13651 -440
- package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
- package/dist/worker/WASQLiteDB.umd.js +13478 -161
- package/dist/worker/WASQLiteDB.umd.js.map +1 -1
- package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js +66 -38
- package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js.map +1 -1
- package/lib/package.json +6 -5
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/package.json +7 -6
- package/src/db/PowerSyncDatabase.ts +224 -0
- package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +47 -0
- package/src/db/adapters/AbstractWebSQLOpenFactory.ts +48 -0
- package/src/db/adapters/AsyncDatabaseConnection.ts +40 -0
- package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +358 -0
- package/src/db/adapters/SSRDBAdapter.ts +94 -0
- package/src/db/adapters/WebDBAdapter.ts +20 -0
- package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +175 -0
- package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +444 -0
- package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +86 -0
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +134 -0
- package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +24 -0
- package/src/db/adapters/web-sql-flags.ts +135 -0
- package/src/db/sync/SSRWebStreamingSyncImplementation.ts +89 -0
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +274 -0
- package/src/db/sync/WebRemote.ts +59 -0
- package/src/db/sync/WebStreamingSyncImplementation.ts +34 -0
- package/src/db/sync/userAgent.ts +78 -0
- package/src/index.ts +13 -0
- package/src/shared/navigator.ts +9 -0
- package/src/worker/db/WASQLiteDB.worker.ts +112 -0
- package/src/worker/db/open-worker-database.ts +62 -0
- package/src/worker/sync/AbstractSharedSyncClientProvider.ts +21 -0
- package/src/worker/sync/BroadcastLogger.ts +142 -0
- package/src/worker/sync/SharedSyncImplementation.ts +520 -0
- package/src/worker/sync/SharedSyncImplementation.worker.ts +14 -0
- package/src/worker/sync/WorkerClient.ts +106 -0
- package/dist/worker/node_modules_crypto-browserify_index_js.umd.js +0 -33734
- package/dist/worker/node_modules_crypto-browserify_index_js.umd.js.map +0 -1
|
@@ -0,0 +1,444 @@
|
|
|
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';
|
|
5
|
+
import { ResolvedWASQLiteOpenFactoryOptions } from './WASQLiteOpenFactory';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* List of currently tested virtual filesystems
|
|
9
|
+
*/
|
|
10
|
+
export enum WASQLiteVFS {
|
|
11
|
+
IDBBatchAtomicVFS = 'IDBBatchAtomicVFS',
|
|
12
|
+
OPFSCoopSyncVFS = 'OPFSCoopSyncVFS',
|
|
13
|
+
AccessHandlePoolVFS = 'AccessHandlePoolVFS'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
export type WASQLiteBroadCastTableUpdateEvent = {
|
|
20
|
+
changedTables: Set<string>;
|
|
21
|
+
connectionId: number;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
export type WASQLiteConnectionListener = {
|
|
28
|
+
tablesUpdated: (event: BatchedUpdateNotification) => void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export type SQLiteModule = Parameters<typeof SQLite.Factory>[0];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
export type WASQLiteModuleFactoryOptions = { dbFileName: string; encryptionKey?: string };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @internal
|
|
43
|
+
*/
|
|
44
|
+
export type WASQLiteModuleFactory = (
|
|
45
|
+
options: WASQLiteModuleFactoryOptions
|
|
46
|
+
) => Promise<{ module: SQLiteModule; vfs: SQLiteVFS }>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
export const AsyncWASQLiteModuleFactory = async () => {
|
|
52
|
+
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
|
|
53
|
+
return factory();
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @internal
|
|
58
|
+
*/
|
|
59
|
+
export const MultiCipherAsyncWASQLiteModuleFactory = async () => {
|
|
60
|
+
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
|
|
61
|
+
return factory();
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @internal
|
|
66
|
+
*/
|
|
67
|
+
export const SyncWASQLiteModuleFactory = async () => {
|
|
68
|
+
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');
|
|
69
|
+
return factory();
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @internal
|
|
74
|
+
*/
|
|
75
|
+
export const MultiCipherSyncWASQLiteModuleFactory = async () => {
|
|
76
|
+
const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');
|
|
77
|
+
return factory();
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @internal
|
|
82
|
+
*/
|
|
83
|
+
export const DEFAULT_MODULE_FACTORIES = {
|
|
84
|
+
[WASQLiteVFS.IDBBatchAtomicVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
85
|
+
let module;
|
|
86
|
+
if (options.encryptionKey) {
|
|
87
|
+
module = await MultiCipherAsyncWASQLiteModuleFactory();
|
|
88
|
+
} else {
|
|
89
|
+
module = await AsyncWASQLiteModuleFactory();
|
|
90
|
+
}
|
|
91
|
+
const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
|
|
92
|
+
return {
|
|
93
|
+
module,
|
|
94
|
+
// @ts-expect-error The types for this static method are missing upstream
|
|
95
|
+
vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
[WASQLiteVFS.AccessHandlePoolVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
99
|
+
let module;
|
|
100
|
+
if (options.encryptionKey) {
|
|
101
|
+
module = await MultiCipherSyncWASQLiteModuleFactory();
|
|
102
|
+
} else {
|
|
103
|
+
module = await SyncWASQLiteModuleFactory();
|
|
104
|
+
}
|
|
105
|
+
// @ts-expect-error The types for this static method are missing upstream
|
|
106
|
+
const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
|
|
107
|
+
return {
|
|
108
|
+
module,
|
|
109
|
+
vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
[WASQLiteVFS.OPFSCoopSyncVFS]: async (options: WASQLiteModuleFactoryOptions) => {
|
|
113
|
+
let module;
|
|
114
|
+
if (options.encryptionKey) {
|
|
115
|
+
module = await MultiCipherSyncWASQLiteModuleFactory();
|
|
116
|
+
} else {
|
|
117
|
+
module = await SyncWASQLiteModuleFactory();
|
|
118
|
+
}
|
|
119
|
+
// @ts-expect-error The types for this static method are missing upstream
|
|
120
|
+
const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
|
|
121
|
+
return {
|
|
122
|
+
module,
|
|
123
|
+
vfs: await OPFSCoopSyncVFS.create(options.dbFileName, module)
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @internal
|
|
130
|
+
* WA-SQLite connection which directly interfaces with WA-SQLite.
|
|
131
|
+
* This is usually instantiated inside a worker.
|
|
132
|
+
*/
|
|
133
|
+
export class WASqliteConnection
|
|
134
|
+
extends BaseObserver<WASQLiteConnectionListener>
|
|
135
|
+
implements AsyncDatabaseConnection<ResolvedWASQLiteOpenFactoryOptions>
|
|
136
|
+
{
|
|
137
|
+
private _sqliteAPI: SQLiteAPI | null = null;
|
|
138
|
+
private _dbP: number | null = null;
|
|
139
|
+
private _moduleFactory: WASQLiteModuleFactory;
|
|
140
|
+
|
|
141
|
+
protected updatedTables: Set<string>;
|
|
142
|
+
protected updateTimer: ReturnType<typeof setTimeout> | null;
|
|
143
|
+
protected statementMutex: Mutex;
|
|
144
|
+
protected broadcastChannel: BroadcastChannel | null;
|
|
145
|
+
/**
|
|
146
|
+
* Unique id for this specific connection. This is used to prevent broadcast table change
|
|
147
|
+
* notification loops.
|
|
148
|
+
*/
|
|
149
|
+
protected connectionId: number;
|
|
150
|
+
|
|
151
|
+
constructor(protected options: ResolvedWASQLiteOpenFactoryOptions) {
|
|
152
|
+
super();
|
|
153
|
+
this.updatedTables = new Set();
|
|
154
|
+
this.updateTimer = null;
|
|
155
|
+
this.broadcastChannel = null;
|
|
156
|
+
this.connectionId = new Date().valueOf() + Math.random();
|
|
157
|
+
this.statementMutex = new Mutex();
|
|
158
|
+
this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
protected get sqliteAPI() {
|
|
162
|
+
if (!this._sqliteAPI) {
|
|
163
|
+
throw new Error(`Initialization has not completed`);
|
|
164
|
+
}
|
|
165
|
+
return this._sqliteAPI;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
protected get dbP() {
|
|
169
|
+
if (!this._dbP) {
|
|
170
|
+
throw new Error(`Initialization has not completed`);
|
|
171
|
+
}
|
|
172
|
+
return this._dbP;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
protected async openDB() {
|
|
176
|
+
this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
|
|
177
|
+
return this._dbP;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
protected async executeEncryptionPragma(): Promise<void> {
|
|
181
|
+
if (this.options.encryptionKey) {
|
|
182
|
+
await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
|
|
183
|
+
}
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
protected async openSQLiteAPI(): Promise<SQLiteAPI> {
|
|
188
|
+
const { module, vfs } = await this._moduleFactory({
|
|
189
|
+
dbFileName: this.options.dbFilename,
|
|
190
|
+
encryptionKey: this.options.encryptionKey
|
|
191
|
+
});
|
|
192
|
+
const sqlite3 = SQLite.Factory(module);
|
|
193
|
+
sqlite3.vfs_register(vfs, true);
|
|
194
|
+
/**
|
|
195
|
+
* Register the PowerSync core SQLite extension
|
|
196
|
+
*/
|
|
197
|
+
module.ccall('powersync_init_static', 'int', []);
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Create the multiple cipher vfs if an encryption key is provided
|
|
201
|
+
*/
|
|
202
|
+
if (this.options.encryptionKey) {
|
|
203
|
+
const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
|
|
204
|
+
if (createResult !== 0) {
|
|
205
|
+
throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return sqlite3;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
protected registerBroadcastListeners() {
|
|
213
|
+
this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
|
|
214
|
+
this.broadcastChannel.addEventListener('message', (event) => {
|
|
215
|
+
const data: WASQLiteBroadCastTableUpdateEvent = event.data;
|
|
216
|
+
if (this.connectionId == data.connectionId) {
|
|
217
|
+
// Ignore messages from the same connection
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Ensuring that we don't rebroadcast the same message
|
|
222
|
+
this.queueTableUpdate(data.changedTables, false);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
protected queueTableUpdate(tableNames: Set<string>, shouldBroadcast = true) {
|
|
227
|
+
tableNames.forEach((tableName) => this.updatedTables.add(tableName));
|
|
228
|
+
if (this.updateTimer == null) {
|
|
229
|
+
this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async init() {
|
|
234
|
+
this._sqliteAPI = await this.openSQLiteAPI();
|
|
235
|
+
await this.openDB();
|
|
236
|
+
this.registerBroadcastListeners();
|
|
237
|
+
await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
|
|
238
|
+
await this.executeEncryptionPragma();
|
|
239
|
+
await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
|
|
240
|
+
|
|
241
|
+
this.sqliteAPI.update_hook(this.dbP, (updateType: number, dbName: string | null, tableName: string | null) => {
|
|
242
|
+
if (!tableName) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const changedTables = new Set([tableName]);
|
|
246
|
+
this.queueTableUpdate(changedTables);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async getConfig(): Promise<ResolvedWASQLiteOpenFactoryOptions> {
|
|
251
|
+
return this.options;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
fireUpdates(shouldBroadcast = true) {
|
|
255
|
+
this.updateTimer = null;
|
|
256
|
+
const event: BatchedUpdateNotification = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
|
|
257
|
+
// Share to other connections
|
|
258
|
+
if (shouldBroadcast) {
|
|
259
|
+
this.broadcastChannel!.postMessage({
|
|
260
|
+
changedTables: this.updatedTables,
|
|
261
|
+
connectionId: this.connectionId
|
|
262
|
+
} satisfies WASQLiteBroadCastTableUpdateEvent);
|
|
263
|
+
}
|
|
264
|
+
this.updatedTables.clear();
|
|
265
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* This executes SQL statements in a batch.
|
|
270
|
+
*/
|
|
271
|
+
async executeBatch(sql: string, bindings?: any[][]): Promise<ProxiedQueryResult> {
|
|
272
|
+
return this.acquireExecuteLock(async (): Promise<ProxiedQueryResult> => {
|
|
273
|
+
let affectedRows = 0;
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
await this.executeSingleStatement('BEGIN TRANSACTION');
|
|
277
|
+
|
|
278
|
+
const wrappedBindings = bindings ? bindings : [];
|
|
279
|
+
for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
|
|
280
|
+
if (stmt === null) {
|
|
281
|
+
return {
|
|
282
|
+
rowsAffected: 0,
|
|
283
|
+
rows: { _array: [], length: 0 }
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
//Prepare statement once
|
|
288
|
+
for (const binding of wrappedBindings) {
|
|
289
|
+
// TODO not sure why this is needed currently, but booleans break
|
|
290
|
+
for (let i = 0; i < binding.length; i++) {
|
|
291
|
+
const b = binding[i];
|
|
292
|
+
if (typeof b == 'boolean') {
|
|
293
|
+
binding[i] = b ? 1 : 0;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (bindings) {
|
|
298
|
+
this.sqliteAPI.bind_collection(stmt, binding);
|
|
299
|
+
}
|
|
300
|
+
const result = await this.sqliteAPI.step(stmt);
|
|
301
|
+
if (result === SQLite.SQLITE_DONE) {
|
|
302
|
+
//The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
|
|
303
|
+
affectedRows += this.sqliteAPI.changes(this.dbP);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
this.sqliteAPI.reset(stmt);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
await this.executeSingleStatement('COMMIT');
|
|
311
|
+
} catch (err) {
|
|
312
|
+
await this.executeSingleStatement('ROLLBACK');
|
|
313
|
+
return {
|
|
314
|
+
rowsAffected: 0,
|
|
315
|
+
rows: { _array: [], length: 0 }
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
const result = {
|
|
319
|
+
rowsAffected: affectedRows,
|
|
320
|
+
rows: { _array: [], length: 0 }
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
return result;
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* This executes single SQL statements inside a requested lock.
|
|
329
|
+
*/
|
|
330
|
+
async execute(sql: string | TemplateStringsArray, bindings?: any[]): Promise<ProxiedQueryResult> {
|
|
331
|
+
// Running multiple statements on the same connection concurrently should not be allowed
|
|
332
|
+
return this.acquireExecuteLock(async () => {
|
|
333
|
+
return this.executeSingleStatement(sql, bindings);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async executeRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]> {
|
|
338
|
+
return this.acquireExecuteLock(async () => {
|
|
339
|
+
return this.executeSingleStatementRaw(sql, bindings);
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async close() {
|
|
344
|
+
this.broadcastChannel?.close();
|
|
345
|
+
await this.sqliteAPI.close(this.dbP);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async registerOnTableChange(callback: OnTableChangeCallback) {
|
|
349
|
+
return this.registerListener({
|
|
350
|
+
tablesUpdated: (event) => callback(event)
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* This requests a lock for executing statements.
|
|
356
|
+
* Should only be used internally.
|
|
357
|
+
*/
|
|
358
|
+
protected acquireExecuteLock = <T>(callback: () => Promise<T>): Promise<T> => {
|
|
359
|
+
return this.statementMutex.runExclusive(callback);
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* This executes a single statement using SQLite3.
|
|
364
|
+
*/
|
|
365
|
+
protected async executeSingleStatement(
|
|
366
|
+
sql: string | TemplateStringsArray,
|
|
367
|
+
bindings?: any[]
|
|
368
|
+
): Promise<ProxiedQueryResult> {
|
|
369
|
+
const results = await this._execute(sql, bindings);
|
|
370
|
+
|
|
371
|
+
const rows: Record<string, any>[] = [];
|
|
372
|
+
for (const resultSet of results) {
|
|
373
|
+
for (const row of resultSet.rows) {
|
|
374
|
+
const outRow: Record<string, any> = {};
|
|
375
|
+
resultSet.columns.forEach((key, index) => {
|
|
376
|
+
outRow[key] = row[index];
|
|
377
|
+
});
|
|
378
|
+
rows.push(outRow);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const result = {
|
|
383
|
+
insertId: this.sqliteAPI.last_insert_id(this.dbP),
|
|
384
|
+
rowsAffected: this.sqliteAPI.changes(this.dbP),
|
|
385
|
+
rows: {
|
|
386
|
+
_array: rows,
|
|
387
|
+
length: rows.length
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* This executes a single statement using SQLite3 and returns the results as an array of arrays.
|
|
396
|
+
*/
|
|
397
|
+
protected async executeSingleStatementRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]> {
|
|
398
|
+
const results = await this._execute(sql, bindings);
|
|
399
|
+
|
|
400
|
+
return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private async _execute(
|
|
404
|
+
sql: string | TemplateStringsArray,
|
|
405
|
+
bindings?: any[]
|
|
406
|
+
): Promise<{ columns: string[]; rows: SQLiteCompatibleType[][] }[]> {
|
|
407
|
+
const results = [];
|
|
408
|
+
for await (const stmt of this.sqliteAPI.statements(this.dbP, sql as string)) {
|
|
409
|
+
let columns;
|
|
410
|
+
const wrappedBindings = bindings ? [bindings] : [[]];
|
|
411
|
+
for (const binding of wrappedBindings) {
|
|
412
|
+
// TODO not sure why this is needed currently, but booleans break
|
|
413
|
+
binding.forEach((b, index, arr) => {
|
|
414
|
+
if (typeof b == 'boolean') {
|
|
415
|
+
arr[index] = b ? 1 : 0;
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
this.sqliteAPI.reset(stmt);
|
|
420
|
+
if (bindings) {
|
|
421
|
+
this.sqliteAPI.bind_collection(stmt, binding);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const rows = [];
|
|
425
|
+
while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {
|
|
426
|
+
const row = this.sqliteAPI.row(stmt);
|
|
427
|
+
rows.push(row);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
columns = columns ?? this.sqliteAPI.column_names(stmt);
|
|
431
|
+
if (columns.length) {
|
|
432
|
+
results.push({ columns, rows });
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// When binding parameters, only a single statement is executed.
|
|
437
|
+
if (bindings) {
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return results;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type PowerSyncOpenFactoryOptions } from '@powersync/common';
|
|
2
|
+
import * as Comlink from 'comlink';
|
|
3
|
+
import { resolveWebPowerSyncFlags } from '../../PowerSyncDatabase';
|
|
4
|
+
import { OpenAsyncDatabaseConnection } from '../AsyncDatabaseConnection';
|
|
5
|
+
import { LockedAsyncDatabaseAdapter } from '../LockedAsyncDatabaseAdapter';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_CACHE_SIZE_KB,
|
|
8
|
+
ResolvedWebSQLOpenOptions,
|
|
9
|
+
TemporaryStorageOption,
|
|
10
|
+
WebSQLFlags
|
|
11
|
+
} from '../web-sql-flags';
|
|
12
|
+
import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection';
|
|
13
|
+
import { WASQLiteVFS } from './WASQLiteConnection';
|
|
14
|
+
import { WASQLiteOpenFactory } from './WASQLiteOpenFactory';
|
|
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 LockedAsyncDatabaseAdapter {
|
|
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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { type ILogLevel, DBAdapter } from '@powersync/common';
|
|
2
|
+
import * as Comlink from 'comlink';
|
|
3
|
+
import { openWorkerDatabasePort, resolveWorkerDatabasePortFactory } from '../../../worker/db/open-worker-database';
|
|
4
|
+
import { AbstractWebSQLOpenFactory } from '../AbstractWebSQLOpenFactory';
|
|
5
|
+
import { AsyncDatabaseConnection, OpenAsyncDatabaseConnection } from '../AsyncDatabaseConnection';
|
|
6
|
+
import { LockedAsyncDatabaseAdapter } from '../LockedAsyncDatabaseAdapter';
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_CACHE_SIZE_KB,
|
|
9
|
+
ResolvedWebSQLOpenOptions,
|
|
10
|
+
TemporaryStorageOption,
|
|
11
|
+
WebSQLOpenFactoryOptions
|
|
12
|
+
} from '../web-sql-flags';
|
|
13
|
+
import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection';
|
|
14
|
+
import { WASqliteConnection, WASQLiteVFS } from './WASQLiteConnection';
|
|
15
|
+
|
|
16
|
+
export interface WASQLiteOpenFactoryOptions extends WebSQLOpenFactoryOptions {
|
|
17
|
+
vfs?: WASQLiteVFS;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ResolvedWASQLiteOpenFactoryOptions extends ResolvedWebSQLOpenOptions {
|
|
21
|
+
vfs: WASQLiteVFS;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface WorkerDBOpenerOptions extends ResolvedWASQLiteOpenFactoryOptions {
|
|
25
|
+
logLevel: ILogLevel;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Opens a SQLite connection using WA-SQLite.
|
|
30
|
+
*/
|
|
31
|
+
export class WASQLiteOpenFactory extends AbstractWebSQLOpenFactory {
|
|
32
|
+
constructor(options: WASQLiteOpenFactoryOptions) {
|
|
33
|
+
super(options);
|
|
34
|
+
|
|
35
|
+
assertValidWASQLiteOpenFactoryOptions(options);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get waOptions(): WASQLiteOpenFactoryOptions {
|
|
39
|
+
// Cast to extended type
|
|
40
|
+
return this.options;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
protected openAdapter(): DBAdapter {
|
|
44
|
+
return new LockedAsyncDatabaseAdapter({
|
|
45
|
+
name: this.options.dbFilename,
|
|
46
|
+
openConnection: () => this.openConnection(),
|
|
47
|
+
debugMode: this.options.debugMode,
|
|
48
|
+
logger: this.logger
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async openConnection(): Promise<AsyncDatabaseConnection> {
|
|
53
|
+
const { enableMultiTabs, useWebWorker } = this.resolvedFlags;
|
|
54
|
+
const {
|
|
55
|
+
vfs = WASQLiteVFS.IDBBatchAtomicVFS,
|
|
56
|
+
temporaryStorage = TemporaryStorageOption.MEMORY,
|
|
57
|
+
cacheSizeKb = DEFAULT_CACHE_SIZE_KB,
|
|
58
|
+
encryptionKey
|
|
59
|
+
} = this.waOptions;
|
|
60
|
+
|
|
61
|
+
if (!enableMultiTabs) {
|
|
62
|
+
this.logger.warn('Multiple tabs are not enabled in this browser');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (useWebWorker) {
|
|
66
|
+
const optionsDbWorker = this.options.worker;
|
|
67
|
+
|
|
68
|
+
const workerPort =
|
|
69
|
+
typeof optionsDbWorker == 'function'
|
|
70
|
+
? resolveWorkerDatabasePortFactory(() =>
|
|
71
|
+
optionsDbWorker({
|
|
72
|
+
...this.options,
|
|
73
|
+
temporaryStorage,
|
|
74
|
+
cacheSizeKb,
|
|
75
|
+
flags: this.resolvedFlags,
|
|
76
|
+
encryptionKey
|
|
77
|
+
})
|
|
78
|
+
)
|
|
79
|
+
: openWorkerDatabasePort(this.options.dbFilename, enableMultiTabs, optionsDbWorker, this.waOptions.vfs);
|
|
80
|
+
|
|
81
|
+
const workerDBOpener = Comlink.wrap<OpenAsyncDatabaseConnection<WorkerDBOpenerOptions>>(workerPort);
|
|
82
|
+
|
|
83
|
+
return new WorkerWrappedAsyncDatabaseConnection({
|
|
84
|
+
remote: workerDBOpener,
|
|
85
|
+
// This tab owns the worker, so we're guaranteed to outlive it.
|
|
86
|
+
remoteCanCloseUnexpectedly: false,
|
|
87
|
+
baseConnection: await workerDBOpener({
|
|
88
|
+
dbFilename: this.options.dbFilename,
|
|
89
|
+
vfs,
|
|
90
|
+
temporaryStorage,
|
|
91
|
+
cacheSizeKb,
|
|
92
|
+
flags: this.resolvedFlags,
|
|
93
|
+
encryptionKey: encryptionKey,
|
|
94
|
+
logLevel: this.logger.getLevel()
|
|
95
|
+
}),
|
|
96
|
+
identifier: this.options.dbFilename,
|
|
97
|
+
onClose: () => {
|
|
98
|
+
if (workerPort instanceof Worker) {
|
|
99
|
+
workerPort.terminate();
|
|
100
|
+
} else {
|
|
101
|
+
workerPort.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
} else {
|
|
106
|
+
// Don't use a web worker
|
|
107
|
+
return new WASqliteConnection({
|
|
108
|
+
dbFilename: this.options.dbFilename,
|
|
109
|
+
dbLocation: this.options.dbLocation,
|
|
110
|
+
debugMode: this.options.debugMode,
|
|
111
|
+
vfs,
|
|
112
|
+
temporaryStorage,
|
|
113
|
+
cacheSizeKb,
|
|
114
|
+
flags: this.resolvedFlags,
|
|
115
|
+
encryptionKey: encryptionKey
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Asserts that the factory options are valid.
|
|
123
|
+
*/
|
|
124
|
+
function assertValidWASQLiteOpenFactoryOptions(options: WASQLiteOpenFactoryOptions): void {
|
|
125
|
+
// The OPFS VFS only works in dedicated web workers.
|
|
126
|
+
if ('vfs' in options && 'flags' in options) {
|
|
127
|
+
const { vfs, flags = {} } = options;
|
|
128
|
+
if (vfs !== WASQLiteVFS.IDBBatchAtomicVFS && 'useWebWorker' in flags && !flags.useWebWorker) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${vfs}).`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AbstractPowerSyncDatabase, DBAdapter, PowerSyncDatabaseOptions } from '@powersync/common';
|
|
2
|
+
import { PowerSyncDatabase } from '../../../db/PowerSyncDatabase';
|
|
3
|
+
import { AbstractWebPowerSyncDatabaseOpenFactory } from '../AbstractWebPowerSyncDatabaseOpenFactory';
|
|
4
|
+
import { WASQLiteOpenFactory } from './WASQLiteOpenFactory';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @deprecated {@link PowerSyncDatabase} can now be constructed directly
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* const powersync = new PowerSyncDatabase({database: {
|
|
11
|
+
* dbFileName: 'powersync.db'
|
|
12
|
+
* }});
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export class WASQLitePowerSyncDatabaseOpenFactory extends AbstractWebPowerSyncDatabaseOpenFactory {
|
|
16
|
+
protected openDB(): DBAdapter {
|
|
17
|
+
const factory = new WASQLiteOpenFactory(this.options);
|
|
18
|
+
return factory.openDB();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
generateInstance(options: PowerSyncDatabaseOptions): AbstractPowerSyncDatabase {
|
|
22
|
+
return new PowerSyncDatabase(options);
|
|
23
|
+
}
|
|
24
|
+
}
|