@ehegnes/wa-sqlite 2.0.0-beta.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -0
  3. package/dist/wa-sqlite-async.mjs +2 -0
  4. package/dist/wa-sqlite-async.wasm +0 -0
  5. package/dist/wa-sqlite-jspi.mjs +2 -0
  6. package/dist/wa-sqlite-jspi.wasm +0 -0
  7. package/dist/wa-sqlite.mjs +2 -0
  8. package/dist/wa-sqlite.wasm +0 -0
  9. package/package.json +44 -0
  10. package/src/FacadeVFS.js +681 -0
  11. package/src/VFS.js +222 -0
  12. package/src/WebLocksMixin.js +411 -0
  13. package/src/examples/AccessHandlePoolVFS.js +458 -0
  14. package/src/examples/IDBBatchAtomicVFS.js +827 -0
  15. package/src/examples/IDBMirrorVFS.js +889 -0
  16. package/src/examples/LazyLock.js +90 -0
  17. package/src/examples/Lock.js +69 -0
  18. package/src/examples/MemoryAsyncVFS.js +100 -0
  19. package/src/examples/MemoryVFS.js +176 -0
  20. package/src/examples/OPFSAdaptiveVFS.js +437 -0
  21. package/src/examples/OPFSAnyContextVFS.js +300 -0
  22. package/src/examples/OPFSCoopSyncVFS.js +597 -0
  23. package/src/examples/OPFSPermutedVFS.js +1217 -0
  24. package/src/examples/OPFSWriteAheadVFS.js +960 -0
  25. package/src/examples/README.md +81 -0
  26. package/src/examples/WriteAhead.js +1174 -0
  27. package/src/examples/tag.js +82 -0
  28. package/src/sqlite-api.js +924 -0
  29. package/src/sqlite-constants.js +275 -0
  30. package/src/types/globals.d.ts +60 -0
  31. package/src/types/index.d.ts +1228 -0
  32. package/src/types/tsconfig.json +6 -0
  33. package/test/AccessHandlePoolVFS.test.js +27 -0
  34. package/test/IDBBatchAtomicVFS.test.js +97 -0
  35. package/test/IDBMirrorVFS.test.js +27 -0
  36. package/test/MemoryAsyncVFS.test.js +27 -0
  37. package/test/MemoryVFS.test.js +27 -0
  38. package/test/OPFSAdaptiveVFS.test.js +27 -0
  39. package/test/OPFSAnyContextVFS.test.js +27 -0
  40. package/test/OPFSCoopSyncVFS.test.js +27 -0
  41. package/test/OPFSWriteAheadVFS.test.js +27 -0
  42. package/test/TestContext.js +96 -0
  43. package/test/WebLocksMixin.test.js +521 -0
  44. package/test/api.test.js +49 -0
  45. package/test/api_exec.js +89 -0
  46. package/test/api_misc.js +63 -0
  47. package/test/api_statements.js +447 -0
  48. package/test/callbacks.test.js +581 -0
  49. package/test/data/idbv5.json +1 -0
  50. package/test/sql.test.js +64 -0
  51. package/test/sql_0001.js +49 -0
  52. package/test/sql_0002.js +52 -0
  53. package/test/sql_0003.js +83 -0
  54. package/test/sql_0004.js +81 -0
  55. package/test/sql_0005.js +76 -0
  56. package/test/test-worker.js +204 -0
  57. package/test/vfs_xAccess.js +2 -0
  58. package/test/vfs_xClose.js +52 -0
  59. package/test/vfs_xOpen.js +91 -0
  60. package/test/vfs_xRead.js +38 -0
  61. package/test/vfs_xWrite.js +36 -0
