interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / wasm / api / sqlite3-vfs-kvvfs.c-pp.js

2168 lines · 77255 bytes Raw Blame History
1/*
2 2025-11-21
3
4 The author disclaims copyright to this source code. In place of a
5 legal notice, here is a blessing:
6
7 * May you do good and not evil.
8 * May you find forgiveness for yourself and forgive others.
9 * May you share freely, never taking more than you give.
10
11 ***********************************************************************
12
13 This file houses the "kvvfs" pieces of the SQLite3 JS API. Most of
14 kvvfs is implemented in src/os_kv.c and exposed/extended for use
15 here via sqlite3-wasm.c.
16
17 Main project home page: https://sqlite.org
18
19 Documentation home page: https://sqlite.org/wasm
20*/
21//#if target:node or omit-kvvfs
22sqlite3ApiBootstrap.initializers.push(function(sqlite3){
23 /* These are JS plumbing, not part of the public API */
24 delete sqlite3.capi.sqlite3_kvvfs_methods;
25 delete sqlite3.capi.KVVfsFile;
26});
27//#else
28//#@ push policy error
29//#savepoint begin
30//#define kvvfs-v2-added-in "3.52.0"
31
32/**
33 kvvfs - the Key/Value VFS - is an SQLite3 VFS which delegates
34 storage of its pages and metadata to a key-value store.
35
36 It was conceived in order to support JS's localStorage and
37 sessionStorage objects. Its native implementation uses files as
38 key/value storage (one file per record) but the JS implementation
39 replaces a few methods so that it can use the aforementioned
40 objects as storage.
41
42 It uses a bespoke ASCII encoding to store each db page as a
43 separate record and stores some metadata, like the db's unencoded
44 size and its journal, as individual records.
45
46 kvvfs is significantly less efficient than a plain in-memory db but
47 it also, as a side effect of its design, offers a JSON-friendly
48 interchange format for exporting and importing databases.
49
50 kvvfs is _not_ designed for heavy db loads. It is relatively
51 malloc()-heavy, having to de/allocate frequently, and it
52 spends much of its time converting the raw db pages into and out of
53 an ASCII encoding.
54
55 But it _does_ work and is "performant enough" for db work of the
56 scale of a db which will fit within sessionStorage or localStorage
57 (just 2-3mb).
58
59 "Version 2" extends it to support using Storage-like objects as
60 backing storage, Storage being the JS class which localStorage and
61 sessionStorage both derive from. This essentially moves the backing
62 store from whatever localStorage and sessionStorage use to an
63 in-memory object.
64
65 This effort is primarily a stepping stone towards eliminating, if
66 it proves possible, the POSIX I/O API dependencies in SQLite's WASM
67 builds. That is: if this VFS works properly, it can be set as the
68 default VFS and we can eliminate the "unix" VFS from the JS/WASM
69 builds (as opposed to server-wise/WASI builds). That still, as of
70 2025-11-23, a ways away, but it's the main driver for version 2 of
71 kvvfs.
72
73 Version 2 remains compatible with version 1 databases and always
74 writes localStorage/sessionStorage metadata in the v1 format, so
75 such dbs can be manipulated freely by either version. For transient
76 storage objects (new in version 2), the format of its record keys
77 is simpified, requiring less space than v1 keys by eliding
78 redundant (in this context) info from the keys.
79
80 Another benefit of v2 is its ability to export dbs into a
81 JSON-friendly (but not human-friendly) format.
82
83 A potential, as-yet-unproven, benefit, would be the ability to plug
84 arbitrary Storage-compatible objects in so that clients could,
85 e.g. asynchronously post updates to db pages to some back-end for
86 backups.
87*/
88sqlite3ApiBootstrap.initializers.push(function(sqlite3){
89 if( sqlite3.config.disable?.vfs?.kvvfs ){
90 return;
91 }
92 'use strict';
93 const capi = sqlite3.capi,
94 sqlite3_kvvfs_methods = capi.sqlite3_kvvfs_methods,
95 KVVfsFile = capi.KVVfsFile,
96 pKvvfs = sqlite3.capi.sqlite3_vfs_find("kvvfs")
97
98 /* These are JS plumbing, not part of the public API */
99 delete capi.sqlite3_kvvfs_methods;
100 delete capi.KVVfsFile;
101
102 if( !pKvvfs ) return /* nothing to do */;
103 if( 0 ){
104 /* This working would be our proverbial holy grail, in that it
105 would allow us to eliminate the current default VFS, which
106 relies on POSIX I/O APIs. Eliminating that dependency would get
107 us one giant step closer to creating wasi-sdk builds. */
108 capi.sqlite3_vfs_register(pKvvfs, 1);
109 }
110
111 const util = sqlite3.util,
112 wasm = sqlite3.wasm,
113 toss3 = util.toss3,
114 hop = (o,k)=>Object.prototype.hasOwnProperty.call(o,k);
115
116 const kvvfsMethods = new sqlite3_kvvfs_methods(
117 /* Wraps the static sqlite3_api_methods singleton */
118 wasm.exports.sqlite3__wasm_kvvfs_methods()
119 );
120 util.assert( 32<=kvvfsMethods.$nKeySize, "unexpected kvvfsMethods.$nKeySize: "+kvvfsMethods.$nKeySize);
121
122 /**
123 Most of the VFS-internal state.
124 */
125 const cache = Object.assign(Object.create(null),{
126 /** Regex matching journal file names. */
127 rxJournalSuffix: /-journal$/,
128 /** Frequently-used C-string. */
129 zKeyJrnl: wasm.allocCString("jrnl"),
130 /** Frequently-used C-string. */
131 zKeySz: wasm.allocCString("sz"),
132 /**
133 The maximum size of a kvvfs record key. It is historically only
134 32, a limitation currently retained only because it's convenient to
135 do so (the underlying code has outgrown the need for the artifically
136 low limit).
137
138 We cache this value here because the end of this init code will
139 dispose of kvvfsMethods, invalidating it.
140 */
141 keySize: kvvfsMethods.$nKeySize,
142 /**
143 WASM heap memory buffers to optimize out some frequent
144 allocations.
145 */
146 buffer: Object.assign(Object.create(null),{
147 /**
148 The size of each buffer in this.pool.
149
150 kvvfsMethods.$nBufferSize is slightly larger than the output
151 space needed for a kvvfs-encoded 64kb db page in a worse-cast
152 encoding (128kb). It is not suitable for arbitrary buffer
153 use, only page de/encoding.
154 */
155 n: kvvfsMethods.$nBufferSize,
156 /**
157 Map of buffer ids to wasm.alloc()'d pointers of size
158 this.n. (Re)used by various internals.
159
160 Buffer ids 0 and 1 are used in the API internals. Other
161 names are used in higher-level APIs.
162
163 See memBuffer() and memBufferFree().
164 */
165 pool: Object.create(null)
166 })
167 });
168
169 /**
170 Returns a (cached) wasm.alloc()'d buffer of cache.buffer.n size,
171 throwing on OOM.
172
173 We leak this one-time alloc because we've no better option.
174 sqlite3_vfs does not have a finalizer, so we've no place to hook
175 in the cleanup. We "could" extend sqlite3_shutdown() to have a
176 cleanup list for stuff like this but that function is never
177 used in JS, so it's hardly worth it.
178 */
179 cache.memBuffer = (id=0)=>cache.buffer.pool[id] ??= wasm.alloc(cache.buffer.n);
180
181 /** Frees the buffer with the given id. */
182 cache.memBufferFree = (id)=>{
183 const b = cache.buffer.pool[id];
184 if( b ){
185 wasm.dealloc(b);
186 delete cache.buffer.pool[id];
187 }
188 };
189
190 const noop = ()=>{};
191 const debug = sqlite3.__isUnderTest
192 ? (...args)=>sqlite3.config.debug?.("kvvfs:", ...args)
193 : noop;
194 const warn = (...args)=>sqlite3.config.warn?.("kvvfs:", ...args);
195 const error = (...args)=>sqlite3.config.error?.("kvvfs:", ...args);
196
197 /**
198 Implementation of JS's Storage interface for use as backing store
199 of the kvvfs. Storage is a native class and its constructor
200 cannot be legally called from JS, making it impossible to
201 directly subclass Storage. This class implements (only) the
202 Storage interface, to make it a drop-in replacement for
203 localStorage/sessionStorage. (Any behavioral discrepancies are to
204 be considered bugs.)
205
206 This impl simply proxies a plain, prototype-less Object, suitable
207 for JSON-ing.
208
209 Design note: Storage has a bit of an odd iteration-related
210 interface as does not (AFAIK) specify specific behavior regarding
211 modification during traversal. Because of that, this class does
212 some seemingly unnecessary things with its #keys member, deleting
213 and recreating it whenever a property index might be invalidated.
214 */
215 class KVVfsStorage {
216 #map = Object.create(null);
217 #keys = null;
218 #size = 0;
219
220 constructor(){
221 this.clear();
222 }
223
224 #getKeys(){
225 return this.#keys ??= Object.keys(this.#map);
226 }
227
228 key(n){
229 if(n < 0 || n >= this.#size) return null;
230 return this.#getKeys()[n];
231 }
232
233 getItem(k){
234 return this.#map[k] ?? null;
235 }
236
237 setItem(k,v){
238 if( !(k in this.#map) ){
239 ++this.#size;
240 this.#keys = null;
241 }
242 this.#map[k] = ''+v;
243 }
244
245 removeItem(k){
246 if( k in this.#map ){
247 delete this.#map[k];
248 --this.#size;
249 this.#keys = null;
250 }
251 }
252
253 clear(){
254 this.#map = Object.create(null);
255 this.#keys = null;
256 this.#size = 0;
257 }
258
259 get length() {
260 return this.#size;
261 }
262 }/*KVVfsStorage*/;
263
264 /** True if v is the name of one of the special persistant Storage
265 objects. */
266 const kvvfsIsPersistentName = (v)=>'local'===v || 'session'===v;
267
268 /**
269 Keys in kvvfs have a prefix of "kvvfs-NAME-", where NAME is the
270 db name. This key is redundant in JS but it's how kvvfs works (it
271 saves each key to a separate file, so needs a distinct namespace
272 per data source name). We retain this prefix in 'local' and
273 'session' storage for backwards compatibility and so that they
274 can co-exist with client data in their storage, but we elide them
275 from "v2" storage, where they're superfluous.
276 */
277 const kvvfsKeyPrefix = (v)=>kvvfsIsPersistentName(v) ? 'kvvfs-'+v+'-' : '';
278
279 /**
280 Throws if storage name n (JS string) is not valid for use as a
281 storage name. Much of this goes back to kvvfs having a fixed
282 buffer size for its keys, and the storage name needing to be
283 encoded in the keys for local/session storage.
284
285 The second argument must only be true when called from xOpen() -
286 it makes names with a "-journal" suffix legal.
287 */
288 const validateStorageName = function(n,mayBeJournal=false){
289 if( kvvfsIsPersistentName(n) ) return;
290 const len = (new Blob([n])).size/*byte length*/;
291 if( !len ) toss3(capi.SQLITE_MISUSE, "Empty name is not permitted.");
292 let maxLen = cache.keySize - 1;
293 if( cache.rxJournalSuffix.test(n) ){
294 if( !mayBeJournal ){
295 toss3(capi.SQLITE_MISUSE,
296 "Storage names may not have a '-journal' suffix.");
297 }
298 }else if( ['-wal','-shm'].filter(v=>n.endsWith(v)).length ){
299 toss3(capi.SQLITE_MISUSE,
300 "Storage names may not have a -wal or -shm suffix.");
301 }else{
302 maxLen -= 8 /* so we have space for a matching "-journal" suffix */;
303 }
304 if( len > maxLen ){
305 toss3(capi.SQLITE_RANGE, "Storage name is too long. Limit =", maxLen);
306 }
307 let i;
308 for( i = 0; i < len; ++i ){
309 const ch = n.codePointAt(i);
310 if( ch<32 ){
311 toss3(capi.SQLITE_RANGE,
312 "Illegal character ("+ch+"d) in storage name:",n);
313 }
314 }
315 };
316
317 /**
318 Create a new instance of the objects which go into
319 cache.storagePool, with a refcount of 1. If passed a Storage-like
320 object as its second argument, it is used for the storage,
321 otherwise it creates a new KVVfsStorage object.
322 */
323 const newStorageObj = (name,storage=undefined)=>Object.assign(Object.create(null),{
324 /**
325 JS string value of this KVVfsFile::$zClass. i.e. the storage's
326 name.
327 */
328 jzClass: name,
329 /**
330 Refcount. This keeps dbs and journals pointing to the same
331 storage for the life of both and enables kvvfs to behave more
332 like a conventional filesystem (a stepping stone towards
333 downstream API goals). Managed by xOpen() and xClose().
334 */
335 refc: 1,
336 /**
337 If true, this storage will be removed by xClose() or
338 sqlite3_js_kvvfs_unlink() when refc reaches 0. The others will
339 persist when refc==0, to give the illusion of real back-end
340 storage. Managed by xOpen() and sqlite3_js_kvvfs_reserve(). By
341 default this is false but the delete-on-close=1 flag can be
342 used to set this to true.
343 */
344 deleteAtRefc0: false,
345 /**
346 The backing store. Must implement the Storage interface.
347 */
348 storage: storage || new KVVfsStorage,
349 /**
350 The storage prefix used for kvvfs keys. It is
351 "kvvfs-STORAGENAME-" for local/session storage and an empty
352 string for other storage. local/session storage must use the
353 long form (A) for backwards compatibility and (B) so that kvvfs
354 can coexist with non-db client data in those backends. Neither
355 (A) nor (B) are concerns for KVVfsStorage objects.
356
357 This prefix mirrors the one generated by os_kv.c's
358 kvrecordMakeKey() and must stay in sync with that one.
359 */
360 keyPrefix: kvvfsKeyPrefix(name),
361 /**
362 KVVfsFile instances currently using this storage. Managed by
363 xOpen() and xClose().
364 */
365 files: [],
366 /**
367 If set, it's an array of objects with various event
368 callbacks. See sqlite3_js_kvvfs_listen(). When there are no
369 listeners, this member is set to undefined (instead of an empty
370 array) to allow us to more easily optimize out calls to
371 notifyListeners() for the common case of no listeners.
372 */
373 listeners: undefined
374 });
375
376 /**
377 Public interface for kvvfs v2. The capi.sqlite3_js_kvvfs_...()
378 routines remain in place for v1. Some members of this class proxy
379 to those functions but use different default argument values in
380 some cases.
381 */
382 const kvvfs = sqlite3.kvvfs = Object.create(null);
383 if( sqlite3.__isUnderTest ){
384 /* For inspection via the dev tools console. */
385 kvvfs.log = Object.assign(Object.create(null),{
386 xOpen: false,
387 xClose: false,
388 xWrite: false,
389 xRead: false,
390 xSync: false,
391 xAccess: false,
392 xFileControl: false,
393 xRcrdRead: false,
394 xRcrdWrite: false,
395 xRcrdDelete: false,
396 });
397 }
398
399 /**
400 Deletes the cache.storagePool entries for store (a
401 cache.storagePool entry) and its db/journal counterpart.
402 */
403 const deleteStorage = function(store){
404 const other = cache.rxJournalSuffix.test(store.jzClass)
405 ? store.jzClass.replace(cache.rxJournalSuffix,'')
406 : store.jzClass+'-journal';
407 kvvfs?.log?.xClose
408 && debug("cleaning up storage handles [", store.jzClass, other,"]",store);
409 delete cache.storagePool[store.jzClass];
410 delete cache.storagePool[other];
411 if( !sqlite3.__isUnderTest ){
412 /* In test runs, leave these for inspection. If we delete them here,
413 any prior dumps of them emitted via the console get cleared out
414 because the console shows live objects instead of call-time
415 static dumps. */
416 delete store.storage;
417 delete store.refc;
418 }
419 };
420
421 /**
422 Add both store.jzClass and store.jzClass+"-journal"
423 to cache.storagePool.
424 */
425 const installStorageAndJournal = (store)=>
426 cache.storagePool[store.jzClass] =
427 cache.storagePool[store.jzClass+'-journal'] = store;
428
429 /**
430 The public name of the current thread's transient storage
431 object. A storage object with this name gets preinstalled.
432 */
433 const nameOfThisThreadStorage = '.';
434
435 /**
436 Map of JS-stringified KVVfsFile::zClass names to
437 reference-counted Storage objects. These objects are created in
438 xOpen(). Their refcount is decremented in xClose(), and the
439 record is destroyed if the refcount reaches 0. We refcount so
440 that concurrent active xOpen()s on a given name, and within a
441 given thread, use the same storage object.
442 */
443 cache.storagePool = Object.assign(Object.create(null),{
444 /* Start off with mappings for well-known names. */
445 [nameOfThisThreadStorage]: newStorageObj(nameOfThisThreadStorage)
446 });
447
448 if( globalThis.Storage ){
449 /* If available, install local/session storage. */
450 if( globalThis.localStorage instanceof globalThis.Storage ){
451 cache.storagePool.local = newStorageObj('local', globalThis.localStorage);
452 }
453 if( globalThis.sessionStorage instanceof globalThis.Storage ){
454 cache.storagePool.session = newStorageObj('session', globalThis.sessionStorage);
455 }
456 }
457
458 cache.builtinStorageNames = Object.keys(cache.storagePool);
459
460 const isBuiltinName = (n)=>cache.builtinStorageNames.indexOf(n)>-1;
461
462 /* Add "-journal" twins for each cache.storagePool entry... */
463 for(const k of Object.keys(cache.storagePool)){
464 /* Journals in kvvfs are are stored as individual records within
465 their Storage-ish object, named "{storage.keyPrefix}jrnl". We
466 always map the db and its journal to the same Storage
467 object. */
468 const orig = cache.storagePool[k];
469 cache.storagePool[k+'-journal'] = orig;
470 }
471
472 cache.setError = (e=undefined, dfltErrCode=capi.SQLITE_ERROR)=>{
473 if( e ){
474 cache.lastError = e;
475 return (e.resultCode | 0) || dfltErrCode;
476 }
477 delete cache.lastError;
478 return 0;
479 };
480
481 cache.popError = ()=>{
482 const e = cache.lastError;
483 delete cache.lastError;
484 return e;
485 };
486
487 /** Exception handler for notifyListeners(). */
488 const catchForNotify = (e)=>{
489 warn("kvvfs.listener handler threw:",e);
490 };
491
492 const kvvfsDecode = wasm.exports.sqlite3__wasm_kvvfs_decode;
493 const kvvfsEncode = wasm.exports.sqlite3__wasm_kvvfs_encode;
494
495 /**
496 Listener events and their argument(s) (via the callback(ev)
497 ev.data member):
498
499 'open': number of opened handles on this storage.
500
501 'close': number of opened handles on this storage.
502
503 'write': key, value
504
505 'delete': key
506
507 'sync': true if it's from xSync(), false if it's from
508 xFileControl().
509
510 For efficiency's sake, all calls to this function should
511 be in the form:
512
513 store.listeners && notifyListeners(...);
514
515 Failing to do so will trigger an exceptin in this function (which
516 will be ignored but may produce a console warning).
517 */
518 const notifyListeners = async function(eventName,store,...args){
519 try{
520 //cache.rxPageNoSuffix ??= /(\d+)$/;
521 if( store.keyPrefix && args[0] ){
522 args[0] = args[0].replace(store.keyPrefix,'');
523 }
524 let u8enc, z0, z1, wcache;
525 for(const ear of store.listeners){
526 const ev = Object.create(null);
527 ev.storageName = store.jzClass;
528 ev.type = eventName;
529 const decodePages = ear.decodePages;
530 const f = ear.events[eventName];
531 if( f ){
532 if( !ear.includeJournal && args[0]==='jrnl' ){
533 continue;
534 }
535 if( 'write'===eventName && ear.decodePages && +args[0]>0 ){
536 /* Decode pages to Uint8Array, caching the result in
537 wcache in case we have more listeners. */
538 ev.data = [args[0]];
539 if( wcache?.[args[0]] ){
540 ev.data[1] = wcache[args[0]];
541 continue;
542 }
543 u8enc ??= new TextEncoder();
544 z0 ??= cache.memBuffer(10);
545 z1 ??= cache.memBuffer(11);
546 const u = u8enc.encode(args[1]);
547 const heap = wasm.heap8u();
548 heap.set(u, Number(z0));
549 heap[wasm.ptr.addn(z0, u.length)] = 0;
550 const rc = kvvfsDecode(z0, z1, cache.buffer.n);
551 if( rc>0 ){
552 wcache ??= Object.create(null);
553 wcache[args[0]]
554 = ev.data[1]
555 = heap.slice(Number(z1), wasm.ptr.addn(z1,rc));
556 }else{
557 continue;
558 }
559 }else{
560 ev.data = args.length
561 ? ((args.length===1) ? args[0] : args)
562 : undefined;
563 }
564 try{f(ev)?.catch?.(catchForNotify)}
565 catch(e){
566 warn("notifyListeners [",store.jzClass,"]",eventName,e);
567 }
568 }
569 }
570 }catch(e){
571 catchForNotify(e);
572 }
573 }/*notifyListeners()*/;
574
575 /**
576 Returns the storage object mapped to the given string zClass
577 (C-string pointer or JS string).
578 */
579 const storageForZClass = (zClass)=>
580 'string'===typeof zClass
581 ? cache.storagePool[zClass]
582 : cache.storagePool[wasm.cstrToJs(zClass)];
583
584
585 const kvvfsMakeKey = wasm.exports.sqlite3__wasm_kvvfsMakeKey;
586 /**
587 Returns a C string from kvvfsMakeKey() OR returns zKey. In the
588 former case the memory is static, so must be copied before a
589 second call. zKey MUST be a pointer passed to a VFS/file method,
590 to allow us to avoid an alloc and/or an snprintf(). It requires
591 C-string arguments for zClass and zKey. zClass may be NULL but
592 zKey may not.
593 */
594 const zKeyForStorage = (store, zClass, zKey)=>{
595 //debug("zKeyForStorage(",store, wasm.cstrToJs(zClass), wasm.cstrToJs(zKey));
596 return (zClass && store.keyPrefix) ? kvvfsMakeKey(zClass, zKey) : zKey;
597 };
598
599 const jsKeyForStorage = (store,zClass,zKey)=>
600 wasm.cstrToJs(zKeyForStorage(store, zClass, zKey));
601
602 const storageGetDbSize = (store)=>+store.storage.getItem(store.keyPrefix + "sz");
603
604 /**
605 sqlite3_file pointers => objects, each of which has:
606
607 .file = KVVfsFile instance
608
609 .jzClass = JS-string form of f.$zClass
610
611 .storage = Storage object. It is shared between a db and its
612 journal.
613 */
614 const pFileHandles = new Map();
615
616 /**
617 Map of filename to lock objects with this structure:
618
619 {.lockType: int, .nShared: int}
620
621 Used by xLock(), xUnlock(), and xCheckReservedLock(). Modelled
622 after the "same-process, same-file, different-db-handle" locking
623 in os_unix.c.
624 */
625 const mapPathToLocks = new Map();
626
627 /**
628 Main xUnlock() impl for kvvfs, also used by xClose(). Expects an
629 xOpen()-created file handle object and the second argument to
630 xUnlock(). It returns void.
631 */
632 const unlockFile = function(fh, lockType){
633 if(fh.lockType<=lockType) return;
634 const lk = mapPathToLocks.get(fh.jzClass);
635 if(fh.lockType>capi.SQLITE_LOCK_SHARED){
636 lk.lockType = capi.SQLITE_LOCK_SHARED;
637 }
638 if(lockType===capi.SQLITE_LOCK_NONE && 0===--lk.nShared
639 /* Maintenance reminder: the && ordering is significant */){
640 mapPathToLocks.delete(fh.jzClass);
641 }
642 fh.lockType = lockType;
643 };
644
645 /**
646 Original WASM functions for methods we partially override.
647 */
648 const originalMethods = {
649 vfs: Object.create(null),
650 ioDb: Object.create(null),
651 ioJrnl: Object.create(null)
652 };
653
654 /** Returns the appropriate originalMethods[X] instance for the
655 given a KVVfsFile instance. */
656 const originalIoMethods = (kvvfsFile)=>
657 originalMethods[kvvfsFile.$isJournal ? 'ioJrnl' : 'ioDb'];
658
659 const pVfs = new capi.sqlite3_vfs(kvvfsMethods.$pVfs);
660 const pIoDb = new capi.sqlite3_io_methods(kvvfsMethods.$pIoDb);
661 const pIoJrnl = new capi.sqlite3_io_methods(kvvfsMethods.$pIoJrnl);
662 const recordHandler =
663 Object.create(null)/** helper for some vfs
664 routines. Populated later. */;
665 const kvvfsInternal = Object.assign(Object.create(null),{
666 pFileHandles,
667 cache,
668 storageForZClass,
669 KVVfsStorage,
670 /**
671 BUG: changing to a page size other than the default,
672 then vacuuming, corrupts the db. As a workaround,
673 until this is resolved, we forcibly disable
674 (pragma page_size=...) changes.
675 */
676 disablePageSizeChange: true
677 });
678 if( kvvfs.log ){
679 // this is a test build
680 kvvfs.internal = kvvfsInternal;
681 }
682
683 /**
684 Implementations for members of the object referred to by
685 sqlite3__wasm_kvvfs_methods(). We swap out some native
686 implementations with these so that we can use JS Storage for
687 their backing store.
688 */
689 const methodOverrides = {
690
691 /**
692 sqlite3_kvvfs_methods's member methods. These perform the
693 fetching, setting, and removal of storage keys on behalf of
694 kvvfs. In the native impl these write each db page to a
695 separate file. This impl stores each db page as a single
696 record in a Storage object which is mapped to zClass.
697
698 A db's size is stored in a record named kvvfs[-storagename]-sz
699 and the journal is stored in kvvfs[-storagename]-jrnl. The
700 [-storagename] part is a remnant of the native impl (so that
701 it has unique filenames per db) and is only used for
702 localStorage and sessionStorage. We elide that part (to save
703 space) from other storage objects but retain it on those two
704 to avoid invalidating pre-version-2 session/localStorage dbs.
705
706 The interface docs for these methods are in src/os_kv.c's
707 kvrecordRead(), kvrecordWrite(), and kvrecordDelete().
708 */
709 recordHandler: {
710 xRcrdRead: (zClass, zKey, zBuf, nBuf)=>{
711 try{
712 const jzClass = wasm.cstrToJs(zClass);
713 const store = storageForZClass(jzClass);
714 if( !store ) return -1;
715 const jXKey = jsKeyForStorage(store, zClass, zKey);
716 kvvfs?.log?.xRcrdRead && warn("xRcrdRead", jzClass, jXKey, nBuf, store );
717 const jV = store.storage.getItem(jXKey);
718 if(null===jV) return -1;
719 const nV = jV.length /* We are relying 100% on v being
720 ** ASCII so that jV.length is equal
721 ** to the C-string's byte length. */;
722 if( 0 ){
723 debug("xRcrdRead", jXKey, store, jV);
724 }
725 if(nBuf<=0) return nV;
726 else if(1===nBuf){
727 wasm.poke(zBuf, 0);
728 return nV;
729 }else if( nBuf<nV ){
730 toss3(capi.SQLITE_RANGE,
731 "xRcrdRead()",jzClass,jXKey,
732 "input buffer is too small: need",
733 nV,"but have",nBuf);
734 }else if( nBuf > nV + 1 ){
735 nBuf = nV + 1;
736 }
737 if( 0 ){
738 debug("xRcrdRead", nBuf, zClass, wasm.cstrToJs(zClass),
739 wasm.cstrToJs(zKey), nV, jV, store);
740 }
741 const nCopy = nV<nBuf ? nV : nBuf-1;
742 const heap = wasm.heap8();
743 for (let i = 0; i < nCopy; ++i) {
744 heap[wasm.ptr.add(zBuf, i)] = jV.codePointAt(i) & 0xff;
745 }
746 heap[wasm.ptr.add(zBuf, nCopy)] = 0;
747 return nCopy;
748 }catch(e){
749 error("kvrecordRead()",e);
750 cache.setError(e);
751 return -2;
752 }
753 },
754
755 xRcrdWrite: (zClass, zKey, zData)=>{
756 try {
757 const store = storageForZClass(zClass);
758 const jxKey = jsKeyForStorage(store, zClass, zKey);
759 const jData = wasm.cstrToJs(zData);
760 kvvfs?.log?.xRcrdWrite && warn("xRcrdWrite",jxKey, store);
761 store.storage.setItem(jxKey, jData);
762 store.listeners && notifyListeners('write', store, jxKey, jData);
763 return 0;
764 }catch(e){
765 error("kvrecordWrite()",e);
766 return cache.setError(e, capi.SQLITE_IOERR);
767 }
768 },
769
770 xRcrdDelete: (zClass, zKey)=>{
771 try {
772 const store = storageForZClass(zClass);
773 const jxKey = jsKeyForStorage(store, zClass, zKey);
774 kvvfs?.log?.xRcrdDelete && warn("xRcrdDelete",jxKey, store);
775 store.storage.removeItem(jxKey);
776 store.listeners && notifyListeners('delete', store, jxKey);
777 return 0;
778 }catch(e){
779 error("kvrecordDelete()",e);
780 return cache.setError(e, capi.SQLITE_IOERR);
781 }
782 }
783 }/*recordHandler*/,
784
785 /**
786 Override certain operations of the underlying sqlite3_vfs and
787 the two sqlite3_io_methods instances so that we can tie
788 Storage objects to db names.
789 */
790 vfs:{
791 /* sqlite3_kvvfs_methods::pVfs's methods */
792 xOpen: function(pProtoVfs,zName,pProtoFile,flags,pOutFlags){
793 cache.popError();
794 let zToFree /* alloc()'d memory for temp db name */;
795 try{
796 if( !zName ){
797 zToFree = wasm.allocCString(""+pProtoFile+"."
798 +(Math.random() * 100000 | 0));
799 zName = zToFree;
800 }
801 const jzClass = wasm.cstrToJs(zName);
802 kvvfs?.log?.xOpen && debug("xOpen",jzClass,"flags =",flags);
803 validateStorageName(jzClass, true);
804 if( (flags & (capi.SQLITE_OPEN_MAIN_DB
805 | capi.SQLITE_OPEN_TEMP_DB
806 | capi.SQLITE_OPEN_TRANSIENT_DB))
807 && cache.rxJournalSuffix.test(jzClass) ){
808 toss3(capi.SQLITE_ERROR,
809 "DB files may not have a '-journal' suffix.");
810 }
811 let s = storageForZClass(jzClass);
812 if( !s && !(flags & capi.SQLITE_OPEN_CREATE) ){
813 toss3(capi.SQLITE_ERROR, "Storage not found:", jzClass);
814 }
815 const rc = originalMethods.vfs.xOpen(pProtoVfs, zName, pProtoFile,
816 flags, pOutFlags);
817 if( rc ) return rc;
818 let deleteAt0 = !!(capi.SQLITE_OPEN_DELETEONCLOSE & flags);
819 if(wasm.isPtr(arguments[1]/*original zName*/)){
820 if(capi.sqlite3_uri_boolean(zName, "delete-on-close", 0)){
821 deleteAt0 = true;
822 }
823 }
824 const f = new KVVfsFile(pProtoFile);
825 util.assert(f.$zClass, "Missing f.$zClass");
826 f.addOnDispose(zToFree);
827 zToFree = undefined;
828 //debug("xOpen", jzClass, s);
829 if( s ){
830 ++s.refc;
831 //no if( true===deleteAt0 ) s.deleteAtRefc0 = true;
832 s.files.push(f);
833 wasm.poke32(pOutFlags, flags);
834 }else{
835 wasm.poke32(pOutFlags, flags | capi.SQLITE_OPEN_CREATE);
836 util.assert( !f.$isJournal, "Opening a journal before its db? "+jzClass );
837 /* Map both zName and zName-journal to the same storage. */
838 const nm = jzClass.replace(cache.rxJournalSuffix,'');
839 s = newStorageObj(nm);
840 installStorageAndJournal(s);
841 s.files.push(f);
842 s.deleteAtRefc0 = deleteAt0;
843 kvvfs?.log?.xOpen
844 && debug("xOpen installed storage handle [",nm, nm+"-journal","]", s);
845 }
846 pFileHandles.set(pProtoFile, Object.assign(Object.create(null),{
847 store: s,
848 file: f,
849 jzClass,
850 lockType: 0
851 }));
852 s.listeners && notifyListeners('open', s, s.files.length);
853 return 0;
854 }catch(e){
855 warn("xOpen:",e);
856 return cache.setError(e);
857 }finally{
858 zToFree && wasm.dealloc(zToFree);
859 }
860 }/*xOpen()*/,
861
862 xDelete: function(pVfs, zName, iSyncFlag){
863 cache.popError();
864 try{
865 const jzName = wasm.cstrToJs(zName);
866 if( cache.rxJournalSuffix.test(jzName) ){
867 recordHandler.xRcrdDelete(zName, cache.zKeyJrnl);
868 }/*
869 else: historically not done, but maybe otherwise delete
870 all db pages from storageForZClass(zName)?
871 */
872 return 0;
873 }catch(e){
874 warn("xDelete",e);
875 return cache.setError(e);
876 }
877 },
878
879 xAccess: function(pProtoVfs, zPath, flags, pResOut){
880 cache.popError();
881 try{
882 const s = storageForZClass(zPath);
883 const jzPath = s?.jzClass || wasm.cstrToJs(zPath);
884 if( kvvfs?.log?.xAccess ){
885 debug("xAccess",jzPath,"flags =",
886 flags,"*pResOut =",wasm.peek32(pResOut),
887 "store =",s);
888 }
889 if( !s ){
890 // From the API docs:
891 /** The xAccess method returns [SQLITE_OK] on success or some
892 ** non-zero error code if there is an I/O error or if the name of
893 ** the file given in the second argument is illegal.
894 */
895 // However, returning non-0 from here is fatal, so we don't do that.
896 try{validateStorageName(jzPath)}
897 catch(e){
898 //warn("xAccess is ignoring name validation failure:",e);
899 wasm.poke32(pResOut, 0);
900 return 0;
901 }
902 }
903 if( s ){
904 const key = s.keyPrefix+
905 (cache.rxJournalSuffix.test(jzPath) ? "jrnl" : "1");
906 const res = s.storage.getItem(key) ? 0 : 1;
907 /* This res value looks completely backwards to me, and
908 is the opposite of the native kvvfs's impl, but it's
909 working, whereas reimplementing the native one
910 faithfully does not. Read the lib-level code of where
911 this is invoked, my expectation is that we set res to 0
912 for not-exists. */
913 //warn("access res",jzPath,res);
914 wasm.poke32(pResOut, res);
915 }else{
916 wasm.poke32(pResOut, 0);
917 }
918 return 0;
919 }catch(e){
920 error('xAccess',e);
921 return cache.setError(e);
922 }
923 },
924
925 xRandomness: function(pVfs, nOut, pOut){
926 const heap = wasm.heap8u();
927 let i = 0;
928 const npOut = Number(pOut);
929 for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
930 return nOut;
931 },
932
933 xGetLastError: function(pVfs,nOut,pOut){
934 const e = cache.popError();
935 debug('xGetLastError',e);
936 if(e){
937 const scope = wasm.scopedAllocPush();
938 try{
939 const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
940 wasm.cstrncpy(pOut, cMsg, nOut);
941 if(n > nOut) wasm.poke8(wasm.ptr.add(pOut,nOut,-1), 0);
942 debug("set xGetLastError",e.message);
943 return (e.resultCode | 0) || capi.SQLITE_IOERR;
944 }catch(e){
945 return capi.SQLITE_NOMEM;
946 }finally{
947 wasm.scopedAllocPop(scope);
948 }
949 }
950 return 0;
951 },
952
953 /**
954 This VFS's xSleep() must be a no-op. In this environment,
955 only db handles within the same thread can ever come into
956 contention, and that contention cannot be resolved if
957 one of the handles sleeps in that same thread.
958 See also: forum:3f0794c5d8
959 */
960 xSleep: (pVfs,ms)=>0,
961
962//#if 0
963 // these impls work but there's currently no pressing need _not_ use
964 // the native impls.
965 xCurrentTime: function(pVfs,pOut){
966 wasm.poke64f(pOut, 2440587.5 + (Date.now()/86400000));
967 return 0;
968 },
969
970 xCurrentTimeInt64: function(pVfs,pOut){
971 wasm.poke64(pOut, (2440587.5 * 86400000) + Date.now());
972 return 0;
973 }
974//#/if
975 }/*.vfs*/,
976
977 /**
978 kvvfs has separate sqlite3_api_methods impls for some of the
979 methods depending on whether it's a db or journal file. Some
980 of the methods use shared impls but others are specific to
981 either db or journal files.
982 */
983 ioDb:{
984 /* sqlite3_kvvfs_methods::pIoDb's methods */
985 xClose: function(pFile){
986 cache.popError();
987 try{
988 const h = pFileHandles.get(pFile);
989 kvvfs?.log?.xClose && debug("xClose", pFile, h);
990 if( h ){
991 pFileHandles.delete(pFile);
992 unlockFile(h, capi.SQLITE_LOCK_NONE);
993 const s = h.store;//storageForZClass(h.jzClass);
994 s.files = s.files.filter((v)=>v!==h.file);
995 if( --s.refc<=0 && s.deleteAtRefc0 ){
996 deleteStorage(s);
997 }
998 originalMethods.ioDb/*same for journals*/.xClose(pFile);
999 h.file.dispose();
1000 s.listeners && notifyListeners('close', s, s.files.length);
1001 }else{
1002 /* Can happen if xOpen fails */
1003 }
1004 return 0;
1005 }catch(e){
1006 error("xClose",e);
1007 return cache.setError(e);
1008 }
1009 },
1010
1011 xFileControl: function(pFile, opId, pArg){
1012 cache.popError();
1013 try{
1014 const h = pFileHandles.get(pFile);
1015 util.assert(h, "Missing KVVfsFile handle");
1016 kvvfs?.log?.xFileControl && debug("xFileControl",h,'op =',opId);
1017 if( opId===capi.SQLITE_FCNTL_PRAGMA
1018 && kvvfsInternal.disablePageSizeChange ){
1019 /* pArg== length-3 (char**) */
1020 //const argv = wasm.cArgvToJs(3, pArg); // the easy way
1021 const zName = wasm.peekPtr(wasm.ptr.add(pArg, wasm.ptr.size));
1022 if( "page_size"===wasm.cstrToJs(zName) ){
1023 kvvfs?.log?.xFileControl
1024 && debug("xFileControl pragma",wasm.cstrToJs(zName));
1025 const zVal = wasm.peekPtr(wasm.ptr.add(pArg, 2*wasm.ptr.size));
1026 if( zVal ){
1027 /* Without this, pragma page_size=N; followed by a
1028 vacuum breaks the db. With this, it continues
1029 working but does not actually change the page
1030 size. */
1031 kvvfs?.log?.xFileControl
1032 && warn("xFileControl pragma", h,
1033 "NOT setting page size to", wasm.cstrToJs(zVal));
1034 h.file.$szPage = -1;
1035 return 0/*corrupts: capi.SQLITE_NOTFOUND*/;
1036 }else if( h.file.$szPage>0 ){
1037 kvvfs?.log?.xFileControl &&
1038 warn("xFileControl", h, "getting page size",h.file.$szPage);
1039 wasm.pokePtr(pArg, wasm.allocCString(""+h.file.$szPage)
1040 /* memory now owned by the library */);
1041 return 0;//capi.SQLITE_NOTFOUND;
1042 }
1043 }
1044 }
1045 const rc = originalMethods.ioDb.xFileControl(pFile, opId, pArg);
1046 if( 0==rc && capi.SQLITE_FCNTL_SYNC===opId ){
1047 h.store.listeners && notifyListeners('sync', h.store, false);
1048 }
1049 return rc;
1050 }catch(e){
1051 error("xFileControl",e);
1052 return cache.setError(e);
1053 }
1054 },
1055
1056 xSync: function(pFile,flags){
1057 cache.popError();
1058 try{
1059 const h = pFileHandles.get(pFile);
1060 kvvfs?.log?.xSync && debug("xSync", h);
1061 util.assert(h, "Missing KVVfsFile handle");
1062 const rc = originalMethods.ioDb.xSync(pFile, flags);
1063 if( 0==rc && h.store.listeners ) notifyListeners('sync', h.store, true);
1064 return rc;
1065 }catch(e){
1066 error("xSync",e);
1067 return cache.setError(e);
1068 }
1069 },
1070
1071 xLock: function(pFile, iLock){
1072 cache.popError();
1073 try{
1074 const h = pFileHandles.get(pFile);
1075 if( capi.SQLITE_LOCK_NONE!==iLock ){
1076 /* Tells the impl to re-read its size. */
1077 originalMethods.ioDb.xLock(pFile, iLock);
1078 }
1079 /**
1080 This impl is based off of the one in the opfs-sahpool VFS
1081 impl which, in turn, is based off of the impl in
1082 os_unix.c.
1083 */
1084 if(h.lockType>=iLock) return 0;
1085 let lk = mapPathToLocks.get(h.jzClass);
1086 if(!lk){
1087 lk = Object.assign(Object.create(null),{
1088 nShared: 0, lockType: capi.SQLITE_LOCK_NONE
1089 });
1090 mapPathToLocks.set(h.jzClass, lk);
1091 }
1092 if(h.lockType!==lk.lockType
1093 && (lk.lockType>=capi.SQLITE_LOCK_PENDING
1094 || iLock>capi.SQLITE_LOCK_SHARED)){
1095 return capi.SQLITE_BUSY;
1096 }
1097 if(iLock===capi.SQLITE_LOCK_SHARED){
1098 ++lk.nShared;
1099 if(lk.lockType===capi.SQLITE_LOCK_NONE) lk.lockType = iLock;
1100 }else if(iLock===capi.SQLITE_LOCK_EXCLUSIVE && lk.nShared>1){
1101 if(h.lockType===capi.SQLITE_LOCK_RESERVED){
1102 h.lockType = lk.lockType = capi.SQLITE_LOCK_PENDING;
1103 }
1104 return capi.SQLITE_BUSY;
1105 }else{
1106 lk.lockType = iLock;
1107 }
1108 h.lockType = iLock;
1109 return 0;
1110 }catch(e){
1111 error("xLock", e);
1112 return cache.setError(e);
1113 }
1114 },
1115
1116 xUnlock: function(pFile, iLock){
1117 cache.popError();
1118 try{
1119 if( capi.SQLITE_LOCK_NONE===iLock ){
1120 /* Tells the impl to re-read its size on the next op. */
1121 originalMethods.ioDb.xUnlock(pFile, iLock);
1122 }
1123 const h = pFileHandles.get(pFile);
1124 unlockFile(h, iLock);
1125 return 0;
1126 }catch(e){
1127 error("xUnlock", e);
1128 return cache.setError(e);
1129 }
1130 },
1131
1132 xCheckReservedLock: function(pFile, pOut){
1133 cache.popError();
1134 try{
1135 const h = pFileHandles.get(pFile);
1136 const lk = mapPathToLocks.get(h.jzClass);
1137 wasm.poke32(pOut,
1138 (!!lk && lk.lockType>capi.SQLITE_LOCK_SHARED)
1139 ? 1 : 0)
1140 return 0;
1141 }catch(e){
1142 error("xCheckReservedLock", e);
1143 return cache.setError(e);
1144 }
1145 },
1146
1147//#if 0
1148 // We override xRead/xWrite only for logging/debugging. They
1149 // should otherwise be disabled (it's faster that way).
1150 xRead: function(pFile,pTgt,n,iOff64){
1151 cache.popError();
1152 try{
1153 if( kvvfs?.log?.xRead ){
1154 const h = pFileHandles.get(pFile);
1155 util.assert(h, "Missing KVVfsFile handle");
1156 debug("xRead", n, iOff64, h);
1157 }
1158 return originalMethods.ioDb.xRead(pFile, pTgt, n, iOff64);
1159 }catch(e){
1160 error("xRead",e);
1161 return cache.setError(e);
1162 }
1163 },
1164 xWrite: function(pFile,pSrc,n,iOff64){
1165 cache.popError();
1166 try{
1167 if( kvvfs?.log?.xWrite ){
1168 const h = pFileHandles.get(pFile);
1169 util.assert(h, "Missing KVVfsFile handle");
1170 debug("xWrite", n, iOff64, h);
1171 }
1172 return originalMethods.ioDb.xWrite(pFile, pSrc, n, iOff64);
1173 }catch(e){
1174 error("xWrite",e);
1175 return cache.setError(e);
1176 }
1177 },
1178//#/if
1179
1180//#if 0
1181 xTruncate: function(pFile,i64){},
1182 xFileSize: function(pFile,pi64Out){},
1183 xSectorSize: function(pFile){},
1184 xDeviceCharacteristics: function(pFile){}
1185//#/if
1186 }/*.ioDb*/,
1187
1188 ioJrnl:{
1189 /* sqlite3_kvvfs_methods::pIoJrnl's methods. Those set to true
1190 are copied as-is from the ioDb objects. Others are specific
1191 to journal files. */
1192 xClose: true,
1193 xLock: true,
1194 xUnlock: true,
1195 xCheckReservedLock: true,
1196//#if 0
1197 xRead: function(pFile,pTgt,n,iOff64){},
1198 xWrite: function(pFile,pSrc,n,iOff64){},
1199 xTruncate: function(pFile,i64){},
1200 xSync: function(pFile,flags){},
1201 xFileControl: function(pFile, opId, pArg){},
1202 xFileSize: function(pFile,pi64Out){},
1203 xSectorSize: true,
1204 xDeviceCharacteristics: true
1205//#/if
1206 }/*.ioJrnl*/
1207 }/*methodOverrides*/;
1208
1209//#if 0
1210 debug("pVfs and friends", pVfs, pIoDb, pIoJrnl,
1211 kvvfsMethods, capi.sqlite3_file.structInfo,
1212 KVVfsFile.structInfo);
1213//#/if
1214
1215 try {
1216 util.assert( cache.buffer.n>1024*129, "Heap buffer is not large enough"
1217 /* Native is SQLITE_KVOS_SZ is 133073 as of this writing */ );
1218 for(const e of Object.entries(methodOverrides.recordHandler)){
1219 // Overwrite kvvfsMethods's callbacks
1220 const k = e[0], f = e[1];
1221 recordHandler[k] = f;
1222 if( 0 ){
1223 // bug: this should work
1224 kvvfsMethods.installMethod(k, f);
1225 }else{
1226 kvvfsMethods[kvvfsMethods.memberKey(k)] =
1227 wasm.installFunction(kvvfsMethods.memberSignature(k), f);
1228 }
1229 }
1230 for(const e of Object.entries(methodOverrides.vfs)){
1231 // Overwrite some pVfs entries and stash the original impls
1232 const k = e[0], f = e[1], km = pVfs.memberKey(k),
1233 member = pVfs.structInfo.members[k]
1234 || util.toss("Missing pVfs.structInfo[",k,"]");
1235 originalMethods.vfs[k] = wasm.functionEntry(pVfs[km]);
1236 pVfs[km] = wasm.installFunction(member.signature, f);
1237 }
1238 for(const e of Object.entries(methodOverrides.ioDb)){
1239 // Similar treatment for pVfs.$pIoDb a.k.a. pIoDb...
1240 const k = e[0], f = e[1], km = pIoDb.memberKey(k);
1241 originalMethods.ioDb[k] = wasm.functionEntry(pIoDb[km])
1242 || util.toss("Missing native pIoDb[",km,"]");
1243 pIoDb[km] = wasm.installFunction(pIoDb.memberSignature(k), f);
1244 }
1245 for(const e of Object.entries(methodOverrides.ioJrnl)){
1246 // Similar treatment for pVfs.$pIoJrnl a.k.a. pIoJrnl...
1247 const k = e[0], f = e[1], km = pIoJrnl.memberKey(k);
1248 originalMethods.ioJrnl[k] = wasm.functionEntry(pIoJrnl[km])
1249 || util.toss("Missing native pIoJrnl[",km,"]");
1250 if( true===f ){
1251 /* use pIoDb's copy */
1252 pIoJrnl[km] = pIoDb[km] || util.toss("Missing copied pIoDb[",km,"]");
1253 }else{
1254 pIoJrnl[km] = wasm.installFunction(pIoJrnl.memberSignature(k), f);
1255 }
1256 }
1257 }finally{
1258 kvvfsMethods.dispose();
1259 pVfs.dispose();
1260 pIoDb.dispose();
1261 pIoJrnl.dispose();
1262 }
1263
1264 /*
1265 That gets all of the low-level bits out of the way. What follows
1266 are the public API additions.
1267 */
1268
1269 /**
1270 Clears all storage used by the kvvfs DB backend, deleting any
1271 DB(s) stored there.
1272
1273 Its argument must be the name of a kvvfs storage object:
1274
1275 - 'session'
1276 - 'local'
1277 - '' - see below.
1278 - A transient kvvfs storage object name.
1279
1280 In the first two cases, only sessionStorage resp. localStorage is
1281 cleared. An empty string resolves to both 'local' and 'session'
1282 storage.
1283
1284 Returns the number of entries cleared.
1285
1286 As of kvvfs version 2:
1287
1288 This API is available in Worker threads but does not have access
1289 to localStorage or sessionStorage in them. Prior versions did not
1290 include this API in Worker threads.
1291
1292 Differences in this function in version 2:
1293
1294 - It accepts an arbitrary storage name. In v1 this was a silent
1295 no-op for any names other than ('local','session','').
1296
1297 - It throws if a db currently has the storage opened UNLESS the
1298 storage object is localStorage or sessionStorage. That version 1
1299 did not throw for this case was due to an architectural
1300 limitation which has since been overcome, but removal of
1301 JsStorageDb.prototype.clearStorage() would be a backwards compatibility
1302 break, so this function permits wiping the storage for those two
1303 cases even if they are opened. Use with care.
1304 */
1305 const sqlite3_js_kvvfs_clear = function callee(which){
1306 if( ''===which ){
1307 return callee('local') + callee('session');
1308 }
1309 const store = storageForZClass(which);
1310 if( !store ) return 0;
1311 if( store.files.length ){
1312 if( globalThis.localStorage===store.storage
1313 || globalThis.sessionStorage===store.storage ){
1314 /* backwards compatibility: allow these to be cleared
1315 while opened. */
1316 }else{
1317 /* Interestingly, kvvfs recovers just fine when the storage is
1318 wiped, so long as the db is not in use and its schema is
1319 recreated before it's used, but client apps should not have
1320 to be faced with that eventuality mid-query (where it
1321 _will_ cause failures). Therefore we disallow it when
1322 storage handles are opened. Kvvfs version 1 could not
1323 detect this case - see the if() block above.
1324 */
1325 toss3(capi.SQLITE_ACCESS,
1326 "Cannot clear in-use database storage.");
1327 }
1328 }
1329 const s = store.storage;
1330 const toRm = [] /* keys to remove */;
1331 let i, n = s.length;
1332 //debug("kvvfs_clear",store,s);
1333 for( i = 0; i < n; ++i ){
1334 const k = s.key(i);
1335 //debug("kvvfs_clear ?",k);
1336 if(!store.keyPrefix || k.startsWith(store.keyPrefix)) toRm.push(k);
1337 }
1338 toRm.forEach((kk)=>s.removeItem(kk));
1339 //alertFilesToReload(store);
1340 return toRm.length;
1341 };
1342
1343 /**
1344 This routine estimates the approximate amount of
1345 storage used by the given kvvfs back-end.
1346
1347 Its arguments are as documented for sqlite3_js_kvvfs_clear(),
1348 only the operation this performs is different.
1349
1350 The returned value is twice the "length" value of every matching
1351 key and value, noting that JavaScript stores each character in 2
1352 bytes.
1353
1354 The returned size is not authoritative from the perspective of
1355 how much data can fit into localStorage and sessionStorage, as
1356 the precise algorithms for determining those limits are
1357 unspecified and may include per-entry overhead invisible to
1358 clients.
1359 */
1360 const sqlite3_js_kvvfs_size = function callee(which){
1361 if( ''===which ){
1362 return callee('local') + callee('session');
1363 }
1364 const store = storageForZClass(which);
1365 if( !store ) return 0;
1366 const s = store.storage;
1367 let i, sz = 0;
1368 for(i = 0; i < s.length; ++i){
1369 const k = s.key(i);
1370 if(!store.keyPrefix || k.startsWith(store.keyPrefix)){
1371 sz += k.length;
1372 sz += s.getItem(k).length;
1373 }
1374 }
1375 return sz * 2 /* because JS uses 2-byte char encoding */;
1376 };
1377
1378 /**
1379 Exports a kvvfs storage object to an object, optionally
1380 JSON-friendly.
1381
1382 Usages:
1383
1384 thisfunc(storageName);
1385 thisfunc(options);
1386
1387 In the latter case, the options object must be an object with
1388 the following properties:
1389
1390 - "name" (string) required. The storage to export.
1391
1392 - "decodePages" (bool=false). If true, the .pages result property
1393 holdes Uint8Array objects holding the raw binary-format db
1394 pages. The default is to use kvvfs-encoded string pages
1395 (JSON-friendly).
1396
1397 - "includeJournal" (bool=false). If true and the db has a current
1398 journal, it is exported as well. (Kvvfs journals are stored as a
1399 single record within the db's storage object.)
1400
1401 The returned object is structured as follows...
1402
1403 - "name": the name of the storage. This is 'local' or 'session'
1404 for localStorage resp. sessionStorage, and an arbitrary name for
1405 transient storage. This propery may be changed before passing
1406 this object to sqlite3_js_kvvfs_import() in order to
1407 import into a different storage object.
1408
1409 - "timestamp": the time this function was called, in Unix
1410 epoch milliseconds.
1411
1412 - "size": the unencoded db size.
1413
1414 - "journal": if options.includeJournal is true and this db has a
1415 journal, it is stored as a string here, otherwise this property
1416 is not set.
1417
1418 - "pages": An array holding the raw encoded db pages in their
1419 proper order.
1420
1421 Throws if this db is not opened.
1422
1423 The encoding of the underlying database is not part of this
1424 interface - it is simply passed on as-is. Interested parties are
1425 directed to src/os_kv.c in the SQLite source tree, with the
1426 caveat that that code also does not offer a public interface.
1427 i.e. the encoding is a private implementation detail of kvvfs.
1428 The format may be changed in the future but kvvfs will continue
1429 to support the current form.
1430
1431 Added in version @kvvfs-v2-added-in@.
1432 */
1433 const sqlite3_js_kvvfs_export = function callee(...args){
1434 let opt;
1435 if( 1===args.length && 'object'===typeof args[0] ){
1436 opt = args[0];
1437 }else if(args.length){
1438 opt = Object.assign(Object.create(null),{
1439 name: args[0],
1440 //decodePages: true
1441 });
1442 }
1443 const store = opt ? storageForZClass(opt.name) : null;
1444 if( !store ){
1445 toss3(capi.SQLITE_NOTFOUND,
1446 "There is no kvvfs storage named",opt?.name);
1447 }
1448 //debug("store to export=",store);
1449 const s = store.storage;
1450 const rc = Object.assign(Object.create(null),{
1451 name: store.jzClass,
1452 timestamp: Date.now(),
1453 pages: []
1454 });
1455 const pages = Object.create(null);
1456 let xpages;
1457 const keyPrefix = store.keyPrefix;
1458 const rxTail = keyPrefix
1459 ? /^kvvfs-[^-]+-(\w+)/ /* X... part of kvvfs-NAME-X... */
1460 : undefined;
1461 let i = 0, n = s.length;
1462 for( ; i < n; ++i ){
1463 const k = s.key(i);
1464 if( !keyPrefix || k.startsWith(keyPrefix) ){
1465 let kk = (keyPrefix ? rxTail.exec(k) : undefined)?.[1] ?? k;
1466 switch( kk ){
1467 case 'jrnl':
1468 if( opt.includeJournal ) rc.journal = s.getItem(k);
1469 break;
1470 case 'sz':
1471 rc.size = +s.getItem(k);
1472 break;
1473 default:
1474 kk = +kk /* coerce to number */;
1475 if( !util.isInt32(kk) || kk<=0 ){
1476 toss3(capi.SQLITE_RANGE, "Malformed kvvfs key: "+k);
1477 }
1478 if( opt.decodePages ){
1479 const spg = s.getItem(k),
1480 n = spg.length,
1481 z = cache.memBuffer(0),
1482 zDec = cache.memBuffer(1),
1483 heap = wasm.heap8u()/* MUST be inited last*/;
1484 let i = 0;
1485 for( ; i < n; ++i ){
1486 heap[wasm.ptr.add(z, i)] = spg.codePointAt(i) & 0xff;
1487 }
1488 heap[wasm.ptr.add(z, i)] = 0;
1489 //debug("Decoding",i,"page bytes");
1490 const nDec = kvvfsDecode(
1491 z, zDec, cache.buffer.n
1492 );
1493 //debug("Decoded",nDec,"page bytes");
1494 pages[kk] = heap.slice(Number(zDec), wasm.ptr.addn(zDec, nDec));
1495 }else{
1496 pages[kk] = s.getItem(k);
1497 }
1498 break;
1499 }
1500 }
1501 }
1502 if( opt.decodePages ) cache.memBufferFree(1);
1503 /* Now sort the page numbers and move them into an array. In JS
1504 property keys are always strings, so we have to coerce them to
1505 numbers so we can get them sorted properly for the array. */
1506 Object.keys(pages).map((v)=>+v).sort().forEach(
1507 (v)=>rc.pages.push(pages[v])
1508 );
1509 return rc;
1510 }/* sqlite3_js_kvvfs_export */;
1511
1512 /**
1513 The counterpart of sqlite3_js_kvvfs_export(). Its
1514 argument must be the result of that function() or
1515 a compatible one.
1516
1517 This either replaces the contents of an existing transient
1518 storage object or installs one named exp.name, setting
1519 the storage's db contents to that of the exp object.
1520
1521 Throws on error. Error conditions include:
1522
1523 - The given storage object is currently opened by any db.
1524 Performing this page-by-page import would invoke undefined
1525 behavior on them.
1526
1527 - Malformed input object.
1528
1529 If it throws after starting the import then it clears the storage
1530 before returning, to avoid leaving the db in an undefined
1531 state. It may throw for any of the above-listed conditions before
1532 reaching that step, in which case the db is not modified. If
1533 exp.name refers to a new storage name then if it throws, the name
1534 does not get installed.
1535
1536 Added in version @kvvfs-v2-added-in@.
1537 */
1538 const sqlite3_js_kvvfs_import = function(exp, overwrite=false){
1539 if( !exp?.timestamp
1540 || !exp.name
1541 || undefined===exp.size
1542 || !Array.isArray(exp.pages) ){
1543 toss3(capi.SQLITE_MISUSE, "Malformed export object.");
1544 }else if( !exp.size
1545 || (exp.size !== (exp.size | 0))
1546 //|| (exp.size % cache.fixedPageSize)
1547 || exp.size>=0x7fffffff ){
1548 toss3(capi.SQLITE_RANGE, "Invalid db size: "+exp.size);
1549 }
1550
1551 validateStorageName(exp.name);
1552 let store = storageForZClass(exp.name);
1553 const isNew = !store;
1554 if( store ){
1555 if( !overwrite ){
1556 //warn("Storage exists:",arguments,store);
1557 toss3(capi.SQLITE_ACCESS,
1558 "Storage '"+exp.name+"' already exists and",
1559 "overwrite was not specified.");
1560 }else if( !store.files || !store.jzClass ){
1561 toss3(capi.SQLITE_ERROR,
1562 "Internal storage object", exp.name,"seems to be malformed.");
1563 }else if( store.files.length ){
1564 toss3(capi.SQLITE_IOERR_ACCESS,
1565 "Cannot import db storage while it is in use.");
1566 }
1567 sqlite3_js_kvvfs_clear(exp.name);
1568 }else{
1569 store = newStorageObj(exp.name);
1570 //warn("Installing new storage:",store);
1571 }
1572 //debug("Importing store",store.poolEntry.files.length, store);
1573 //debug("object to import:",exp);
1574 const keyPrefix = kvvfsKeyPrefix(exp.name);
1575 let zEnc;
1576 try{
1577 /* Force the native KVVfsFile instances to re-read the db
1578 and page size. */;
1579 const s = store.storage;
1580 s.setItem(keyPrefix+'sz', exp.size);
1581 if( exp.journal ) s.setItem(keyPrefix+'jrnl', exp.journal);
1582 if( exp.pages[0] instanceof Uint8Array ){
1583 /* raw binary pages */
1584 //debug("pages",exp.pages);
1585 exp.pages.forEach((u,ndx)=>{
1586 const n = u.length;
1587 if( 0 && cache.fixedPageSize !== n ){
1588 util.toss3(capi.SQLITE_RANGE,"Unexpected page size:", n);
1589 }
1590 zEnc ??= cache.memBuffer(1);
1591 const zBin = cache.memBuffer(0),
1592 heap = wasm.heap8u()/*MUST be inited last*/;
1593 /* Copy u to the heap and encode the heap copy via C. This
1594 is _presumably_ faster than porting the encoding algo to
1595 JS. */
1596 heap.set(u, Number(zBin));
1597 heap[wasm.ptr.addn(zBin,n)] = 0;
1598 const rc = kvvfsEncode(zBin, n, zEnc);
1599 util.assert( rc < cache.buffer.n,
1600 "Impossibly long output - possibly smashed the heap" );
1601 util.assert( 0===wasm.peek8(wasm.ptr.add(zEnc,rc)),
1602 "Expecting NUL-terminated encoded output" );
1603 const jenc = wasm.cstrToJs(zEnc);
1604 //debug("(un)encoded page:",u,jenc);
1605 s.setItem(keyPrefix+(ndx+1), jenc);
1606 });
1607 }else if( exp.pages[0] ){
1608 /* kvvfs-encoded pages */
1609 exp.pages.forEach((v,ndx)=>s.setItem(keyPrefix+(ndx+1), v));
1610 }
1611 if( isNew ) installStorageAndJournal(store);
1612 }catch{
1613 if( !isNew ){
1614 try{sqlite3_js_kvvfs_clear(exp.name);}catch(ee){/*ignored*/}
1615 }
1616 }finally{
1617 if( zEnc ) cache.memBufferFree(1);
1618 }
1619 return this;
1620 };
1621
1622 /**
1623 If no kvvfs storage exists with the given name, one is
1624 installed. If one exists, its reference count is increased so
1625 that it won't be freed by the closing of a database or journal
1626 file.
1627
1628 Throws if the name is not valid for a new storage object.
1629
1630 Added in version @kvvfs-v2-added-in@.
1631 */
1632 const sqlite3_js_kvvfs_reserve = function(name){
1633 let store = storageForZClass(name);
1634 if( store ){
1635 ++store.refc;
1636 return;
1637 }
1638 validateStorageName(name);
1639 installStorageAndJournal(newStorageObj(name));
1640 };
1641
1642 /**
1643 Conditionally "unlinks" a kvvfs storage object, reducing its
1644 reference count by 1.
1645
1646 This is a no-op if name ends in "-journal" or refers to a
1647 built-in storage object.
1648
1649 It will not lower the refcount below the number of
1650 currently-opened db/journal files for the storage (so that it
1651 cannot delete it out from under them).
1652
1653 If the refcount reaches 0 then the storage object is
1654 removed.
1655
1656 Returns true if it reduces the refcount, else false. A result of
1657 true does not necessarily mean that the storage unit was removed,
1658 just that its refcount was lowered. Similarly, a result of false
1659 does not mean that the storage is removed - it may still have
1660 opened handles.
1661
1662 Added in version @kvvfs-v2-added-in@.
1663 */
1664 const sqlite3_js_kvvfs_unlink = function(name){
1665 const store = storageForZClass(name);
1666 if( !store
1667 || kvvfsIsPersistentName(store.jzClass)
1668 || isBuiltinName(store.jzClass)
1669 || cache.rxJournalSuffix.test(name) ) return false;
1670 if( store.refc > store.files.length || 0===store.files.length ){
1671 if( --store.refc<=0 ){
1672 /* Ignoring deleteAtRefc0 for an explicit unlink */
1673 deleteStorage(store);
1674 }
1675 return true;
1676 }
1677 return false;
1678 };
1679
1680 /**
1681 Adds an event listener to a kvvfs storage object. The idea is
1682 that this can be used to asynchronously back up one kvvfs storage
1683 object to another or another channel entirely. (The caveat in the
1684 latter case is that kvvfs's format is not readily consumable by
1685 downstream code.)
1686
1687 Its argument must be an object with the following properties:
1688
1689 - storage: the name of the kvvfs storage object.
1690
1691 - reserve [=false]: if true, sqlite3_js_kvvfs_reserve() is used
1692 to ensure that the storage exists if it does not already.
1693 If this is false and the storage does not exist then an
1694 exception is thrown.
1695
1696 - events: an object which may have any of the following
1697 callback function properties: open, close, write, delete.
1698
1699 - decodePages [=false]: if true, write events will receive each
1700 db page write in the form of a Uint8Array holding the raw binary
1701 db page. The default is to emit the kvvfs-format page because it
1702 requires no extra work, we already have it in hand, and it's
1703 often smaller. It's not great for interchange, though.
1704
1705 - includeJournal [=false]: if true, writes and deletes of
1706 "jrnl" records are included. If false, no events are sent
1707 for journal updates.
1708
1709 Passing the same object to sqlite3_js_kvvfs_unlisten() will
1710 remove the listener.
1711
1712 Each one of the events callbacks will be called asynchronously
1713 when the given storage performs those operations. They may be
1714 asynchronous functions but are not required to be (the events are
1715 fired async either way, but making the event callbacks async may
1716 be advantageous when multiple listeners are involved). All
1717 exceptions, including those via Promises, are ignored but may (or
1718 may not) trigger warning output on the console.
1719
1720 Each callback gets passed a single object with the following
1721 properties:
1722
1723 .type = the same as the name of the callback
1724
1725 .storageName = the name of the storage object
1726
1727 .data = callback-dependent:
1728
1729 - 'open' and 'close' get an integer, the number of
1730 currently-opened handles on the storage.
1731
1732 - 'write' gets a length-two array holding the key and value which
1733 were written. The key is always a string, even if it's a db page
1734 number. For db-page records, the value's type depends on
1735 opt.decodePages. All others, including the journal, are strings.
1736 (The journal, being a kvvfs-specific format, is delivered in
1737 that same JSON-friendly format.) More details below.
1738
1739 - 'delete' gets the string-type key of the deleted record.
1740
1741 - 'sync' gets a boolean value: true if it was triggered by db
1742 file's xSync(), false if it was triggered by xFileControl(). The
1743 latter triggers before the xSync() and also triggers if the DB
1744 has PRAGMA SYNCHRONOUS=OFF (in which case xSync() is not
1745 triggered).
1746
1747 The key/value arguments to 'write', and key argument to 'delete',
1748 are in one of the following forms:
1749
1750 - 'sz' = the unencoded db size as a string. This specific key is
1751 key is never deleted, so is only ever passed to 'write' events.
1752
1753 - 'jrnl' = the current db journal as a kvvfs-encoded string. This
1754 journal format is not useful anywhere except in the kvvfs
1755 internals. These events are not fired if opt.includeJournal is
1756 false.
1757
1758 - '[1-9][0-9]*' (a db page number) = Its type depends on
1759 opt.decodePages. These may be written and deleted in arbitrary
1760 order.
1761
1762 Design note: JS has StorageEvents but only in the main thread,
1763 which is why the listeners are not based on that.
1764
1765 Added in version @kvvfs-v2-added-in@.
1766 */
1767 const sqlite3_js_kvvfs_listen = function(opt){
1768 if( !opt || 'object'!==typeof opt ){
1769 toss3(capi.SQLITE_MISUSE, "Expecting a listener object.");
1770 }
1771 let store = storageForZClass(opt.storage);
1772 if( !store ){
1773 if( opt.storage && opt.reserve ){
1774 sqlite3_js_kvvfs_reserve(opt.storage);
1775 store = storageForZClass(opt.storage);
1776 util.assert(store,
1777 "Unexpectedly cannot fetch reserved storage "
1778 +opt.storage);
1779 }else{
1780 toss3(capi.SQLITE_NOTFOUND,"No such storage:",opt.storage);
1781 }
1782 }
1783 if( opt.events ){
1784 (store.listeners ??= []).push(opt);
1785 }
1786 };
1787
1788 /**
1789 Removes the kvvfs event listeners for the given options
1790 object. It must be passed the same object instance which was
1791 passed to sqlite3_js_kvvfs_listen().
1792
1793 This has no side effects if opt is invalid or is not a match for
1794 any listeners.
1795
1796 Return true if it unregisters its argument, else false.
1797
1798 Added in version @kvvfs-v2-added-in@.
1799 */
1800 const sqlite3_js_kvvfs_unlisten = function(opt){
1801 const store = storageForZClass(opt?.storage);
1802 if( store?.listeners && opt.events ){
1803 const n = store.listeners.length;
1804 store.listeners = store.listeners.filter((v)=>v!==opt);
1805 const rc = n>store.listeners.length;
1806 if( !store.listeners.length ){
1807 // to speed up downstream checks for listeners
1808 store.listeners = undefined;
1809 }
1810 return rc;
1811 }
1812 return false;
1813 };
1814
1815 sqlite3.kvvfs.reserve = sqlite3_js_kvvfs_reserve;
1816 sqlite3.kvvfs.import = sqlite3_js_kvvfs_import;
1817 sqlite3.kvvfs.export = sqlite3_js_kvvfs_export;
1818 sqlite3.kvvfs.unlink = sqlite3_js_kvvfs_unlink;
1819 sqlite3.kvvfs.listen = sqlite3_js_kvvfs_listen;
1820 sqlite3.kvvfs.unlisten = sqlite3_js_kvvfs_unlisten;
1821 sqlite3.kvvfs.exists = (name)=>!!storageForZClass(name);
1822 sqlite3.kvvfs.estimateSize = sqlite3_js_kvvfs_size;
1823 sqlite3.kvvfs.clear = sqlite3_js_kvvfs_clear;
1824
1825
1826 if( globalThis.Storage ){
1827 /**
1828 Prior to version 2, kvvfs was only available in the main
1829 thread. We retain that for the v1 APIs, exposing them only in
1830 the main UI thread. As of version 2, kvvfs is available in all
1831 threads but only via its v2 interface (sqlite3.kvvfs).
1832
1833 These versions have a default argument value of "" which the v2
1834 versions lack.
1835 */
1836 capi.sqlite3_js_kvvfs_size = (which="")=>sqlite3_js_kvvfs_size(which);
1837 capi.sqlite3_js_kvvfs_clear = (which="")=>sqlite3_js_kvvfs_clear(which);
1838 }
1839
1840//#if not omit-oo1
1841 if(sqlite3.oo1?.DB){
1842 /**
1843 Functionally equivalent to DB(storageName,'c','kvvfs') except
1844 that it throws if the given storage name is not one of 'local'
1845 or 'session'.
1846
1847 As of version 3.46, the argument may optionally be an options
1848 object in the form:
1849
1850 {
1851 filename: 'session'|'local',
1852 ... etc. (all options supported by the DB ctor)
1853 }
1854
1855 noting that the 'vfs' option supported by main DB
1856 constructor is ignored here: the vfs is always 'kvvfs'.
1857 */
1858 const DB = sqlite3.oo1.DB;
1859 sqlite3.oo1.JsStorageDb = function(
1860 storageName = sqlite3.oo1.JsStorageDb.defaultStorageName
1861 ){
1862 const opt = DB.dbCtorHelper.normalizeArgs(...arguments);
1863 opt.vfs = 'kvvfs';
1864 if( 0 ){
1865 // Current tests rely on these, but that's arguably a bug
1866 if( opt.flags ) opt.flags = 'cw'+opt.flags;
1867 else opt.flags = 'cw';
1868 }
1869 switch( opt.filename ){
1870 /* sqlite3_open(), in these builds, recognizes the names
1871 below and performs some magic which we want to bypass
1872 here for sanity's sake. */
1873 case ":sessionStorage:": opt.filename = 'session'; break;
1874 case ":localStorage:": opt.filename = 'local'; break;
1875 }
1876 const m = /(file:(\/\/)?)([^?]+)/.exec(opt.filename);
1877 validateStorageName( m ? m[3] : opt.filename);
1878 DB.dbCtorHelper.call(this, opt);
1879 };
1880 sqlite3.oo1.JsStorageDb.defaultStorageName
1881 = cache.storagePool.session ? 'session' : nameOfThisThreadStorage;
1882 const jdb = sqlite3.oo1.JsStorageDb;
1883 jdb.prototype = Object.create(DB.prototype);
1884 jdb.clearStorage = sqlite3_js_kvvfs_clear;
1885 /**
1886 DEPRECATED: the inherited method of this name (as opposed to
1887 the "static" class method) is deprecated with version 2 of
1888 kvvfs. This function will, for backwards comaptibility,
1889 continue to work with localStorage and sessionStorage, but will
1890 throw for all other storage because they are opened. Version 1
1891 was not capable of recognizing that the storage was opened so
1892 permitted wiping it out at any time, but that was arguably a
1893 bug.
1894
1895 Clears this database instance's storage or throws if this
1896 instance has been closed. Returns the number of
1897 database pages which were cleaned up.
1898 */
1899 jdb.prototype.clearStorage = function(){
1900 return jdb.clearStorage(this.affirmOpen().dbFilename(), true);
1901 };
1902 /** Equivalent to sqlite3_js_kvvfs_size(). */
1903 jdb.storageSize = sqlite3_js_kvvfs_size;
1904 /**
1905 Returns the _approximate_ number of bytes this database takes
1906 up in its storage or throws if this instance has been closed.
1907 */
1908 jdb.prototype.storageSize = function(){
1909 return jdb.storageSize(this.affirmOpen().dbFilename(), true);
1910 };
1911 }/*sqlite3.oo1.JsStorageDb*/
1912//#/if not omit-oo1
1913
1914 if( sqlite3.__isUnderTest && sqlite3.vtab ){
1915 /**
1916 An eponymous vtab for inspecting the kvvfs state. This is only
1917 intended for use in testing and development, not part of the
1918 public API.
1919 */
1920 const cols = Object.assign(Object.create(null),{
1921 rowid: {type: 'INTEGER'},
1922 name: {type: 'TEXT'},
1923 nRef: {type: 'INTEGER'},
1924 nOpen: {type: 'INTEGER'},
1925 isTransient: {type: 'INTEGER'},
1926 dbSize: {type: 'INTEGER'}
1927 });
1928 Object.keys(cols).forEach((v,i)=>cols[v].colId = i);
1929
1930 const VT = sqlite3.vtab;
1931 const ProtoCursor = Object.assign(Object.create(null),{
1932 row: function(){
1933 return cache.storagePool[this.names[this.rowid]];
1934 }
1935 });
1936 Object.assign(Object.create(ProtoCursor),{
1937 rowid: 0,
1938 names: Object.keys(cache.storagePool)
1939 .filter(v=>!cache.rxJournalSuffix.test(v))
1940 });
1941 const cursorState = function(cursor, reset){
1942 const o = (cursor instanceof capi.sqlite3_vtab_cursor)
1943 ? cursor
1944 : VT.xCursor.get(cursor);
1945 if( reset || !o.vTabState ){
1946 o.vTabState = Object.assign(Object.create(ProtoCursor),{
1947 rowid: 0,
1948 names: Object.keys(cache.storagePool)
1949 .filter(v=>!cache.rxJournalSuffix.test(v))
1950 });
1951 }
1952 return o.vTabState;
1953 };
1954
1955 const dbg = 1 ? ()=>{} : (...args)=>debug("vtab",...args);
1956
1957 const theModule = function f(){
1958 return f.mod ??= new sqlite3.capi.sqlite3_module().setupModule({
1959 catchExceptions: true,
1960 methods: {
1961 xConnect: function(pDb, pAux, argc, argv, ppVtab, pzErr){
1962 dbg("xConnect");
1963 try{
1964 const xcol = [];
1965 Object.keys(cols).forEach((k)=>{
1966 xcol.push(k+" "+cols[k].type);
1967 });
1968 const rc = capi.sqlite3_declare_vtab(
1969 pDb, "CREATE TABLE ignored("+xcol.join(',')+")"
1970 );
1971 if(0===rc){
1972 const t = VT.xVtab.create(ppVtab);
1973 util.assert(
1974 (t === VT.xVtab.get(wasm.peekPtr(ppVtab))),
1975 "output pointer check failed"
1976 );
1977 }
1978 return rc;
1979 }catch(e){
1980 return VT.xError('xConnect', e, capi.SQLITE_ERROR);
1981 }
1982 },
1983 xCreate: wasm.ptr.null, // eponymous only
1984 //xCreate: true, // copy xConnect, i.e. also eponymous only
1985 xDisconnect: function(pVtab){
1986 dbg("xDisconnect",...arguments);
1987 VT.xVtab.dispose(pVtab);
1988 return 0;
1989 },
1990 xOpen: function(pVtab, ppCursor){
1991 dbg("xOpen",...arguments);
1992 VT.xCursor.create(ppCursor);
1993 return 0;
1994 },
1995 xClose: function(pCursor){
1996 dbg("xClose",...arguments);
1997 const c = VT.xCursor.unget(pCursor);
1998 delete c.vTabState;
1999 c.dispose();
2000 return 0;
2001 },
2002 xNext: function(pCursor){
2003 dbg("xNext",...arguments);
2004 const c = VT.xCursor.get(pCursor);
2005 ++cursorState(c).rowid;
2006 return 0;
2007 },
2008 xColumn: function(pCursor, pCtx, iCol){
2009 dbg("xColumn",...arguments);
2010 //const c = VT.xCursor.get(pCursor);
2011 const st = cursorState(pCursor);
2012 const store = st.row();
2013 util.assert(store, "Unexpected xColumn call");
2014 switch(iCol){
2015 case cols.rowid.colId:
2016 capi.sqlite3_result_int(pCtx, st.rowid);
2017 break;
2018 case cols.name.colId:
2019 capi.sqlite3_result_text(pCtx, store.jzClass, -1, capi.SQLITE_TRANSIENT);
2020 break;
2021 case cols.nRef.colId:
2022 capi.sqlite3_result_int(pCtx, store.refc);
2023 break;
2024 case cols.nOpen.colId:
2025 capi.sqlite3_result_int(pCtx, store.files.length);
2026 break;
2027 case cols.isTransient.colId:
2028 capi.sqlite3_result_int(pCtx, !!store.deleteAtRefc0);
2029 break;
2030 case cols.dbSize.colId:
2031 capi.sqlite3_result_int(pCtx, storageGetDbSize(store));
2032 break;
2033 default:
2034 capi.sqlite3_result_error(pCtx, "Invalid column id: "+iCol);
2035 return capi.SQLITE_RANGE;
2036 }
2037 return 0;
2038 },
2039 xRowid: function(pCursor, ppRowid64){
2040 dbg("xRowid",...arguments);
2041 const st = cursorState(pCursor);
2042 VT.xRowid(ppRowid64, st.rowid);
2043 return 0;
2044 },
2045 xEof: function(pCursor){
2046 const st = cursorState(pCursor);
2047 dbg("xEof?="+(!st.row()),...arguments);
2048 return !st.row();
2049 },
2050 xFilter: function(pCursor, idxNum, idxCStr,
2051 argc, argv/* [sqlite3_value* ...] */){
2052 dbg("xFilter",...arguments);
2053 const st = cursorState(pCursor, true);
2054 return 0;
2055 },
2056 xBestIndex: function(pVtab, pIdxInfo){
2057 dbg("xBestIndex",...arguments);
2058 //const t = VT.xVtab.get(pVtab);
2059 const pii = new capi.sqlite3_index_info(pIdxInfo);
2060 pii.$estimatedRows = cache.storagePool.size;
2061 pii.$estimatedCost = 1.0;
2062 pii.dispose();
2063 return 0;
2064 }
2065 }
2066 })/*setupModule*/;
2067 }/*theModule()*/;
2068
2069 sqlite3.kvvfs.create_module = function(pDb, name="sqlite_kvvfs"){
2070 return capi.sqlite3_create_module(pDb, name, theModule(),
2071 wasm.ptr.null);
2072 };
2073
2074 }/* virtual table */
2075
2076//#if 0
2077 /**
2078 The idea here is a simpler wrapper for listening to kvvfs
2079 changes. Clients would override its onXyz() event methods
2080 instead of providing callbacks for sqlite3.kvvfs.listen(), the
2081 main (only?) benefit of which is that this class would do the
2082 sorting-out and validation of event state before calling the
2083 overloaded callbacks.
2084 */
2085 kvvfs.Listener = class KvvfsListener {
2086 #store;
2087 #listener;
2088
2089 constructor(opt){
2090 this.#listenTo(opt);
2091 }
2092
2093 #event(ev){
2094 switch(ev.type){
2095 case 'open': this.onOpen(ev.data); break;
2096 case 'close': this.onClose(ev.data); break;
2097 case 'sync': this.onSync(ev.data); break;
2098 case 'delete':
2099 switch(ev.data){
2100 case 'jrnl': break;
2101 default:{
2102 const n = +ev.data;
2103 util.assert( n>0, "Expecting positive db page number" );
2104 this.onPageChange(n, null);
2105 break;
2106 }
2107 }
2108 break;
2109 case 'write':{
2110 const key = ev.data[0], val = ev.data[1];
2111 switch( key ){
2112 case 'jrnl': break;
2113 case 'sz':{
2114 const sz = +val;
2115 util.assert( sz>0, "Expecting a db page number" );
2116 this.onSizeChange(sz);
2117 break;
2118 }
2119 default:
2120 T.assert( +key>0, "Expecting a positive db page number" );
2121 this.onPageChange(+key, val);
2122 break;
2123 }
2124 break;
2125 }
2126 }
2127 }
2128
2129 #listenTo(opt){
2130 if(this.#listener){
2131 sqlite3_js_kvvfs_unlisten(this.#listener);
2132 this.#listener = undefined;
2133 }
2134 const eventHandler = async function(ev){this.event(ev)}.bind(this);
2135 const li = Object.assign(
2136 { /* Defaults */
2137 reserve: false,
2138 includeJournal: false,
2139 decodePages: false,
2140 storage: null
2141 },
2142 (/*client options*/opt||{}),
2143 {/*hard-coded options*/
2144 events: Object.assign(Object.create(null),{
2145 'open': eventHandler,
2146 'close': eventHandler,
2147 'write': eventHandler,
2148 'delete': eventHandler,
2149 'sync': eventHandler
2150 })
2151 }
2152 );
2153 sqlite3_js_kvvfs_listen(li);
2154 this.#listener = li;
2155 }
2156
2157 async onSizeChange(sz){}
2158 async onPageChange(pgNo,content/*null for delete*/){}
2159 async onSync(mode/*true=xSync, false=xFileControl*/){}
2160 async onOpen(count){}
2161 async onClose(count){}
2162 }/*KvvfsListener*/;
2163//#/if nope
2164
2165})/*sqlite3ApiBootstrap.initializers*/;
2166//#savepoint rollback
2167//#@ pop policy
2168//#/if kvvfs disabled