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-api-worker1.c-pp.js

678 lines · 21146 bytes Raw Blame History
1//#if not omit-oo1 and not omit-worker1
2/**
3 2022-07-22
4
5 The author disclaims copyright to this source code. In place of a
6 legal notice, here is a blessing:
7
8 * May you do good and not evil.
9 * May you find forgiveness for yourself and forgive others.
10 * May you share freely, never taking more than you give.
11
12 ***********************************************************************
13
14 This file implements the initializer for SQLite's "Worker API #1", a
15 very basic DB access API intended to be scripted from a main window
16 thread via Worker-style messages. Because of limitations in that
17 type of communication, this API is minimalistic and only capable of
18 serving relatively basic DB requests (e.g. it cannot process nested
19 query loops concurrently).
20
21 This file requires that the core C-style sqlite3 API and OO API #1
22 have been loaded.
23*/
24
25/**
26 sqlite3.initWorker1API() implements a Worker-based wrapper around
27 SQLite3 OO API #1, colloquially known as "Worker API #1".
28
29 In order to permit this API to be loaded in worker threads without
30 automatically registering onmessage handlers, initializing the
31 worker API requires calling initWorker1API(). If this function is
32 called from a non-worker thread then it throws an exception. It
33 must only be called once per Worker.
34
35 When initialized, it installs message listeners to receive Worker
36 messages and then it posts a message in the form:
37
38 ```
39 {type:'sqlite3-api', result:'worker1-ready'}
40 ```
41
42 to let the client know that it has been initialized. Clients may
43 optionally depend on this function not returning until
44 initialization is complete, as the initialization is synchronous.
45 In some contexts, however, listening for the above message is
46 a better fit.
47
48 Note that the worker-based interface can be slightly quirky because
49 of its async nature. In particular, any number of messages may be posted
50 to the worker before it starts handling any of them. If, e.g., an
51 "open" operation fails, any subsequent messages will fail. The
52 Promise-based wrapper for this API (`sqlite3-worker1-promiser.js`)
53 is more comfortable to use in that regard.
54
55 The documentation for the input and output worker messages for
56 this API follows...
57
58 ====================================================================
59 Common message format...
60
61 Each message posted to the worker has an operation-independent
62 envelope and operation-dependent arguments:
63
64 ```
65 {
66 type: string, // one of: 'open', 'close', 'exec', 'export', 'config-get'
67
68 messageId: OPTIONAL arbitrary value. The worker will copy it as-is
69 into response messages to assist in client-side dispatching.
70
71 dbId: a db identifier string (returned by 'open') which tells the
72 operation which database instance to work on. If not provided, the
73 first-opened db is used. This is an "opaque" value, with no
74 inherently useful syntax or information. Its value is subject to
75 change with any given build of this API and cannot be used as a
76 basis for anything useful beyond its one intended purpose.
77
78 args: ...operation-dependent arguments...
79
80 // the framework may add other properties for testing or debugging
81 // purposes.
82
83 }
84 ```
85
86 Response messages, posted back to the main thread, look like:
87
88 ```
89 {
90 type: string. Same as above except for error responses, which have the type
91 'error',
92
93 messageId: same value, if any, provided by the inbound message
94
95 dbId: the id of the db which was operated on, if any, as returned
96 by the corresponding 'open' operation.
97
98 result: ...operation-dependent result...
99
100 }
101 ```
102
103 ====================================================================
104 Error responses
105
106 Errors are reported messages in an operation-independent format:
107
108 ```
109 {
110 type: "error",
111
112 messageId: ...as above...,
113
114 dbId: ...as above...
115
116 result: {
117
118 operation: type of the triggering operation: 'open', 'close', ...
119
120 message: ...error message text...
121
122 errorClass: string. The ErrorClass.name property from the thrown exception.
123
124 input: the message object which triggered the error.
125
126 stack: _if available_, a stack trace array.
127
128 }
129
130 }
131 ```
132
133
134 ====================================================================
135 "config-get"
136
137 This operation fetches the serializable parts of the sqlite3 API
138 configuration.
139
140 Message format:
141
142 ```
143 {
144 type: "config-get",
145 messageId: ...as above...,
146 args: currently ignored and may be elided.
147 }
148 ```
149
150 Response:
151
152 ```
153 {
154 type: "config-get",
155 messageId: ...as above...,
156 result: {
157
158 version: sqlite3.version object
159
160 bigIntEnabled: bool. True if BigInt support is enabled.
161
162 vfsList: result of sqlite3.capi.sqlite3_js_vfs_list()
163 }
164 }
165 ```
166
167
168 ====================================================================
169 "open" a database
170
171 Message format:
172
173 ```
174 {
175 type: "open",
176 messageId: ...as above...,
177 args:{
178
179 filename [=":memory:" or "" (unspecified)]: the db filename.
180 See the sqlite3.oo1.DB constructor for peculiarities and
181 transformations,
182
183 vfs: sqlite3_vfs name. Ignored if filename is ":memory:" or "".
184 This may change how the given filename is resolved.
185 }
186 }
187 ```
188
189 Response:
190
191 ```
192 {
193 type: "open",
194 messageId: ...as above...,
195 result: {
196 filename: db filename, possibly differing from the input.
197
198 dbId: an opaque ID value which must be passed in the message
199 envelope to other calls in this API to tell them which db to
200 use. If it is not provided to future calls, they will default to
201 operating on the least-recently-opened db. This property is, for
202 API consistency's sake, also part of the containing message
203 envelope. Only the `open` operation includes it in the `result`
204 property.
205
206 persistent: true if the given filename resides in the
207 known-persistent storage, else false.
208
209 vfs: name of the VFS the "main" db is using.
210 }
211 }
212 ```
213
214 ====================================================================
215 "close" a database
216
217 Message format:
218
219 ```
220 {
221 type: "close",
222 messageId: ...as above...
223 dbId: ...as above...
224 args: OPTIONAL {unlink: boolean}
225 }
226 ```
227
228 If the `dbId` does not refer to an opened ID, this is a no-op. If
229 the `args` object contains a truthy `unlink` value then the database
230 will be unlinked (deleted) after closing it. The inability to close a
231 db (because it's not opened) or delete its file does not trigger an
232 error.
233
234 Response:
235
236 ```
237 {
238 type: "close",
239 messageId: ...as above...,
240 result: {
241
242 filename: filename of closed db, or undefined if no db was closed
243
244 }
245 }
246 ```
247
248 ====================================================================
249 "exec" SQL
250
251 All SQL execution is processed through the exec operation. It offers
252 most of the features of the oo1.DB.exec() method, with a few limitations
253 imposed by the state having to cross thread boundaries.
254
255 Message format:
256
257 ```
258 {
259 type: "exec",
260 messageId: ...as above...
261 dbId: ...as above...
262 args: string (SQL) or {... see below ...}
263 }
264 ```
265
266 Response:
267
268 ```
269 {
270 type: "exec",
271 messageId: ...as above...,
272 dbId: ...as above...
273 result: {
274 input arguments, possibly modified. See below.
275 }
276 }
277 ```
278
279 The arguments are in the same form accepted by oo1.DB.exec(), with
280 the exceptions noted below.
281
282 If `args.countChanges` (added in version 3.43) is truthy then the
283 `result` property contained by the returned object will have a
284 `changeCount` property which holds the number of changes made by the
285 provided SQL. Because the SQL may contain an arbitrary number of
286 statements, the `changeCount` is calculated by calling
287 `sqlite3_total_changes()` before and after the SQL is evaluated. If
288 the value of `countChanges` is 64 then the `changeCount` property
289 will be returned as a 64-bit integer in the form of a BigInt (noting
290 that that will trigger an exception if used in a BigInt-incapable
291 build). In the latter case, the number of changes is calculated by
292 calling `sqlite3_total_changes64()` before and after the SQL is
293 evaluated.
294
295 If the `args.lastInsertRowId` (added in version 3.50.0) is truthy
296 then the `result` property contained by the returned object will
297 have a `lastInsertRowId` will hold a BigInt-type value corresponding
298 to the result of sqlite3_last_insert_rowid(). This value is only
299 fetched once, after the SQL is run, regardless of how many
300 statements the SQL contains. This API has no idea whether the SQL
301 contains any INSERTs, so it is up to the client to apply/rely on
302 this property only when it makes sense to do so.
303
304 A function-type args.callback property cannot cross
305 the window/Worker boundary, so is not useful here. If
306 args.callback is a string then it is assumed to be a
307 message type key, in which case a callback function will be
308 applied which posts each row result via:
309
310 postMessage({type: thatKeyType,
311 rowNumber: 1-based-#,
312 row: theRow,
313 columnNames: anArray
314 })
315
316 And, at the end of the result set (whether or not any result rows
317 were produced), it will post an identical message with
318 (row=undefined, rowNumber=null) to alert the caller than the result
319 set is completed. Note that a row value of `null` is a legal row
320 result for certain arg.rowMode values.
321
322 (Design note: we don't use (row=undefined, rowNumber=undefined) to
323 indicate end-of-results because fetching those would be
324 indistinguishable from fetching from an empty object unless the
325 client used hasOwnProperty() (or similar) to distinguish "missing
326 property" from "property with the undefined value". Similarly,
327 `null` is a legal value for `row` in some case , whereas the db
328 layer won't emit a result value of `undefined`.)
329
330 The callback proxy must not recurse into this interface. An exec()
331 call will tie up the Worker thread, causing any recursion attempt
332 to wait until the first exec() is completed.
333
334 The response is the input options object (or a synthesized one if
335 passed only a string), noting that options.resultRows and
336 options.columnNames may be populated by the call to db.exec().
337
338
339 ====================================================================
340 "export" the current db
341
342 To export the underlying database as a byte array...
343
344 Message format:
345
346 ```
347 {
348 type: "export",
349 messageId: ...as above...,
350 dbId: ...as above...
351 }
352 ```
353
354 Response:
355
356 ```
357 {
358 type: "export",
359 messageId: ...as above...,
360 dbId: ...as above...
361 result: {
362 byteArray: Uint8Array (as per sqlite3_js_db_export()),
363 filename: the db filename,
364 mimetype: "application/x-sqlite3"
365 }
366 }
367 ```
368
369*/
370sqlite3ApiBootstrap.initializers.push(function(sqlite3){
371const util = sqlite3.util;
372sqlite3.initWorker1API = function(){
373 'use strict';
374 const toss = (...args)=>{throw new Error(args.join(' '))};
375 if(!(globalThis.WorkerGlobalScope instanceof Function)){
376 toss("initWorker1API() must be run from a Worker thread.");
377 }
378 const sqlite3 = this.sqlite3 || toss("Missing this.sqlite3 object.");
379 const DB = sqlite3.oo1.DB;
380
381 /**
382 Returns the app-wide unique ID for the given db, creating one if
383 needed.
384 */
385 const getDbId = function(db){
386 let id = wState.idMap.get(db);
387 if(id) return id;
388 id = 'db#'+(++wState.idSeq)+':'+
389 Math.floor(Math.random() * 100000000)+':'+
390 Math.floor(Math.random() * 100000000);
391 /** ^^^ can't simply use db.pointer b/c closing/opening may re-use
392 the same address, which could map pending messages to a wrong
393 instance.
394
395 2025-07: https://github.com/sqlite/sqlite-wasm/issues/113
396 demonstrates that two Worker1s can end up with the same IDs,
397 despite using different instances of the library, so we need
398 to add some randomness to the IDs instead of relying on the
399 pointer addresses.
400 */
401 wState.idMap.set(db, id);
402 return id;
403 };
404
405 /**
406 Internal helper for managing Worker-level state.
407 */
408 const wState = {
409 /**
410 Each opened DB is added to this.dbList, and the first entry in
411 that list is the default db. As each db is closed, its entry is
412 removed from the list.
413 */
414 dbList: [],
415 /** Sequence number of dbId generation. */
416 idSeq: 0,
417 /** Map of DB instances to dbId. */
418 idMap: new WeakMap,
419 /** Temp holder for "transferable" postMessage() state. */
420 xfer: [],
421 open: function(opt){
422 const db = new DB(opt);
423 this.dbs[getDbId(db)] = db;
424 if(this.dbList.indexOf(db)<0) this.dbList.push(db);
425 return db;
426 },
427 close: function(db,alsoUnlink){
428 if(db){
429 delete this.dbs[getDbId(db)];
430 const filename = db.filename;
431 const pVfs = util.sqlite3__wasm_db_vfs(db.pointer, 0);
432 db.close();
433 const ddNdx = this.dbList.indexOf(db);
434 if(ddNdx>=0) this.dbList.splice(ddNdx, 1);
435 if(alsoUnlink && filename && pVfs){
436 util.sqlite3__wasm_vfs_unlink(pVfs, filename);
437 }
438 }
439 },
440 /**
441 Posts the given worker message value. If xferList is provided,
442 it must be an array, in which case a copy of it passed as
443 postMessage()'s second argument and xferList.length is set to
444 0.
445 */
446 post: function(msg,xferList){
447 if(xferList && xferList.length){
448 globalThis.postMessage( msg, Array.from(xferList) );
449 xferList.length = 0;
450 }else{
451 globalThis.postMessage(msg);
452 }
453 },
454 /** Map of DB IDs to DBs. */
455 dbs: Object.create(null),
456 /** Fetch the DB for the given id. Throw if require=true and the
457 id is not valid, else return the db or undefined. */
458 getDb: function(id,require=true){
459 return this.dbs[id]
460 || (require ? toss("Unknown (or closed) DB ID:",id) : undefined);
461 }
462 };
463
464 /** Throws if the given db is falsy or not opened, else returns its
465 argument. */
466 const affirmDbOpen = function(db = wState.dbList[0]){
467 return (db && db.pointer) ? db : toss("DB is not opened.");
468 };
469
470 /** Extract dbId from the given message payload. */
471 const getMsgDb = function(msgData,affirmExists=true){
472 const db = wState.getDb(msgData.dbId,false) || wState.dbList[0];
473 return affirmExists ? affirmDbOpen(db) : db;
474 };
475
476 const getDefaultDbId = function(){
477 return wState.dbList[0] && getDbId(wState.dbList[0]);
478 };
479
480 const isSpecialDbFilename = (n)=>{
481 return ""===n || ':'===n[0];
482 };
483
484 /**
485 A level of "organizational abstraction" for the Worker1
486 API. Each method in this object must map directly to a Worker1
487 message type key. The onmessage() dispatcher attempts to
488 dispatch all inbound messages to a method of this object,
489 passing it the event.data part of the inbound event object. All
490 methods must return a plain Object containing any result
491 state, which the dispatcher may amend. All methods must throw
492 on error.
493 */
494 const wMsgHandler = {
495 open: function(ev){
496 const oargs = Object.create(null), args = (ev.args || Object.create(null));
497 if(args.simulateError){ // undocumented internal testing option
498 toss("Throwing because of simulateError flag.");
499 }
500 const rc = Object.create(null);
501 oargs.vfs = args.vfs;
502 oargs.filename = args.filename || "";
503 const db = wState.open(oargs);
504 rc.filename = db.filename;
505 rc.persistent = !!sqlite3.capi.sqlite3_js_db_uses_vfs(db.pointer, "opfs");
506 rc.dbId = getDbId(db);
507 rc.vfs = db.dbVfsName();
508 return rc;
509 },
510
511 close: function(ev){
512 const db = getMsgDb(ev,false);
513 const response = {
514 filename: db && db.filename
515 };
516 if(db){
517 const doUnlink = ((ev.args && 'object'===typeof ev.args)
518 ? !!ev.args.unlink : false);
519 wState.close(db, doUnlink);
520 }
521 return response;
522 },
523
524 exec: function(ev){
525 const rc = (
526 'string'===typeof ev.args
527 ) ? {sql: ev.args} : (ev.args || Object.create(null));
528 if('stmt'===rc.rowMode){
529 toss("Invalid rowMode for 'exec': stmt mode",
530 "does not work in the Worker API.");
531 }else if(!rc.sql){
532 toss("'exec' requires input SQL.");
533 }
534 const db = getMsgDb(ev);
535 if(rc.callback || Array.isArray(rc.resultRows)){
536 // Part of a copy-avoidance optimization for blobs
537 db._blobXfer = wState.xfer;
538 }
539 const theCallback = rc.callback;
540 let rowNumber = 0;
541 const hadColNames = !!rc.columnNames;
542 if('string' === typeof theCallback){
543 if(!hadColNames) rc.columnNames = [];
544 /* Treat this as a worker message type and post each
545 row as a message of that type. */
546 rc.callback = function(row,stmt){
547 wState.post({
548 type: theCallback,
549 columnNames: rc.columnNames,
550 rowNumber: ++rowNumber,
551 row: row
552 }, wState.xfer);
553 }
554 }
555 try {
556 const changeCount = !!rc.countChanges
557 ? db.changes(true,(64===rc.countChanges))
558 : undefined;
559 db.exec(rc);
560 if(undefined !== changeCount){
561 rc.changeCount = db.changes(true,64===rc.countChanges) - changeCount;
562 }
563 const lastInsertRowId = !!rc.lastInsertRowId
564 ? sqlite3.capi.sqlite3_last_insert_rowid(db)
565 : undefined;
566 if( undefined!==lastInsertRowId ){
567 rc.lastInsertRowId = lastInsertRowId;
568 }
569 if(rc.callback instanceof Function){
570 rc.callback = theCallback;
571 /* Post a sentinel message to tell the client that the end
572 of the result set has been reached (possibly with zero
573 rows). */
574 wState.post({
575 type: theCallback,
576 columnNames: rc.columnNames,
577 rowNumber: null /*null to distinguish from "property not set"*/,
578 row: undefined /*undefined because null is a legal row value
579 for some rowType values, but undefined is not*/
580 });
581 }
582 }finally{
583 delete db._blobXfer;
584 if(rc.callback) rc.callback = theCallback;
585 }
586 return rc;
587 }/*exec()*/,
588
589 'config-get': function(){
590 const rc = Object.create(null), src = sqlite3.config;
591 [
592 'bigIntEnabled'
593 ].forEach(function(k){
594 if(Object.getOwnPropertyDescriptor(src, k)) rc[k] = src[k];
595 });
596 rc.version = sqlite3.version;
597 rc.vfsList = sqlite3.capi.sqlite3_js_vfs_list();
598 return rc;
599 },
600
601 /**
602 Exports the database to a byte array, as per
603 sqlite3_serialize(). Response is an object:
604
605 {
606 byteArray: Uint8Array (db file contents),
607 filename: the current db filename,
608 mimetype: 'application/x-sqlite3'
609 }
610 */
611 export: function(ev){
612 const db = getMsgDb(ev);
613 const response = {
614 byteArray: sqlite3.capi.sqlite3_js_db_export(db.pointer),
615 filename: db.filename,
616 mimetype: 'application/x-sqlite3'
617 };
618 wState.xfer.push(response.byteArray.buffer);
619 return response;
620 }/*export()*/,
621
622 toss: function(ev){
623 toss("Testing worker exception");
624 }
625 }/*wMsgHandler*/;
626
627 globalThis.onmessage = async function(ev){
628 ev = ev.data;
629 let result, dbId = ev.dbId, evType = ev.type;
630 const arrivalTime = performance.now();
631 try {
632 if(wMsgHandler.hasOwnProperty(evType) &&
633 wMsgHandler[evType] instanceof Function){
634 result = await wMsgHandler[evType](ev);
635 }else{
636 toss("Unknown db worker message type:",ev.type);
637 }
638 }catch(err){
639 evType = 'error';
640 result = {
641 operation: ev.type,
642 message: err.message,
643 errorClass: err.name,
644 input: ev
645 };
646 if(err.stack){
647 result.stack = ('string'===typeof err.stack)
648 ? err.stack.split(/\n\s*/) : err.stack;
649 }
650 if(0) sqlite3.config.warn("Worker is propagating an exception to main thread.",
651 "Reporting it _here_ for the stack trace:",err,result);
652 }
653 if(!dbId){
654 dbId = result.dbId/*from 'open' cmd*/
655 || getDefaultDbId();
656 }
657 // Timing info is primarily for use in testing this API. It's not part of
658 // the public API. arrivalTime = when the worker got the message.
659 wState.post({
660 type: evType,
661 dbId: dbId,
662 messageId: ev.messageId,
663 workerReceivedTime: arrivalTime,
664 workerRespondTime: performance.now(),
665 departureTime: ev.departureTime,
666 // TODO: move the timing bits into...
667 //timing:{
668 // departure: ev.departureTime,
669 // workerReceived: arrivalTime,
670 // workerResponse: performance.now();
671 //},
672 result: result
673 }, wState.xfer);
674 };
675 globalThis.postMessage({type:'sqlite3-api',result:'worker1-ready'});
676}.bind({sqlite3});
677});
678//#/if global snip