@@ -0,0 +1,437 @@
1
+ // Copyright 2024 Roy T. Hashimoto. All Rights Reserved.
2
+ import { FacadeVFS } from '../FacadeVFS.js';
3
+ import * as VFS from '../VFS.js';
4
+ import { WebLocksMixin } from '../WebLocksMixin.js';
5
+
6
+ const LOCK_NOTIFY_INTERVAL = 1000;
7
+
8
+ const hasUnsafeAccessHandle =
9
+ globalThis.FileSystemSyncAccessHandle.prototype.hasOwnProperty('mode');
10
+
11
+ /**
12
+ * @param {string} pathname
13
+ * @param {boolean} create
14
+ * @returns {Promise<[FileSystemDirectoryHandle, string]>}
15
+ */
16
+ async function getPathComponents(pathname, create) {
17
+ const [_, directories, filename] = pathname.match(/[/]?(.*)[/](.*)$/);
18
+
19
+ let directoryHandle = await navigator.storage.getDirectory();
20
+ for (const directory of directories.split('/')) {
21
+ if (directory) {
22
+ directoryHandle = await directoryHandle.getDirectoryHandle(directory, { create });
23
+ }
24
+ }
25
+ return [directoryHandle, filename];
26
+ };
27
+
28
+ class File {
29
+ /** @type {string} */ pathname;
30
+ /** @type {number} */ flags;
31
+ /** @type {FileSystemFileHandle} */ fileHandle;
32
+ /** @type {FileSystemSyncAccessHandle} */ accessHandle;
33
+
34
+ // The rest of the properties are for platforms without readwrite-unsafe
35
+ // access handles. Only one connection can have an open access handle
36
+ // so coordination is needed in addition to the SQLite locking model.
37
+ //
38
+ // Opening and closing the access handle is expensive so we leave the
39
+ // handle open unless another connection signals on BroadcastChannel.
40
+ /** @type {BroadcastChannel} */ handleRequestChannel;
41
+ /** @type {function} */ handleLockReleaser = null;
42
+ /** @type {boolean} */ isHandleRequested = false;
43
+ /** @type {boolean} */ isFileLocked = false;
44
+
45
+ // SQLite makes one read on file open that is not protected by a lock.
46
+ // This needs to be handled as a special case.
47
+ /** @type {function} */ openLockReleaser = null;
48
+
49
+ constructor(pathname, flags) {
50
+ this.pathname = pathname;
51
+ this.flags = flags;
52
+ }
53
+ }
54
+
55
+ export class OPFSAdaptiveVFS extends WebLocksMixin(FacadeVFS) {
56
+ /** @type {Map<number, File>} */ mapIdToFile = new Map();
57
+ lastError = null;
58
+
59
+ log = null;
60
+
61
+ static async create(name, module, options) {
62
+ const vfs = new OPFSAdaptiveVFS(name, module, options);
63
+ await vfs.isReady();
64
+ return vfs;
65
+ }
66
+
67
+ constructor(name, module, options = {}) {
68
+ super(name, module, options);
69
+ }
70
+
71
+ getFilename(fileId) {
72
+ const pathname = this.mapIdToFile.get(fileId).pathname;
73
+ return `OPFS:${pathname}`
74
+ }
75
+
76
+ /**
77
+ * @param {string?} zName
78
+ * @param {number} fileId
79
+ * @param {number} flags
80
+ * @param {DataView} pOutFlags
81
+ * @returns {Promise<number>}
82
+ */
83
+ async jOpen(zName, fileId, flags, pOutFlags) {
84
+ try {
85
+ const url = new URL(zName || Math.random().toString(36).slice(2), 'file://');
86
+ const pathname = url.pathname;
87
+
88
+ const file = new File(pathname, flags);
89
+ this.mapIdToFile.set(fileId, file);
90
+
91
+ const create = !!(flags & VFS.SQLITE_OPEN_CREATE);
92
+ const [directoryHandle, filename] = await getPathComponents(pathname, create);
93
+ file.fileHandle = await directoryHandle.getFileHandle(filename, { create });
94
+
95
+ if ((flags & VFS.SQLITE_OPEN_MAIN_DB) && !hasUnsafeAccessHandle) {
96
+ file.handleRequestChannel = new BroadcastChannel(this.getFilename(fileId));
97
+
98
+ // Acquire the access handle lock. The first read of a database
99
+ // file is done outside xLock/xUnlock so we get that lock here.
100
+ function notify() {
101
+ file.handleRequestChannel.postMessage(null);
102
+ }
103
+ const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);
104
+ setTimeout(notify);
105
+
106
+ file.openLockReleaser = await new Promise((resolve, reject) => {
107
+ navigator.locks.request(this.getFilename(fileId), lock => {
108
+ clearInterval(notifyId);
109
+ if (!lock) return reject();
110
+ return new Promise(release => {
111
+ resolve(release);
112
+ });
113
+ });
114
+ });
115
+ this.log?.('access handle acquired for open');
116
+ }
117
+
118
+ // @ts-ignore
119
+ file.accessHandle = await file.fileHandle.createSyncAccessHandle({
120
+ mode: 'readwrite-unsafe'
121
+ });
122
+
123
+ pOutFlags.setInt32(0, flags, true);
124
+ return VFS.SQLITE_OK;
125
+ } catch (e) {
126
+ this.lastError = e;
127
+ return VFS.SQLITE_CANTOPEN;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * @param {string} zName
133
+ * @param {number} syncDir
134
+ * @returns {Promise<number>}
135
+ */
136
+ async jDelete(zName, syncDir) {
137
+ try {
138
+ const url = new URL(zName, 'file://');
139
+ const pathname = url.pathname;
140
+
141
+ const [directoryHandle, name] = await getPathComponents(pathname, false);
142
+ const result = directoryHandle.removeEntry(name, { recursive: false });
143
+ if (syncDir) {
144
+ await result;
145
+ }
146
+ return VFS.SQLITE_OK;
147
+ } catch (e) {
148
+ return VFS.SQLITE_IOERR_DELETE;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * @param {string} zName
154
+ * @param {number} flags
155
+ * @param {DataView} pResOut
156
+ * @returns {Promise<number>}
157
+ */
158
+ async jAccess(zName, flags, pResOut) {
159
+ try {
160
+ const url = new URL(zName, 'file://');
161
+ const pathname = url.pathname;
162
+
163
+ const [directoryHandle, dbName] = await getPathComponents(pathname, false);
164
+ const fileHandle = await directoryHandle.getFileHandle(dbName, { create: false });
165
+ pResOut.setInt32(0, 1, true);
166
+ return VFS.SQLITE_OK;
167
+ } catch (e) {
168
+ if (e.name === 'NotFoundError') {
169
+ pResOut.setInt32(0, 0, true);
170
+ return VFS.SQLITE_OK;
171
+ }
172
+ this.lastError = e;
173
+ return VFS.SQLITE_IOERR_ACCESS;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @param {number} fileId
179
+ * @returns {Promise<number>}
180
+ */
181
+ async jClose(fileId) {
182
+ try {
183
+ const file = this.mapIdToFile.get(fileId);
184
+ this.mapIdToFile.delete(fileId);
185
+ await file?.accessHandle?.close();
186
+
187
+ if (file?.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {
188
+ const [directoryHandle, name] = await getPathComponents(file.pathname, false);
189
+ await directoryHandle.removeEntry(name, { recursive: false });
190
+ }
191
+ return VFS.SQLITE_OK;
192
+ } catch (e) {
193
+ return VFS.SQLITE_IOERR_DELETE;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * @param {number} fileId
199
+ * @param {Uint8Array} pData
200
+ * @param {number} iOffset
201
+ * @returns {number}
202
+ */
203
+ jRead(fileId, pData, iOffset) {
204
+ try {
205
+ const file = this.mapIdToFile.get(fileId);
206
+
207
+ // On Chrome (at least), passing pData to accessHandle.read() is
208
+ // an error because pData is a Proxy of a Uint8Array. Calling
209
+ // subarray() produces a real Uint8Array and that works.
210
+ const bytesRead = file.accessHandle.read(pData.subarray(), { at: iOffset });
211
+ if (file.openLockReleaser) {
212
+ // We obtained the access handle on file open.
213
+ file.accessHandle.close();
214
+ file.accessHandle = null;
215
+ file.openLockReleaser();
216
+ file.openLockReleaser = null;
217
+ this.log?.('access handle released for open');
218
+ }
219
+
220
+ if (bytesRead < pData.byteLength) {
221
+ pData.fill(0, bytesRead);
222
+ return VFS.SQLITE_IOERR_SHORT_READ;
223
+ }
224
+ return VFS.SQLITE_OK;
225
+ } catch (e) {
226
+ this.lastError = e;
227
+ return VFS.SQLITE_IOERR_READ;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * @param {number} fileId
233
+ * @param {Uint8Array} pData
234
+ * @param {number} iOffset
235
+ * @returns {number}
236
+ */
237
+ jWrite(fileId, pData, iOffset) {
238
+ try {
239
+ const file = this.mapIdToFile.get(fileId);
240
+
241
+ // On Chrome (at least), passing pData to accessHandle.write() is
242
+ // an error because pData is a Proxy of a Uint8Array. Calling
243
+ // subarray() produces a real Uint8Array and that works.
244
+ file.accessHandle.write(pData.subarray(), { at: iOffset });
245
+ return VFS.SQLITE_OK;
246
+ } catch (e) {
247
+ this.lastError = e;
248
+ return VFS.SQLITE_IOERR_WRITE;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * @param {number} fileId
254
+ * @param {number} iSize
255
+ * @returns {number}
256
+ */
257
+ jTruncate(fileId, iSize) {
258
+ try {
259
+ const file = this.mapIdToFile.get(fileId);
260
+ file.accessHandle.truncate(iSize);
261
+ return VFS.SQLITE_OK;
262
+ } catch (e) {
263
+ this.lastError = e;
264
+ return VFS.SQLITE_IOERR_TRUNCATE;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * @param {number} fileId
270
+ * @param {number} flags
271
+ * @returns {number}
272
+ */
273
+ jSync(fileId, flags) {
274
+ try {
275
+ const file = this.mapIdToFile.get(fileId);
276
+ file.accessHandle.flush();
277
+ return VFS.SQLITE_OK;
278
+ } catch (e) {
279
+ this.lastError = e;
280
+ return VFS.SQLITE_IOERR_FSYNC;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * @param {number} fileId
286
+ * @param {DataView} pSize64
287
+ * @returns {number}
288
+ */
289
+ jFileSize(fileId, pSize64) {
290
+ try {
291
+ const file = this.mapIdToFile.get(fileId);
292
+ const size = file.accessHandle.getSize();
293
+ pSize64.setBigInt64(0, BigInt(size), true);
294
+ return VFS.SQLITE_OK;
295
+ } catch (e) {
296
+ this.lastError = e;
297
+ return VFS.SQLITE_IOERR_FSTAT;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * @param {number} fileId
303
+ * @param {number} lockType
304
+ * @returns {Promise<number>}
305
+ */
306
+ async jLock(fileId, lockType) {
307
+ if (hasUnsafeAccessHandle) return super.jLock(fileId, lockType);
308
+
309
+ const file = this.mapIdToFile.get(fileId);
310
+ if (!file.isFileLocked) {
311
+ file.isFileLocked = true;
312
+ if (!file.handleLockReleaser) {
313
+ // Listen for other connections wanting the access handle.
314
+ file.handleRequestChannel.onmessage = event => {
315
+ if(!file.isFileLocked) {
316
+ // We have the access handle but the file is not locked.
317
+ // Release the access handle for the requester.
318
+ file.accessHandle.close();
319
+ file.accessHandle = null;
320
+ file.handleLockReleaser();
321
+ file.handleLockReleaser = null;
322
+ this.log?.('access handle requested and released');
323
+ } else {
324
+ // We're still using the access handle, so mark it to be
325
+ // released when we're done.
326
+ file.isHandleRequested = true;
327
+ this.log?.('access handle requested');
328
+ }
329
+ file.handleRequestChannel.onmessage = null;
330
+ };
331
+
332
+ // We don't have the access handle. First acquire the lock.
333
+ file.handleLockReleaser = await new Promise((resolve, reject) => {
334
+ // Tell everyone we want the access handle.
335
+ function notify() {
336
+ file.handleRequestChannel.postMessage(null);
337
+ }
338
+ const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);
339
+ setTimeout(notify);
340
+
341
+ navigator.locks.request(this.getFilename(fileId), lock => {
342
+ clearInterval(notifyId);
343
+ if (!lock) return reject();
344
+ return new Promise(release => {
345
+ resolve(release);
346
+ });
347
+ });
348
+ });
349
+
350
+ // The access handle should now be available.
351
+ file.accessHandle = await file.fileHandle.createSyncAccessHandle();
352
+ this.log?.('access handle acquired');
353
+ }
354
+
355
+ }
356
+ return VFS.SQLITE_OK;
357
+ }
358
+
359
+ /**
360
+ * @param {number} fileId
361
+ * @param {number} lockType
362
+ * @returns {Promise<number>}
363
+ */
364
+ async jUnlock(fileId, lockType) {
365
+ if (hasUnsafeAccessHandle) return super.jUnlock(fileId, lockType);
366
+
367
+ if (lockType === VFS.SQLITE_LOCK_NONE) {
368
+ const file = this.mapIdToFile.get(fileId);
369
+ if (file.isHandleRequested) {
370
+ if (file.handleLockReleaser) {
371
+ // Another connection wants the access handle.
372
+ file.accessHandle.close();
373
+ file.accessHandle = null;
374
+ file.handleLockReleaser();
375
+ file.handleLockReleaser = null;
376
+ this.log?.('access handle released');
377
+ }
378
+ file.isHandleRequested = false;
379
+ }
380
+ file.isFileLocked = false;
381
+ }
382
+ return VFS.SQLITE_OK;
383
+ }
384
+
385
+ /**
386
+ * @param {number} fileId
387
+ * @param {number} op
388
+ * @param {DataView} pArg
389
+ * @returns {number|Promise<number>}
390
+ */
391
+ jFileControl(fileId, op, pArg) {
392
+ try {
393
+ const file = this.mapIdToFile.get(fileId);
394
+ switch (op) {
395
+ case VFS.SQLITE_FCNTL_PRAGMA:
396
+ const key = extractString(pArg, 4);
397
+ const value = extractString(pArg, 8);
398
+ this.log?.('xFileControl', file.pathname, 'PRAGMA', key, value);
399
+ switch (key.toLowerCase()) {
400
+ case 'journal_mode':
401
+ if (value &&
402
+ !hasUnsafeAccessHandle &&
403
+ !['off', 'memory', 'delete', 'wal'].includes(value.toLowerCase())) {
404
+ throw new Error('journal_mode must be "off", "memory", "delete", or "wal"');
405
+ }
406
+ break;
407
+ case 'write_hint':
408
+ return super.jFileControl(fileId, WebLocksMixin.WRITE_HINT_OP_CODE, null);
409
+ }
410
+ break;
411
+ }
412
+ } catch (e) {
413
+ this.lastError = e;
414
+ return VFS.SQLITE_IOERR;
415
+ }
416
+ return super.jFileControl(fileId, op, pArg);
417
+ }
418
+
419
+ jGetLastError(zBuf) {
420
+ if (this.lastError) {
421
+ console.error(this.lastError);
422
+ const outputArray = zBuf.subarray(0, zBuf.byteLength - 1);
423
+ const { written } = new TextEncoder().encodeInto(this.lastError.message, outputArray);
424
+ zBuf[written] = 0;
425
+ }
426
+ return VFS.SQLITE_OK
427
+ }
428
+ }
429
+
430
+ function extractString(dataView, offset) {
431
+ const p = dataView.getUint32(offset, true);
432
+ if (p) {
433
+ const chars = new Uint8Array(dataView.buffer, p);
434
+ return new TextDecoder().decode(chars.subarray(0, chars.indexOf(0)));
435
+ }
436
+ return null;
437
+ }