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 / tester1.c-pp.js

4879 lines · 183860 bytes Raw Blame History
1/*
2 2022-10-12
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 Main functional and regression tests for the sqlite3 WASM API.
14
15 This mini-framework works like so:
16
17 This script adds a series of test groups, each of which contains an
18 arbitrary number of tests, into a queue. After loading of the
19 sqlite3 WASM/JS module is complete, that queue is processed. If any
20 given test fails, the whole thing fails. This script is built such
21 that it can run from the main UI thread or worker thread. Test
22 groups and individual tests can be assigned a predicate function
23 which determines whether to run them or not, and this is
24 specifically intended to be used to toggle certain tests on or off
25 for the main/worker threads or the availability (or not) of
26 optional features such as int64 support.
27
28 Each test group defines a single state object which gets applied as
29 the test functions' `this` for all tests in that group. Test
30 functions can use that to, e.g., set up a db in an early test and
31 close it in a later test. Each test gets passed the sqlite3
32 namespace object as its only argument.
33*/
34/*
35 This file is intended to be processed by c-pp to inject (or not)
36 code specific to ES6 modules which is illegal in non-module code.
37
38 Non-ES6 module build and ES6 module for the main-thread:
39
40 ./c-pp -f tester1.c-pp.js -o tester1.js
41
42 ES6 worker module build:
43
44 ./c-pp -f tester1.c-pp.js -o tester1-esm.mjs -Dtarget:es6-module
45*/
46//#@ policy error
47//#if target:es6-module
48import {default as sqlite3InitModule} from "@sqlite3.js@";
49globalThis.sqlite3InitModule = sqlite3InitModule;
50//#else
51'use strict';
52//#/if
53/* Predicate for tests/groups. */
54const isUIThread = ()=>(globalThis.window===self && globalThis.document);
55/* Predicate for tests/groups. */
56const isWorker = ()=>!isUIThread();
57/* Predicate for tests/groups. */
58const testIsTodo = ()=>false;
59const haveWasmCTests = ()=>{
60 return !!wasm.exports.sqlite3__wasm_test_intptr;
61};
62
63let SQLite3 /* populated after module load */;
64const hasOpfs = ()=>!!SQLite3?.oo1?.OpfsDb;
65
66/**
67 Set up our output channel differently depending on whether we are
68 running in a worker thread or the main (UI) thread.
69*/
70const logClass = (()=>{
71 const mapToString = (v)=>{
72 switch(typeof v){
73 case 'number': case 'string': case 'boolean':
74 case 'undefined': case 'bigint':
75 return ''+v;
76 default: break;
77 }
78 if(null===v) return 'null';
79 if(v instanceof Error){
80 v = {
81 message: v.message,
82 stack: v.stack,
83 errorClass: v.name
84 };
85 }
86 return JSON.stringify(v,undefined,2);
87 };
88 const normalizeArgs = (args)=>args.map(mapToString);
89 let logClass;
90 if( isUIThread() ){
91 console.log("Running in the UI thread.");
92 const logTarget = document.querySelector('#test-output');
93 logClass = function(cssClass,...args){
94 const ln = document.createElement('div');
95 if(cssClass){
96 for(const c of (Array.isArray(cssClass) ? cssClass : [cssClass])){
97 ln.classList.add(c);
98 }
99 }
100 ln.append(document.createTextNode(normalizeArgs(args).join(' ')));
101 logTarget.append(ln);
102 };
103 const cbReverse = document.querySelector('#cb-log-reverse');
104 const cbReverseKey = 'tester1:cb-log-reverse';
105 const cbReverseIt = ()=>{
106 logTarget.classList[cbReverse.checked ? 'add' : 'remove']('reverse');
107 localStorage.setItem(cbReverseKey, cbReverse.checked ? 1 : 0);
108 };
109 cbReverse.addEventListener('change', cbReverseIt, true);
110 if(localStorage.getItem(cbReverseKey)){
111 cbReverse.checked = !!(+localStorage.getItem(cbReverseKey));
112 }
113 cbReverseIt();
114 }else{ /* Worker thread */
115 console.log("Running in a Worker thread.");
116 logClass = function(cssClass,...args){
117 postMessage({
118 type:'log',
119 payload:{cssClass, args: normalizeArgs(args)}
120 });
121 };
122 }
123 return logClass;
124})()/*logClass*/;
125
126const log = (...args)=>{
127 //console.log(...args);
128 logClass('',...args);
129}
130const warn = (...args)=>{
131 console.warn(...args);
132 logClass('warning',...args);
133}
134const error = (...args)=>{
135 console.error(...args);
136 logClass('error',...args);
137};
138
139const debug = (...args)=>{
140 console.debug('tester1',...args);
141};
142
143const reportFinalTestStatus = function(pass){
144 debug("Final test status:",pass);
145 if(isUIThread()){
146 let e = document.querySelector('#color-target');
147 e.classList.add(pass ? 'tests-pass' : 'tests-fail');
148 e = document.querySelector('title');
149 e.innerText = (pass ? '✅PASS' : '🔥FAIL') + ': ' + e.innerText;
150 }else{
151 postMessage({type:'test-result', payload:{pass}});
152 }
153 TestUtil.checkHeapSize(true);
154};
155
156const toss = (...args)=>{
157 error(...args);
158 throw new Error(args.join(' '));
159};
160const tossQuietly = (...args)=>{
161 throw new Error(args.join(' '));
162};
163
164const roundMs = (ms)=>Math.round(ms*100)/100;
165
166const looksLikePtr = (v,positive=true)=> positive ? v>0 : v>=0;
167
168/**
169 Helpers for writing sqlite3-specific tests.
170*/
171const TestUtil = {
172 /** Running total of the number of tests run via
173 this API. */
174 counter: 0,
175 /**
176 If expr is a function, it is called and its result
177 is returned, coerced to a bool, else expr, coerced to
178 a bool, is returned.
179 */
180 toBool: function(expr){
181 return (expr instanceof Function) ? !!expr() : !!expr;
182 },
183 /** Throws if expr is false. If expr is a function, it is called
184 and its result is evaluated. If passed multiple arguments,
185 those after the first are a message string which get applied
186 as an exception message if the assertion fails. The message
187 arguments are concatenated together with a space between each.
188 */
189 assert: function f(expr, ...msg){
190 ++this.counter;
191 if(!this.toBool(expr)){
192 throw new Error(msg.length ? msg.join(' ') : "Assertion failed.");
193 }
194 return this;
195 },
196 /** Calls f() and squelches any exception it throws. If it
197 does not throw, this function throws. */
198 mustThrow: function(f, msg){
199 ++this.counter;
200 let err;
201 try{ f(); } catch(e){err=e;}
202 if(!err) throw new Error(msg || "Expected exception.");
203 return this;
204 },
205 /**
206 Works like mustThrow() but expects filter to be a regex,
207 function, or string to match/filter the resulting exception
208 against. If f() does not throw, this test fails and an Error is
209 thrown. If filter is a regex, the test passes if
210 filter.test(error.message) passes. If it's a function, the test
211 passes if filter(error) returns truthy. If it's a string, the
212 test passes if the filter matches the exception message
213 precisely. If filter is a number then it is compared against
214 the resultCode property of the exception. In all other cases
215 the test fails, throwing an Error.
216
217 If it throws, msg is used as the error report unless it's falsy,
218 in which case a default is used.
219 */
220 mustThrowMatching: function(f, filter, msg){
221 ++this.counter;
222 let err;
223 try{ f(); } catch(e){err=e;}
224 if(!err) throw new Error(msg || "Expected exception.");
225 let pass = false;
226 if(filter instanceof RegExp) pass = filter.test(err.message);
227 else if(filter instanceof Function) pass = filter(err);
228 else if('string' === typeof filter) pass = (err.message === filter);
229 else if('number' === typeof filter) pass = (err.resultCode === filter);
230 if(!pass){
231 console.error("Filter",filter,"rejected exception",err);
232 throw new Error(msg || ("Filter rejected this exception: <<"+err.message+">>"));
233 }
234 return this;
235 },
236 /** Throws if expr is truthy or expr is a function and expr()
237 returns truthy. */
238 throwIf: function(expr, msg){
239 ++this.counter;
240 if(this.toBool(expr)) throw new Error(msg || "throwIf() failed");
241 return this;
242 },
243 /** Throws if expr is falsy or expr is a function and expr()
244 returns falsy. */
245 throwUnless: function(expr, msg){
246 ++this.counter;
247 if(!this.toBool(expr)) throw new Error(msg || "throwUnless() failed");
248 return this;
249 },
250 eqApprox: (v1,v2,factor=0.05)=>(v1>=(v2-factor) && v1<=(v2+factor)),
251 TestGroup: (function(){
252 let groupCounter = 0;
253 const TestGroup = function(name, predicate){
254 this.number = ++groupCounter;
255 this.name = name;
256 this.predicate = predicate;
257 this.tests = [];
258 };
259 TestGroup.prototype = {
260 addTest: function(testObj){
261 this.tests.push(testObj);
262 return this;
263 },
264 run: async function(sqlite3){
265 logClass('group-start',"Group #"+this.number+':',this.name);
266 if(this.predicate){
267 const p = this.predicate(sqlite3);
268 if(!p || 'string'===typeof p){
269 logClass(['warning','skipping-group'],
270 "SKIPPING group:", p ? p : "predicate says to" );
271 return;
272 }
273 }
274 const assertCount = TestUtil.counter;
275 const groupState = Object.create(null);
276 const skipped = [];
277 let runtime = 0, i = 0;
278 for(const t of this.tests){
279 ++i;
280 const n = this.number+"."+i;
281 logClass('one-test-line', n+":", t.name);
282 if(t.predicate){
283 const p = t.predicate(sqlite3);
284 if(!p || 'string'===typeof p){
285 logClass(['warning','skipping-test'],
286 "SKIPPING:", p ? p : "predicate says to" );
287 skipped.push( n+': '+t.name );
288 continue;
289 }
290 }
291 const tc = TestUtil.counter, now = performance.now();
292 let rc = t.test.call(groupState, sqlite3);
293 /*if(rc instanceof Promise){
294 rc = rc.catch((e)=>{
295 error("Test failure:",e);
296 throw e;
297 });
298 }*/
299 await rc;
300 const then = performance.now();
301 runtime += then - now;
302 logClass(['faded','one-test-summary'],
303 TestUtil.counter - tc, 'assertion(s) in',
304 roundMs(then-now),'ms');
305 TestUtil.checkHeapSize();
306 }
307 logClass(['green','group-end'],
308 "#"+this.number+":",
309 (TestUtil.counter - assertCount),
310 "assertion(s) in",roundMs(runtime),"ms");
311 if(0 && skipped.length){
312 logClass('warning',"SKIPPED test(s) in group",this.number+":",skipped);
313 }
314 }
315 };
316 return TestGroup;
317 })()/*TestGroup*/,
318 testGroups: [],
319 currentTestGroup: undefined,
320 addGroup: function(name, predicate){
321 this.testGroups.push( this.currentTestGroup =
322 new this.TestGroup(name, predicate) );
323 return this;
324 },
325 addTest: function(name, callback){
326 let predicate;
327 if(1===arguments.length){
328 this.currentTestGroup.addTest(arguments[0]);
329 }else{
330 this.currentTestGroup.addTest({
331 name, predicate, test: callback
332 });
333 }
334 return this;
335 },
336 runTests: async function(sqlite3){
337 return new Promise(async function(pok,pnok){
338 try {
339 let runtime = 0;
340 for(let g of this.testGroups){
341 const now = performance.now();
342 await g.run(sqlite3);
343 runtime += performance.now() - now;
344 }
345 logClass(['strong','green','full-test-summary'],
346 "Done running tests.",TestUtil.counter,"assertions in",
347 roundMs(runtime),'ms');
348 pok();
349 reportFinalTestStatus(true);
350 }catch(e){
351 error(e);
352 pnok(e);
353 reportFinalTestStatus(false);
354 }
355 }.bind(this));
356 },
357
358 checkHeapSize: function(force=false){
359 const heapSize = SQLite3.wasm.heap8().byteLength;
360 if( force || heapSize !== TestUtil.lastHeapSize ){
361 TestUtil.lastHeapSize = heapSize;
362 log('WASM heap size:', heapSize,'bytes');
363 }
364 }
365}/*TestUtil*/;
366const T = TestUtil;
367T.g = T.addGroup;
368T.t = T.addTest;
369let capi, wasm/*assigned after module init*/;
370const sahPoolConfig = {
371 name: 'opfs-sahpool-tester1',
372 clearOnInit: true,
373 initialCapacity: 6
374};
375
376//#if enable-see
377/**
378 Code consolidator for SEE sanity checks for various VFSes. ctor
379 is the VFS's oo1.DB-type constructor. ctorOptFunc(bool) is a
380 function which must return a constructor args object for ctor. It
381 is passed true if the db needs to be cleaned up/unlinked before
382 opening it (OPFS) and false if not (how that is done is
383 VFS-dependent). dbUnlink is a _synchronous_ function which is
384 expected to unlink() the db file if the ctorOpfFunc does not do
385 so when passed true (namely for kvvfs).
386
387 This function initializes the db described by the result of
388 ctorOptFunc(bool), writes some secret info into it, and re-opens
389 it twice to confirm that it can be read with an SEE key and
390 cannot be read without one.
391
392 If unlinkDbAtEnd is truthy then dbUnlink() is (on success)
393 called before returning.
394*/
395T.seeBaseCheck = function(ctor, ctorOptFunc, dbUnlink, unlinkDbAtEnd=true){
396 let initDb = true;
397 const tryKey = function(keyKey, key, expectCount){
398 let db;
399 //console.debug('tryKey()',arguments);
400 try {
401 if (initDb) {
402 const ctoropt = ctorOptFunc(initDb);
403 initDb = false;
404 db = new ctor({
405 ...ctoropt,
406 [keyKey]: key
407 });
408 db.exec([
409 "drop table if exists t;",
410 "create table t(a);"
411 ]);
412 db.close();
413 db = null;
414 // Ensure that it's actually encrypted...
415 let err;
416 try {
417 db = new ctor(ctorOptFunc(false));
418 T.assert(db, 'db opened') /* opening is fine, but... */;
419 db.exec("select 1 from sqlite_schema");
420 console.warn("(should not be reached) sessionStorage =", sessionStorage);
421 } catch (e) {
422 err = e;
423 } finally {
424 db.close()
425 db = null;
426 }
427 T.assert(err, "Expecting an exception")
428 .assert(capi.SQLITE_NOTADB == err.resultCode,
429 "Expecting NOTADB");
430 }/*initDb*/
431 db = new ctor({
432 ...ctorOptFunc(false),
433 [keyKey]: key
434 });
435 db.exec("insert into t(a) values (1),(2)");
436 T.assert(expectCount === db.selectValue('select sum(a) from t'));
437 } finally {
438 if (db) db.close();
439 }
440 };
441 const hexFoo = new Uint8Array([0x66,0x6f,0x6f]/*=="foo"*/);
442 dbUnlink();
443 tryKey('textkey', 'foo', 3);
444 T.assert( !initDb );
445 tryKey('textkey', 'foo', 6);
446 dbUnlink();
447 initDb = true;
448 tryKey('key', 'foo', 3);
449 T.assert( !initDb );
450 tryKey('key', hexFoo, 6);
451 dbUnlink();
452 initDb = true;
453 tryKey('hexkey', hexFoo, 3);
454 T.assert( !initDb );
455 tryKey('hexkey', hexFoo, 6);
456 if( unlinkDbAtEnd ) dbUnlink();
457};
458//#/if enable-see
459
460/* Tests common to "opfs" and "opfs-wl". These tests manipulate
461 "this" and must run in order.
462*/
463T.opfsCommon = {
464 sanityChecks: async function(vfsName, oo1Ctor, sqlite3){
465 T.assert(capi.sqlite3_vfs_find(vfsName));
466 const opfs = sqlite3.opfs;
467 const filename = this.opfsDbFile = '/dir/sqlite3-tester1.db';
468 const fileUri = 'file://'+filename+'?delete-before-open=1';
469 const initSql = [
470 'create table p(a);',
471 'insert into p(a) values(1),(2),(3)'
472 ];
473 let db = new oo1Ctor(fileUri);
474 try {
475 db.exec(initSql);
476 T.assert(3 === db.selectValue('select count(*) from p'));
477 db.close();
478 db = new oo1Ctor(filename);
479 db.exec('insert into p(a) values(4),(5),(6)');
480 T.assert(6 === db.selectValue('select count(*) from p'));
481 this.opfsDbExport = capi.sqlite3_js_db_export(db);
482 T.assert(this.opfsDbExport instanceof Uint8Array)
483 .assert(this.opfsDbExport.byteLength>0
484 && 0===this.opfsDbExport.byteLength % 512);
485 }finally{
486 db.close();
487 db = null;
488 }
489 T.assert(await opfs.entryExists(filename));
490 try {
491 db = new oo1Ctor(fileUri);
492 db.exec(initSql) /* will throw if delete-before-open did not work */;
493 T.assert(3 === db.selectValue('select count(*) from p'));
494 }finally{
495 if(db) db.close();
496 }
497 },
498
499 importer: async function(vfsName, oo1Ctor, sqlite3){
500 let db;
501 const filename = this.opfsDbFile;
502 try {
503 const exp = this.opfsDbExport;
504 delete this.opfsDbExport;
505 this.opfsImportSize = await oo1Ctor.importDb(filename, exp);
506 db = new oo1Ctor(this.opfsDbFile);
507 T.assert(6 === db.selectValue('select count(*) from p')).
508 assert( this.opfsImportSize == exp.byteLength );
509 db.close();
510 db = null;
511 this.opfsUnlink =
512 (fn=filename)=>sqlite3.util.sqlite3__wasm_vfs_unlink(vfsName, fn);
513 this.opfsUnlink(filename);
514 T.assert(!(await sqlite3.opfs.entryExists(filename)));
515 // Try again with a function as an input source:
516 let cursor = 0;
517 const blockSize = 512, end = exp.byteLength;
518 const reader = async function(){
519 if(cursor >= exp.byteLength){
520 return undefined;
521 }
522 const rv = exp.subarray(cursor, cursor+blockSize>end ? end : cursor+blockSize);
523 cursor += blockSize;
524 return rv;
525 };
526 this.opfsImportSize = await oo1Ctor.importDb(filename, reader);
527 db = new oo1Ctor(this.opfsDbFile);
528 T.assert(6 === db.selectValue('select count(*) from p')).
529 assert( this.opfsImportSize == exp.byteLength );
530 }finally{
531 if(db) db.close();
532 }
533 },
534
535 opfsUtil: async function(vfsName, oo1Ctor, sqlite3){
536 const filename = this.opfsDbFile;
537 const unlink = this.opfsUnlink;
538 T.assert(filename && !!unlink);
539 delete this.opfsDbFile;
540 delete this.opfsUnlink;
541 /**************************************************************
542 ATTENTION CLIENT-SIDE USERS: sqlite3.opfs is NOT intended
543 for client-side use. It is only for this project's own
544 internal use. Its APIs are subject to change or removal at
545 any time. The sqlite3.opfs namespace is REMOVED from the
546 sqlite3 namespace in non-test runs of the library.
547 ***************************************************************/
548 const opfs = sqlite3.opfs;
549 const fSize = this.opfsImportSize;
550 delete this.opfsImportSize;
551 let sh;
552 try{
553 T.assert(await opfs.entryExists(filename));
554 const [dirHandle, filenamePart] = await opfs.getDirForFilename(filename, false);
555 const fh = await dirHandle.getFileHandle(filenamePart);
556 sh = await fh.createSyncAccessHandle();
557 T.assert(fSize === await sh.getSize());
558 await sh.close();
559 sh = undefined;
560 unlink();
561 T.assert(!(await opfs.entryExists(filename)));
562 }finally{
563 if(sh) await sh.close();
564 unlink();
565 }
566
567 // Some sanity checks of the opfs utility functions...
568 const testDir = '/sqlite3-opfs-'+opfs.randomFilename(12);
569 const aDir = testDir+'/test/dir';
570 T.assert(await opfs.mkdir(aDir), "mkdir failed")
571 .assert(await opfs.mkdir(aDir), "mkdir must pass if the dir exists")
572 .assert(!(await opfs.unlink(testDir+'/test')), "delete 1 should have failed (dir not empty)")
573 .assert((await opfs.unlink(testDir+'/test/dir')), "delete 2 failed")
574 .assert(!(await opfs.unlink(testDir+'/test/dir')),
575 "delete 2b should have failed (dir already deleted)")
576 .assert((await opfs.unlink(testDir, true)), "delete 3 failed")
577 .assert(!(await opfs.entryExists(testDir)),
578 "entryExists(",testDir,") should have failed");
579 }
580}/*T.opfsCommon*/;
581
582////////////////////////////////////////////////////////////////////////
583// End of infrastructure setup. Now define the tests...
584////////////////////////////////////////////////////////////////////////
585
586////////////////////////////////////////////////////////////////////
587T.g('Basic sanity checks')
588 .t({
589 name:'sqlite3_config()',
590 test:function(sqlite3){
591 for(const k of [
592 'SQLITE_CONFIG_GETMALLOC', 'SQLITE_CONFIG_URI'
593 ]){
594 T.assert(capi[k] > 0);
595 }
596 T.assert(capi.SQLITE_MISUSE===capi.sqlite3_config(
597 capi.SQLITE_CONFIG_URI, 1
598 ), "MISUSE because the library has already been initialized.");
599 T.assert(capi.SQLITE_MISUSE === capi.sqlite3_config(
600 // not enough args
601 capi.SQLITE_CONFIG_GETMALLOC
602 ));
603 T.assert(capi.SQLITE_NOTFOUND === capi.sqlite3_config(
604 // unhandled-in-JS config option
605 capi.SQLITE_CONFIG_GETMALLOC, 1
606 ));
607 if(0){
608 log("We cannot _fully_ test sqlite3_config() after the library",
609 "has been initialized (which it necessarily has been to",
610 "set up various bindings) and we cannot shut it down ",
611 "without losing the VFS registrations.");
612 T.assert(0 === capi.sqlite3_config(
613 capi.SQLITE_CONFIG_URI, 1
614 ));
615 }
616 }
617 })/*sqlite3_config()*/
618
619////////////////////////////////////////////////////////////////////
620 .t({
621 name: "JS wasm-side allocator",
622 test: function(sqlite3){
623 if(sqlite3.config.useStdAlloc){
624 warn("Using system allocator. This violates the docs and",
625 "may cause grief with certain APIs",
626 "(e.g. sqlite3_deserialize()).");
627 T.assert(wasm.alloc.impl === wasm.exports.malloc)
628 .assert(wasm.dealloc === wasm.exports.free)
629 .assert(wasm.realloc.impl === wasm.exports.realloc);
630 }else{
631 T.assert(wasm.alloc.impl === wasm.exports.sqlite3_malloc)
632 .assert(wasm.dealloc.impl === wasm.exports.sqlite3_free)
633 .assert(wasm.realloc.impl === wasm.exports.sqlite3_realloc);
634 }
635 }
636 })
637 .t('Namespace object checks', function(sqlite3){
638 const wasmCtypes = wasm.ctype;
639 T.assert(wasmCtypes.structs[0].name==='sqlite3_vfs').
640 assert(wasmCtypes.structs[0].members.szOsFile.sizeof>=4).
641 assert(wasmCtypes.structs[1/*sqlite3_io_methods*/
642 ].members.xFileSize.offset>0);
643 [ /* Spot-check a handful of constants to make sure they got installed... */
644 'SQLITE_SCHEMA','SQLITE_NULL','SQLITE_UTF8','SQLITE_UTF8_ZT',
645 'SQLITE_STATIC', 'SQLITE_DIRECTONLY',
646 'SQLITE_OPEN_CREATE', 'SQLITE_OPEN_DELETEONCLOSE'
647 ].forEach((k)=>T.assert('number' === typeof capi[k]));
648 [/* Spot-check a few of the WASM API methods. */
649 'alloc', 'dealloc', 'installFunction'
650 ].forEach((k)=>T.assert(wasm[k] instanceof Function));
651
652 T.assert(capi.sqlite3_errstr(capi.SQLITE_IOERR_ACCESS).indexOf("I/O")>=0).
653 assert(capi.sqlite3_errstr(capi.SQLITE_CORRUPT).indexOf('malformed')>0).
654 assert(capi.sqlite3_errstr(capi.SQLITE_OK) === 'not an error');
655
656 try {
657 throw new sqlite3.WasmAllocError;
658 }catch(e){
659 T.assert(e instanceof Error)
660 .assert(e instanceof sqlite3.WasmAllocError)
661 .assert("Allocation failed." === e.message);
662 }
663 try {
664 throw new sqlite3.WasmAllocError("test",{
665 cause: 3
666 });
667 }catch(e){
668 T.assert(3 === e.cause)
669 .assert("test" === e.message);
670 }
671 try {throw new sqlite3.WasmAllocError("test","ing",".")}
672 catch(e){T.assert("test ing ." === e.message)}
673
674 try{ throw new sqlite3.SQLite3Error(capi.SQLITE_SCHEMA) }
675 catch(e){
676 T.assert('SQLITE_SCHEMA' === e.message)
677 .assert(capi.SQLITE_SCHEMA === e.resultCode);
678 }
679 try{ sqlite3.SQLite3Error.toss(capi.SQLITE_CORRUPT,{cause: true}) }
680 catch(e){
681 T.assert('SQLITE_CORRUPT' === e.message)
682 .assert(capi.SQLITE_CORRUPT === e.resultCode)
683 .assert(true===e.cause);
684 }
685 try{ sqlite3.SQLite3Error.toss("resultCode check") }
686 catch(e){
687 T.assert(capi.SQLITE_ERROR === e.resultCode)
688 .assert('resultCode check' === e.message);
689 }
690 })
691////////////////////////////////////////////////////////////////////
692 .t('strglob/strlike', function(sqlite3){
693 T.assert(0===capi.sqlite3_strglob("*.txt", "foo.txt")).
694 assert(0!==capi.sqlite3_strglob("*.txt", "foo.xtx")).
695 assert(0===capi.sqlite3_strlike("%.txt", "foo.txt", 0)).
696 assert(0!==capi.sqlite3_strlike("%.txt", "foo.xtx", 0));
697 })
698
699////////////////////////////////////////////////////////////////////
700;/*end of basic sanity checks*/
701
702////////////////////////////////////////////////////////////////////
703T.g('C/WASM Utilities')
704 .t('sqlite3.wasm namespace', function(sqlite3){
705 // TODO: break this into smaller individual test functions.
706 const w = wasm;
707 const chr = (x)=>x.charCodeAt(0);
708 //log("heap getters...");
709 {
710 const li = [8, 16, 32];
711 if(w.bigIntEnabled) li.push(64);
712 for(const n of li){
713 const bpe = n/8;
714 const s = w.heapForSize(n,false);
715 T.assert(bpe===s.BYTES_PER_ELEMENT).
716 assert(w.heapForSize(s.constructor) === s);
717 const u = w.heapForSize(n,true);
718 T.assert(bpe===u.BYTES_PER_ELEMENT).
719 assert(s!==u).
720 assert(w.heapForSize(u.constructor) === u);
721 }
722 }
723
724 // alloc(), realloc(), allocFromTypedArray()
725 {
726 let m = w.alloc(14);
727 let m2 = w.realloc(m, 16);
728 T.assert(m === m2/* because of alignment */);
729 let x = w.realloc(m, 0);
730 T.assert(w.ptr.null === x);
731 m = m2 = 0;
732
733 // Check allocation limits and allocator's responses...
734 T.assert('number' === typeof sqlite3.capi.SQLITE_MAX_ALLOCATION_SIZE);
735 if(!sqlite3.config.useStdAlloc){
736 const tooMuch = sqlite3.capi.SQLITE_MAX_ALLOCATION_SIZE + 1,
737 isAllocErr = (e)=>e instanceof sqlite3.WasmAllocError;
738 T.mustThrowMatching(()=>w.alloc(tooMuch), isAllocErr)
739 .assert(w.ptr.null === w.alloc.impl(tooMuch))
740 .mustThrowMatching(()=>w.realloc(0, tooMuch), isAllocErr)
741 .assert(w.ptr.null === w.realloc.impl(wasm.ptr.null, tooMuch));
742 }
743
744 // Check allocFromTypedArray()...
745 const byteList = [11,22,33]
746 const u = new Uint8Array(byteList);
747 m = w.allocFromTypedArray(u);
748 let mAsNumber = Number(m);
749 for(let i = 0; i < u.length; ++i){
750 T.assert(u[i] === byteList[i])
751 .assert(u[i] === w.peek8(mAsNumber + i));
752 }
753 w.dealloc(m);
754 m = w.allocFromTypedArray(u.buffer);
755 mAsNumber = Number(m);
756 for(let i = 0; i < u.length; ++i){
757 T.assert(u[i] === byteList[i])
758 .assert(u[i] === w.peek8(mAsNumber + i));
759 }
760
761 w.dealloc(m);
762 T.mustThrowMatching(
763 ()=>w.allocFromTypedArray(1),
764 'Value is not of a supported TypedArray type.'
765 );
766 }
767
768 { // Test peekXYZ()/pokeXYZ()...
769 const m = w.alloc(8);
770 T.assert( 17 === w.poke8(m,17).peek8(m) )
771 .assert( 31987 === w.poke16(m,31987).peek16(m) )
772 .assert( 345678 === w.poke32(m,345678).peek32(m) )
773 .assert(
774 T.eqApprox( 345678.9, w.poke32f(m,345678.9).peek32f(m) )
775 ).assert(
776 T.eqApprox( 4567890123.4, w.poke64f(m, 4567890123.4).peek64f(m) )
777 );
778 if(w.bigIntEnabled){
779 T.assert(
780 BigInt(Number.MAX_SAFE_INTEGER) ===
781 w.poke64(m, Number.MAX_SAFE_INTEGER).peek64(m)
782 );
783 }
784 w.dealloc(m);
785 }
786
787 // isPtr32()
788 {
789 const ip = w.isPtr32;
790 T.assert(ip(0))
791 .assert(!ip(-1))
792 .assert(!ip(1.1))
793 .assert(ip(0xffffffff))
794 /* 4GB is okay, but 4GB+1 is not */
795 .assert(!ip(0x100000000))
796 .assert(ip(0x7fffffff))
797 .assert(!ip())
798 .assert(!ip(null)/*might change: under consideration*/)
799 ;
800 }
801
802 //log("jstrlen()...");
803 {
804 T.assert(3 === w.jstrlen("abc")).assert(4 === w.jstrlen("äbc"));
805 }
806
807 //log("jstrcpy()...");
808 {
809 const fillChar = 10;
810 let ua = new Uint8Array(8), rc,
811 refill = ()=>ua.fill(fillChar);
812 refill();
813 rc = w.jstrcpy("hello", ua);
814 T.assert(6===rc).assert(0===ua[5]).assert(chr('o')===ua[4]);
815 refill();
816 ua[5] = chr('!');
817 rc = w.jstrcpy("HELLO", ua, 0, -1, false);
818 T.assert(5===rc).assert(chr('!')===ua[5]).assert(chr('O')===ua[4]);
819 refill();
820 rc = w.jstrcpy("the end", ua, 4);
821 //log("rc,ua",rc,ua);
822 T.assert(4===rc).assert(0===ua[7]).
823 assert(chr('e')===ua[6]).assert(chr('t')===ua[4]);
824 refill();
825 rc = w.jstrcpy("the end", ua, 4, -1, false);
826 T.assert(4===rc).assert(chr(' ')===ua[7]).
827 assert(chr('e')===ua[6]).assert(chr('t')===ua[4]);
828 refill();
829 rc = w.jstrcpy("", ua, 0, 1, true);
830 //log("rc,ua",rc,ua);
831 T.assert(1===rc).assert(0===ua[0]);
832 refill();
833 rc = w.jstrcpy("x", ua, 0, 1, true);
834 //log("rc,ua",rc,ua);
835 T.assert(1===rc).assert(0===ua[0]);
836 refill();
837 rc = w.jstrcpy('äbä', ua, 0, 1, true);
838 T.assert(1===rc, 'Must not write partial multi-byte char.')
839 .assert(0===ua[0]);
840 refill();
841 rc = w.jstrcpy('äbä', ua, 0, 2, true);
842 T.assert(1===rc, 'Must not write partial multi-byte char.')
843 .assert(0===ua[0]);
844 refill();
845 rc = w.jstrcpy('äbä', ua, 0, 2, false);
846 T.assert(2===rc).assert(fillChar!==ua[1]).assert(fillChar===ua[2]);
847 }/*jstrcpy()*/
848
849 //log("cstrncpy()...");
850 {
851 const scope = w.scopedAllocPush();
852 try {
853 let cStr = w.scopedAllocCString("");
854 T.assert(0===w.cstrlen(cStr))
855 .assert(null===w.cstrlen(3.1));
856 cStr = w.scopedAllocCString("hello");
857 const n = w.cstrlen(cStr);
858 T.assert( 5===n );
859 const nPtr = w.ptr.coerce(n);
860 let cpy = w.scopedAlloc(n+10);
861 let rc = w.cstrncpy(cpy, cStr, n+10);
862 T.assert(n+1 === rc).
863 assert("hello" === w.cstrToJs(cpy)).
864 assert(chr('o') === w.peek8( w.ptr.add(cpy,nPtr, -1))).
865 assert(0 === w.peek8( w.ptr.add(cpy,nPtr) ) );
866 let cStr2 = w.scopedAllocCString("HI!!!");
867 rc = w.cstrncpy(cpy, cStr2, 3);
868 T.assert(3===rc).
869 assert("HI!lo" === w.cstrToJs(cpy)).
870 assert(chr('!') === w.peek8( w.ptr.add(cpy, 2) )).
871 assert(chr('l') === w.peek8( w.ptr.add(cpy, 3) ) );
872 }finally{
873 w.scopedAllocPop(scope);
874 }
875 }
876
877 //log("jstrToUintArray()...");
878 {
879 let a = w.jstrToUintArray("hello", false);
880 T.assert(5===a.byteLength).assert(chr('o')===a[4]);
881 a = w.jstrToUintArray("hello", true);
882 T.assert(6===a.byteLength).assert(chr('o')===a[4]).assert(0===a[5]);
883 a = w.jstrToUintArray("äbä", false);
884 T.assert(5===a.byteLength).assert(chr('b')===a[2]);
885 a = w.jstrToUintArray("äbä", true);
886 T.assert(6===a.byteLength).assert(chr('b')===a[2]).assert(0===a[5]);
887 }
888
889 //log("allocCString()...");
890 {
891 const jstr = "hällo, world!";
892 const [cstr, n] = w.allocCString(jstr, true);
893 T.assert(14 === n)
894 .assert(0===w.peek8(w.ptr.add(cstr,n)))
895 .assert(chr('!')===w.peek8(w.ptr.add(cstr,n,-1)));
896 w.dealloc(cstr);
897 }
898
899 //log("scopedAlloc() and friends...");
900 {
901 const alloc = w.alloc, dealloc = w.dealloc;
902 w.alloc = w.dealloc = null;
903 T.assert(!w.scopedAlloc.level)
904 .mustThrowMatching(()=>w.scopedAlloc(1), /No scopedAllocPush/)
905 .mustThrowMatching(()=>w.scopedAllocPush(), /missing alloc/);
906 w.alloc = alloc;
907 T.mustThrowMatching(()=>w.scopedAllocPush(), /missing alloc/);
908 w.dealloc = dealloc;
909 T.mustThrowMatching(()=>w.scopedAllocPop(), /Invalid state/)
910 .mustThrowMatching(()=>w.scopedAlloc(1), /No scopedAllocPush/)
911 .mustThrowMatching(()=>w.scopedAlloc.level=0, /read-only/);
912 const asc = w.scopedAllocPush();
913 let asc2, reachedEnd = false;
914 try {
915 const p1 = w.scopedAlloc(16),
916 p2 = w.scopedAlloc(16);
917 T.assert(1===w.scopedAlloc.level)
918 .assert(looksLikePtr(p1))
919 .assert(looksLikePtr(p2))
920 .assert(asc.ptr[0] === p1/*API internals*/)
921 .assert(asc.ptr[1]===p2/*API internals*/);
922 asc2 = w.scopedAllocPush();
923 const p3 = w.scopedAlloc(16);
924 T.assert(2===w.scopedAlloc.level)
925 .assert(looksLikePtr(p3))
926 .assert(2===asc.ptr.length/*API internals*/)
927 .assert(p3===asc2.ptr[0]/*API internals*/);
928
929 const [z1, z2, z3] = w.scopedAllocPtr(3);
930 T.assert(typeof w.ptr.null===typeof z1).assert(z2>z1).assert(z3>z2)
931 .assert(w.ptr.null===w.peekPtr(z1), 'allocPtr() must zero the targets')
932 .assert(w.ptr.null===w.peekPtr(z3));
933 reachedEnd = true;
934 }finally{
935 // Pop them in "incorrect" order to make sure they behave:
936 w.scopedAllocPop(asc);
937 T.assert(!asc.ptr/*API internals*/);
938 T.mustThrowMatching(()=>w.scopedAllocPop(asc),
939 /Invalid state object/);
940 if(asc2){
941 if( reachedEnd ){
942 T.assert(2===asc2.ptr.length/*API internals*/,
943 'Should be p3 and z1');
944 }
945 w.scopedAllocPop(asc2);
946 T.assert(!asc2.ptr/*API internals*/);
947 T.mustThrowMatching(()=>w.scopedAllocPop(asc2),
948 /Invalid state object/);
949 }
950 }
951 T.assert(0===w.scopedAlloc.level);
952 w.scopedAllocCall(function(){
953 T.assert(1===w.scopedAlloc.level);
954 const [cstr, n] = w.scopedAllocCString("hello, world", true);
955 T.assert(12 === n)
956 .assert(0===w.peek8( w.ptr.add(cstr,n) ))
957 .assert(chr('d')===w.peek8( w.ptr.add(cstr, n, -1) ));
958 });
959 }/*scopedAlloc()*/
960
961 //log("xCall()...");
962 {
963 const pJson = w.xCall('sqlite3__wasm_enum_json');
964 T.assert(looksLikePtr(pJson)).assert(w.cstrlen(pJson)>300);
965 }
966
967 //log("xWrap()...");
968 {
969 T.mustThrowMatching(()=>w.xWrap('sqlite3_libversion',null,'i32'),
970 /requires 0 arg/).
971 assert(w.xWrap.resultAdapter('i32') instanceof Function).
972 assert(w.xWrap.argAdapter('i32') instanceof Function);
973 let fw = w.xWrap('sqlite3_libversion','utf8');
974 T.mustThrowMatching(()=>fw(1), /requires 0 arg/);
975 let rc = fw();
976 T.assert('string'===typeof rc).assert(rc.length>5);
977 rc = w.xCallWrapped('sqlite3__wasm_enum_json','*');
978 T.assert(rc>0 && looksLikePtr(rc));
979 rc = w.xCallWrapped('sqlite3__wasm_enum_json','utf8');
980 T.assert('string'===typeof rc).assert(rc.length>300);
981
982
983 { // 'string:static' argAdapter() sanity checks...
984 const argAd = w.xWrap.argAdapter('string:static');
985 const p0 = argAd('foo'), p1 = argAd('bar');
986 T.assert(w.isPtr(p0) && w.isPtr(p1))
987 .assert(p0 !== p1)
988 .assert(p0 === argAd(['f','o','o'].join('')))
989 .assert(p1 === argAd('bar'.split('').join('')));
990 }
991
992 // 'string:flexible' argAdapter() sanity checks...
993 w.scopedAllocCall(()=>{
994 const toFlexStr = w.xWrap.argAdapter('string:flexible');
995 const cj = (v)=>w.cstrToJs(toFlexStr(v));
996 //console.debug("toFlexStr(new Uint8Array([72, 73]))",toFlexStr(new Uint8Array([72, 73])));
997 T.assert('Hi' === cj('Hi'))
998 .assert('hi' === cj(['h','i']))
999 .assert('HI' === cj(new Uint8Array([72, 73])));
1000 });
1001
1002 // jsFuncToWasm()
1003 {
1004 const fsum3 = (x,y,z)=>x+y+z;
1005 fw = w.jsFuncToWasm('i(iii)', fsum3);
1006 T.assert(fw instanceof Function)
1007 .assert( fsum3 !== fw )
1008 .assert( 3 === fw.length )
1009 .assert( 6 === fw(1,2,3) );
1010 T.mustThrowMatching( ()=>w.jsFuncToWasm('x()', function(){}),
1011 /Invalid signature letter: x/);
1012 }
1013
1014 // xWrap(Function,...)
1015 {
1016 let fp;
1017 try {
1018 const fmy = function fmy(i,s,d){
1019 if(fmy.debug) log("fmy(",...arguments,")");
1020 T.assert( 3 === i )
1021 .assert( w.isPtr(s) )
1022 .assert( w.cstrToJs(s) === 'a string' )
1023 .assert( T.eqApprox(1.2, d) );
1024 return w.allocCString("hi");
1025 };
1026 fmy.debug = false;
1027 const xwArgs = ['string:dealloc', ['i32', 'string', 'f64']];
1028 fw = w.xWrap(fmy, ...xwArgs);
1029 const fmyArgs = [3, 'a string', 1.2];
1030 let rc = fw(...fmyArgs);
1031 T.assert( 'hi' === rc );
1032 if(0){
1033 /* Retain this as a "reminder to self"...
1034
1035 This extra level of indirection does not work: the
1036 string argument is ending up as a null in fmy() but
1037 the numeric arguments are making their ways through
1038
1039 What's happening is: installFunction() is creating a
1040 WASM-compatible function instance. When we pass a JS string
1041 into there it's getting coerced into `null` before being passed
1042 on to the lower-level wrapper.
1043 */
1044 fmy.debug = true;
1045 fp = wasm.installFunction('i(isd)', fw);
1046 fw = w.functionEntry(fp);
1047 rc = fw(...fmyArgs);
1048 log("rc =",rc);
1049 T.assert( 'hi' === rc );
1050 // Similarly, this does not work:
1051 //let fpw = w.xWrap(fp, null, [null,null,null]);
1052 //rc = fpw(...fmyArgs);
1053 //log("rc =",rc);
1054 //T.assert( 'hi' === rc );
1055 }
1056 }finally{
1057 wasm.uninstallFunction(fp);
1058 }
1059 }
1060
1061 if(haveWasmCTests()){
1062 if(!sqlite3.config.useStdAlloc){
1063 fw = w.xWrap('sqlite3__wasm_test_str_hello', 'utf8:dealloc',['i32']);
1064 rc = fw(0);
1065 T.assert('hello'===rc);
1066 rc = fw(1);
1067 T.assert(null===rc);
1068 }
1069
1070 if(w.bigIntEnabled){
1071 w.xWrap.resultAdapter('thrice', (v)=>3n*BigInt(v));
1072 w.xWrap.argAdapter('twice', (v)=>2n*BigInt(v));
1073 fw = w.xWrap('sqlite3__wasm_test_int64_times2','thrice','twice');
1074 rc = fw(1);
1075 T.assert(12n===rc);
1076
1077 w.scopedAllocCall(function(){
1078 const pI1 = w.scopedAlloc(w.ptr.size), pI2 = w.ptr.add(pI1, w.ptr.size);
1079 w.pokePtr([pI1, pI2], w.ptr.null);
1080 const f = w.xWrap('sqlite3__wasm_test_int64_minmax',undefined,['i64*','i64*']);
1081 const [r1, r2] = w.peek64([pI1, pI2]);
1082 T.assert(!Number.isSafeInteger(r1)).assert(!Number.isSafeInteger(r2));
1083 });
1084 }
1085 }
1086 }/*xWrap()*/
1087 }/*WhWasmUtil*/)
1088
1089////////////////////////////////////////////////////////////////////
1090 .t({
1091 name: 'sqlite3.StructBinder (jaccwabyt🐇)',
1092 predicate: (sqlite3)=>!!sqlite3.wasm.exports.sqlite3__wasm_test_struct
1093 || "Built without SQLITE_WASM_ENABLE_C_TESTS",
1094 test: function(sqlite3){
1095 const S = sqlite3, W = S.wasm;
1096 const MyStructDef = {
1097 sizeof: 0, members: {}
1098 };
1099 const addMember = function(tgt, name, member){
1100 member.offset = tgt.sizeof;
1101 tgt.sizeof += member.sizeof;
1102 tgt.members[name] = member;
1103 };
1104 const msd = MyStructDef;
1105 addMember(msd, 'p4', {sizeof: 4, signature: "i"});
1106 addMember(msd, 'pP', {sizeof: wasm.ptr.size, signature: "P"});
1107 addMember(msd, 'ro', {
1108 sizeof: 4,
1109 signature: "i",
1110 readOnly: true
1111 });
1112 addMember(msd, 'cstr', {
1113 sizeof: wasm.ptr.size,
1114 signature: "s"
1115 });
1116 if(W.bigIntEnabled){
1117 addMember(msd, 'p8', {sizeof: 8, signature: "j"});
1118 }
1119 const StructType = S.StructBinder.StructType;
1120 const K = S.StructBinder('my_struct',MyStructDef);
1121 //K.debugFlags(0x03);
1122 T.mustThrowMatching(()=>K(), /via 'new'/).
1123 mustThrowMatching(()=>new K('hi'), (err)=>{
1124 return /Invalid pointer/.test(err.message)/*32-bit*/
1125 || /.*bigint.*/i.test(err.message)/*64-bit*/;
1126 });
1127 const k1 = new K(), k2 = new K();
1128 try {
1129 T.assert(k1.constructor === K).
1130 assert(K.isA(k1)).
1131 assert(k1 instanceof K).
1132 assert(K.prototype.lookupMember('p4').key === '$p4').
1133 assert(K.prototype.lookupMember('$p4').name === 'p4').
1134 mustThrowMatching(()=>K.prototype.lookupMember('nope'), /not a mapped/).
1135 assert(undefined === K.prototype.lookupMember('nope',false)).
1136 assert(k1 instanceof StructType).
1137 assert(StructType.isA(k1)).
1138 mustThrowMatching(()=>k1.$ro = 1, /read-only/);
1139 Object.keys(MyStructDef.members).forEach(function(key){
1140 key = K.memberKey(key);
1141 T.assert(0 == k1[key],
1142 "Expecting allocation to zero the memory "+
1143 "for "+key+" but got: "+k1[key]+
1144 " from "+k1.memoryDump());
1145 });
1146 T.assert(looksLikePtr(k1.pointer)).
1147 mustThrowMatching(()=>k1.pointer = 1, /pointer/);
1148 k1.$p4 = 1; k1.$pP = 2;
1149 T.assert(1 == k1.$p4).assert(2 == k1.$pP);
1150 if(MyStructDef.members.$p8){
1151 k1.$p8 = 1/*must not throw despite not being a BigInt*/;
1152 k1.$p8 = BigInt(Number.MAX_SAFE_INTEGER * 2);
1153 T.assert(BigInt(2 * Number.MAX_SAFE_INTEGER) === k1.$p8);
1154 }
1155 T.assert(!k1.ondispose);
1156 k1.setMemberCString('cstr', "A C-string.");
1157 T.assert(Array.isArray(k1.ondispose)).
1158 assert(k1.ondispose[0] === k1.$cstr).
1159 assert(looksLikePtr(k1.$cstr)).
1160 assert('A C-string.' === k1.memberToJsString('$cstr'));
1161 k1.$pP = k2;
1162 T.assert(k1.$pP === k2.pointer);
1163 k1.$pP = null/*null is special-cased to 0.*/;
1164 T.assert(0==k1.$pP);
1165 let ptr = k1.pointer;
1166 k1.dispose();
1167 T.assert(undefined === k1.pointer).
1168 mustThrowMatching(()=>{k1.$pP=1}, /disposed/);
1169 }finally{
1170 k1.dispose();
1171 k2.dispose();
1172 }
1173
1174 if(!W.bigIntEnabled){
1175 log("Skipping WasmTestStruct tests: BigInt not enabled.");
1176 return;
1177 }
1178
1179 const WTStructDesc =
1180 W.ctype.structs.filter((e)=>'WasmTestStruct'===e.name)[0];
1181 const autoResolvePtr = true /* EXPERIMENTAL */;
1182 if(autoResolvePtr){
1183 WTStructDesc.members.ppV.signature = 'P';
1184 }
1185 const WTStruct = S.StructBinder(WTStructDesc);
1186 //log(WTStruct.structName, WTStruct.structInfo);
1187 const wts = new WTStruct();
1188 //log("WTStruct.prototype keys:",Object.keys(WTStruct.prototype));
1189 try{
1190 T.assert(wts.constructor === WTStruct).
1191 assert(WTStruct.memberKeys().indexOf('$ppV')>=0).
1192 assert(wts.memberKeys().indexOf('$v8')>=0).
1193 assert(!K.isA(wts)).
1194 assert(WTStruct.isA(wts)).
1195 assert(wts instanceof WTStruct).
1196 assert(wts instanceof StructType).
1197 assert(StructType.isA(wts)).
1198 assert(looksLikePtr(wts.pointer)).assert(0==wts.$v4).assert(0n===wts.$v8).
1199 assert(0==wts.$ppV).assert(0==wts.$xFunc);
1200 const testFunc = 1
1201 ? W.xGet('sqlite3__wasm_test_struct'/*name gets mangled in -O3 builds!*/)
1202 : W.xWrap('sqlite3__wasm_test_struct', undefined, '*');
1203 let counter = 0;
1204 //log("wts.pointer =",wts.pointer);
1205 const wtsFunc = function(arg){
1206 /*log("This from a JS function called from C, "+
1207 "which itself was called from JS. arg =",arg);*/
1208 ++counter;
1209 if(3===counter){
1210 tossQuietly("Testing exception propagation.");
1211 }
1212 }
1213 wts.$v4 = 10; wts.$v8 = 20;
1214 wts.$xFunc = W.installFunction(wtsFunc, wts.memberSignature('xFunc'))
1215 //console.debug("wts.memberSignature('xFunc')",wts.memberSignature('xFunc'));
1216 //console.debug("wts.$xFunc",wts.$xFunc, W.functionEntry(wts.$xFunc));
1217 T.assert(0===counter).assert(10 === wts.$v4).assert(20n === wts.$v8)
1218 .assert(0 == wts.$ppV).assert(looksLikePtr(wts.$xFunc))
1219 .assert(0 == wts.$cstr)
1220 .assert(wts.memberIsString('$cstr'))
1221 .assert(!wts.memberIsString('$v4'))
1222 .assert(null === wts.memberToJsString('$cstr'))
1223 .assert(W.functionEntry(wts.$xFunc) instanceof Function);
1224 /* It might seem silly to assert that the values match
1225 what we just set, but recall that all of those property
1226 reads and writes are, via property interceptors,
1227 actually marshaling their data to/from a raw memory
1228 buffer, so merely reading them back is actually part of
1229 testing the struct-wrapping API. */
1230
1231 if( 0 ){
1232 console.debug("wts",wts,"wts.pointer",wts.pointer,
1233 "testFunc",testFunc/*FF v142 emits the wrong function here!*/);
1234 }
1235 testFunc(wts.pointer);
1236 //log("wts.pointer, wts.$ppV",wts.pointer, wts.$ppV);
1237 T.assert(1===counter).assert(20 === wts.$v4).assert(40n === wts.$v8)
1238 .assert(wts.$ppV === wts.pointer)
1239 .assert('string' === typeof wts.memberToJsString('cstr'))
1240 .assert(wts.memberToJsString('cstr') === wts.memberToJsString('$cstr'))
1241 .mustThrowMatching(()=>wts.memberToJsString('xFunc'),
1242 /Invalid member type signature for C-string/)
1243 ;
1244 testFunc(wts.pointer);
1245 T.assert(2===counter).assert(40 === wts.$v4).assert(80n === wts.$v8)
1246 .assert(wts.$ppV === wts.pointer);
1247 /** The 3rd call to wtsFunc throw from JS, which is called
1248 from C, which is called from JS. Let's ensure that
1249 that exception propagates back here... */
1250 T.mustThrowMatching(()=>testFunc(wts.pointer),/Testing/);
1251 W.uninstallFunction(wts.$xFunc);
1252 wts.$xFunc = 0;
1253 wts.$ppV = 0;
1254 T.assert(!wts.$ppV);
1255 //WTStruct.debugFlags(0x03);
1256 wts.$ppV = wts;
1257 T.assert(wts.pointer === wts.$ppV)
1258 wts.setMemberCString('cstr', "A C-string.");
1259 T.assert(Array.isArray(wts.ondispose)).
1260 assert(wts.ondispose[0] === wts.$cstr).
1261 assert('A C-string.' === wts.memberToJsString('cstr'));
1262 const ptr = wts.pointer;
1263 wts.dispose();
1264 T.assert(ptr).assert(undefined === wts.pointer);
1265 }finally{
1266 wts.dispose();
1267 }
1268
1269 if(1){ // ondispose of other struct instances
1270 const s1 = new WTStruct, s2 = new WTStruct, s3 = new WTStruct;
1271 T.assert(s1.lookupMember instanceof Function)
1272 .assert(s1.addOnDispose instanceof Function);
1273 s1.addOnDispose(s2,"testing variadic args");
1274 T.assert(2===s1.ondispose.length);
1275 s2.addOnDispose(s3);
1276 s1.dispose();
1277 T.assert(!s2.pointer,"Expecting s2 to be ondispose'd by s1.");
1278 T.assert(!s3.pointer,"Expecting s3 to be ondispose'd by s2.");
1279 }
1280 }
1281 }/*StructBinder*/)
1282
1283////////////////////////////////////////////////////////////////////
1284 .t('sqlite3.wasm.pstack', function(sqlite3){
1285 const P = wasm.pstack;
1286 const isAllocErr = (e)=>e instanceof sqlite3.WasmAllocError;
1287 const stack = P.pointer;
1288 T.assert(0===Number(stack) % 8 /* must be 8-byte aligned */);
1289 try{
1290 const remaining = P.remaining;
1291 T.assert(P.quota >= 4096)
1292 .assert(remaining === P.quota)
1293 .mustThrowMatching(()=>P.alloc(0), isAllocErr)
1294 .mustThrowMatching(()=>P.alloc(-1), isAllocErr)
1295 .mustThrowMatching(
1296 ()=>P.alloc('i33'),
1297 (e)=>e instanceof sqlite3.WasmAllocError
1298 );
1299 ;
1300 let p1 = P.alloc(12);
1301 T.assert(p1 == Number(stack) - 16/*8-byte aligned*/)
1302 .assert(P.pointer === p1);
1303 let p2 = P.alloc(7);
1304 T.assert(p2 == Number(p1)-8/*8-byte aligned, stack grows downwards*/)
1305 .mustThrowMatching(()=>P.alloc(remaining), isAllocErr)
1306 .assert(24 == Number(stack) - Number(p2))
1307 .assert(P.pointer === p2);
1308 let n = remaining - (Number(stack) - Number(p2));
1309 let p3 = P.alloc(n);
1310 T.assert(p3 == Number(stack)-Number(remaining))
1311 .mustThrowMatching(()=>P.alloc(1), isAllocErr);
1312 }finally{
1313 P.restore(stack);
1314 }
1315
1316 T.assert(P.pointer === stack);
1317 try {
1318 const [p1, p2, p3] = P.allocChunks(3,'i32');
1319 let sPos = wasm.ptr.add(stack,-16)/*pstack alloc always rounds to multiple of 8*/;
1320 T.assert(P.pointer === sPos)
1321 .assert(p1 === sPos)
1322 .assert(p2 == Number(p1) + 4)
1323 .assert(p3 == Number(p2) + 4);
1324 T.mustThrowMatching(()=>P.allocChunks(1024, 1024 * 16),
1325 (e)=>e instanceof sqlite3.WasmAllocError)
1326 }finally{
1327 P.restore(stack);
1328 }
1329
1330 T.assert(P.pointer === stack);
1331 try {
1332 let [p1, p2, p3] = P.allocPtr(3,false);
1333 let sPos = wasm.ptr.add(stack,
1334 -(4===wasm.ptr.size
1335 ? 16/*pstack alloc always rounds to multiple of 8*/
1336 : 24));
1337 T.assert(P.pointer === p1)
1338 .assert(p1 === sPos)
1339 .assert(p2 == Number(p1) + wasm.ptr.size)
1340 .assert(p3 == Number(p2) + wasm.ptr.size);
1341 [p1, p2, p3] = P.allocPtr(3);
1342 T.assert(P.pointer === wasm.ptr.add(sPos, -24)/*3 x 8 bytes*/)
1343 .assert(p2 == Number(p1) + 8)
1344 .assert(p3 == Number(p2) + 8);
1345 p1 = P.allocPtr();
1346 T.assert(looksLikePtr(p1));
1347 }finally{
1348 P.restore(stack);
1349 }
1350 }/*pstack tests*/)
1351////////////////////////////////////////////////////////////////////
1352;/*end of C/WASM utils checks*/
1353
1354T.g('sqlite3_randomness()')
1355 .t('To memory buffer', function(sqlite3){
1356 const stack = wasm.pstack.pointer;
1357 try{
1358 const n = 520;
1359 const p = wasm.pstack.alloc(n);
1360 T.assert(0==wasm.peek8(p))
1361 .assert(0==wasm.peek8(wasm.ptr.add(p,n,-1)));
1362 T.assert(undefined === capi.sqlite3_randomness(n - 10, p));
1363 let j, check = 0;
1364 const heap = wasm.heap8u();
1365 for(j = 0; j < 10 && 0===check; ++j){
1366 check += heap[wasm.ptr.add(p, j)];
1367 }
1368 T.assert(check > 0);
1369 check = 0;
1370 // Ensure that the trailing bytes were not modified...
1371 for(j = n - 10; j < n && 0===check; ++j){
1372 check += heap[wasm.ptr.add(p, j)];
1373 }
1374 T.assert(0===check);
1375 }finally{
1376 wasm.pstack.restore(stack);
1377 }
1378 })
1379 .t('To byte array', function(sqlite3){
1380 const ta = new Uint8Array(117);
1381 let i, n = 0;
1382 for(i=0; i<ta.byteLength && 0===n; ++i){
1383 n += ta[i];
1384 }
1385 T.assert(0===n)
1386 .assert(ta === capi.sqlite3_randomness(ta));
1387 for(i=ta.byteLength-10; i<ta.byteLength && 0===n; ++i){
1388 n += ta[i];
1389 }
1390 T.assert(n>0);
1391 const t0 = new Uint8Array(0);
1392 T.assert(t0 === capi.sqlite3_randomness(t0),
1393 "0-length array is a special case");
1394 })
1395;/*end sqlite3_randomness() checks*/
1396
1397////////////////////////////////////////////////////////////////////////
1398T.g('sqlite3.oo1')
1399 .t({
1400 name:'Create db',
1401 //predicate: (sqlite3)=>
1402 test: function(sqlite3){
1403 const dbFile = '/tester1.db';
1404 sqlite3.util.sqlite3__wasm_vfs_unlink(0, dbFile);
1405 const db = this.db = new sqlite3.oo1.DB(dbFile, 0 ? 'ct' : 'c');
1406 db.onclose = {
1407 disposeAfter: [],
1408 disposeBefore: [
1409 (db)=>{
1410 //console.debug("db.onclose.before dropping modules");
1411 //sqlite3.capi.sqlite3_drop_modules(db.pointer, 0);
1412 }
1413 ],
1414 before: function(db){
1415 while(this.disposeBefore.length){
1416 const v = this.disposeBefore.shift();
1417 console.debug("db.onclose.before cleaning up:",v);
1418 if(wasm.isPtr(v)) wasm.dealloc(v);
1419 else if(v instanceof sqlite3.StructBinder.StructType){
1420 v.dispose();
1421 }else if(v instanceof Function){
1422 try{ v(db) } catch(e){
1423 console.warn("beforeDispose() callback threw:",e);
1424 }
1425 }
1426 }
1427 },
1428 after: function(){
1429 while(this.disposeAfter.length){
1430 const v = this.disposeAfter.shift();
1431 console.debug("db.onclose.after cleaning up:",v);
1432 if(wasm.isPtr(v)) wasm.dealloc(v);
1433 else if(v instanceof sqlite3.StructBinder.StructType){
1434 v.dispose();
1435 }else if(v instanceof Function){
1436 try{v()} catch(e){/*ignored*/}
1437 }
1438 }
1439 }
1440 };
1441
1442 T.assert(wasm.isPtr(db.pointer))
1443 .mustThrowMatching(()=>db.pointer=1, /read-only/)
1444 .assert(0===sqlite3.capi.sqlite3_extended_result_codes(db.pointer,1))
1445 .assert('main'===db.dbName(0))
1446 .assert('string' === typeof db.dbVfsName())
1447 .assert(db.pointer === wasm.xWrap.testConvertArg('sqlite3*',db));
1448 // Custom db error message handling via sqlite3_prepare_v2/v3()
1449 let rc = capi.sqlite3_prepare_v3(db.pointer, {/*invalid*/}, -1, 0, null, null);
1450 T.assert(capi.SQLITE_MISUSE === rc)
1451 .assert(0 === capi.sqlite3_errmsg(db.pointer).indexOf("Invalid SQL"))
1452 .assert(dbFile === db.dbFilename())
1453 .assert(!db.dbFilename('nope'));
1454 //Sanity check DB.checkRc()...
1455 let ex;
1456 try{db.checkRc(rc)}
1457 catch(e){ex = e}
1458 T.assert(ex instanceof sqlite3.SQLite3Error)
1459 .assert(capi.SQLITE_MISUSE===ex.resultCode)
1460 .assert(0===ex.message.indexOf("SQLITE_MISUSE: sqlite3 result code"))
1461 .assert(ex.message.indexOf("Invalid SQL")>0);
1462 T.assert(db === db.checkRc(0))
1463 .assert(db === sqlite3.oo1.DB.checkRc(db,0))
1464 .assert(null === sqlite3.oo1.DB.checkRc(null,0));
1465 this.progressHandlerCount = 0;
1466 if( wasm.compileOptionUsed('OMIT_PROGRESS_CALLBACK') ){
1467 T.assert( !capi.sqlite3_progress_handler );
1468 }else{
1469 T.assert( !!capi.sqlite3_progress_handler );
1470 capi.sqlite3_progress_handler(db, 5, (p)=>{
1471 ++this.progressHandlerCount;
1472 return 0;
1473 }, 0);
1474 }
1475 }
1476 })
1477
1478////////////////////////////////////////////////////////////////////
1479 .t({
1480 name: "oo1.DB/Stmt.wrapDbHandle()",
1481 test: function(sqlite3){
1482 /* Maintenance reminder: this function is early in the list to
1483 demonstrate that the wrappers for this.db created by this
1484 function do not interfere with downstream tests, e.g. by
1485 closing this.db.pointer. */
1486 //sqlite3.config.debug("Proxying",this.db);
1487 const misuseMsg = "SQLITE_MISUSE: Argument must be a WASM sqlite3 pointer";
1488 T.mustThrowMatching(()=>sqlite3.oo1.DB.wrapHandle(this.db), misuseMsg)
1489 .mustThrowMatching(()=>sqlite3.oo1.DB.wrapHandle(0), misuseMsg);
1490 let dw = sqlite3.oo1.DB.wrapHandle(this.db.pointer);
1491 //sqlite3.config.debug('dw',dw);
1492 T.assert( dw, '!!dw' )
1493 .assert( dw instanceof sqlite3.oo1.DB, 'dw is-a oo1.DB' )
1494 .assert( dw.pointer, 'dw.pointer' )
1495 .assert( dw.pointer === this.db.pointer, 'dw.pointer===db.pointer' )
1496 .assert( dw.filename === this.db.filename, 'dw.filename===db.filename' );
1497
1498 T.assert( dw === dw.exec("select 1") );
1499 let q;
1500 try {
1501 q = dw.prepare("select 1");
1502 T.assert( q.step() )
1503 .assert( !q.step() );
1504 }finally{
1505 if( q ) q.finalize();
1506 }
1507 dw.close();
1508 T.assert( !dw.pointer )
1509 .assert( this.db === this.db.exec("select 1") );
1510 dw = undefined;
1511
1512 let pDb = 0, pStmt = 0;
1513 const stack = wasm.pstack.pointer;
1514 try {
1515 const ppOut = wasm.pstack.allocPtr();
1516 T.assert( 0==wasm.peekPtr(ppOut) );
1517 let rc = capi.sqlite3_open_v2( ":memory:", ppOut,
1518 capi.SQLITE_OPEN_CREATE
1519 | capi.SQLITE_OPEN_READWRITE,
1520 0);
1521 T.assert( 0===rc, 'open_v2()' );
1522 pDb = wasm.peekPtr(ppOut);
1523 wasm.pokePtr(ppOut, 0);
1524 T.assert( pDb>0, 'pDb>0' );
1525 const pTmp = pDb;
1526 dw = sqlite3.oo1.DB.wrapHandle(pDb, true);
1527 pDb = 0;
1528 //sqlite3.config.debug("dw",dw);
1529 T.assert( pTmp===dw.pointer, 'pTmp===dw.pointer' );
1530 T.assert( dw.filename === "", "dw.filename == "+dw.filename );
1531 let q = dw.prepare("select 1");
1532 try {
1533 T.assert( q.step(), "step()" );
1534 T.assert( !q.step(), "!step()" );
1535 }finally{
1536 q.finalize();
1537 q = undefined;
1538 }
1539 T.assert( dw===dw.exec("select 1") );
1540 dw.affirmOpen();
1541 const select1 = "select 1";
1542 rc = capi.sqlite3_prepare_v2( dw, select1, -1, ppOut, 0 );
1543 T.assert( 0===rc, 'prepare_v2() rc='+rc );
1544 pStmt = wasm.peekPtr(ppOut);
1545 T.assert( pStmt && wasm.isPtr(pStmt), 'pStmt is valid?' );
1546 try {
1547 //log( "capi.sqlite3_sql() =",capi.sqlite3_sql(pStmt));
1548 T.assert( select1 === capi.sqlite3_sql(pStmt), 'SQL mismatch' );
1549 q = sqlite3.oo1.Stmt.wrapHandle(dw, pStmt, false);
1550 //log("q@"+pStmt+" does not own handle");
1551 T.assert( q.step(), "step()" )
1552 .assert( !q.step(), "!step()" );
1553 q.finalize();
1554 q = undefined;
1555 T.assert( select1 === capi.sqlite3_sql(pStmt), 'SQL mismatch'
1556 /* This will fail if we've mismanaged pStmt's lifetime */);
1557 q = sqlite3.oo1.Stmt.wrapHandle(dw, pStmt, true);
1558 pStmt = 0;
1559 q.reset();
1560 T.assert( q.step(), "step()" )
1561 .assert( !q.step(), "!step()" );
1562 }finally{
1563 if( pStmt ){
1564 capi.sqlite3_finalize(pStmt);
1565 T.assert( !q?.pointer, "Expecting !q?.pointer" );
1566 }else if( q ){
1567 T.assert( q.pointer, "Expecting q.pointer" );
1568 //console.warn("sqlite3_finalize(",q,")");
1569 capi.sqlite3_finalize(
1570 q
1571 /* legal with sqlite3_finalize() as of the
1572 [disposal-notification] branch. Will properly
1573 clean up q. */
1574 );
1575 T.assert(!q.pointer, "Expecting !q.pointer after finalize");
1576 }
1577 }
1578 }finally{
1579 wasm.pstack.restore(stack);
1580 if( pDb ){ capi.sqlite3_close_v2(pDb); }
1581 else if( dw ){ dw.close(); }
1582 }
1583 }
1584 })/*oo1.DB/Stmt.wrapHandle()*/
1585
1586////////////////////////////////////////////////////////////////////
1587 .t('sqlite3_db_config() and sqlite3_status()', function(sqlite3){
1588 let rc = capi.sqlite3_db_config(this.db, capi.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, 0, 0);
1589 T.assert(0===rc);
1590 rc = capi.sqlite3_db_config(this.db, capi.SQLITE_DBCONFIG_MAX+1, 0);
1591 T.assert(capi.SQLITE_MISUSE === rc);
1592 rc = capi.sqlite3_db_config(this.db, capi.SQLITE_DBCONFIG_MAINDBNAME, "main");
1593 T.assert(0 === rc);
1594 const stack = wasm.pstack.pointer;
1595 try {
1596 const [pCur, pHi] = wasm.pstack.allocChunks(2,'i64');
1597 wasm.poke32([pCur, pHi], 0);
1598 let [vCur, vHi] = wasm.peek32(pCur, pHi);
1599 T.assert(0===vCur).assert(0===vHi);
1600 rc = capi.sqlite3_status(capi.SQLITE_STATUS_MEMORY_USED,
1601 pCur, pHi, 0);
1602 [vCur, vHi] = wasm.peek32(pCur, pHi);
1603 //console.warn("i32 vCur,vHi",vCur,vHi);
1604 T.assert(0 === rc).assert(vCur > 0).assert(vHi >= vCur);
1605 if(wasm.bigIntEnabled){
1606 // Again in 64-bit. Recall that pCur and pHi are allocated
1607 // large enough to account for this re-use.
1608 wasm.poke64([pCur, pHi], 0);
1609 rc = capi.sqlite3_status64(capi.SQLITE_STATUS_MEMORY_USED,
1610 pCur, pHi, 0);
1611 [vCur, vHi] = wasm.peek64([pCur, pHi]);
1612 //console.warn("i64 vCur,vHi",vCur,vHi);
1613 T.assert(0 === rc).assert(vCur > 0).assert(vHi >= vCur);
1614 }
1615 }finally{
1616 wasm.pstack.restore(stack);
1617 }
1618
1619 capi.sqlite3_db_config(this.db, capi.SQLITE_DBCONFIG_ENABLE_COMMENTS, 0, null);
1620 T.mustThrow(()=>this.db.exec("select 1 /* with comments */"), "SQL comments are disallowed");
1621 capi.sqlite3_db_config(this.db, capi.SQLITE_DBCONFIG_ENABLE_COMMENTS, 1, null);
1622 this.db.exec("select 1 /* with comments */");
1623 /* SQLITE_DBCONFIG_ENABLE_ATTACH_... are in the ATTACH-specific tests */
1624 })
1625
1626////////////////////////////////////////////////////////////////////
1627 .t('DB.Stmt', function(sqlite3){
1628 this.textEncoder = new TextEncoder('utf-8');
1629 let st = this.db.prepare( this.textEncoder.encode("select 3 as a") );
1630 let rc;
1631 try {
1632 T.assert(wasm.isPtr(st.pointer))
1633 .mustThrowMatching(()=>st.pointer=1, /read-only/)
1634 .assert(1===this.db.openStatementCount())
1635 .assert(
1636 capi.sqlite3_stmt_status(
1637 st, capi.SQLITE_STMTSTATUS_RUN, 0
1638 ) === 0)
1639 .assert('a' === st.getColumnName(0))
1640 .mustThrowMatching(()=>st.columnCount=2,
1641 /columnCount property is read-only/)
1642 .assert(1===st.columnCount)
1643 .assert(0===st.parameterCount)
1644 .assert(0===capi.sqlite3_bind_parameter_count(st))
1645 .mustThrow(()=>st.bind(1,null))
1646 .assert(true===st.step())
1647 .assert(3 === st.get(0))
1648 .mustThrow(()=>st.get(1))
1649 .mustThrow(()=>st.get(0,~capi.SQLITE_INTEGER))
1650 .assert(3 === st.get(0,capi.SQLITE_INTEGER))
1651 .assert(3 === st.getInt(0))
1652 .assert('3' === st.get(0,capi.SQLITE_TEXT))
1653 .assert('3' === st.getString(0))
1654 .assert(3.0 === st.get(0,capi.SQLITE_FLOAT))
1655 .assert(3.0 === st.getFloat(0))
1656 .assert(3 === st.get({}).a)
1657 .assert(3 === st.get([])[0])
1658 .assert(3 === st.getJSON(0))
1659 .assert(st.get(0,capi.SQLITE_BLOB) instanceof Uint8Array)
1660 .assert(1===st.get(0,capi.SQLITE_BLOB).length)
1661 .assert(st.getBlob(0) instanceof Uint8Array)
1662 .assert('3'.charCodeAt(0) === st.getBlob(0)[0])
1663 .assert(false===st.step())
1664 .mustThrowMatching(()=>st.get(0),
1665 "Stmt.step() has not (recently) returned true.")
1666 .assert(
1667 capi.sqlite3_stmt_status(
1668 st, capi.SQLITE_STMTSTATUS_RUN, 0
1669 ) > 0);
1670
1671 T.assert(this.progressHandlerCount>0
1672 || wasm.compileOptionUsed('OMIT_PROGRESS_CALLBACK'),
1673 "Expecting progress callback.");
1674
1675 st.finalize();
1676
1677 /**
1678 Ensure that Stmt.get(object|array, non-undefined-type-id)
1679 coerces all result columns to the specied type. Prior to
1680 3.54 the second argument was ignored for the object|array
1681 cases, causing all columns in the query to use their
1682 db-determined type. That is incidentally the right thing
1683 for 99.99% of use cases, but now clients may coerce them if
1684 they like.
1685 */
1686 st = this.db.prepare(
1687 "select '1' one, '2.2' two, 3 three"
1688 );
1689 T.assert( st.step() );
1690 const li = st.get([], capi.SQLITE_INTEGER);
1691 st.reset();
1692 T.assert(3===li.length)
1693 .assert(1===li[0])
1694 .assert(2===li[1])
1695 .assert(3===li[2]);
1696 T.assert( st.step() );
1697 li.length = 0;
1698 st.get(li, capi.SQLITE_TEXT);
1699 st.reset();
1700 T.assert(3===li.length)
1701 .assert('1'===li[0])
1702 .assert('2.2'===li[1])
1703 .assert('3'===li[2]);
1704 T.assert( st.step() );
1705 const ob = st.get(Object.create(null), capi.SQLITE_INTEGER);
1706 st.reset();
1707 T.assert(1===ob.one)
1708 .assert(2===ob.two)
1709 .assert(3===ob.three);
1710 }finally{
1711 rc = st.finalize();
1712 }
1713 T.assert(!st.pointer)
1714 .assert(0===this.db.openStatementCount())
1715 .assert(0===rc);
1716
1717 T.mustThrowMatching(()=>new sqlite3.oo1.Stmt("hi"), function(err){
1718 return (err instanceof sqlite3.SQLite3Error)
1719 && capi.SQLITE_MISUSE === err.resultCode
1720 && 0 < err.message.indexOf("Do not call the Stmt constructor directly.")
1721 });
1722 })
1723
1724 ////////////////////////////////////////////////////////////////////////
1725 .t('sqlite3_bind_text/blob() with JS values', function(){
1726 /* Derived from [bugs:bbb715c3f2a0e989]. */
1727 const q = this.db.prepare("select ?1, typeof(?1), octet_length(?1)");
1728 const enc = this.textEncoder, denc = new TextDecoder('utf-8');
1729 const BindText = capi.sqlite3_bind_text, BindBlob = capi.sqlite3_bind_blob;
1730 /* Bind value v of length n to q using binding function f(), step
1731 it, fetch it, reset it, and return the fetched row. */
1732 const bindAndGet = (f, v, n)=>{
1733 const rc = f(q, 1, v, n, capi.SQLITE_WASM_DEALLOC);
1734 q.step();
1735 const rv = q.get([]);
1736 T.assert( 3===rv.length );
1737 rv.unshift(rc);
1738 q.reset(true);
1739 return rv;
1740 };
1741 /* Pass (v,n) through sqlite3_bind_text() and affirm that
1742 expect === column 0 of the result. */
1743 const checkText = (v, n, expect)=>{
1744 const [rc, val, type, len] = bindAndGet(BindText, v, n);
1745 T.assert(0===rc)
1746 .assert(expect===val)
1747 .assert('text'===type)
1748 .assert(enc.encode(expect).byteLength===len);
1749 };
1750 /* Pass (v,n) through sqlite3_bind_blob() and affirm that
1751 the resulting value has a length of expectLen. Returns
1752 the resulting Uint8Array.*/
1753 const checkBlob = (v, n, expectLen)=>{
1754 const [rc, val, type, len] = bindAndGet(BindBlob, v, n);
1755 T.assert(0===rc, "bind_blob rc", rc)
1756 .assert('blob'===type)
1757 .assert(expectLen===len)
1758 .assert(val instanceof Uint8Array && expectLen===val.byteLength);
1759 return val;
1760 };
1761 const checkBlobText = (v, n, expectLen, expectText)=>{
1762 const rv = checkBlob(v, n, expectLen);
1763 T.assert(denc.decode(rv)===expectText, "checkBlobText()", expectText);
1764 }
1765 try{
1766 checkText("SQLite", -1, "SQLite");
1767 checkText(["Früh","stück"], -1, "Frühstück");
1768 checkText("", -1, "");
1769 checkText(enc.encode("SQLite"), -1, "SQLite");
1770 const xenc = enc.encode("a string");
1771 checkText(new Int8Array(xenc), -1, "a string");
1772 checkText(xenc.buffer, -1, "a string");
1773 checkBlobText("SQLite", -1, 6, "SQLite");
1774 checkBlobText("SQLite", 2, 6, "SQLite");
1775 checkBlob("", -1, 0);
1776 checkBlobText(["SQL", "i", "te"], -1, 6, "SQLite");
1777 T.assert("SQL"===denc.decode(checkBlob(enc.encode("SQLite"), 3, 3)));
1778 T.assert(capi.SQLITE_MISUSE===bindAndGet(
1779 BindBlob, {}, -1
1780 )[0]);
1781 T.assert(capi.SQLITE_MISUSE===bindAndGet(
1782 BindText, {}, -1
1783 )[0]);
1784 }finally{
1785 q.finalize();
1786 }
1787 })/*sqlite3_bind_text/blob()*/
1788
1789////////////////////////////////////////////////////////////////////////
1790 .t('sqlite3_js_...()', function(){
1791 const db = this.db;
1792 if(1){
1793 const vfsList = capi.sqlite3_js_vfs_list();
1794 T.assert(vfsList.length>1);
1795 wasm.scopedAllocCall(()=>{
1796 const vfsArg = (v)=>wasm.xWrap.testConvertArg('sqlite3_vfs*',v);
1797 for(const v of vfsList){
1798 T.assert('string' === typeof v);
1799 const pVfs = capi.sqlite3_vfs_find(v);
1800 T.assert(wasm.isPtr(pVfs))
1801 .assert(pVfs===vfsArg(v));
1802 const vfs = new capi.sqlite3_vfs(pVfs);
1803 try { T.assert(vfsArg(vfs)===pVfs) }
1804 finally{ vfs.dispose() }
1805 }
1806 });
1807 }
1808 /**
1809 Trivia: the magic db name ":memory:" does not actually use the
1810 "memdb" VFS unless "memdb" is _explicitly_ provided as the VFS
1811 name. Instead, it uses the default VFS with an in-memory btree.
1812 Thus this.db's VFS may not be memdb even though it's an in-memory
1813 db.
1814 */
1815 const pVfsMem = capi.sqlite3_vfs_find('memdb'),
1816 pVfsDflt = capi.sqlite3_vfs_find(0),
1817 pVfsDb = capi.sqlite3_js_db_vfs(db.pointer);
1818 T.assert(pVfsMem > 0)
1819 .assert(pVfsDflt > 0)
1820 .assert(pVfsDb > 0)
1821 .assert(pVfsMem !== pVfsDflt
1822 /* memdb lives on top of the default vfs */)
1823 .assert(pVfsDb === pVfsDflt || pVfsDb === pVfsMem)
1824 ;
1825 /*const vMem = new capi.sqlite3_vfs(pVfsMem),
1826 vDflt = new capi.sqlite3_vfs(pVfsDflt),
1827 vDb = new capi.sqlite3_vfs(pVfsDb);*/
1828 const duv = capi.sqlite3_js_db_uses_vfs;
1829 T.assert(pVfsDflt === duv(db.pointer, 0)
1830 || pVfsMem === duv(db.pointer,0))
1831 .assert(!duv(db.pointer, "foo"))
1832 ;
1833 }/*sqlite3_js_...()*/)
1834
1835////////////////////////////////////////////////////////////////////
1836 .t('Table t', function(sqlite3){
1837 const db = this.db;
1838 let list = [];
1839 this.progressHandlerCount = 0;
1840 //wasm.xWrap.debug = true;
1841 let rc = db.exec({
1842 sql:['CREATE TABLE t(a,b);',
1843 // ^^^ using TEMP TABLE breaks the db export test
1844 "INSERT INTO t(a,b) VALUES(1,2),(3,4),",
1845 "(?,?)"/*intentionally missing semicolon to test for
1846 off-by-one bug in string-to-WASM conversion*/],
1847 saveSql: list,
1848 bind: [5,6]
1849 });
1850 //debug("Exec'd SQL:", list);
1851 T.assert(rc === db)
1852 .assert(2 === list.length)
1853 .assert('string'===typeof list[1])
1854 .assert(3===db.changes())
1855 .assert(this.progressHandlerCount > 0
1856 || wasm.compileOptionUsed('OMIT_PROGRESS_CALLBACK'),
1857 "Expecting progress callback.")
1858 if(wasm.bigIntEnabled){
1859 T.assert(3n===db.changes(false,true));
1860 }
1861 rc = db.exec({
1862 sql: "INSERT INTO t(a,b) values('blob',X'6869') RETURNING 13",
1863 rowMode: 0
1864 });
1865 T.assert(Array.isArray(rc))
1866 .assert(1===rc.length)
1867 .assert(13 === rc[0])
1868 .assert(1===db.changes());
1869
1870 let vals = db.selectValues('select a from t order by a limit 2');
1871 T.assert( 2 === vals.length )
1872 .assert( 1===vals[0] && 3===vals[1] );
1873 vals = db.selectValues('select a from t order by a limit $L',
1874 {$L:2}, capi.SQLITE_TEXT);
1875 T.assert( 2 === vals.length )
1876 .assert( '1'===vals[0] && '3'===vals[1] );
1877 vals = undefined;
1878
1879 let blob = db.selectValue("select b from t where a='blob'");
1880 T.assert(blob instanceof Uint8Array).
1881 assert(0x68===blob[0] && 0x69===blob[1]);
1882 blob = null;
1883 blob = db.selectValue("select ?1", new Uint8Array([97,0,98,0,99]),
1884 sqlite3.capi.SQLITE_TEXT);
1885 T.assert("a\0b\0c"===blob, "Something is amiss with embedded NULs");
1886 let counter = 0, colNames = [];
1887 list.length = 0;
1888 db.exec(new TextEncoder('utf-8').encode("SELECT a a, b b FROM t"),{
1889 rowMode: 'object',
1890 resultRows: list,
1891 columnNames: colNames,
1892 _myState: 3 /* Accessible from the callback */,
1893 callback: function(row,stmt){
1894 ++counter;
1895 T.assert(
1896 3 === this._myState
1897 /* Recall that "this" is the options object. */
1898 ).assert(
1899 this.columnNames===colNames
1900 ).assert(
1901 this.columnNames[0]==='a' && this.columnNames[1]==='b'
1902 ).assert(
1903 (row.a%2 && row.a<6) || 'blob'===row.a
1904 );
1905 }
1906 });
1907 T.assert(2 === colNames.length)
1908 .assert('a' === colNames[0])
1909 .assert(4 === counter)
1910 .assert(4 === list.length);
1911 colNames = [];
1912 db.exec({
1913 /* Ensure that columnNames is populated for empty result sets. */
1914 sql: "SELECT a a, b B FROM t WHERE 0",
1915 columnNames: colNames
1916 });
1917 T.assert(2===colNames.length)
1918 .assert('a'===colNames[0] && 'B'===colNames[1]);
1919 list.length = 0;
1920 db.exec("SELECT a a, b b FROM t",{
1921 rowMode: 'array',
1922 callback: function(row,stmt){
1923 ++counter;
1924 T.assert(Array.isArray(row))
1925 .assert((0===row[1]%2 && row[1]<7)
1926 || (row[1] instanceof Uint8Array));
1927 }
1928 });
1929 T.assert(8 === counter);
1930 T.assert(Number.MIN_SAFE_INTEGER ===
1931 db.selectValue("SELECT "+Number.MIN_SAFE_INTEGER)).
1932 assert(Number.MAX_SAFE_INTEGER ===
1933 db.selectValue("SELECT "+Number.MAX_SAFE_INTEGER));
1934 counter = 0;
1935 let rv = db.exec({
1936 sql: "SELECT a FROM t",
1937 callback: ()=>(1===++counter),
1938 });
1939 T.assert(db === rv)
1940 .assert(2===counter,
1941 "Expecting exec step() loop to stop if callback returns false.");
1942 /** If exec() is passed neither callback nor returnValue but
1943 is passed an explicit rowMode then the default returnValue
1944 is the whole result set, as if an empty resultRows option
1945 had been passed. */
1946 rv = db.exec({
1947 sql: "SELECT -1 UNION ALL SELECT -2 UNION ALL SELECT -3 ORDER BY 1 DESC",
1948 rowMode: 0
1949 });
1950 T.assert(Array.isArray(rv)).assert(3===rv.length)
1951 .assert(-1===rv[0]).assert(-3===rv[2]);
1952 rv = db.exec("SELECT 1 WHERE 0",{rowMode: 0});
1953 T.assert(Array.isArray(rv)).assert(0===rv.length);
1954 if(wasm.bigIntEnabled && haveWasmCTests()){
1955 const mI = wasm.xCall('sqlite3__wasm_test_int64_max');
1956 const b = BigInt(Number.MAX_SAFE_INTEGER * 2);
1957 T.assert(b === db.selectValue("SELECT "+b)).
1958 assert(b === db.selectValue("SELECT ?", b)).
1959 assert(mI == db.selectValue("SELECT $x", {$x:mI}));
1960 }else{
1961 /* Curiously, the JS spec seems to be off by one with the definitions
1962 of MIN/MAX_SAFE_INTEGER:
1963
1964 https://github.com/emscripten-core/emscripten/issues/17391 */
1965 T.mustThrow(()=>db.selectValue("SELECT "+(Number.MAX_SAFE_INTEGER+1))).
1966 mustThrow(()=>db.selectValue("SELECT "+(Number.MIN_SAFE_INTEGER-1)));
1967 }
1968
1969 let st = db.prepare("update t set b=:b where a='blob'");
1970 try {
1971 T.assert(0===st.columnCount)
1972 .assert(1===st.parameterCount)
1973 .assert(1===capi.sqlite3_bind_parameter_count(st))
1974 .assert( false===st.isReadOnly() );
1975 const ndx = st.getParamIndex(':b');
1976 T.assert(1===ndx);
1977 st.bindAsBlob(ndx, "ima blob")
1978 /*step() skipped intentionally*/.reset(true);
1979 } finally {
1980 T.assert(0===st.finalize())
1981 .assert(undefined===st.finalize());
1982 }
1983
1984 try {
1985 db.prepare("/*empty SQL*/");
1986 toss("Must not be reached.");
1987 }catch(e){
1988 T.assert(e instanceof sqlite3.SQLite3Error)
1989 .assert(0==e.message.indexOf('Cannot prepare empty'));
1990 }
1991
1992 counter = 0;
1993 db.exec({
1994 // Check for https://sqlite.org/forum/forumpost/895425b49a
1995 sql: "pragma table_info('t')",
1996 rowMode: 'object',
1997 callback: function(row){
1998 ++counter;
1999 T.assert(row.name==='a' || row.name==='b');
2000 }
2001 });
2002 T.assert(2===counter);
2003 })/*setup table T*/
2004
2005////////////////////////////////////////////////////////////////////
2006 .t({
2007 name: "sqlite3_set_authorizer()",
2008 predicate: ()=>!!wasm.exports.sqlite3_set_authorizer || "Missing sqlite3_set_authorizer()",
2009 test:function(sqlite3){
2010 T.assert(capi.SQLITE_IGNORE>0)
2011 .assert(capi.SQLITE_DENY>0);
2012 const db = this.db;
2013 const ssa = capi.sqlite3_set_authorizer;
2014 const n = db.selectValue('select count(*) from t');
2015 T.assert(n>0);
2016 let authCount = 0;
2017 let rc = ssa(db, function(pV, iCode, s0, s1, s2, s3){
2018 ++authCount;
2019 return capi.SQLITE_IGNORE;
2020 }, 0);
2021 T.assert(0===rc)
2022 .assert(
2023 undefined === db.selectValue('select count(*) from t')
2024 /* Note that the count() never runs, so we get undefined
2025 instead of 0. */
2026 )
2027 .assert(authCount>0);
2028 authCount = 0;
2029 db.exec("update t set a=-9999");
2030 T.assert(authCount>0);
2031 /* Reminder: we don't use DELETE because, from the C API docs:
2032
2033 "If the action code is [SQLITE_DELETE] and the callback
2034 returns [SQLITE_IGNORE] then the [DELETE] operation proceeds
2035 but the [truncate optimization] is disabled and all rows are
2036 deleted individually."
2037 */
2038 rc = ssa(db, null, 0);
2039 authCount = 0;
2040 T.assert(-9999 != db.selectValue('select a from t'))
2041 .assert(0===authCount);
2042 rc = ssa(db, function(pV, iCode, s0, s1, s2, s3){
2043 ++authCount;
2044 return capi.SQLITE_DENY;
2045 }, 0);
2046 T.assert(0===rc);
2047 let err;
2048 try{ db.exec("select 1 from t") }
2049 catch(e){ err = e }
2050 T.assert(err instanceof sqlite3.SQLite3Error)
2051 .assert(err.message.indexOf('not authorized'>0))
2052 .assert(1===authCount);
2053 authCount = 0;
2054 rc = ssa(db, function(...args){
2055 ++authCount;
2056 return capi.SQLITE_OK;
2057 }, 0);
2058 T.assert(0===rc);
2059 T.assert(n === db.selectValue('select count(*) from t'))
2060 .assert(authCount>0);
2061 authCount = 0;
2062 rc = ssa(db, function(pV, iCode, s0, s1, s2, s3){
2063 ++authCount;
2064 throw new Error("Testing catching of authorizer.");
2065 }, 0);
2066 T.assert(0===rc);
2067 authCount = 0;
2068 err = undefined;
2069 try{ db.exec("select 1 from t") }
2070 catch(e){err = e}
2071 T.assert(err instanceof Error)
2072 .assert(err.message.indexOf('not authorized')>0)
2073 /* Note that the thrown message is trumped/overwritten
2074 by the authorizer process. */
2075 .assert(1===authCount);
2076 rc = ssa(db, 0, 0);
2077 authCount = 0;
2078 T.assert(0===rc);
2079 T.assert(n === db.selectValue('select count(*) from t'))
2080 .assert(0===authCount);
2081 }
2082 })/*sqlite3_set_authorizer()*/
2083
2084////////////////////////////////////////////////////////////////////////
2085 .t("sqlite3_table_column_metadata()", function(sqlite3){
2086 const stack = wasm.pstack.pointer;
2087 try{
2088 const [pzDT, pzColl, pNotNull, pPK, pAuto] =
2089 wasm.pstack.allocPtr(5);
2090 const rc = capi.sqlite3_table_column_metadata(
2091 this.db, "main", "t", "rowid",
2092 pzDT, pzColl, pNotNull, pPK, pAuto
2093 );
2094 T.assert(0===rc)
2095 .assert("INTEGER"===wasm.cstrToJs(wasm.peekPtr(pzDT)))
2096 .assert("BINARY"===wasm.cstrToJs(wasm.peekPtr(pzColl)))
2097 .assert(0===wasm.peek32(pNotNull))
2098 .assert(1===wasm.peek32(pPK))
2099 .assert(0===wasm.peek32(pAuto))
2100 }finally{
2101 wasm.pstack.restore(stack);
2102 }
2103 })
2104
2105////////////////////////////////////////////////////////////////////////
2106 .t('selectArray/Object()', function(sqlite3){
2107 const db = this.db;
2108 let rc = db.selectArray('select a, b from t where a=?', 5);
2109 T.assert(Array.isArray(rc))
2110 .assert(2===rc.length)
2111 .assert(5===rc[0] && 6===rc[1]);
2112 rc = db.selectArray('select a, b from t where b=-1');
2113 T.assert(undefined === rc);
2114 rc = db.selectObject('select a A, b b from t where b=?', 6);
2115 T.assert(rc && 'object'===typeof rc)
2116 .assert(5===rc.A)
2117 .assert(6===rc.b);
2118 rc = db.selectArray('select a, b from t where b=-1');
2119 T.assert(undefined === rc);
2120 })
2121////////////////////////////////////////////////////////////////////////
2122 .t('selectArrays/Objects()', function(sqlite3){
2123 const db = this.db;
2124 const sql = 'select a, b from t where a=? or b=? order by a';
2125 let rc = db.selectArrays(sql, [1, 4]);
2126 T.assert(Array.isArray(rc))
2127 .assert(2===rc.length)
2128 .assert(2===rc[0].length)
2129 .assert(1===rc[0][0])
2130 .assert(2===rc[0][1])
2131 .assert(3===rc[1][0])
2132 .assert(4===rc[1][1])
2133 rc = db.selectArrays(sql, [99,99]);
2134 T.assert(Array.isArray(rc)).assert(0===rc.length);
2135 rc = db.selectObjects(sql, [1,4]);
2136 T.assert(Array.isArray(rc))
2137 .assert(2===rc.length)
2138 .assert('object' === typeof rc[1])
2139 .assert(1===rc[0].a)
2140 .assert(2===rc[0].b)
2141 .assert(3===rc[1].a)
2142 .assert(4===rc[1].b);
2143 })
2144////////////////////////////////////////////////////////////////////////
2145 .t('selectArray/Object/Values() via INSERT/UPDATE...RETURNING', function(sqlite3){
2146 let rc = this.db.selectObject("INSERT INTO t(a,b) VALUES(83,84) RETURNING a as AA");
2147 T.assert(83===rc.AA);
2148 rc = this.db.selectArray("UPDATE T set a=85 WHERE a=83 RETURNING b as BB");
2149 T.assert(Array.isArray(rc)).assert(84===rc[0]);
2150 //log("select * from t:",this.db.selectObjects("select * from t order by a"));
2151 rc = this.db.selectValues("UPDATE T set a=a*1 RETURNING a");
2152 T.assert(Array.isArray(rc))
2153 .assert(5 === rc.length)
2154 .assert('number'===typeof rc[0])
2155 .assert(rc[0]|0 === rc[0] /* is small integer */);
2156 })
2157////////////////////////////////////////////////////////////////////////
2158 .t({
2159 name: 'sqlite3_js_db_export()',
2160 predicate: ()=>true,
2161 test: function(sqlite3){
2162 const db = this.db;
2163 const xp = capi.sqlite3_js_db_export(db.pointer);
2164 T.assert(xp instanceof Uint8Array)
2165 .assert(xp.byteLength>0)
2166 .assert(0 === xp.byteLength % 512);
2167 this.dbExport = xp;
2168 }
2169 }/*sqlite3_js_db_export()*/)
2170 .t({
2171 name: 'sqlite3_js_posix_create_file()',
2172 predicate: ()=>true,
2173 test: function(sqlite3){
2174 const db = this.db;
2175 const filename = "sqlite3_js_posix_create_file.db";
2176 capi.sqlite3_js_posix_create_file(filename, this.dbExport);
2177 delete this.dbExport;
2178 const db2 = new sqlite3.oo1.DB(filename,'r');
2179 try {
2180 const sql = "select count(*) from t";
2181 const n = db.selectValue(sql);
2182 T.assert(n>0 && db2.selectValue(sql) === n);
2183 }finally{
2184 db2.close();
2185 sqlite3.util.sqlite3__wasm_vfs_unlink(0, filename);
2186 }
2187 }
2188 }/*sqlite3_js_posix_create_file()*/)
2189
2190////////////////////////////////////////////////////////////////////
2191 .t({
2192 name:'Scalar UDFs',
2193 test: function(sqlite3){
2194 const db = this.db;
2195 db.createFunction(
2196 "foo",
2197 1 ? (pCx,a,b)=>a+b
2198 : (pCx,a,b)=>{
2199 /*return sqlite3.capi.sqlite3_result_error_js(
2200 db, sqlite3.capi.SQLITE_ERROR, "foo???"
2201 );*/
2202 console.debug("foo UDF", pCx, a, b);
2203 return Number(a)+Number(b);
2204 }
2205 );
2206 T.assert(7===db.selectValue("select foo(3,4)")).
2207 assert(5===db.selectValue("select foo(3,?)",2)).
2208 assert(5===db.selectValue("select foo(?,?2)",[1,4])).
2209 assert(5===db.selectValue("select foo($a,$b)",{$a:0,$b:5}));
2210 db.createFunction("bar", {
2211 arity: -1,
2212 xFunc: (pCx,...args)=>{
2213 T.assert(db.pointer === capi.sqlite3_context_db_handle(pCx));
2214 let rc = 0;
2215 for(const v of args) rc += v;
2216 return rc;
2217 }
2218 }).createFunction({
2219 name: "asis",
2220 xFunc: (pCx,arg)=>arg
2221 });
2222 T.assert(0===db.selectValue("select bar()")).
2223 assert(1===db.selectValue("select bar(1)")).
2224 assert(3===db.selectValue("select bar(1,2)")).
2225 assert(-1===db.selectValue("select bar(1,2,-4)")).
2226 assert('hi' === db.selectValue("select asis('hi')")).
2227 assert('hi' === db.selectValue("select ?",'hi')).
2228 assert(null === db.selectValue("select null")).
2229 assert(null === db.selectValue("select asis(null)")).
2230 assert(1 === db.selectValue("select ?",1)).
2231 assert(2 === db.selectValue("select ?",[2])).
2232 assert(3 === db.selectValue("select $a",{$a:3})).
2233 assert(T.eqApprox(3.1,db.selectValue("select 3.0 + 0.1"))).
2234 assert(T.eqApprox(1.3,db.selectValue("select asis(1 + 0.3)")));
2235
2236 let blobArg = new Uint8Array([0x68, 0x69]);
2237 let blobRc = db.selectValue(
2238 "select asis(?1)",
2239 blobArg.buffer/*confirm that ArrayBuffer is handled as a Uint8Array*/
2240 );
2241 T.assert(blobRc instanceof Uint8Array).
2242 assert(2 === blobRc.length).
2243 assert(0x68==blobRc[0] && 0x69==blobRc[1]);
2244 blobRc = db.selectValue("select asis(X'6869')");
2245 T.assert(blobRc instanceof Uint8Array).
2246 assert(2 === blobRc.length).
2247 assert(0x68==blobRc[0] && 0x69==blobRc[1]);
2248
2249 blobArg = new Int8Array([0x68, 0x69]);
2250 //debug("blobArg=",blobArg);
2251 blobRc = db.selectValue("select asis(?1)", blobArg);
2252 T.assert(blobRc instanceof Uint8Array).
2253 assert(2 === blobRc.length);
2254 //debug("blobRc=",blobRc);
2255 T.assert(0x68==blobRc[0] && 0x69==blobRc[1]);
2256
2257 let rc = sqlite3.capi.sqlite3_create_function_v2(
2258 this.db, "foo", 0, -1, 0, 0, 0, 0, 0
2259 );
2260 T.assert(
2261 sqlite3.capi.SQLITE_FORMAT === rc,
2262 "For invalid eTextRep argument."
2263 );
2264 rc = sqlite3.capi.sqlite3_create_function_v2(this.db, "foo", 0);
2265 T.assert(
2266 sqlite3.capi.SQLITE_MISUSE === rc,
2267 "For invalid arg count."
2268 );
2269
2270 /* Confirm that we can map and unmap the same function with
2271 multiple arities... */
2272 const fCounts = [0,0];
2273 const fArityCheck = function(pCx){
2274 return ++fCounts[arguments.length-1];
2275 };
2276 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = true;
2277 rc = capi.sqlite3_create_function_v2(
2278 db, "nary", 0, capi.SQLITE_UTF8, 0, fArityCheck, 0, 0, 0
2279 );
2280 T.assert( 0===rc );
2281 rc = capi.sqlite3_create_function_v2(
2282 db, "nary", 1, capi.SQLITE_UTF8, 0, fArityCheck, 0, 0, 0
2283 );
2284 T.assert( 0===rc );
2285 const sqlFArity0 = "select nary()";
2286 const sqlFArity1 = "select nary(1)";
2287 T.assert( 1 === db.selectValue(sqlFArity0) )
2288 .assert( 1 === fCounts[0] ).assert( 0 === fCounts[1] );
2289 T.assert( 1 === db.selectValue(sqlFArity1) )
2290 .assert( 1 === fCounts[0] ).assert( 1 === fCounts[1] );
2291 capi.sqlite3_create_function_v2(
2292 db, "nary", 0, capi.SQLITE_UTF8, 0, 0, 0, 0, 0
2293 );
2294 T.mustThrowMatching((()=>db.selectValue(sqlFArity0)),
2295 (e)=>((e instanceof sqlite3.SQLite3Error)
2296 && e.message.indexOf("wrong number of arguments")>0),
2297 "0-arity variant was uninstalled.");
2298 T.assert( 2 === db.selectValue(sqlFArity1) )
2299 .assert( 1 === fCounts[0] ).assert( 2 === fCounts[1] );
2300 capi.sqlite3_create_function_v2(
2301 db, "nary", 1, capi.SQLITE_UTF8, 0, 0, 0, 0, 0
2302 );
2303 T.mustThrowMatching((()=>db.selectValue(sqlFArity1)),
2304 (e)=>((e instanceof sqlite3.SQLite3Error)
2305 && e.message.indexOf("no such function")>0),
2306 "1-arity variant was uninstalled.");
2307 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = false;
2308 }
2309 })
2310
2311////////////////////////////////////////////////////////////////////
2312 .t({
2313 name: 'Aggregate UDFs',
2314 //predicate: ()=>false,
2315 test: function(sqlite3){
2316 const db = this.db;
2317 const sjac = capi.sqlite3_js_aggregate_context;
2318 db.createFunction({
2319 name: 'summer',
2320 xStep: (pCtx, n)=>{
2321 const ac = sjac(pCtx, 4);
2322 wasm.poke32(ac, wasm.peek32(ac) + Number(n));
2323 },
2324 xFinal: (pCtx)=>{
2325 const ac = sjac(pCtx, 0);
2326 return ac ? wasm.peek32(ac) : 0;
2327 }
2328 });
2329 let v = db.selectValue([
2330 "with cte(v) as (",
2331 "select 3 union all select 5 union all select 7",
2332 ") select summer(v), summer(v+1) from cte"
2333 /* ------------------^^^^^^^^^^^ ensures that we're handling
2334 sqlite3_aggregate_context() properly. */
2335 ]);
2336 T.assert(15===v);
2337 T.mustThrowMatching(()=>db.selectValue("select summer(1,2)"),
2338 /wrong number of arguments/);
2339
2340 db.createFunction({
2341 name: 'summerN',
2342 arity: -1,
2343 xStep: (pCtx, ...args)=>{
2344 const ac = sjac(pCtx, 4);
2345 let sum = wasm.peek32(ac);
2346 for(const v of args) sum += Number(v);
2347 wasm.poke32(ac, sum);
2348 },
2349 xFinal: (pCtx)=>{
2350 const ac = sjac(pCtx, 0);
2351 capi.sqlite3_result_int( pCtx, ac ? wasm.peek32(ac) : 0 );
2352 // xFinal() may either return its value directly or call
2353 // sqlite3_result_xyz() and return undefined. Both are
2354 // functionally equivalent.
2355 }
2356 });
2357 T.assert(18===db.selectValue('select summerN(1,8,9), summerN(2,3,4)'));
2358 T.mustThrowMatching(()=>{
2359 db.createFunction('nope',{
2360 xFunc: ()=>{}, xStep: ()=>{}
2361 });
2362 }, /scalar or aggregate\?/);
2363 T.mustThrowMatching(()=>{
2364 db.createFunction('nope',{xStep: ()=>{}});
2365 }, /Missing xFinal/);
2366 T.mustThrowMatching(()=>{
2367 db.createFunction('nope',{xFinal: ()=>{}});
2368 }, /Missing xStep/);
2369 T.mustThrowMatching(()=>{
2370 db.createFunction('nope',{});
2371 }, /Missing function-type properties/);
2372 T.mustThrowMatching(()=>{
2373 db.createFunction('nope',{xFunc:()=>{}, xDestroy:'nope'});
2374 }, /xDestroy property must be a function/);
2375 T.mustThrowMatching(()=>{
2376 db.createFunction('nope',{xFunc:()=>{}, pApp:'nope'});
2377 }, /Invalid value for pApp/);
2378 }
2379 }/*aggregate UDFs*/)
2380
2381////////////////////////////////////////////////////////////////////////
2382 .t({
2383 name: 'Aggregate UDFs (64-bit)',
2384 predicate: ()=>wasm.bigIntEnabled,
2385 //predicate: ()=>false,
2386 test: function(sqlite3){
2387 const db = this.db;
2388 const sjac = capi.sqlite3_js_aggregate_context;
2389 db.createFunction({
2390 name: 'summer64',
2391 xStep: (pCtx, n)=>{
2392 const ac = sjac(pCtx, 8);
2393 wasm.poke64(ac, wasm.peek64(ac) + BigInt(n));
2394 },
2395 xFinal: (pCtx)=>{
2396 const ac = sjac(pCtx, 0);
2397 return ac ? wasm.peek64(ac) : 0n;
2398 }
2399 });
2400 let v = db.selectValue([
2401 "with cte(v) as (",
2402 "select 9007199254740991 union all select 1 union all select 2",
2403 ") select summer64(v), summer64(v+1) from cte"
2404 ]);
2405 T.assert(9007199254740994n===v);
2406 }
2407 }/*aggregate UDFs*/)
2408
2409////////////////////////////////////////////////////////////////////
2410 .t({
2411 name: 'Window UDFs',
2412 predicate: (sqlite3)=>!!sqlite3.wasm.exports.sqlite3_create_window_function
2413 /*!sqlite3.wasm.compileOptionUsed('OMIT_WINDOWFUNC')*/
2414 || "Missing window functions",
2415 test: function(){
2416 /* Example window function, table, and results taken from:
2417 https://sqlite.org/windowfunctions.html#udfwinfunc */
2418 const db = this.db;
2419 const sjac = (cx,n=4)=>capi.sqlite3_js_aggregate_context(cx,n);
2420 const xValueFinal = (pCtx)=>{
2421 const ac = sjac(pCtx, 0);
2422 return ac ? wasm.peek32(ac) : 0;
2423 };
2424 const xStepInverse = (pCtx, n)=>{
2425 const ac = sjac(pCtx);
2426 wasm.poke32(ac, wasm.peek32(ac) + Number(n));
2427 };
2428 db.createFunction({
2429 name: 'winsumint',
2430 xStep: (pCtx, n)=>xStepInverse(pCtx, n),
2431 xInverse: (pCtx, n)=>xStepInverse(pCtx, -n),
2432 xFinal: xValueFinal,
2433 xValue: xValueFinal
2434 });
2435 db.exec([
2436 "CREATE TEMP TABLE twin(x, y); INSERT INTO twin VALUES",
2437 "('a', 4),('b', 5),('c', 3),('d', 8),('e', 1)"
2438 ]);
2439 let rc = db.exec({
2440 returnValue: 'resultRows',
2441 sql:[
2442 "SELECT x, winsumint(y) OVER (",
2443 "ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING",
2444 ") AS sum_y ",
2445 "FROM twin ORDER BY x;"
2446 ]
2447 });
2448 T.assert(Array.isArray(rc))
2449 .assert(5 === rc.length);
2450 let count = 0;
2451 for(const row of rc){
2452 switch(++count){
2453 case 1: T.assert('a'===row[0] && 9===row[1]); break;
2454 case 2: T.assert('b'===row[0] && 12===row[1]); break;
2455 case 3: T.assert('c'===row[0] && 16===row[1]); break;
2456 case 4: T.assert('d'===row[0] && 12===row[1]); break;
2457 case 5: T.assert('e'===row[0] && 9===row[1]); break;
2458 default: toss("Too many rows to window function.");
2459 }
2460 }
2461 const resultRows = [];
2462 rc = db.exec({
2463 resultRows,
2464 returnValue: 'resultRows',
2465 sql:[
2466 "SELECT x, winsumint(y) OVER (",
2467 "ORDER BY x ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING",
2468 ") AS sum_y ",
2469 "FROM twin ORDER BY x;"
2470 ]
2471 });
2472 T.assert(rc === resultRows)
2473 .assert(5 === rc.length);
2474
2475 rc = db.exec({
2476 returnValue: 'saveSql',
2477 sql: "select 1; select 2; -- empty\n; select 3"
2478 });
2479 T.assert(Array.isArray(rc))
2480 .assert(3===rc.length)
2481 .assert('select 1;' === rc[0])
2482 .assert('select 2;' === rc[1])
2483 .assert('-- empty\n; select 3' === rc[2]
2484 /* Strange but true. */);
2485 T.mustThrowMatching(()=>{
2486 db.exec({sql:'', returnValue: 'nope'});
2487 }, /Invalid returnValue/);
2488
2489 db.exec("DROP TABLE twin");
2490 }
2491 }/*window UDFs*/)
2492
2493////////////////////////////////////////////////////////////////////
2494 .t("ATTACH", function(sqlite3){
2495 const db = this.db;
2496 const resultRows = [];
2497 db.exec({
2498 sql:new TextEncoder('utf-8').encode([
2499 // ^^^ testing string-vs-typedarray handling in exec()
2500 "attach 'session' as foo;",
2501 "create table foo.bar(a);",
2502 "insert into foo.bar(a) values(1),(2),(3);",
2503 "select a from foo.bar order by a;"
2504 ].join('')),
2505 rowMode: 0,
2506 resultRows
2507 });
2508 T.assert(3===resultRows.length)
2509 .assert(2===resultRows[1]);
2510 T.assert(2===db.selectValue('select a from foo.bar where a>1 order by a'));
2511
2512 /** Demonstrate the JS-simplified form of the sqlite3_exec() callback... */
2513 let colCount = 0, rowCount = 0;
2514 let rc = capi.sqlite3_exec(
2515 db, "select a, a*2 from foo.bar", function(aVals, aNames){
2516 //console.warn("execCallback(",arguments,")");
2517 colCount = aVals.length;
2518 ++rowCount;
2519 T.assert(2===aVals.length)
2520 .assert(2===aNames.length)
2521 .assert(+(aVals[1]) === 2 * +(aVals[0]));
2522 }, 0, 0
2523 );
2524 T.assert(0===rc).assert(3===rowCount).assert(2===colCount);
2525 rc = capi.sqlite3_exec(
2526 db.pointer, "select a from foo.bar", ()=>{
2527 tossQuietly("Testing throwing from exec() callback.");
2528 }, 0, 0
2529 );
2530 T.assert(capi.SQLITE_ABORT === rc);
2531
2532 /* Demonstrate how to get access to the "full" callback
2533 signature, as opposed to the simplified JS-specific one... */
2534 rowCount = colCount = 0;
2535 const pCb = wasm.installFunction('i(pipp)', function(pVoid,nCols,aVals,aCols){
2536 /* Tip: wasm.cArgvToJs() can be used to convert aVals and
2537 aCols to arrays: const vals = wasm.cArgvToJs(nCols,
2538 aVals); */
2539 ++rowCount;
2540 colCount = nCols;
2541 T.assert(2 === nCols)
2542 .assert(wasm.isPtr(pVoid))
2543 .assert(wasm.isPtr(aVals))
2544 .assert(wasm.isPtr(aCols))
2545 .assert(+wasm.cstrToJs(wasm.peekPtr(wasm.ptr.add(aVals, wasm.ptr.size)))
2546 === 2 * +wasm.cstrToJs(wasm.peekPtr(aVals)));
2547 return 0;
2548 });
2549 try {
2550 T.assert(wasm.isPtr(pCb));
2551 rc = capi.sqlite3_exec(
2552 db, new TextEncoder('utf-8').encode("select a, a*2 from foo.bar"),
2553 pCb, 0, 0
2554 );
2555 T.assert(0===rc)
2556 .assert(3===rowCount)
2557 .assert(2===colCount);
2558 }finally{
2559 wasm.uninstallFunction(pCb);
2560 }
2561
2562 // Demonstrate that an OOM result does not propagate through sqlite3_exec()...
2563 rc = capi.sqlite3_exec(
2564 db, ["select a,"," a*2 from foo.bar"], (aVals, aNames)=>{
2565 sqlite3.WasmAllocError.toss("just testing");
2566 }, 0, 0
2567 );
2568 T.assert(capi.SQLITE_ABORT === rc);
2569
2570 db.exec("detach foo");
2571 T.mustThrow(()=>db.exec("select * from foo.bar"),
2572 "Because foo is no longer attached.");
2573
2574 /* SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE/WRITE... */
2575 const db2 = new sqlite3.oo1.DB();
2576 try{
2577 capi.sqlite3_db_config(db2, capi.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, 0, null);
2578 T.mustThrow(()=>db2.exec("attach 'attached.db' as foo"),
2579 "Cannot create a new db via ATTACH");
2580 capi.sqlite3_db_config(db2, capi.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, 1, null);
2581 db2.exec([
2582 "attach 'attached.db' as foo;",
2583 "create table foo.t(a);",
2584 "insert into foo.t(a) values(1);",
2585 "detach foo;"
2586 ]);
2587 capi.sqlite3_db_config(db2, capi.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, 0, null);
2588 db2.exec("attach 'attached.db' as foo");
2589 T.mustThrow(()=>db2.exec("insert into foo.t(a) values(2)"),
2590 "ATTACH_WRITE is false");
2591 capi.sqlite3_db_config(db2, capi.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, 1, null);
2592 db2.exec([
2593 "detach foo;",
2594 "attach 'attached.db' as foo;",
2595 "insert into foo.t(a) values(2);",
2596 "drop table foo.t;",
2597 "detach foo"
2598 ]);
2599 }finally{
2600 db2.close();
2601 }
2602 })/*ATTACH tests*/
2603
2604////////////////////////////////////////////////////////////////////
2605 .t("Read-only", function(sqlite3){
2606 T.assert( 0===capi.sqlite3_db_readonly(this.db, "main") );
2607 const db = new sqlite3.oo1.DB('file://'+this.db.filename+'?mode=ro');
2608 T.assert( 1===capi.sqlite3_db_readonly(db, "main") );
2609 T.assert( -1===capi.sqlite3_db_readonly(db, "nope") );
2610 db.close();
2611 })
2612
2613////////////////////////////////////////////////////////////////////
2614 .t({
2615 name: 'C-side WASM tests',
2616 predicate: ()=>(haveWasmCTests() || "Not compiled in."),
2617 test: function(){
2618 const w = wasm, db = this.db;
2619 const stack = w.scopedAllocPush();
2620 let ptrInt;
2621 const origValue = 512;
2622 try{
2623 ptrInt = w.scopedAlloc(4);
2624 w.poke32(ptrInt,origValue);
2625 const cf = w.xGet('sqlite3__wasm_test_intptr');
2626 const oldPtrInt = ptrInt;
2627 T.assert(origValue === w.peek32(ptrInt));
2628 const rc = cf(ptrInt);
2629 T.assert(2*origValue === rc).
2630 assert(rc === w.peek32(ptrInt)).
2631 assert(oldPtrInt === ptrInt);
2632 const pi64 = w.scopedAlloc(8)/*ptr to 64-bit integer*/;
2633 const o64 = 0x010203040506/*>32-bit integer*/;
2634 if(w.bigIntEnabled){
2635 w.poke64(pi64, o64);
2636 //log("pi64 =",pi64, "o64 = 0x",o64.toString(16), o64);
2637 const v64 = ()=>w.peek64(pi64)
2638 T.assert(v64() == o64);
2639 //T.assert(o64 === w.peek64(pi64));
2640 const cf64w = w.xGet('sqlite3__wasm_test_int64ptr');
2641 cf64w(pi64);
2642 T.assert(v64() == BigInt(2 * o64));
2643 cf64w(pi64);
2644 T.assert(v64() == BigInt(4 * o64));
2645
2646 const biTimes2 = w.xGet('sqlite3__wasm_test_int64_times2');
2647 T.assert(BigInt(2 * o64) ===
2648 biTimes2(BigInt(o64)/*explicit conv. required to avoid TypeError
2649 in the call :/ */));
2650
2651 const pMin = w.scopedAlloc(16);
2652 const pMax = w.ptr.add(pMin, 8);
2653 const g64 = (p)=>w.peek64(p);
2654 w.poke64([pMin, pMax], 0);
2655 const minMaxI64 = [
2656 w.xCall('sqlite3__wasm_test_int64_min'),
2657 w.xCall('sqlite3__wasm_test_int64_max')
2658 ];
2659 T.assert(minMaxI64[0] < BigInt(Number.MIN_SAFE_INTEGER)).
2660 assert(minMaxI64[1] > BigInt(Number.MAX_SAFE_INTEGER));
2661 //log("int64_min/max() =",minMaxI64, typeof minMaxI64[0]);
2662 w.xCall('sqlite3__wasm_test_int64_minmax', pMin, pMax);
2663 T.assert(g64(pMin) === minMaxI64[0], "int64 mismatch").
2664 assert(g64(pMax) === minMaxI64[1], "int64 mismatch");
2665 //log("pMin",g64(pMin), "pMax",g64(pMax));
2666 w.poke64(pMin, minMaxI64[0]);
2667 T.assert(g64(pMin) === minMaxI64[0]).
2668 assert(minMaxI64[0] === db.selectValue("select ?",g64(pMin))).
2669 assert(minMaxI64[1] === db.selectValue("select ?",g64(pMax)));
2670 const rxRange = /too big/;
2671 T.mustThrowMatching(()=>{db.prepare("select ?").bind(minMaxI64[0] - BigInt(1))},
2672 rxRange).
2673 mustThrowMatching(()=>{db.prepare("select ?").bind(minMaxI64[1] + BigInt(1))},
2674 (e)=>rxRange.test(e.message));
2675 }else{
2676 log("No BigInt support. Skipping related tests.");
2677 log("\"The problem\" here is that we can manipulate, at the byte level,",
2678 "heap memory to set 64-bit values, but we can't get those values",
2679 "back into JS because of the lack of 64-bit integer support.");
2680 }
2681 }finally{
2682 //const x = w.scopedAlloc(1), y = w.scopedAlloc(1), z = w.scopedAlloc(1);
2683 //log("x=",x,"y=",y,"z=",z); // just looking at the alignment
2684 w.scopedAllocPop(stack);
2685 }
2686 }
2687 }/* jaccwabyt-specific tests */)
2688
2689////////////////////////////////////////////////////////////////////////
2690 .t({
2691 name: 'virtual table #1: eponymous w/ manual exception handling',
2692 predicate: (sqlite3)=>(!!sqlite3.vtab || "Missing vtab support"),
2693 test: function(sqlite3){
2694 const VT = sqlite3.vtab;
2695 const tmplCols = Object.assign(Object.create(null),{
2696 A: 0, B: 1
2697 });
2698 /**
2699 The vtab demonstrated here is a JS-ification of
2700 ext/misc/templatevtab.c.
2701 */
2702 const tmplMod = new sqlite3.capi.sqlite3_module();
2703 T.assert(!tmplMod.$xUpdate);
2704 const dbg = 1 ? ()=>{} : sqlite3.config.debug;
2705 //tmplMod.debugFlags(0x03);
2706 tmplMod.setupModule({
2707 catchExceptions: false,
2708 methods: {
2709 xConnect: function(pDb, pAux, argc, argv, ppVtab, pzErr){
2710 dbg("xConnect",...arguments);
2711 try{
2712 const args = wasm.cArgvToJs(argc, argv);
2713 T.assert(args.length>=3)
2714 .assert(args[0] === 'testvtab')
2715 .assert(args[1] === 'main')
2716 .assert(args[2] === 'testvtab');
2717 const rc = capi.sqlite3_declare_vtab(
2718 pDb, "CREATE TABLE ignored1(a,b)"
2719 );
2720 if(0===rc){
2721 const t = VT.xVtab.create(ppVtab);
2722 T.assert(t === VT.xVtab.get(wasm.peekPtr(ppVtab)));
2723 }
2724 return rc;
2725 }catch(e){
2726 if(!(e instanceof sqlite3.WasmAllocError)){
2727 wasm.dealloc(wasm.peekPtr, pzErr);
2728 wasm.pokePtr(pzErr, wasm.allocCString(e.message));
2729 }
2730 return VT.xError('xConnect',e);
2731 }
2732 },
2733 xCreate: true /* just for testing. Will be removed afterwards. */,
2734 xDisconnect: function(pVtab){
2735 dbg("xDisconnect",...arguments);
2736 try {
2737 VT.xVtab.unget(pVtab).dispose();
2738 return 0;
2739 }catch(e){
2740 return VT.xError('xDisconnect',e);
2741 }
2742 },
2743 xOpen: function(pVtab, ppCursor){
2744 dbg("xOpen",...arguments);
2745 try{
2746 const t = VT.xVtab.get(pVtab),
2747 c = VT.xCursor.create(ppCursor);
2748 T.assert(t instanceof capi.sqlite3_vtab)
2749 .assert(c instanceof capi.sqlite3_vtab_cursor);
2750 c._rowId = 0;
2751 return 0;
2752 }catch(e){
2753 return VT.xError('xOpen',e);
2754 }
2755 },
2756 xClose: function(pCursor){
2757 dbg("xClose",...arguments);
2758 try{
2759 const c = VT.xCursor.unget(pCursor);
2760 T.assert(c instanceof capi.sqlite3_vtab_cursor)
2761 .assert(!VT.xCursor.get(pCursor));
2762 c.dispose();
2763 return 0;
2764 }catch(e){
2765 return VT.xError('xClose',e);
2766 }
2767 },
2768 xNext: function(pCursor){
2769 dbg("xNext",...arguments);
2770 try{
2771 const c = VT.xCursor.get(pCursor);
2772 ++c._rowId;
2773 return 0;
2774 }catch(e){
2775 return VT.xError('xNext',e);
2776 }
2777 },
2778 xColumn: function(pCursor, pCtx, iCol){
2779 dbg("xColumn",...arguments);
2780 try{
2781 const c = VT.xCursor.get(pCursor);
2782 switch(iCol){
2783 case tmplCols.A:
2784 capi.sqlite3_result_int(pCtx, 1000 + c._rowId);
2785 break;
2786 case tmplCols.B:
2787 capi.sqlite3_result_int(pCtx, 2000 + c._rowId);
2788 break;
2789 default: sqlite3.SQLite3Error.toss("Invalid column id",iCol);
2790 }
2791 return 0;
2792 }catch(e){
2793 return VT.xError('xColumn',e);
2794 }
2795 },
2796 xRowid: function(pCursor, ppRowid64){
2797 dbg("xRowid",...arguments);
2798 try{
2799 const c = VT.xCursor.get(pCursor);
2800 VT.xRowid(ppRowid64, c._rowId);
2801 return 0;
2802 }catch(e){
2803 return VT.xError('xRowid',e);
2804 }
2805 },
2806 xEof: function(pCursor){
2807 dbg("xEof",...arguments);
2808 const c = VT.xCursor.get(pCursor),
2809 rc = c._rowId>=10;
2810 return rc;
2811 },
2812 xFilter: function(pCursor, idxNum, idxCStr,
2813 argc, argv/* [sqlite3_value* ...] */){
2814 dbg("xFilter",...arguments);
2815 try{
2816 const c = VT.xCursor.get(pCursor);
2817 c._rowId = 0;
2818 const list = capi.sqlite3_values_to_js(argc, argv);
2819 T.assert(argc === list.length);
2820 //log(argc,"xFilter value(s):",list);
2821 return 0;
2822 }catch(e){
2823 return VT.xError('xFilter',e);
2824 }
2825 },
2826 xBestIndex: function(pVtab, pIdxInfo){
2827 dbg("xBestIndex",...arguments);
2828 try{
2829 //const t = VT.xVtab.get(pVtab);
2830 const sii = capi.sqlite3_index_info;
2831 const pii = new sii(pIdxInfo);
2832 pii.$estimatedRows = 10;
2833 pii.$estimatedCost = 10.0;
2834 //log("xBestIndex $nConstraint =",pii.$nConstraint);
2835 if(pii.$nConstraint>0){
2836 // Validate nthConstraint() and nthConstraintUsage()
2837 const max = pii.$nConstraint;
2838 for(let i=0; i < max; ++i ){
2839 let v = pii.nthConstraint(i,true);
2840 T.assert(wasm.isPtr(v));
2841 v = pii.nthConstraint(i);
2842 T.assert(v instanceof sii.sqlite3_index_constraint)
2843 .assert(v.pointer >= pii.$aConstraint);
2844 v.dispose();
2845 v = pii.nthConstraintUsage(i,true);
2846 T.assert(wasm.isPtr(v));
2847 v = pii.nthConstraintUsage(i);
2848 T.assert(v instanceof sii.sqlite3_index_constraint_usage)
2849 .assert(v.pointer >= pii.$aConstraintUsage);
2850 v.$argvIndex = i;//just to get some values into xFilter
2851 v.dispose();
2852 }
2853 }
2854 //log("xBestIndex $nOrderBy =",pii.$nOrderBy);
2855 if(pii.$nOrderBy>0){
2856 // Validate nthOrderBy()
2857 const max = pii.$nOrderBy;
2858 for(let i=0; i < max; ++i ){
2859 let v = pii.nthOrderBy(i,true);
2860 T.assert(wasm.isPtr(v));
2861 v = pii.nthOrderBy(i);
2862 T.assert(v instanceof sii.sqlite3_index_orderby)
2863 .assert(v.pointer >= pii.$aOrderBy);
2864 v.dispose();
2865 }
2866 }
2867 pii.dispose();
2868 return 0;
2869 }catch(e){
2870 return VT.xError('xBestIndex',e);
2871 }
2872 }
2873 }
2874 });
2875 this.db.onclose.disposeAfter.push(tmplMod);
2876 T.assert(!tmplMod.$xUpdate)
2877 .assert(wasm.isPtr(tmplMod.$xRowid))
2878 .assert(wasm.isPtr(tmplMod.$xCreate))
2879 .assert(tmplMod.$xCreate === tmplMod.$xConnect,
2880 "setupModule() must make these equivalent and "+
2881 "installMethods() must avoid re-compiling identical functions");
2882 tmplMod.$xCreate = wasm.ptr.null /* make tmplMod eponymous-only */;
2883 let rc = capi.sqlite3_create_module(
2884 this.db, "testvtab", tmplMod, 0
2885 );
2886 this.db.checkRc(rc);
2887 const list = this.db.selectArrays(
2888 "SELECT a,b FROM testvtab where a<9999 and b>1 order by a, b"
2889 /* Query is shaped so that it will ensure that some constraints
2890 end up in xBestIndex(). */
2891 );
2892 T.assert(10===list.length)
2893 .assert(1000===list[0][0])
2894 .assert(2009===list[list.length-1][1]);
2895 }
2896 })/*custom vtab #1*/
2897
2898////////////////////////////////////////////////////////////////////////
2899 .t({
2900 name: 'virtual table #2: non-eponymous w/ automated exception wrapping',
2901 predicate: (sqlite3)=>!!sqlite3.vtab || "Missing vtab support",
2902 test: function(sqlite3){
2903 const VT = sqlite3.vtab;
2904 const tmplCols = Object.assign(Object.create(null),{
2905 A: 0, B: 1
2906 });
2907 /**
2908 The vtab demonstrated here is a JS-ification of
2909 ext/misc/templatevtab.c.
2910 */
2911 let throwOnCreate = 1 ? 0 : capi.SQLITE_CANTOPEN
2912 /* ^^^ just for testing exception wrapping. Note that sqlite
2913 always translates errors from a vtable to a generic
2914 SQLITE_ERROR unless it's from xConnect()/xCreate() and that
2915 callback sets an error string. */;
2916 const vtabTrace = 1
2917 ? ()=>{}
2918 : (methodName,...args)=>console.debug('sqlite3_module::'+methodName+'():',...args);
2919 const modConfig = {
2920 /* catchExceptions changes how the methods are wrapped */
2921 catchExceptions: true,
2922 name: "vtab2test",
2923 methods:{
2924 xCreate: function(pDb, pAux, argc, argv, ppVtab, pzErr){
2925 vtabTrace("xCreate",...arguments);
2926 if(throwOnCreate){
2927 sqlite3.SQLite3Error.toss(
2928 throwOnCreate,
2929 "Throwing a test exception."
2930 );
2931 }
2932 const args = wasm.cArgvToJs(argc, argv);
2933 vtabTrace("xCreate","argv:",args);
2934 T.assert(args.length>=3);
2935 const rc = capi.sqlite3_declare_vtab(
2936 pDb, "CREATE TABLE ignored2(a,b)"
2937 );
2938 if(0===rc){
2939 const t = VT.xVtab.create(ppVtab);
2940 T.assert(t === VT.xVtab.get(wasm.peekPtr(ppVtab)));
2941 vtabTrace("xCreate",...arguments," ppVtab =",t.pointer);
2942 }
2943 return rc;
2944 },
2945 xConnect: true,
2946 xDestroy: function(pVtab){
2947 vtabTrace("xDestroy/xDisconnect",pVtab);
2948 VT.xVtab.dispose(pVtab);
2949 },
2950 xDisconnect: true,
2951 xOpen: function(pVtab, ppCursor){
2952 const t = VT.xVtab.get(pVtab),
2953 c = VT.xCursor.create(ppCursor);
2954 T.assert(t instanceof capi.sqlite3_vtab)
2955 .assert(c instanceof capi.sqlite3_vtab_cursor);
2956 vtabTrace("xOpen",...arguments," cursor =",c.pointer);
2957 c._rowId = 0;
2958 },
2959 xClose: function(pCursor){
2960 vtabTrace("xClose",...arguments);
2961 const c = VT.xCursor.unget(pCursor);
2962 T.assert(c instanceof capi.sqlite3_vtab_cursor)
2963 .assert(!VT.xCursor.get(pCursor));
2964 c.dispose();
2965 },
2966 xNext: function(pCursor){
2967 vtabTrace("xNext",...arguments);
2968 const c = VT.xCursor.get(pCursor);
2969 ++c._rowId;
2970 },
2971 xColumn: function(pCursor, pCtx, iCol){
2972 vtabTrace("xColumn",...arguments);
2973 const c = VT.xCursor.get(pCursor);
2974 switch(iCol){
2975 case tmplCols.A:
2976 capi.sqlite3_result_int(pCtx, 1000 + c._rowId);
2977 break;
2978 case tmplCols.B:
2979 capi.sqlite3_result_int(pCtx, 2000 + c._rowId);
2980 break;
2981 default: sqlite3.SQLite3Error.toss("Invalid column id",iCol);
2982 }
2983 },
2984 xRowid: function(pCursor, ppRowid64){
2985 vtabTrace("xRowid",...arguments);
2986 const c = VT.xCursor.get(pCursor);
2987 VT.xRowid(ppRowid64, c._rowId);
2988 },
2989 xEof: function(pCursor){
2990 vtabTrace("xEof",...arguments);
2991 return VT.xCursor.get(pCursor)._rowId>=10;
2992 },
2993 xFilter: function(pCursor, idxNum, idxCStr,
2994 argc, argv/* [sqlite3_value* ...] */){
2995 vtabTrace("xFilter",...arguments);
2996 const c = VT.xCursor.get(pCursor);
2997 c._rowId = 0;
2998 const list = capi.sqlite3_values_to_js(argc, argv);
2999 T.assert(argc === list.length);
3000 },
3001 xBestIndex: function(pVtab, pIdxInfo){
3002 vtabTrace("xBestIndex",...arguments);
3003 //const t = VT.xVtab.get(pVtab);
3004 const pii = VT.xIndexInfo(pIdxInfo);
3005 pii.$estimatedRows = 10;
3006 pii.$estimatedCost = 10.0;
3007 pii.dispose();
3008 }
3009 }/*methods*/
3010 };
3011 const tmplMod = VT.setupModule(modConfig);
3012 T.assert(1===tmplMod.$iVersion);
3013 this.db.onclose.disposeAfter.push(tmplMod);
3014 this.db.checkRc(capi.sqlite3_create_module(
3015 this.db.pointer, modConfig.name, tmplMod.pointer, 0
3016 ));
3017 this.db.exec([
3018 "create virtual table testvtab2 using ",
3019 modConfig.name,
3020 "(arg1 blah, arg2 bloop)"
3021 ]);
3022 if(0){
3023 /* If we DROP TABLE then xDestroy() is called. If the
3024 vtab is instead destroyed when the db is closed,
3025 xDisconnect() is called. */
3026 this.db.onclose.disposeBefore.push(function(db){
3027 console.debug("Explicitly dropping testvtab2 via disposeBefore handler...");
3028 db.exec(
3029 /** DROP TABLE is the only way to get xDestroy() to be called. */
3030 "DROP TABLE testvtab2"
3031 );
3032 });
3033 }
3034 let list = this.db.selectArrays(
3035 "SELECT a,b FROM testvtab2 where a<9999 and b>1 order by a, b"
3036 /* Query is shaped so that it will ensure that some
3037 constraints end up in xBestIndex(). */
3038 );
3039 T.assert(10===list.length)
3040 .assert(1000===list[0][0])
3041 .assert(2009===list[list.length-1][1]);
3042
3043 list = this.db.selectArrays(
3044 "SELECT a,b FROM testvtab2 where a<9999 and b>1 order by b, a limit 5"
3045 );
3046 T.assert(5===list.length)
3047 .assert(1000===list[0][0])
3048 .assert(2004===list[list.length-1][1]);
3049
3050 // Call it as a table-valued function...
3051 list = this.db.selectArrays([
3052 "SELECT a,b FROM ", modConfig.name,
3053 " where a<9999 and b>1 order by b, a limit 1"
3054 ]);
3055 T.assert(1===list.length)
3056 .assert(1000===list[0][0])
3057 .assert(2000===list[0][1]);
3058 }
3059 })/*custom vtab #2*/
3060////////////////////////////////////////////////////////////////////////
3061 .t('Custom collation', function(sqlite3){
3062 let collationCounter = 0;
3063 let myCmp = function(pArg,n1,p1,n2,p2){
3064 //int (*)(void*,int,const void*,int,const void*)
3065 ++collationCounter;
3066 const rc = wasm.exports.sqlite3_strnicmp(p1,p2,(n1<n2?n1:n2));
3067 return rc ? rc : (n1 - n2);
3068 };
3069 let rc = capi.sqlite3_create_collation_v2(this.db, "mycollation", capi.SQLITE_UTF8,
3070 0, myCmp, 0);
3071 this.db.checkRc(rc);
3072 rc = this.db.selectValue("select 'hi' = 'HI' collate mycollation");
3073 T.assert(1===rc).assert(1===collationCounter);
3074 rc = this.db.selectValue("select 'hii' = 'HI' collate mycollation");
3075 T.assert(0===rc).assert(2===collationCounter);
3076 rc = this.db.selectValue("select 'hi' = 'HIi' collate mycollation");
3077 T.assert(0===rc).assert(3===collationCounter);
3078 rc = capi.sqlite3_create_collation(this.db,"hi",capi.SQLITE_UTF8/*not enough args*/);
3079 T.assert(capi.SQLITE_MISUSE === rc);
3080 rc = capi.sqlite3_create_collation_v2(this.db,"hi",capi.SQLITE_UTF8+1/*invalid encoding*/,0,0,0);
3081 T.assert(capi.SQLITE_FORMAT === rc)
3082 .mustThrowMatching(()=>this.db.checkRc(rc),
3083 /SQLITE_UTF8 is the only supported encoding./);
3084 /*
3085 We need to ensure that replacing that collation function does
3086 the right thing. We don't have a handle to the underlying WASM
3087 pointer from here, so cannot verify (without digging through
3088 internal state) that the old one gets uninstalled, but we can
3089 verify that a new one properly replaces it. (That said,
3090 console.warn() output has shown that the uninstallation does
3091 happen.)
3092 */
3093 collationCounter = 0;
3094 myCmp = function(pArg,n1,p1,n2,p2){
3095 --collationCounter;
3096 return 0;
3097 };
3098 rc = capi.sqlite3_create_collation_v2(this.db, "MYCOLLATION", capi.SQLITE_UTF8,
3099 0, myCmp, 0);
3100 this.db.checkRc(rc);
3101 rc = this.db.selectValue("select 'hi' = 'HI' collate mycollation");
3102 T.assert(rc>0).assert(-1===collationCounter);
3103 rc = this.db.selectValue("select 'a' = 'b' collate mycollation");
3104 T.assert(rc>0).assert(-2===collationCounter);
3105 rc = capi.sqlite3_create_collation_v2(this.db, "MYCOLLATION", capi.SQLITE_UTF8,
3106 0, null, 0);
3107 this.db.checkRc(rc);
3108 rc = 0;
3109 try {
3110 this.db.selectValue("select 'a' = 'b' collate mycollation");
3111 }catch(e){
3112 /* Why is e.resultCode not automatically an extended result
3113 code? The DB() class enables those automatically. */
3114 rc = sqlite3.capi.sqlite3_extended_errcode(this.db);
3115 }
3116 T.assert(capi.SQLITE_ERROR_MISSING_COLLSEQ === rc);
3117 })/*custom collation*/
3118
3119////////////////////////////////////////////////////////////////////////
3120 .t('Close db', function(sqlite3){
3121 T.assert(this.db).assert(wasm.isPtr(this.db.pointer));
3122 //wasm.sqlite3__wasm_db_reset(this.db); // will leak virtual tables!
3123 /* Leave some stray resources open... */
3124 const stmtStray = this.db.prepare("select 1");
3125 T.assert( stmtStray.pointer );
3126 const stmtDupe = sqlite3.oo1.Stmt.wrapHandle(this.db, stmtStray.pointer);
3127 T.assert( stmtStray.pointer === stmtDupe.pointer );
3128 const dw = sqlite3.oo1.DB.wrapHandle(this.db.pointer);
3129 T.assert( dw.pointer === this.db.pointer );
3130 //console.debug("this.db =",this.db.pointer,this.db);
3131
3132 /* Close db... */
3133 if( 0 ) this.db.close();
3134 else capi.sqlite3_close_v2(this.db)/*as of [disposal-notification] branch*/;
3135 /* Ensure the strays have been disconnected. */
3136 //console.debug("this.db =",this.db.pointer,this.db);
3137 T.assert(!this.db.pointer, "Expecting !db.pointer")
3138 .assert(!stmtStray.pointer, "Stmt should have been finalized")
3139 .assert(!stmtDupe.pointer, "Stmt should have been finalized")
3140 .assert(!dw.pointer, "shared-handle wrapper should have been disconnected");
3141 })
3142;/* end of oo1 checks */
3143
3144////////////////////////////////////////////////////////////////////////
3145T.g('kvvfs')
3146//#if omit-kvvfs
3147 .t({
3148 name: 'kvvfs',
3149 predicate: ()=>'kvvfs disabled by omit-kvvfs',
3150 test: ()=>{}
3151 })
3152//#else
3153 .t({
3154 name: 'kvvfs v1 API availability',
3155 test: function(sqlite3){
3156 const capi = sqlite3.capi;
3157 if( isUIThread() ){
3158 T.assert( !!capi.sqlite3_js_kvvfs_size )
3159 .assert( !!capi.sqlite3_js_kvvfs_clear );
3160 }else{
3161 /* Historical behaviour retained not for compatibility but
3162 to help avoid some confusion between the v1 and v2 kvvfs
3163 APIs (namely in how the v1 variants handle empty
3164 strings). */
3165 T.assert( !capi.sqlite3_js_kvvfs_clear )
3166 .assert( !capi.sqlite3_js_kvvfs_size );
3167 }
3168 const k = sqlite3.kvvfs;
3169 T.assert( k && 'object'===typeof k );
3170 for(const n of ['reserve', 'import', 'export',
3171 'unlink', 'listen', 'unlisten',
3172 'exists',
3173 'estimateSize', 'clear'] ){
3174 T.assert( k[n] instanceof Function );
3175 }
3176 if( 0 ){
3177 const scope = wasm.scopedAllocPush();
3178 try{
3179 const pg = [
3180 "53514C69746520666F726D61742033b20b0101b402020d02d02l01d0",
3181 "4l01jb02b2E91E00Dd011FD3b1FD3dxl2B010617171701377461626C",
3182 "656B767666736B7676667302435245415445205441424C45206B76766673286129"
3183 ].join('');
3184 const n = pg.length;
3185 const pI = wasm.scopedAlloc( n+1 );
3186 const nO = 8192 * 2;
3187 const pO = wasm.scopedAlloc( nO );
3188 const heap = wasm.heap8u();
3189 let i;
3190 for( i=0; i<n; ++i ){
3191 heap[wasm.ptr.add(pI, i)] = pg.codePointAt(i) & 0xff;
3192 }
3193 heap[wasm.ptr.add(pI, i)] = 0;
3194 const rc = wasm.exports.sqlite3__wasm_kvvfs_decode(pI, pO, nO);
3195 const u = heap.slice(pO, wasm.ptr.add(pO,rc));
3196 debug("decode rc=", rc, u);
3197 }finally{
3198 wasm.scopedAllocPop(scope);
3199 }
3200 }
3201 }
3202 }/*kvvfs API availability*/)
3203 .t({
3204 name: 'kvvfs sessionStorage',
3205 predicate: ()=>(globalThis.sessionStorage || "sessionStorage is unavailable"),
3206 test: function(sqlite3){
3207 const JDb = sqlite3.oo1.JsStorageDb;
3208 const pVfs = capi.sqlite3_vfs_find('kvvfs');
3209 T.assert(looksLikePtr(pVfs));
3210 const pStorage = sqlite3.kvvfs.internal.storageForZClass('session');
3211 T.assert( 0 === pStorage.files.length )
3212 .assert( globalThis.sessionStorage===pStorage.storage )
3213 .assert( 'kvvfs-session-' === pStorage.keyPrefix );
3214 const filename = this.kvvfsDbFile = 'session';
3215 const unlink = this.kvvfsUnlink = ()=>sqlite3.kvvfs.clear(filename);
3216 unlink();
3217 let db = new JDb(filename);
3218 try {
3219 db.exec([
3220 'create table kvvfs(a);',
3221 'insert into kvvfs(a) values(1),(2),(3)'
3222 ]);
3223 T.assert(3 === db.selectValue('select count(*) from kvvfs'))
3224 .assert( db.storageSize() > 0, "Db size counting is broken" );
3225 db.close();
3226 db = undefined;
3227 db = new JDb(filename);
3228 db.exec('insert into kvvfs(a) values(4),(5),(6)');
3229 T.assert(6 === db.selectValue('select count(*) from kvvfs'));
3230 }finally{
3231 if( db ){
3232 db.close();
3233 db = null;
3234 }
3235 }
3236 //console.debug("sessionStorage",globalThis.sessionStorage);
3237 const corruptJrnl = [
3238 /* Test that it recovers properly from a bad journal:
3239 https://sqlite.org/bugs/forumpost/20e208fe172cae4f */
3240 pStorage.keyPrefix+'jrnl',
3241 'cb d9d505f920a163d7ffffffffdeadbeef000000010000020000001000'
3242 ];
3243 sessionStorage.setItem(...corruptJrnl);
3244 //console.debug("sessionStorage",globalThis.sessionStorage);
3245 T.assert( corruptJrnl[1] === sessionStorage.getItem(corruptJrnl[0]) );
3246 try{
3247 db = new JDb(filename);
3248 T.assert(6 === db.selectValue('select count(*) from kvvfs'));
3249 db.exec('insert into kvvfs(a) values(7),(8),(9)');
3250 T.assert(9 === db.selectValue('select count(*) from kvvfs'));
3251 T.assert( corruptJrnl[1] !== sessionStorage.getItem(corruptJrnl[0]) );
3252 }finally{
3253 if( db ) db.close();
3254 }
3255 }
3256 }/*kvvfs sanity checks*/)
3257 .t({
3258 name: 'transient kvvfs',
3259 //predicate: ()=>false,
3260 test: function(sqlite3){
3261 const filename = '.' /* preinstalled instance */;
3262 const JDb = sqlite3.oo1.JsStorageDb;
3263 const DB = sqlite3.oo1.DB;
3264 T.mustThrowMatching(()=>new JDb(""), capi.SQLITE_MISUSE);
3265 T.mustThrowMatching(()=>{
3266 new JDb("this\ns an illegal - contains control characters");
3267 /* We don't have a way to get error strings from xOpen()
3268 to this point? xOpen() does not have a handle to the
3269 db and SQLite is not calling xGetLastError() to fetch
3270 the error string. */
3271 }, capi.SQLITE_RANGE);
3272 T.mustThrowMatching(()=>{new JDb("foo-journal");},
3273 capi.SQLITE_MISUSE);
3274 T.mustThrowMatching(()=>{new JDb("foo-wal");},
3275 capi.SQLITE_MISUSE);
3276 T.mustThrowMatching(()=>{new JDb("foo-shm");},
3277 capi.SQLITE_MISUSE);
3278 T.mustThrowMatching(()=>{
3279 new JDb("01234567890123456789"+
3280 "01234567890123456789"+
3281 "01234567890123456789"+
3282 "01234567890123456789"+
3283 "01234567890123456789"+
3284 "01234567890123456789"+
3285 "0"/*too long*/);
3286 }, capi.SQLITE_RANGE);
3287 {
3288 const name = "01234567890123456789012" /* max name length */;
3289 (new JDb(name)).close();
3290 T.assert( sqlite3.kvvfs.unlink(name) );
3291 }
3292 sqlite3.kvvfs.clear(filename);
3293 let db = new JDb(filename);
3294 const sqlSetup = [
3295 'create table kvvfs(a);',
3296 'insert into kvvfs(a) values(1),(2),(3)'
3297 ];
3298 try {
3299 T.assert( 0===db.storageSize(), "expecting 0 storage size" );
3300 T.mustThrowMatching(()=>db.clearStorage(), /in-use/);
3301 //db.clearStorage();
3302 T.assert( 0===db.storageSize(), "expecting 0 storage size" );
3303 db.exec(sqlSetup);
3304 T.assert( 0<db.storageSize(), "expecting non-0 db size" );
3305 T.mustThrowMatching(()=>db.clearStorage(), /in-use/);
3306 //db.clearStorage(/*wiping everything out from under it*/);
3307 T.assert( 0<db.storageSize(), "expecting non-0 storage size" );
3308 //db.exec(sqlSetup/*that actually worked*/);
3309 /* Clearing the storage out from under the db does actually
3310 work so long as we re-initialize it before reading.
3311 It is tentatively disallowed for sanity's sake rather
3312 than it not working.
3313 */
3314 T.assert( 0<db.storageSize(), "expecting non-0 db size" );
3315 const close = ()=>{
3316 db.close();
3317 db = undefined;
3318 };
3319 T.assert(3 === db.selectValue('select count(*) from kvvfs'));
3320 close();
3321 const exportDb = sqlite3.kvvfs.export;
3322 db = new JDb(filename);
3323 db.exec('insert into kvvfs(a) values(4),(5),(6)');
3324 T.assert(6 === db.selectValue('select count(*) from kvvfs'));
3325 const exp = exportDb({name:filename,includeJournal:true});
3326 T.assert( filename===exp.name, "Broken export filename" )
3327 .assert( exp?.size > 0, "Missing db size" )
3328 .assert( exp?.pages?.length > 0, "Missing db pages" );
3329 console.debug("kvvfs to Object:",exp);
3330 close();
3331 const dbFileRaw = 'file:new-storage?vfs=kvvfs&delete-on-close=1';
3332 db = new DB({
3333 filename: dbFileRaw,
3334 //flags: 'ct'
3335 });
3336 db.exec(sqlSetup);
3337 const dbFilename = db.dbFilename();
3338 //console.warn("db.dbFilename() =",dbFilename);
3339 T.assert(3 === db.selectValue('select count(*) from kvvfs'));
3340 debug("kvvfs to Object:",exportDb(dbFilename));
3341 const n = sqlite3.kvvfs.estimateSize( dbFilename );
3342 T.assert( n>0, "Db size count failed" );
3343 if( 1 ){
3344 // Concurrent open of that same name uses the same storage
3345 const x = new JDb(dbFilename);
3346 T.assert(3 === db.selectValue('select count(*) from kvvfs'));
3347 x.close();
3348 }
3349 close();
3350 // When the final instance of a name is closed, the storage
3351 // disappears...
3352 T.mustThrowMatching(function(){
3353 /* Ensure that 'new-storage' was deleted when its refcount
3354 went to 0, because of its 'transient' flag. By default
3355 the objects are retained, like a filesystem would. */
3356 let ddb = new JDb(dbFilename);
3357 try{ddb.selectValue('select a from kvvfs')}
3358 finally{ddb.close()}
3359 }, /no such table: kvvfs/);
3360 }finally{
3361 if( db ) db.close();
3362 }
3363 }
3364 }/*transient kvvfs*/)
3365 .t({
3366 name: 'concurrent transient kvvfs',
3367 //predicate: ()=>false,
3368 test: function(sqlite3){
3369 const filename = 'myStorage';
3370 const kvvfs = sqlite3.kvvfs;
3371 const DB = sqlite3.oo1.DB;
3372 const JDb = sqlite3.oo1.JsStorageDb;
3373 let db;
3374 let duo;
3375 let q1, q2;
3376 const sqlSetup = [
3377 'create table kvvfs(a);',
3378 'insert into kvvfs(a) values(1),(2),(3)'
3379 ];
3380 const sqlCount = 'select count(*) from kvvfs';
3381 try {
3382 const exportDb = sqlite3.kvvfs.export;
3383 const dbFileRaw = 'file:'+filename+'?vfs=kvvfs&delete-on-close=1';
3384 sqlite3.kvvfs.clear(filename);
3385 db = new DB(dbFileRaw);
3386 db.exec(sqlSetup);
3387 T.assert(3 === db.selectValue(sqlCount));
3388 duo = new JDb(filename);
3389 duo.exec('insert into kvvfs(a) values(4),(5),(6)');
3390 T.assert(6 === db.selectValue(sqlCount));
3391 const expOpt = {
3392 name: filename,
3393 decodePages: true
3394 };
3395 let exp = exportDb(expOpt);
3396 let expectRows = 6;
3397 debug("exported db",exp);
3398 db.close();
3399 T.assert(expectRows === duo.selectValue(sqlCount));
3400 duo.close();
3401 T.mustThrowMatching(function(){
3402 let ddb = new JDb(filename);
3403 try{ddb.selectValue('select a from kvvfs')}
3404 finally{ddb.close()}
3405 }, /.*no such table: kvvfs.*/);
3406 T.assert( kvvfs.unlink(filename) )
3407 .assert( !kvvfs.exists(filename) );
3408 const importDb = sqlite3.kvvfs.import;
3409 duo = new JDb(dbFileRaw);
3410 T.mustThrowMatching(()=>importDb(exp,true), /.*in use.*/);
3411 duo.close();
3412 importDb(exp, true);
3413 duo = new JDb(dbFileRaw);
3414 T.assert(expectRows === duo.selectValue(sqlCount));
3415 let newCount;
3416 try{
3417 duo.transaction(()=>{
3418 duo.exec("insert into kvvfs(a) values(7)");
3419 newCount = duo.selectValue(sqlCount);
3420 T.assert(false, "rolling back");
3421 });
3422 }catch(e){/*ignored*/}
3423 T.assert(7===newCount, "Unexpected row count before rollback")
3424 .assert(expectRows === duo.selectValue(sqlCount),
3425 "Unexpected row count after rollback");
3426 duo.close();
3427 T.assert( kvvfs.unlink(filename) )
3428 .assert( !kvvfs.exists(filename) );
3429 importDb(exp, true);
3430 db = new JDb({
3431 filename,
3432 flags: 'c'
3433 /* BUG: without the 'c' flag, the db works until we try to
3434 vacuum, at which point it fails with "read only db". */
3435 });
3436 duo = new JDb(filename);
3437 T.assert(expectRows === duo.selectValue(sqlCount));
3438 const sqlIns1 = "insert into kvvfs(a) values(?)";
3439 q1 = db.prepare(sqlIns1);
3440 q2 = duo.prepare(sqlIns1);
3441 q1.bind('from q1');
3442 T.assert(capi.SQLITE_DONE===capi.sqlite3_step(q1),
3443 "Unexpected step result");
3444 ++expectRows;
3445 T.assert(expectRows === duo.selectValue(sqlCount),
3446 "Unexpected record count.");
3447 q2.bind('from q2').step();
3448 ++expectRows;
3449 T.assert(expectRows === db.selectValue(sqlCount),
3450 "Unexpected record count.");
3451
3452 q1.reset();
3453 q2.reset();
3454 T.mustThrowMatching(
3455 ()=>db.transaction("IMMEDIATE",()=>q2.step()),
3456 (err)=>capi.SQLITE_BUSY===err.resultCode,
3457 "Expecting db to be locked."
3458 );
3459 q1.reset().stepFinalize();
3460 ++expectRows;
3461 T.assert(expectRows === db.selectValue(sqlCount),
3462 "Unexpected record count after unlock.");
3463 T.assert( capi.SQLITE_BUSY==q2.resetNoThrow() );
3464 q2.stepFinalize();
3465 ++expectRows;
3466 T.assert(expectRows === db.selectValue(sqlCount),
3467 "Unexpected record count after unlock.");
3468
3469 if( 1 ){
3470 debug("Begin vacuum/page size test...");
3471 const defaultPageSize = 1024 * 8 /* build-time default */;
3472 const pageSize = 0
3473 ? defaultPageSize
3474 : 1024 * 16 /* any valid value other than the default */;
3475 if( 0 ){
3476 debug("Export before vacuum", exportDb(expOpt));
3477 debug("page size before vacuum",
3478 db.selectArray(
3479 "select page_size from pragma_page_size()"
3480 ));
3481 }
3482 //kvvfs.log.xFileControl = true;
3483 //kvvfs.log.xAccess = true;
3484 db.exec([
3485 "BEGIN;",
3486 "insert into kvvfs(a) values(randomblob(16000/*>pg size*/));",
3487 "COMMIT;",
3488 "delete from kvvfs where octet_length(a)>100;",
3489 "pragma page_size="+pageSize+";",
3490 "vacuum;",
3491 "select 1;"
3492 ]);
3493 const expectPageSize = kvvfs.internal.disablePageSizeChange
3494 ? defaultPageSize
3495 : pageSize;
3496 const gotPageSize = db.selectValue(
3497 "select page_size from pragma_page_size()"
3498 );
3499 T.assert(+gotPageSize === expectPageSize,
3500 "Expecting page size",expectPageSize,
3501 "got",gotPageSize);
3502 T.assert(expectRows === duo.selectValue(sqlCount),
3503 "Unexpected record count.");
3504 kvvfs.log.xAccess = kvvfs.log.xFileControl = false;
3505 T.assert(expectRows === duo.selectValue(sqlCount),
3506 "Unexpected record count.");
3507 exp = exportDb(expOpt);
3508 debug("Exported page-expanded db",exp);
3509 if( 0 ){
3510 debug("vacuumed export",exp);
3511 }
3512 debug("End vacuum/page size test.");
3513 }else{
3514 expectRows = 6;
3515 }
3516 db.close();
3517 duo.close();
3518 T.assert( kvvfs.unlink(exp.name) )
3519 .assert( !kvvfs.exists(exp.name) );
3520 importDb(exp);
3521 T.assert( kvvfs.exists(exp.name) );
3522 db = new JDb(exp.name);
3523 //debug("column count after export",db.selectValue(sqlCount));
3524 T.assert(expectRows === db.selectValue(sqlCount),
3525 "Unexpected record count.");
3526 /*
3527 TODO: more advanced concurrent use tests, e.g. looping
3528 over a query in one connection while writing from
3529 another. Currently that will probably corrupt the db, and
3530 kvvfs's journaling does not support multiple journals per
3531 storage unit. We need to test the locking and fix it as
3532 appropriate.
3533 */
3534 }finally{
3535 q1?.finalize?.();
3536 q2?.finalize?.();
3537 db?.close?.();
3538 duo?.close?.();
3539 }
3540 }
3541 }/*concurrent transient kvvfs*/)
3542 .t({
3543 name: 'kvvfs listeners (experiment)',
3544 test: function(sqlite3){
3545 const kvvfs = sqlite3.kvvfs;
3546 const filename = 'listen';
3547 let db;
3548 try {
3549 const DB = sqlite3.oo1.DB;
3550 const sqlSetup = [
3551 'create table kvvfs(a);',
3552 'insert into kvvfs(a) values(1),(2),(3)'
3553 ];
3554 const sqlCount = "select count(*) from kvvfs";
3555 const sqlSelectSchema = "select * from sqlite_schema";
3556 const counts = Object.create(null);
3557 const incr = (key)=>counts[key] = 1 + (counts[key] ?? 0);
3558 const pglog = Object.assign(Object.create(null),{
3559 pages: [],
3560 jrnl: undefined,
3561 size: undefined,
3562 includeJournal: false,
3563 decodePages: true,
3564 exception: new Error("Testing that exceptions from listeners do not interfere")
3565 });
3566 const toss = ()=>{
3567 if( pglog.exception ){
3568 const e = pglog.exception;
3569 delete pglog.exception;
3570 throw e;
3571 }
3572 };
3573 const listener = {
3574 storage: filename,
3575 reserve: true,
3576 includeJournal: pglog.includeJournal,
3577 decodePages: pglog.decodePages,
3578 events: {
3579 /**
3580 These may be async but must not be in this case
3581 because we can't test their result without a lot of
3582 hoop-jumping if they are. Kvvfs calls these
3583 asynchronously, though.
3584 */
3585 'open': (ev)=>{
3586 //console.warn('open',ev);
3587 incr(ev.type);
3588 T.assert(filename===ev.storageName)
3589 .assert('number'===typeof ev.data);
3590 },
3591 'close': (ev)=>{
3592 //console.warn('close',ev);
3593 incr(ev.type);
3594 T.assert('number'===typeof ev.data);
3595 toss();
3596 },
3597 'delete': (ev)=>{
3598 //console.warn('delete',ev);
3599 incr(ev.type);
3600 T.assert('string'===typeof ev.data);
3601 switch(ev.data){
3602 case 'jrnl':
3603 T.assert(pglog.includeJournal);
3604 pglog.jrnl = null;
3605 break;
3606 default:{
3607 const n = +ev.data;
3608 T.assert( n>0, "Expecting positive db page number" );
3609 if( n < pglog.pages.length ){
3610 pglog.size = undefined;
3611 }
3612 pglog.pages[n] = undefined;
3613 break;
3614 }
3615 }
3616 },
3617 'sync': (ev)=>{
3618 incr(ev.data ? 'xSync' : 'xFileControlSync');
3619 },
3620 'write': (ev)=>{
3621 //console.warn('write',ev);
3622 incr(ev.type);
3623 T.assert(Array.isArray(ev.data));
3624 const key = ev.data[0], val = ev.data[1];
3625 T.assert('string'===typeof key);
3626 switch( key ){
3627 case 'jrnl':
3628 T.assert(pglog.includeJournal);
3629 pglog.jrnl = val;
3630 break;
3631 case 'sz':{
3632 const sz = +val;
3633 T.assert( sz>0, "Expecting a db page number" );
3634 if( sz < pglog.sz ){
3635 pglog.pages.length = sz / pglog.pages.length;
3636 }
3637 pglog.size = sz;
3638 break;
3639 }
3640 default:
3641 T.assert( +key>0, "Expecting a positive db page number" );
3642 pglog.pages[+key] = val;
3643 if( pglog.decodePages ){
3644 T.assert( val instanceof Uint8Array );
3645 }else{
3646 T.assert( 'string'===typeof val );
3647 }
3648 break;
3649 }
3650 }
3651 }
3652 };
3653 kvvfs.listen(listener);
3654 const dbFileRaw = 'file:'+filename+'?vfs=kvvfs&delete-on-close=1';
3655 const expOpt = {
3656 name: filename,
3657 //decodePages: true
3658 };
3659 db = new DB(dbFileRaw);
3660 db.exec(sqlSetup);
3661 T.assert(db.selectObjects(sqlSelectSchema)?.length>0,
3662 "Unexpected empty schema");
3663 db.close();
3664 debug("kvvfs listener counts:",counts);
3665 T.assert( counts.open );
3666 T.assert( counts.close );
3667 T.assert( listener.includeJournal ? counts.delete : !counts.delete );
3668 T.assert( counts.write );
3669 T.assert( counts.xSync );
3670 T.assert( counts.xFileControlSync>=counts.xSync );
3671 T.assert( counts.open===counts.close );
3672 T.assert( pglog.includeJournal
3673 ? (null===pglog.jrnl)
3674 : (undefined===pglog.jrnl),
3675 "Unexpected pglog.jrnl value: "+pglog.jrnl );
3676 if( 1 ){
3677 T.assert(undefined===pglog.pages[0], "Expecting empty slot 0");
3678 pglog.pages.shift();
3679 //debug("kvvfs listener pageLog", pglog);
3680 }
3681 const before = JSON.stringify(counts);
3682 T.assert( kvvfs.unlisten(listener) );
3683 T.assert( !kvvfs.unlisten(listener) );
3684 db = new DB(dbFileRaw);
3685 T.assert( db.selectObjects(sqlSelectSchema)?.length>0 );
3686 const exp = kvvfs.export(expOpt);
3687 const expectRows = db.selectValue(sqlCount);
3688 db.exec("delete from kvvfs");
3689 db.close();
3690 const after = JSON.stringify(counts);
3691 T.assert( before===after, "Expecting no events after unlistening." );
3692 if( 0 ){
3693 exp = kvvfs.export(expOpt);
3694 debug("Post-delete export:",exp);
3695 }
3696 if( 1 ){
3697 // Replace the storage with the pglog state...
3698 const bogoExp = {
3699 name: filename,
3700 size: pglog.size,
3701 timestamp: Date.now(),
3702 pages: pglog.pages
3703 };
3704 //debug("exp",exp);
3705 //debug("bogoExp",bogoExp);
3706 kvvfs.import(bogoExp, true);
3707 //debug("Re-exported", kvvfs.export(expOpt));
3708 db = new DB(dbFileRaw);
3709 // Failing on the next line despite exports looking good
3710 T.assert(db.selectObjects(sqlSelectSchema)?.length>0,
3711 "Empty schema on imported db");
3712 T.assert(expectRows===db.selectValue(sqlCount));
3713 db.close();
3714 }
3715 }finally{
3716 db?.close?.();
3717 kvvfs.unlink(filename);
3718 }
3719 }
3720 })/*kvvfs listeners */
3721 .t({
3722 name: 'kvvfs vtab',
3723 predicate: (sqlite3)=>!!sqlite3.kvvfs.create_module,
3724 test: function(sqlite3){
3725 const kvvfs = sqlite3.kvvfs;
3726 const db = new sqlite3.oo1.DB();
3727 const db2 = new sqlite3.oo1.DB('file:foo?vfs=kvvfs&delete-on-close=1');
3728 try{
3729 kvvfs.create_module(db);
3730 let rc = db.selectObjects("select * from sqlite_kvvfs order by name");
3731 debug("sqlite_kvvfs vtab:", rc);
3732 const nDb = rc.length;
3733 rc = db.selectObject("select * from sqlite_kvvfs where name='foo'");
3734 T.assert(rc, "Expecting foo storage record")
3735 .assert('foo'===rc.name, "Unexpected name")
3736 .assert(1===rc.nRef, "Unexpected refcount");
3737 db2.close();
3738 rc = db.selectObjects("select * from sqlite_kvvfs");
3739 T.assert( !rc.filter((o)=>o.name==='foo').length,
3740 "Expecting foo storage to be gone");
3741 debug("sqlite_kvvfs vtab:", rc);
3742 T.assert( rc.length+1 === nDb,
3743 "Unexpected storage count: got",rc.length,"expected",nDb);
3744 }finally{
3745 db.close();
3746 db2.close();
3747 }
3748 }
3749 })/* kvvfs vtab */
3750//#if enable-see
3751 .t({
3752 name: 'kvvfs SEE encryption in sessionStorage',
3753 predicate: ()=>(!!globalThis.sessionStorage
3754 || "sessionStorage is not available"),
3755 test: async function(sqlite3){
3756 const JDb = sqlite3.oo1.JsStorageDb;
3757 T.seeBaseCheck(JDb,
3758 (isInit)=>{
3759 return {filename: "session"};
3760 },
3761 ()=>JDb.clearStorage('session'));
3762 }
3763 })/*kvvfs with SEE*/
3764//#/if enable-see
3765//#/if kvvfs
3766;/* end kvvfs tests */
3767
3768////////////////////////////////////////////////////////////////////////
3769T.g('Hook APIs')
3770 .t({
3771 name: "sqlite3_commit/rollback/update_hook()",
3772 predicate: ()=>wasm.bigIntEnabled || "Update hook requires int64",
3773 test: function(sqlite3){
3774 let countCommit = 0, countRollback = 0;;
3775 const db = new sqlite3.oo1.DB(':memory:',1 ? 'c' : 'ct');
3776 let rc = capi.sqlite3_commit_hook(db, (p)=>{
3777 //debug("commit hook",arguments);
3778 ++countCommit;
3779 return (17 == p) ? 0 : capi.SQLITE_ERROR;
3780 }, 17);
3781 T.assert( wasm.ptr.null === rc );
3782
3783 // Commit hook...
3784 T.assert( 0!=capi.sqlite3_get_autocommit(db) );
3785 db.exec("BEGIN; SELECT 1; COMMIT");
3786 T.assert(0 === countCommit,
3787 "No-op transactions (mostly) do not trigger commit hook.");
3788 db.exec("BEGIN EXCLUSIVE; SELECT 1; COMMIT");
3789 T.assert(1 === countCommit,
3790 "But EXCLUSIVE transactions do.");
3791 db.transaction((d)=>{
3792 T.assert( 0==capi.sqlite3_get_autocommit(db) );
3793 d.exec("create table t(a)");
3794 });
3795 T.assert(2 === countCommit);
3796 T.assert(17 == capi.sqlite3_commit_hook(db, 0, 0));
3797
3798 // Rollback hook:
3799 rc = capi.sqlite3_rollback_hook(db, (p)=>{
3800 ++countRollback;
3801 T.assert( 21 == p );
3802 }, 21);
3803 T.assert( wasm.ptr.null===rc );
3804 T.mustThrowMatching(()=>{
3805 db.transaction('drop table t',()=>{})
3806 }, (e)=>{
3807 return (capi.SQLITE_MISUSE === e.resultCode)
3808 && ( e.message.indexOf('Invalid argument') > 0 );
3809 });
3810 T.assert(0 === countRollback, "Transaction was not started.");
3811 T.mustThrowMatching(()=>{
3812 db.transaction('immediate', ()=>{
3813 sqlite3.SQLite3Error.toss(capi.SQLITE_FULL,'testing rollback hook');
3814 });
3815 }, (e)=>{
3816 //console.error("transaction error:",e);
3817 return capi.SQLITE_FULL === e.resultCode
3818 });
3819 T.assert(1 === countRollback);
3820 T.assert(21 == capi.sqlite3_rollback_hook(db, 0, 0));
3821
3822 // Update hook...
3823 const countUpdate = Object.create(null);
3824 capi.sqlite3_update_hook(db, (p,op,dbName,tbl,rowid)=>{
3825 T.assert('main' === dbName.toLowerCase())
3826 .assert('t' === tbl.toLowerCase())
3827 .assert(33==p)
3828 .assert('bigint' === typeof rowid);
3829 switch(op){
3830 case capi.SQLITE_INSERT:
3831 case capi.SQLITE_UPDATE:
3832 case capi.SQLITE_DELETE:
3833 countUpdate[op] = (countUpdate[op]||0) + 1;
3834 break;
3835 default: toss("Unexpected hook operator:",op);
3836 }
3837 }, 33);
3838 db.transaction((d)=>{
3839 db.exec([
3840 "insert into t(a) values(1);",
3841 "update t set a=2;",
3842 "update t set a=3;",
3843 "delete from t where a=3;"
3844 // update hook is not called for an unqualified DELETE
3845 ]);
3846 });
3847 T.assert(1 === countRollback)
3848 .assert(2 === countCommit)
3849 .assert(1 === countUpdate[capi.SQLITE_INSERT])
3850 .assert(2 === countUpdate[capi.SQLITE_UPDATE])
3851 .assert(1 === countUpdate[capi.SQLITE_DELETE]);
3852 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = true;
3853 T.assert(33 == capi.sqlite3_update_hook(db, 0, 0));
3854 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = false;
3855 db.close();
3856 }
3857 })/* commit/rollback/update hooks */
3858 .t({
3859 name: "sqlite3_preupdate_hook()",
3860 predicate: ()=>capi.sqlite3_preupdate_hook || "Missing pre-update hook API",
3861 test: function(sqlite3){
3862 const db = new sqlite3.oo1.DB(':memory:', 1 ? 'c' : 'ct');
3863 const countHook = Object.create(null);
3864 let rc = capi.sqlite3_preupdate_hook(
3865 db, function(p, pDb, op, zDb, zTbl, iKey1, iKey2){
3866 T.assert(9 == p)
3867 .assert(db.pointer === pDb)
3868 .assert(1 === capi.sqlite3_preupdate_count(pDb))
3869 .assert( 0 > capi.sqlite3_preupdate_blobwrite(pDb) );
3870 countHook[op] = (countHook[op]||0) + 1;
3871 switch(op){
3872 case capi.SQLITE_INSERT:
3873 case capi.SQLITE_UPDATE:
3874 T.assert('number' === typeof capi.sqlite3_preupdate_new_js(pDb, 0));
3875 break;
3876 case capi.SQLITE_DELETE:
3877 T.assert('number' === typeof capi.sqlite3_preupdate_old_js(pDb, 0));
3878 break;
3879 default: toss("Unexpected hook operator:",op);
3880 }
3881 },
3882 9
3883 );
3884 T.assert( 0==rc );
3885 db.transaction((d)=>{
3886 d.exec([
3887 "create table t(a);",
3888 "insert into t(a) values(1);",
3889 "update t set a=2;",
3890 "update t set a=3;",
3891 "delete from t where a=3"
3892 ]);
3893 });
3894 T.assert(1 === countHook[capi.SQLITE_INSERT])
3895 .assert(2 === countHook[capi.SQLITE_UPDATE])
3896 .assert(1 === countHook[capi.SQLITE_DELETE]);
3897 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = true;
3898 T.assert( !!capi.sqlite3_preupdate_hook(db, 0, 0) );
3899 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = false;
3900 T.assert( !capi.sqlite3_preupdate_hook(db, 0, 0) );
3901 db.close();
3902 }
3903 })/*pre-update hooks*/
3904;/*end hook API tests*/
3905
3906////////////////////////////////////////////////////////////////////////
3907T.g('Auto-extension API')
3908 .t({
3909 name: "Auto-extension sanity checks.",
3910 test: function(sqlite3){
3911 let counter = 0;
3912 const fp = wasm.installFunction('i(ppp)', function(pDb,pzErr,pApi){
3913 ++counter;
3914 return 0;
3915 });
3916 (new sqlite3.oo1.DB()).close();
3917 T.assert( 0===counter );
3918 capi.sqlite3_auto_extension(fp);
3919 (new sqlite3.oo1.DB()).close();
3920 T.assert( 1===counter );
3921 (new sqlite3.oo1.DB()).close();
3922 T.assert( 2===counter );
3923 capi.sqlite3_cancel_auto_extension(fp);
3924 wasm.uninstallFunction(fp);
3925 (new sqlite3.oo1.DB()).close();
3926 T.assert( 2===counter );
3927 }
3928 });
3929
3930////////////////////////////////////////////////////////////////////////
3931T.g('Session API')
3932 .t({
3933 name: 'Session API sanity checks',
3934 predicate: ()=>!!capi.sqlite3changegroup_add || "Missing session API",
3935 test: function(sqlite3){
3936 //warn("The session API tests could use some expansion.");
3937 const db1 = new sqlite3.oo1.DB(), db2 = new sqlite3.oo1.DB();
3938 const sqlInit = [
3939 "create table t(rowid INTEGER PRIMARY KEY,a,b); ",
3940 "insert into t(rowid,a,b) values",
3941 "(1,'a1','b1'),",
3942 "(2,'a2','b2'),",
3943 "(3,'a3','b3');"
3944 ].join('');
3945 db1.exec(sqlInit);
3946 db2.exec(sqlInit);
3947 T.assert(3 === db1.selectValue("select count(*) from t"))
3948 .assert('b3' === db1.selectValue('select b from t where rowid=3'));
3949 const stackPtr = wasm.pstack.pointer;
3950 try{
3951 let ppOut = wasm.pstack.allocPtr();
3952 let rc = capi.sqlite3session_create(db1, "main", ppOut);
3953 T.assert(0===rc);
3954 let pSession = wasm.peekPtr(ppOut);
3955 T.assert(pSession && wasm.isPtr(pSession));
3956 capi.sqlite3session_table_filter(pSession, (pCtx, tbl)=>{
3957 T.assert('t' === tbl).assert( 99 === pCtx );
3958 return 1;
3959 }, 99);
3960 db1.exec([
3961 "update t set b='bTwo' where rowid=2;",
3962 "update t set a='aThree' where rowid=3;",
3963 "delete from t where rowid=1;",
3964 "insert into t(rowid,a,b) values(4,'a4','b4')"
3965 ]);
3966 T.assert('bTwo' === db1.selectValue("select b from t where rowid=2"))
3967 .assert(undefined === db1.selectValue('select a from t where rowid=1'))
3968 .assert('b4' === db1.selectValue('select b from t where rowid=4'))
3969 .assert(3 === db1.selectValue('select count(*) from t'));
3970
3971 const testSessionEnable =
3972 false /* it's not yet clear whether these test failures are
3973 broken tests or broken bindings. */;
3974 if(testSessionEnable){
3975 rc = capi.sqlite3session_enable(pSession, 0);
3976 T.assert( 0 === rc )
3977 .assert( 0 === capi.sqlite3session_enable(pSession, -1) );
3978 db1.exec("delete from t where rowid=2;");
3979 rc = capi.sqlite3session_enable(pSession, 1);
3980 T.assert( rc > 0 )
3981 .assert( capi.sqlite3session_enable(pSession, -1) > 0 )
3982 .assert(undefined === db1.selectValue('select a from t where rowid=2'));
3983 }else{
3984 //warn("sqlite3session_enable() tests are currently disabled.");
3985 }
3986 let db1Count = db1.selectValue("select count(*) from t");
3987 T.assert( db1Count === (testSessionEnable ? 2 : 3) );
3988
3989 /* Capture changeset and destroy session. */
3990 let pnChanges = wasm.pstack.alloc('i32'),
3991 ppChanges = wasm.pstack.allocPtr();
3992 rc = capi.sqlite3session_changeset(pSession, pnChanges, ppChanges);
3993 T.assert( 0 === rc );
3994 capi.sqlite3session_delete(pSession);
3995 pSession = 0;
3996 const pChanges = wasm.peekPtr(ppChanges),
3997 nChanges = wasm.peek32(pnChanges);
3998 T.assert( pChanges && wasm.isPtr( pChanges ) )
3999 .assert( nChanges > 0 );
4000
4001 /* Revert db1 via an inverted changeset, but keep pChanges
4002 and nChanges for application to db2. */
4003 rc = capi.sqlite3changeset_invert( nChanges, pChanges, pnChanges, ppChanges );
4004 T.assert( 0 === rc );
4005 rc = capi.sqlite3changeset_apply(
4006 db1, wasm.peek32(pnChanges), wasm.peekPtr(ppChanges), 0, (pCtx, eConflict, pIter)=>{
4007 return 1;
4008 }, 0
4009 );
4010 T.assert( 0 === rc );
4011 wasm.dealloc( wasm.peekPtr(ppChanges) );
4012 pnChanges = ppChanges = 0;
4013 T.assert('b2' === db1.selectValue("select b from t where rowid=2"))
4014 .assert('a1' === db1.selectValue('select a from t where rowid=1'))
4015 .assert(undefined === db1.selectValue('select b from t where rowid=4'));
4016 db1Count = db1.selectValue("select count(*) from t");
4017 T.assert(3 === db1Count);
4018
4019 /* Apply pre-reverted changeset (pChanges, nChanges) to
4020 db2... */
4021 rc = capi.sqlite3changeset_apply(
4022 db2, nChanges, pChanges, 0, (pCtx, eConflict, pIter)=>{
4023 return pCtx ? 1 : 0
4024 }, 1
4025 );
4026 wasm.dealloc( pChanges );
4027 T.assert( 0 === rc )
4028 .assert( 'b4' === db2.selectValue('select b from t where rowid=4') )
4029 .assert( 'aThree' === db2.selectValue('select a from t where rowid=3') )
4030 .assert( undefined === db2.selectValue('select b from t where rowid=1') );
4031 if(testSessionEnable){
4032 T.assert( (undefined === db2.selectValue('select b from t where rowid=2')),
4033 "But... the session was disabled when rowid=2 was deleted?" );
4034 log("rowids from db2.t:",db2.selectValues('select rowid from t order by rowid'));
4035 T.assert( 3 === db2.selectValue('select count(*) from t') );
4036 }else{
4037 T.assert( 'bTwo' === db2.selectValue('select b from t where rowid=2') )
4038 .assert( 3 === db2.selectValue('select count(*) from t') );
4039 }
4040 }finally{
4041 wasm.pstack.restore(stackPtr);
4042 db1.close();
4043 db2.close();
4044 }
4045 }
4046 })/*session API sanity tests*/
4047;/*end of session API group*/;
4048////////////////////////////////////////////////////////////////////////
4049T.g('Backup API')
4050 .t({
4051 //predicate: ()=>'skipping due to triggering inexplicable exception in unrelated code',
4052 name: 'Backup API sanity checks',
4053 test: function(sqlite3){
4054 const capi = sqlite3.capi;
4055 const dbSrc = new sqlite3.oo1.DB(), dbDest = new sqlite3.oo1.DB();
4056 let pBackup;
4057 try{
4058 dbSrc.exec([
4059 "CREATE TABLE t(id INTEGER PRIMARY KEY, val TEXT);",
4060 "INSERT INTO t(val) VALUES('alpha'), ('beta'), ('gamma'), ('delta');"
4061 ]);
4062 pBackup = capi.sqlite3_backup_init(dbDest, "main", dbSrc, "main");
4063 T.assert( sqlite3.wasm.isPtr(pBackup), "Expecting pointer from sqlite3_backup_init()" );
4064 let rc;
4065 do{
4066 rc = capi.sqlite3_backup_step(pBackup, 1);
4067 const nRemaining = capi.sqlite3_backup_remaining(pBackup);
4068 const nPageCount = capi.sqlite3_backup_pagecount(pBackup);
4069 T.assert(nRemaining>=0, "Expecting integer nRemaining");
4070 T.assert(nPageCount>=0, "Expecting integer nPageCount");
4071 }while( 0===rc );
4072 T.assert(capi.SQLITE_DONE===rc, "Expecting SQLITE_DONE from backup_step()");
4073 rc = capi.sqlite3_backup_finish(pBackup);
4074 pBackup = null
4075 T.assert(0===rc, "Expecting 0 from backup_finish()")
4076 .assert( dbDest.selectValue('select count(*) from t'),
4077 "Expecting data to have been backed up" );
4078 }finally{
4079 if( pBackup ){
4080 sqlite3.capi.sqlite3_backup_finish(pBackup);
4081 }
4082 dbDest.close();
4083 dbSrc.close();
4084 }
4085 }
4086 });
4087////////////////////////////////////////////////////////////////////////
4088// Tests for "opfs" and "opfs-wl" are essentially identical, so...
4089//#query {
4090select 'opfs' vfsName, 'OPFS: Origin-Private File System' label, 'OpfsDb' oo1Ctor
4091UNION ALL
4092select 'opfs-wl', 'OPFS with Web Locks', 'OpfsWlDb'
4093}
4094T.g('@vfsName@: @label@',
4095 (sqlite3)=>(!!capi.sqlite3_vfs_find("@vfsName@") || 'requires "@vfsName@" VFS'))
4096 .t({
4097 name: '@vfsName@ db sanity checks',
4098 test: async (sqlite3)=>{
4099 await T.opfsCommon.sanityChecks('@vfsName@', sqlite3.oo1.@oo1Ctor@, sqlite3);
4100 }
4101 })
4102 .t({
4103 name: '@vfsName@ import/export',
4104 test: async (sqlite3)=>{
4105 await T.opfsCommon.importer('@vfsName@', sqlite3.oo1.@oo1Ctor@, sqlite3);
4106 }
4107 })
4108//#if vfsName = "opfs"
4109//#// This is independent of the VFS, so only test this once
4110 .t({
4111 name: '(Internal-use) OPFS utility APIs',
4112 test: async (sqlite3)=>{
4113 await T.opfsCommon.opfsUtil("@vfsName@", sqlite3.oo1.@oo1Ctor@, sqlite3);
4114 }
4115 })
4116//#/if
4117//#if enable-see
4118 .t({
4119 name: '@vfsName@ with SEE encryption',
4120 predicate: (sqlite3)=>!!sqlite3.oo1.@oo1Ctor@,
4121 test: async function(sqlite3){
4122 const ctor = sqlite3.oo1.@oo1Ctor@;
4123 const filename = 'sqlite3-see.edb';
4124 const ctorOpt = {filename: 'file:///'+filename};
4125 const opfs = sqlite3.opfs;
4126 const initer = function(isInit){
4127 const opt = {...ctorOpt};
4128 if( isInit ) opt.filename += '?delete-before-open=1';
4129 return opt;
4130 };
4131
4132 T.seeBaseCheck(ctor, initer, ()=>{}, false);
4133 /*
4134 Ensure that ctor.importDb() correctly handles SEE-encrypted
4135 dbs. For more details search below for forumpost/f84bef3552.
4136 */
4137 let exp = await opfs.getRootDir()
4138 .then(d=>d.getFileHandle(filename))
4139 .then(fh=>fh.getFile())
4140 .then(f=>f.bytes());
4141 await opfs.unlink(filename);
4142 T.assert( exp.byteLength > 100 && 0===(exp.byteLength % 512) );
4143 const got = await ctor.importDb(filename, exp);
4144 T.assert(exp.byteLength === got);
4145 exp = null;
4146 const db = new ctor({...initer(false), key: 'foo'});
4147 try{
4148 T.assert( 4 === db.selectValue("select count(*) from t") )
4149 .assert( 6 === db.selectValue("select sum(a) from t") );
4150 }finally{
4151 db.close();
4152 await opfs.unlink(filename);
4153 }
4154 }
4155 })
4156//#/if enable-see
4157;/* end OPFS tests */
4158//#/query
4159////////////////////////////////////////////////////////////////////////
4160T.g('"opfs-sahpool" VFS',
4161 (sqlite3)=>((isWorker() && !!sqlite3.installOpfsSAHPoolVfs)
4162 || 'requires "opfs-sahpool" VFS'))
4163 .t({
4164 name: 'SAH sanity checks',
4165 test: async function(sqlite3){
4166 T.assert(!sqlite3.capi.sqlite3_vfs_find(sahPoolConfig.name))
4167 .assert(sqlite3.capi.sqlite3_js_vfs_list().indexOf(sahPoolConfig.name) < 0)
4168 const inst = sqlite3.installOpfsSAHPoolVfs,
4169 catcher = (e)=>{
4170 error("Cannot load SAH pool VFS.",
4171 "This might not be a problem,",
4172 "depending on the environment.");
4173 return false;
4174 };
4175 let u1, u2;
4176 // Ensure that two immediately-consecutive installations
4177 // resolve to the same Promise instead of triggering
4178 // a locking error.
4179 const P1 = inst(sahPoolConfig).then(u=>u1 = u).catch(catcher),
4180 P2 = inst(sahPoolConfig).then(u=>u2 = u).catch(catcher);
4181 await Promise.all([P1, P2]);
4182 if(!(await P1)) return;
4183 T.assert(u1 === u2)
4184 .assert(sahPoolConfig.name === u1.vfsName)
4185 .assert(sqlite3.capi.sqlite3_vfs_find(sahPoolConfig.name))
4186 .assert(u1.getCapacity() >= sahPoolConfig.initialCapacity
4187 /* If a test fails before we get to nuke the VFS, we
4188 can have more than the initial capacity on the next
4189 run. */)
4190 .assert(u1.getCapacity() + 2 === (await u2.addCapacity(2)))
4191 .assert(2 === (await u2.reduceCapacity(2)))
4192 .assert(sqlite3.capi.sqlite3_js_vfs_list().indexOf(sahPoolConfig.name) >= 0);
4193
4194 T.assert(0 === u1.getFileCount());
4195 const dbName = '/foo.db';
4196 //wasm.xWrap.debug = true;
4197 let db = new u1.OpfsSAHPoolDb(dbName);
4198 T.assert(db instanceof sqlite3.oo1.DB)
4199 .assert(1 === u1.getFileCount());
4200 db.exec([
4201 'pragma locking_mode=exclusive;',
4202 'pragma journal_mode=wal;'
4203 /* WAL mode only works in this VFS if locking_mode=exclusive
4204 is invoked prior to the first db access, as this build
4205 does not have the shared-memory APIs needed for WAL without
4206 exclusive-mode locking. See:
4207
4208 https://sqlite.org/wal.html#use_of_wal_without_shared_memory
4209
4210 Note that WAL mode here DOES NOT add any concurrency capabilities
4211 to this VFS, but it MAY provide slightly improved performance
4212 over the other journaling modes.
4213 */,
4214 'create table t(a);',
4215 'insert into t(a) values(1),(2),(3)'
4216 ]);
4217 T.assert(2 === u1.getFileCount() /* one is the journal file */)
4218 .assert(3 === db.selectValue('select count(*) from t'))
4219 .assert(
4220 'wal'===db.selectValue('pragma journal_mode')
4221 || wasm.compileOptionUsed('OMIT_WAL')
4222 );
4223 db.close();
4224 T.assert(1 === u1.getFileCount());
4225 db = new u2.OpfsSAHPoolDb(dbName);
4226 T.assert(1 === u1.getFileCount())
4227 .mustThrowMatching(
4228 ()=>u1.pauseVfs(),
4229 (err)=>{
4230 return capi.SQLITE_MISUSE===err.resultCode
4231 && /SQLITE_MISUSE: Cannot pause VFS /.test(err.message);
4232 },
4233 "Cannot pause VFS with opened db."
4234 );
4235 db.close();
4236 T.assert( u2===u2.pauseVfs() )
4237 .assert( u2.isPaused() )
4238 .assert( !capi.sqlite3_vfs_find(u2.vfsName) )
4239 .mustThrowMatching(()=>new u2.OpfsSAHPoolDb(dbName),
4240 /.+no such vfs: .+/,
4241 "VFS is not available")
4242 .assert( u2===await u2.unpauseVfs() )
4243 .assert( u2===await u1.unpauseVfs(), "unpause is a no-op if the VFS is not paused" )
4244 .assert( !!capi.sqlite3_vfs_find(u2.vfsName) );
4245 const fileNames = u1.getFileNames();
4246 T.assert(1 === fileNames.length)
4247 .assert(dbName === fileNames[0])
4248 .assert(1 === u1.getFileCount())
4249
4250 if(1){ // test exportFile() and importDb()
4251 const dbytes = u1.exportFile(dbName);
4252 T.assert(dbytes.length >= 4096);
4253 const dbName2 = '/exported.db';
4254 let nWrote = u1.importDb(dbName2, dbytes);
4255 T.assert( 2 == u1.getFileCount() )
4256 .assert( dbytes.byteLength == nWrote );
4257 let db2 = new u1.OpfsSAHPoolDb(dbName2);
4258 T.assert(db2 instanceof sqlite3.oo1.DB)
4259 .assert('wal' !== db2.selectValue("pragma journal_mode")
4260 /* importDb() unsets the WAL-mode header for
4261 historical reasons. Because clients must
4262 explicitly enable pragma locking_mode=exclusive
4263 before using WAL, that behavior is retained. */)
4264 .assert(3 === db2.selectValue('select count(*) from t'));
4265 db2.close();
4266 T.assert(true === u1.unlink(dbName2))
4267 .assert(false === u1.unlink(dbName2))
4268 .assert(1 === u1.getFileCount())
4269 .assert(1 === u1.getFileNames().length);
4270 // Try again with a function as an input source:
4271 let cursor = 0;
4272 const blockSize = 1024, end = dbytes.byteLength;
4273 const reader = async function(){
4274 if(cursor >= dbytes.byteLength){
4275 return undefined;
4276 }
4277 const rv = dbytes.subarray(cursor, cursor+blockSize>end ? end : cursor+blockSize);
4278 cursor += blockSize;
4279 return rv;
4280 };
4281 nWrote = await u1.importDb(dbName2, reader);
4282 T.assert( 2 == u1.getFileCount() );
4283 db2 = new u1.OpfsSAHPoolDb(dbName2);
4284 T.assert(db2 instanceof sqlite3.oo1.DB)
4285 .assert(3 === db2.selectValue('select count(*) from t'));
4286 db2.close();
4287 T.assert(true === u1.unlink(dbName2))
4288 .assert(dbytes.byteLength == nWrote);
4289 }
4290
4291 T.assert(true === u1.unlink(dbName))
4292 .assert(false === u1.unlink(dbName))
4293 .assert(0 === u1.getFileCount())
4294 .assert(0 === u1.getFileNames().length);
4295
4296 // Demonstrate that two SAH pools can coexist so long as
4297 // they have different names.
4298 const conf2 = JSON.parse(JSON.stringify(sahPoolConfig));
4299 conf2.name += '-test2';
4300 const POther = await inst(conf2);
4301 //log("Installed second SAH instance as",conf2.name);
4302 T.assert(0 === POther.getFileCount())
4303 .assert(true === await POther.removeVfs());
4304
4305 if(0){
4306 /* Enable this block to inspect vfs's contents via the dev
4307 console or OPFS Explorer browser extension. The
4308 following bits will remove them. */
4309 return;
4310 }
4311 T.assert(true === await u2.removeVfs())
4312 .assert(false === await u1.removeVfs())
4313 .assert(!sqlite3.capi.sqlite3_vfs_find(sahPoolConfig.name));
4314
4315 let cErr, u3;
4316 conf2.$testThrowPhase2 = new Error("Testing throwing during init.");
4317 conf2.name = sahPoolConfig.name+'-err';
4318 const P3 = await inst(conf2).then(u=>u3 = u).catch((e)=>cErr=e);
4319 T.assert(P3 === conf2.$testThrowPhase2)
4320 .assert(cErr === P3)
4321 .assert(undefined === u3)
4322 .assert(!sqlite3.capi.sqlite3_vfs_find(conf2.name));
4323 delete conf2.$testThrowPhase2;
4324 T.assert(cErr === await inst(conf2).catch(e=>e),
4325 "Init result is cached even if it failed");
4326
4327 /* Ensure that the forceReinitIfPreviouslyFailed fallback bypasses
4328 the VFS init cache... */
4329 cErr = u3 = undefined;
4330 conf2.forceReinitIfPreviouslyFailed = true;
4331 conf2.verbosity = 3;
4332 const P3b = await inst(conf2).then(u=>u3 = u).catch((e)=>cErr=e);
4333 T.assert(undefined === cErr)
4334 .assert(P3b === u3)
4335 .assert(P3b === await inst(conf2))
4336 .assert(true === await u3.removeVfs())
4337 .assert(false === await P3b.removeVfs());
4338 }
4339 }/*OPFS SAH Pool sanity checks*/)
4340//#if enable-see
4341 .t({
4342 name: '"opfs-sahpool" VFS with SEE encryption',
4343 test: async function(sqlite3){
4344 const inst = sqlite3.installOpfsSAHPoolVfs,
4345 catcher = (e)=>{
4346 error("Cannot load SAH pool VFS.",
4347 "This might not be a problem,",
4348 "depending on the environment.");
4349 return false;
4350 };
4351 const poolConfig = {
4352 name: 'opfs-sahpool-see',
4353 clearOnInit: true,
4354 initialCapacity: 6
4355 }
4356 let poolUtil;
4357 const P1 = await inst(poolConfig).then(u=>poolUtil = u).catch(catcher);
4358 if( !poolUtil ) return;
4359 const dbFile = '/sqlite3-see.edb';
4360 T.seeBaseCheck(
4361 poolUtil.OpfsSAHPoolDb,
4362 (isInit)=>{return {filename: dbFile}},
4363 ()=>poolUtil.unlink(dbFile),
4364 false
4365 );
4366 /* Ensure that importDb() does the right thing for an
4367 SEE-encrypted DB: https://sqlite.org/see/forumpost/f84bef3552 */
4368 let exp = poolUtil.exportFile(dbFile);
4369 T.assert( exp.byteLength > 100 && 0===(exp.byteLength % 512) );
4370 poolUtil.unlink(dbFile);
4371 const got = poolUtil.importDb(dbFile, exp);
4372 T.assert(exp.byteLength === got);
4373 exp = null;
4374 const db = new poolUtil.OpfsSAHPoolDb({
4375 filename: dbFile,
4376 key: 'foo'
4377 });
4378 try{
4379 T.assert( 4 === db.selectValue("select count(*) from t") )
4380 .assert( 6 === db.selectValue("select sum(a) from t") );
4381 }finally{
4382 db.close();
4383 }
4384 poolUtil.removeVfs();
4385 }
4386 })/*opfs-sahpool with SEE*/
4387//#/if enable-see
4388;
4389
4390////////////////////////////////////////////////////////////////////////
4391T.g('Misc. APIs')
4392 .t('bind_parameter_...', function(sqlite3){
4393 const db = new sqlite3.oo1.DB();
4394 db.exec("create table t(a)");
4395 const stmt = db.prepare("insert into t(a) values($a)");
4396 T.assert( 1===capi.sqlite3_bind_parameter_count(stmt) )
4397 .assert( 1===stmt.parameterCount )
4398 .assert( 1===capi.sqlite3_bind_parameter_index(stmt, "$a") )
4399 .assert( 0===capi.sqlite3_bind_parameter_index(stmt, ":a") )
4400 .assert( 1===stmt.getParamIndex("$a") )
4401 .assert( 0===stmt.getParamIndex(":a") )
4402 .assert( "$a"===capi.sqlite3_bind_parameter_name(stmt, 1) )
4403 .assert( null===capi.sqlite3_bind_parameter_name(stmt, 0) )
4404 .assert( "$a"===stmt.getParamName(1) )
4405 .assert( null===stmt.getParamName(0) );
4406 stmt.finalize();
4407 db.close();
4408 })
4409
4410/**
4411 Ensure that certain Stmt members throw when called
4412 via DB.exec().
4413*/
4414 .t('locked-by-exec() APIs', function(sqlite3){
4415 const db = new sqlite3.oo1.DB();
4416 db.exec("create table t(a);insert into t(a) values(1);");
4417 let checkCount = 0;
4418 const checkOp = function(op){
4419 ++checkCount;
4420 T.mustThrowMatching(() => {
4421 db.exec({
4422 sql: "select ?1",
4423 bind: op,
4424 callback: (row, stmt) => {
4425 switch (row[0]) {
4426 case 'bind': stmt.bind(1); break;
4427 case 'finalize':
4428 case 'clearBindings':
4429 case 'reset':
4430 case 'step': stmt[op](); break;
4431 }
4432 }
4433 });
4434 }, /Operation is illegal when statement is locked.*/)
4435 };
4436 try{
4437 checkOp('bind');
4438 checkOp('finalize');
4439 checkOp('clearBindings');
4440 checkOp('reset');
4441 checkOp('step');
4442 T.assert(5===checkCount);
4443 }finally{
4444 db.close();
4445 }
4446 })
4447
4448////////////////////////////////////////////////////////////////////
4449 .t("Misc. stmt_...", function(sqlite3){
4450 const db = new sqlite3.oo1.DB();
4451 db.exec("create table t(a doggiebiscuits); insert into t(a) values(123)");
4452 let stmt;
4453 try{
4454 stmt = db.prepare("select a, a+1 from t");
4455 T.assert( stmt.isReadOnly() )
4456 .assert( 0===capi.sqlite3_stmt_isexplain(stmt) )
4457 .assert( 0===capi.sqlite3_stmt_explain(stmt, 1) )
4458 .assert( 0!==capi.sqlite3_stmt_isexplain(stmt) )
4459 .assert( 0===capi.sqlite3_stmt_explain(stmt, 2) )
4460 .assert( 0!==capi.sqlite3_stmt_isexplain(stmt) )
4461 .assert( 0===capi.sqlite3_stmt_explain(stmt, 0) )
4462 .assert( 0===capi.sqlite3_stmt_isexplain(stmt) );
4463 let n = 0;
4464 while( capi.SQLITE_ROW === capi.sqlite3_step(stmt) ){
4465 ++n;
4466 T.assert( 0!==capi.sqlite3_stmt_explain(stmt, 1),
4467 "Because stmt is busy" )
4468 .assert( capi.sqlite3_stmt_busy(stmt) )
4469 .assert( stmt.isBusy() )
4470 .assert( 0!==capi.sqlite3_stmt_readonly(stmt) )
4471 .assert( true===stmt.isReadOnly() );
4472 const sv = capi.sqlite3_column_value(stmt, 0);
4473 T.assert( 123===capi.sqlite3_value_int(sv) )
4474 .assert( "doggiebiscuits"===capi.sqlite3_column_decltype(stmt,0) )
4475 .assert( null===capi.sqlite3_column_decltype(stmt,1) );
4476 }
4477 T.assert( 1===n )
4478 .assert( 0===capi.sqlite3_stmt_busy(stmt) )
4479 .assert( !stmt.isBusy() );
4480
4481 if( wasm.exports.sqlite3_column_origin_name ){
4482 //log("Column metadata APIs enabled");
4483 T.assert( "t" === capi.sqlite3_column_table_name(stmt, 0))
4484 .assert("a" === capi.sqlite3_column_origin_name(stmt, 0))
4485 .assert("main" === capi.sqlite3_column_database_name(stmt, 0))
4486 }else{
4487 log("Column metadata APIs not enabled");
4488 } // column metadata APIs
4489 stmt.finalize(); stmt = null;
4490 stmt = db.prepare("select ?1").bind(new Uint8Array([97,0,98,0,99]));
4491 stmt.step();
4492 const sv = capi.sqlite3_column_value(stmt,0);
4493 T.assert("a\0b\0c"===capi.sqlite3_value_text(sv),
4494 "Expecting NULs to have survived.");
4495 stmt.finalize(); stmt = null;
4496
4497 /* sqlite3_bind_zeroblob() (added in 3.53) */
4498 stmt = db.prepare("select ?1");
4499 T.assert( 0===capi.sqlite3_bind_zeroblob(stmt, 1, 53) );
4500 T.assert( stmt.step() );
4501 const b = stmt.get(0);
4502 stmt.finalize(); stmt = null;
4503 T.assert( b instanceof Uint8Array )
4504 .assert( 53===b.length );
4505
4506 }finally{
4507 if(stmt) stmt.finalize();
4508 db.close();
4509 }
4510 })
4511
4512 ////////////////////////////////////////////////////////////////////
4513 .t("sqlite3_js_on_pointer_dispose()", function(sqlite3){
4514 /* Added in 3.55.0 */
4515 const jopd = sqlite3.capi.sqlite3_js_on_pointer_dispose;
4516 const seenD = new Set() /* distinct pointers passed to onDispose() */;
4517 const onDispose = function callee(p){
4518 ++callee.nCall;
4519 seenD.add(p);
4520 };
4521 onDispose.nCall = 0;
4522 /* A second onDispose which we manually convert to wasm to test
4523 jopd's handling of these. We "could" just install a wasm
4524 wrapper for onDispose but we want a separate per-invocation
4525 state for test purposes. */
4526 const onDispose2 = function callee(p){
4527 ++callee.nCall;
4528 seenD.add(p);
4529 };
4530 onDispose2.nCall = 0;
4531 let wOnDispose = wasm.installFunction("v(p)", onDispose2);
4532 const udf = function callee(pCx,a){++callee.nCall;};
4533 udf.nCall = 0;
4534 const db = new sqlite3.oo1.DB();
4535 T.assert( jopd('sqlite3*', db.pointer, wOnDispose) );
4536 T.assert( jopd('sqlite3*', db.pointer, ()=>{
4537 wasm.uninstallFunction(wOnDispose);
4538 wOnDispose = null
4539 }) );
4540 const db2 = sqlite3.oo1.DB.wrapHandle(
4541 db.pointer
4542 /* This object must also be disconnected when db is closed. */
4543 );
4544 let q2;
4545 try{
4546 T.assert( wOnDispose )
4547 .assert( jopd('sqlite3*', db.pointer, onDispose) )
4548 .assert( jopd('sqlite3*', db.pointer, onDispose2) )
4549 /* jopd returns "an unespecified falsy value" for arg validation
4550 errors, but for the sake of testing we can differentiate
4551 them... */
4552 .assert( false===jopd('nope', db.pointer, onDispose),
4553 "Type ID validation failed." )
4554 .assert( null===jopd('sqlite3*', 'nope', onDispose),
4555 "Pointer validation failed" )
4556 .assert( undefined===jopd('sqlite3*', db.pointer, 'nope'),
4557 "Callback validation failed." );
4558 db.exec(["create table t(a);",
4559 "insert into t(a) values(1),(2),(3)"]);
4560 db.createFunction("foo", udf);
4561 const q = db.prepare("select foo(1), foo(a) from t");
4562 T.assert( jopd('sqlite3_stmt*', q.pointer, onDispose) )
4563 .assert( jopd('sqlite3_stmt*', db.pointer, onDispose2) )
4564 q2 = sqlite3.oo1.Stmt.wrapHandle(
4565 /* This object must also be disconnected when db is closed. */
4566 db, q.pointer, false
4567 );
4568 while( q2.step() );
4569 T.assert( db.isOpen() )
4570 .assert( db2.isOpen() );
4571 /*
4572 Do not finalize() q or q2, for test purposes. q will be
4573 cleaned up when a jopd event triggers for db (when it's
4574 closed), and q2 will be unplugged when that happens. We assert
4575 that below.
4576 */
4577 }finally{
4578 sqlite3.capi.sqlite3_close_v2(
4579 /* As of 3.55.0 this will cleanly disconnect the oo1 db object
4580 instead of leaving it pointing to a stale pointer. */
4581 db
4582 );
4583 }
4584 T.assert( !db.isOpen(), "Expecting db to be disconnected" )
4585 .assert( !db2.isOpen(), "Expecting db2 to be disconnected" )
4586 .assert( !q2.pointer, "Lingering q2.pointer" )
4587 .assert( !wOnDispose, "Lingering wasm func installation")
4588 .assert( seenD.size === 2, "db + stmt" )
4589 .assert( udf.nCall === 6, "2 UDF call points, 3 rows" )
4590 .assert( onDispose.nCall === seenD.size, "db + stmt" )
4591 .assert( onDispose2.nCall === seenD.size, "db + stmt" );
4592 })
4593
4594////////////////////////////////////////////////////////////////////
4595 .t("interrupt", function(sqlite3){
4596 const db = new sqlite3.oo1.DB();
4597 try {
4598 T.assert( 0===capi.sqlite3_is_interrupted(db) );
4599 capi.sqlite3_interrupt(db);
4600 T.assert( 0!==capi.sqlite3_is_interrupted(db) );
4601 }finally{
4602 db.close();
4603 }
4604 })
4605
4606////////////////////////////////////////////////////////////////////
4607 .t("sqlite3_set_errmsg()", function(sqlite3){
4608 /* Added in 3.51.0 */
4609 const db = new sqlite3.oo1.DB();//(':memory:','wt');
4610 try{
4611 const capi = sqlite3.capi;
4612 const sse = capi.sqlite3_set_errmsg,
4613 sec = capi.sqlite3_errcode,
4614 sem = capi.sqlite3_errmsg;
4615 T.assert( 0===sec(db) )
4616 .assert( "not an error"===sem(db) );
4617 let rc = sse(db, capi.SQLITE_RANGE, "nope");
4618 T.assert( 0==rc )
4619 .assert( capi.SQLITE_RANGE===sec(db) )
4620 .assert( "nope"===sem(db) );
4621 rc = sse(0, 0, 0);
4622 T.assert( capi.SQLITE_MISUSE===rc );
4623 rc = sse(db, 0, 0);
4624 T.assert( 0===rc )
4625 .assert( 0===sec(db) )
4626 .assert( "not an error"===sem(db) );
4627 }finally{
4628 db.close();
4629 }
4630 });
4631
4632
4633////////////////////////////////////////////////////////////////////
4634T.g('Bug Reports')
4635 .t({
4636 name: 'Delete via bound parameter in subquery',
4637 predicate: ()=>wasm.compileOptionUsed('ENABLE_FTS5') || "Missing FTS5",
4638 test: function(sqlite3){
4639 /**
4640 Testing https://sqlite.org/forum/forumpost/40ce55bdf5 with
4641 the exception that that post uses "external content" for
4642 the FTS index. This isn't testing a fix, just confirming
4643 that the bug report is not really a bug.
4644 */
4645 const db = new sqlite3.oo1.DB();//(':memory:','wt');
4646 db.exec([
4647 "create virtual table f using fts5 (path);",
4648 "insert into f(path) values('abc'),('def'),('ghi');"
4649 ]);
4650 const fetchEm = ()=> db.exec({
4651 sql: "SELECT * FROM f order by path",
4652 rowMode: 'array'
4653 });
4654 /*const dump = function(lbl){
4655 let rc = fetchEm();
4656 log((lbl ? (lbl+' results') : ''),rc);
4657 };*/
4658 //dump('Full fts table');
4659 let rc = fetchEm();
4660 T.assert(3===rc.length);
4661 db.exec(
4662 ["delete from f where rowid in (",
4663 "select rowid from f where path = :path",
4664 ")"],
4665 {bind: {":path": "def"}}
4666 );
4667 //dump('After deleting one entry via subquery');
4668 rc = fetchEm();
4669 T.assert(2===rc.length)
4670 .assert('abcghi'===rc.join(''));
4671 //log('rc =',rc);
4672 db.close();
4673 }
4674 })
4675 .t({
4676 name: 'r/o connection recovery from write op error',
4677 predicate: ()=>hasOpfs() || 'requires "opfs" VFS',
4678 //predicate: ()=>false,
4679 test: async function(sqlite3){
4680 /* https://sqlite.org/forum/forumpost/cf37d5ff1182c31081
4681
4682 The "opfs" VFS (but not SAHPool) was formerly misbehaving
4683 after a write attempt was made on a db opened with
4684 mode=ro. This test ensures that that behavior is fixed and
4685 compares that behavior with other VFSes. */
4686 const tryOne = function(vfsName,descr){
4687 const uri = 'file:///foo.db';
4688 let db = new sqlite3.oo1.DB(uri + (vfsName ? '?vfs='+vfsName : ''));
4689 db.exec([
4690 "drop table if exists t;",
4691 "create table t(a);",
4692 "insert into t(a) values('abc'),('def'),('ghi');"
4693 ]);
4694 db.close();
4695 db = new sqlite3.oo1.DB(uri+'?mode=ro'+
4696 (vfsName ? '&vfs='+vfsName : ''));
4697 let err;
4698 try {
4699 db.exec('insert into t(a) values(1)');
4700 }catch(e){
4701 err = e;
4702 }
4703 T.assert(err && (err.message.indexOf('SQLITE_READONLY')===0));
4704 try{
4705 db.exec('select a from t');
4706 }finally{
4707 db.close();
4708 }
4709 };
4710 const poolConfig = JSON.parse(JSON.stringify(sahPoolConfig));
4711 poolConfig.name = 'opfs-sahpool-cf37d5ff11';
4712 let poolUtil;
4713 await sqlite3.installOpfsSAHPoolVfs(poolConfig).then(p=>poolUtil=p);
4714 T.assert(!!sqlite3.capi.sqlite3_vfs_find(poolConfig.name), "Expecting to find just-registered VFS");
4715 try{
4716 tryOne(false, "Emscripten filesystem");
4717 tryOne(poolConfig.name);
4718 tryOne('opfs');
4719 }finally{
4720 await poolUtil.removeVfs();
4721 }
4722 }
4723 })
4724 .t({
4725 /* https://github.com/sqlite/sqlite-wasm/issues/92 */
4726 name: 'sqlite3_set_auxdata() binding signature',
4727 test: function(sqlite3){
4728 const db = new sqlite3.oo1.DB();
4729 const stack = wasm.pstack.pointer;
4730 const pAux = wasm.pstack.alloc(4);
4731 let pAuxDestructed = 0;
4732 const cxSeen = new Set;
4733 const pAuxDtor = wasm.installFunction('v(p)', function(ptr){
4734 //log("freeing auxdata");
4735 ++pAuxDestructed;
4736 });
4737 let pAuxDtorDestructed = false;
4738 db.onclose = {
4739 after: ()=>{
4740 pAuxDtorDestructed = true;
4741 wasm.uninstallFunction(pAuxDtor);
4742 }
4743 };
4744 let nAuxSet = 0 /* how many times we set aux data */;
4745 let nAuxReused = 0 /* how many times we reused aux data */;
4746 try{
4747 db.createFunction("auxtest",{
4748 xFunc: function(pCx, x, y){
4749 T.assert(wasm.isPtr(pCx));
4750 cxSeen.add(pCx);
4751 const localAux = capi.sqlite3_get_auxdata(pCx, 0);
4752 if( !localAux ){
4753 //log("setting auxdata");
4754 /**
4755 We do provide an automated way to clean up auxdata
4756 finalizer functions (the 4th argument to
4757 sqlite3_set_auxdata()) which get automatically
4758 converted from JS to WASM because it's prohibitively
4759 expensive. Instead, follow the pattern show in this
4760 function: use wasm.installFunction() to create the
4761 function, then pass the resulting function pointer
4762 this function, and cleanup (at some point) using
4763 wasm.uninstallFunction().
4764 */
4765 ++nAuxSet;
4766 capi.sqlite3_set_auxdata(pCx, 0, pAux, pAuxDtor);
4767 }else{
4768 //log("reusing auxdata",localAux);
4769 T.assert(pAux===localAux);
4770 ++nAuxReused;
4771 }
4772 return x;
4773 }
4774 });
4775 //console.error("Before 2x UDF w/ aux data for 4 rows");
4776 db.exec([
4777 "create table t(a);",
4778 "insert into t(a) values(1),(2),(-1),(-2);",
4779 "select auxtest(1,a), auxtest(1,a) from t order by a"
4780 ]);
4781 T.assert( 2===cxSeen.size, "Else my understanding here is wrong:",
4782 cxSeen.size );
4783 //console.error("After 2x UDF w/ aux data for 4 rows");
4784 }finally{
4785 db.close();
4786 wasm.pstack.restore(stack);
4787 }
4788 T.assert(2==nAuxSet)
4789 .assert(6===nAuxReused)
4790 .assert(pAuxDestructed===nAuxSet);
4791 }
4792 })
4793;/*end of Bug Reports group*/;
4794
4795////////////////////////////////////////////////////////////////////////
4796log("Loading and initializing sqlite3 WASM module...");
4797if(1){
4798 globalThis.sqlite3ApiConfig = {
4799 //debug: ()=>{}, log: ()=>{}, warn: ()=>{}, error: ()=>{},
4800 disable: {
4801 vfs: {
4802 kvvfs: false,
4803 opfs: false,
4804 "opfs-sahpool": false,
4805 "opfs-wl": false
4806 }
4807 }
4808 }
4809}
4810//#if not target:es6-module
4811if(!globalThis.sqlite3InitModule && !isUIThread()){
4812 /* Vanilla worker, as opposed to an ES6 module worker */
4813 /*
4814 If sqlite3.js is in a directory other than this script, in order
4815 to get sqlite3.js to resolve sqlite3.wasm properly, we have to
4816 explicitly tell it where sqlite3.js is being loaded from. We do
4817 that by passing the `sqlite3.dir=theDirName` URL argument to
4818 _this_ script. That URL argument will be seen by the JS/WASM
4819 loader and it will adjust the sqlite3.wasm path accordingly. If
4820 sqlite3.js/.wasm are in the same directory as this script then
4821 that's not needed.
4822
4823 URL arguments passed as part of the filename via importScripts()
4824 are simply lost, and such scripts see the globalThis.location of
4825 _this_ script.
4826 */
4827 let sqlite3Js = '@sqlite3.js@'
4828 .split('/').pop()/*the build-injected name has a dir part and
4829 we specifically want to test the following
4830 support for locating the wasm, so remove
4831 that dir part. */;
4832 const urlParams = new URL(globalThis.location.href).searchParams;
4833 const s3d = urlParams.get('sqlite3.dir');
4834 if( s3d ){
4835 if( s3d.indexOf(':')<0 && s3d.indexOf('//')<0 ){
4836 sqlite3Js = s3d + '/' + sqlite3Js;
4837 }else{
4838 throw new Error("Invalid sqlite3.dir value: "+s3d);
4839 }
4840 }
4841 importScripts(sqlite3Js);
4842}
4843//#/if
4844globalThis.sqlite3InitModule.__isUnderTest =
4845 true /* disables certain API-internal cleanup so that we can
4846 test internal APIs from here */;
4847globalThis.sqlite3InitModule({
4848 print: log,
4849 printErr: error
4850}).then(async function(sqlite3){
4851 TestUtil.assert(!!sqlite3.util);
4852 log("Done initializing WASM/JS bits. Running tests...");
4853 sqlite3.config.warn("Installing sqlite3 bits as global S for local dev/test purposes.");
4854 globalThis.S = sqlite3;
4855 /*await sqlite3.installOpfsSAHPoolVfs(sahPoolConfig)
4856 .then((u)=>log("Loaded",u.vfsName,"VFS"))
4857 .catch(e=>{
4858 log("Cannot install OpfsSAHPool.",e);
4859 });*/
4860 capi = sqlite3.capi;
4861 wasm = sqlite3.wasm;
4862 log("sqlite3 version:",capi.sqlite3_libversion(),
4863 capi.sqlite3_sourceid());
4864 if(wasm.bigIntEnabled){
4865 log("BigInt/int64 support is enabled.");
4866 }else{
4867 logClass('warning',"BigInt/int64 support is disabled.");
4868 }
4869 if(haveWasmCTests()){
4870 log("sqlite3__wasm_test_...() APIs are available.");
4871 }else{
4872 logClass('warning',"sqlite3__wasm_test_...() APIs unavailable.");
4873 }
4874 log("registered vfs list =",capi.sqlite3_js_vfs_list().join(', '));
4875 SQLite3 = sqlite3;
4876 log("WASM pointer size:",wasm.ptr.size,"bytes.");
4877 TestUtil.checkHeapSize();
4878 TestUtil.runTests(sqlite3);
4879});