Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/wasm/SQLTester/SQLTester.mjs # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / wasm / SQLTester / SQLTester.mjs` 1338 lines Β· 37230 bytes Raw Blame History 1 /* 2 ** 2023-08-29 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a 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 ** This file contains the main application entry pointer for the JS 13 ** implementation of the SQLTester framework. 14 ** 15 ** This version is not well-documented because it's a direct port of 16 ** the Java implementation, which is documented: in the main SQLite3 17 ** source tree, see ext/jni/src/org/sqlite/jni/capi/SQLTester.java. 18 */ 19 20 import sqlite3ApiInit from '/jswasm/sqlite3.mjs'; 21 22 const sqlite3 = await sqlite3ApiInit(); 23 24 const log = (...args)=>{ 25 console.log('SQLTester:',...args); 26 }; 27 28 /** 29 Try to install vfsName as the new default VFS. Once this succeeds 30 (returns true) then it becomes a no-op on future calls. Throws if 31 VFS registration as the default VFS fails but has no side effects 32 if vfsName is not currently registered. 33 */ 34 const tryInstallVfs = function f(vfsName){ 35 if(f.vfsName) return false; 36 const pVfs = sqlite3.capi.sqlite3_vfs_find(vfsName); 37 if(pVfs){ 38 log("Installing",'"'+vfsName+'"',"as default VFS."); 39 const rc = sqlite3.capi.sqlite3_vfs_register(pVfs, 1); 40 if(rc){ 41 sqlite3.SQLite3Error.toss(rc,"While trying to register",vfsName,"vfs."); 42 } 43 f.vfsName = vfsName; 44 } 45 return !!pVfs; 46 }; 47 tryInstallVfs.vfsName = undefined; 48 49 if( 0 && globalThis.WorkerGlobalScope ){ 50 // Try OPFS storage, if available... 51 if( 1 && sqlite3.oo1.OpfsDb ){ 52 /* Really slow with these tests */ 53 tryInstallVfs("opfs"); 54 }else if( sqlite3.installOpfsSAHPoolVfs ){ 55 await sqlite3.installOpfsSAHPoolVfs({ 56 clearOnInit: true, 57 initialCapacity: 15, 58 name: 'opfs-SQLTester' 59 }).then(pool=>{ 60 tryInstallVfs(pool.vfsName); 61 }).catch(e=>{ 62 log("OpfsSAHPool could not load:",e); 63 }); 64 } 65 } 66 // Return a new enum entry value 67 const newE = ()=>Object.create(null); 68 69 const newObj = (props)=>Object.assign(newE(), props); 70 71 /** 72 Modes for how to escape (or not) column values and names from 73 SQLTester.execSql() to the result buffer output. 74 */ 75 const ResultBufferMode = Object.assign(Object.create(null),{ 76 //! Do not append to result buffer 77 NONE: newE(), 78 //! Append output escaped. 79 ESCAPED: newE(), 80 //! Append output as-is 81 ASIS: newE() 82 }); 83 84 /** 85 Modes to specify how to emit multi-row output from 86 SQLTester.execSql() to the result buffer. 87 */ 88 const ResultRowMode = newObj({ 89 //! Keep all result rows on one line, space-separated. 90 ONELINE: newE(), 91 //! Add a newline between each result row. 92 NEWLINE: newE() 93 }); 94 95 class SQLTesterException extends globalThis.Error { 96 constructor(testScript, ...args){ 97 if(testScript){ 98 super( [testScript.getOutputPrefix()+": ", ...args].join('') ); 99 }else{ 100 super( args.join('') ); 101 } 102 this.name = 'SQLTesterException'; 103 } 104 isFatal() { return false; } 105 } 106 107 SQLTesterException.toss = (...args)=>{ 108 throw new SQLTesterException(...args); 109 } 110 111 class DbException extends SQLTesterException { 112 constructor(testScript, pDb, rc, closeDb=false){ 113 super(testScript, "DB error #"+rc+": "+sqlite3.capi.sqlite3_errmsg(pDb)); 114 this.name = 'DbException'; 115 if( closeDb ) sqlite3.capi.sqlite3_close_v2(pDb); 116 } 117 isFatal() { return true; } 118 } 119 120 class TestScriptFailed extends SQLTesterException { 121 constructor(testScript, ...args){ 122 super(testScript,...args); 123 this.name = 'TestScriptFailed'; 124 } 125 isFatal() { return true; } 126 } 127 128 class UnknownCommand extends SQLTesterException { 129 constructor(testScript, cmdName){ 130 super(testScript, cmdName); 131 this.name = 'UnknownCommand'; 132 } 133 isFatal() { return true; } 134 } 135 136 class IncompatibleDirective extends SQLTesterException { 137 constructor(testScript, ...args){ 138 super(testScript,...args); 139 this.name = 'IncompatibleDirective'; 140 } 141 } 142 143 //! For throwing where an expression is required. 144 const toss = (errType, ...args)=>{ 145 throw new errType(...args); 146 }; 147 148 const __utf8Decoder = new TextDecoder(); 149 const __utf8Encoder = new TextEncoder('utf-8'); 150 //! Workaround for Util.utf8Decode() 151 const __SAB = ('undefined'===typeof globalThis.SharedArrayBuffer) 152 ? function(){} : globalThis.SharedArrayBuffer; 153 154 155 /* Frequently-reused regexes. */ 156 const Rx = newObj({ 157 requiredProperties: / REQUIRED_PROPERTIES:[ \t]*(\S.*)\s*$/, 158 scriptModuleName: / SCRIPT_MODULE_NAME:[ \t]*(\S+)\s*$/, 159 mixedModuleName: / ((MIXED_)?MODULE_NAME):[ \t]*(\S+)\s*$/, 160 command: /^--(([a-z-]+)( .*)?)$/, 161 //! "Special" characters - we have to escape output if it contains any. 162 special: /[\x00-\x20\x22\x5c\x7b\x7d]/, 163 squiggly: /[{}]/ 164 }); 165 166 const Util = newObj({ 167 toss, 168 169 unlink: function f(fn){ 170 if(!f.unlink){ 171 f.unlink = sqlite3.wasm.xWrap('sqlite3__wasm_vfs_unlink','int', 172 ['*','string']); 173 } 174 return 0==f.unlink(0,fn); 175 }, 176 177 argvToString: (list)=>{ 178 const m = [...list]; 179 m.shift() /* strip command name */; 180 return m.join(" ") 181 }, 182 183 utf8Decode: function(arrayBuffer, begin, end){ 184 return __utf8Decoder.decode( 185 (arrayBuffer.buffer instanceof __SAB) 186 ? arrayBuffer.slice(begin, end) 187 : arrayBuffer.subarray(begin, end) 188 ); 189 }, 190 191 utf8Encode: (str)=>__utf8Encoder.encode(str), 192 193 strglob: sqlite3.wasm.xWrap('sqlite3__wasm_SQLTester_strglob','int', 194 ['string','string']) 195 })/*Util*/; 196 197 /** 198 Output logger utility. 199 */ 200 class Outer { 201 #lnBuf = []; 202 #verbosity = 0; 203 #logger = console.log.bind(console); 204 205 constructor(func){ 206 if(func) this.setFunc(func); 207 } 208 209 logger(...args){ 210 if(args.length){ 211 this.#logger = args[0]; 212 return this; 213 } 214 return this.#logger; 215 } 216 217 out(...args){ 218 if( this.getOutputPrefix && !this.#lnBuf.length ){ 219 this.#lnBuf.push(this.getOutputPrefix()); 220 } 221 this.#lnBuf.push(...args); 222 return this; 223 } 224 225 #outlnImpl(vLevel, ...args){ 226 if( this.getOutputPrefix && !this.#lnBuf.length ){ 227 this.#lnBuf.push(this.getOutputPrefix()); 228 } 229 this.#lnBuf.push(...args,'\n'); 230 const msg = this.#lnBuf.join(''); 231 this.#lnBuf.length = 0; 232 this.#logger(msg); 233 return this; 234 } 235 236 outln(...args){ 237 return this.#outlnImpl(0,...args); 238 } 239 240 outputPrefix(){ 241 if( 0==arguments.length ){ 242 return (this.getOutputPrefix 243 ? (this.getOutputPrefix() ?? '') : ''); 244 }else{ 245 this.getOutputPrefix = arguments[0]; 246 return this; 247 } 248 } 249 250 static #verboseLabel = ["πŸ”ˆ",/*"πŸ”‰",*/"πŸ”Š","πŸ“’"]; 251 verboseN(lvl, args){ 252 if( this.#verbosity>=lvl ){ 253 this.#outlnImpl(lvl, Outer.#verboseLabel[lvl-1],': ',...args); 254 } 255 } 256 verbose1(...args){ return this.verboseN(1,args); } 257 verbose2(...args){ return this.verboseN(2,args); } 258 verbose3(...args){ return this.verboseN(3,args); } 259 260 verbosity(){ 261 const rc = this.#verbosity; 262 if(arguments.length) this.#verbosity = +arguments[0]; 263 return rc; 264 } 265 266 }/*Outer*/ 267 268 class SQLTester { 269 270 //! Console output utility. 271 #outer = new Outer().outputPrefix( ()=>'SQLTester: ' ); 272 //! List of input scripts. 273 #aScripts = []; 274 //! Test input buffer. 275 #inputBuffer = []; 276 //! Test result buffer. 277 #resultBuffer = []; 278 //! Output representation of SQL NULL. 279 #nullView; 280 metrics = newObj({ 281 //! Total tests run 282 nTotalTest: 0, 283 //! Total test script files run 284 nTestFile: 0, 285 //! Test-case count for to the current TestScript 286 nTest: 0, 287 //! Names of scripts which were aborted. 288 failedScripts: [] 289 }); 290 #emitColNames = false; 291 //! True to keep going regardless of how a test fails. 292 #keepGoing = false; 293 #db = newObj({ 294 //! The list of available db handles. 295 list: new Array(7), 296 //! Index into this.list of the current db. 297 iCurrentDb: 0, 298 //! Name of the default db, re-created for each script. 299 initialDbName: "test.db", 300 //! Buffer for REQUIRED_PROPERTIES pragmas. 301 initSql: ['select 1;'], 302 //! (sqlite3*) to the current db. 303 currentDb: function(){ 304 return this.list[this.iCurrentDb]; 305 } 306 }); 307 308 constructor(){ 309 this.reset(); 310 } 311 312 outln(...args){ return this.#outer.outln(...args); } 313 out(...args){ return this.#outer.out(...args); } 314 outer(...args){ 315 if(args.length){ 316 this.#outer = args[0]; 317 return this; 318 } 319 return this.#outer; 320 } 321 verbose1(...args){ return this.#outer.verboseN(1,args); } 322 verbose2(...args){ return this.#outer.verboseN(2,args); } 323 verbose3(...args){ return this.#outer.verboseN(3,args); } 324 verbosity(...args){ 325 const rc = this.#outer.verbosity(...args); 326 return args.length ? this : rc; 327 } 328 setLogger(func){ 329 this.#outer.logger(func); 330 return this; 331 } 332 333 incrementTestCounter(){ 334 ++this.metrics.nTotalTest; 335 ++this.metrics.nTest; 336 } 337 338 reset(){ 339 this.clearInputBuffer(); 340 this.clearResultBuffer(); 341 this.#clearBuffer(this.#db.initSql); 342 this.closeAllDbs(); 343 this.metrics.nTest = 0; 344 this.#nullView = "nil"; 345 this.#emitColNames = false; 346 this.#db.iCurrentDb = 0; 347 //this.#db.initSql.push("SELECT 1;"); 348 } 349 350 appendInput(line, addNL){ 351 this.#inputBuffer.push(line); 352 if( addNL ) this.#inputBuffer.push('\n'); 353 } 354 appendResult(line, addNL){ 355 this.#resultBuffer.push(line); 356 if( addNL ) this.#resultBuffer.push('\n'); 357 } 358 appendDbInitSql(sql){ 359 this.#db.initSql.push(sql); 360 if( this.currentDb() ){ 361 this.execSql(null, true, ResultBufferMode.NONE, null, sql); 362 } 363 } 364 365 #runInitSql(pDb){ 366 let rc = 0; 367 for(const sql of this.#db.initSql){ 368 this.#outer.verbose2("RUNNING DB INIT CODE: ",sql); 369 rc = this.execSql(pDb, false, ResultBufferMode.NONE, null, sql); 370 if( rc ) break; 371 } 372 return rc; 373 } 374 375 #clearBuffer(buffer){ 376 buffer.length = 0; 377 return buffer; 378 } 379 380 clearInputBuffer(){ return this.#clearBuffer(this.#inputBuffer); } 381 clearResultBuffer(){return this.#clearBuffer(this.#resultBuffer); } 382 383 getInputText(){ return this.#inputBuffer.join(''); } 384 getResultText(){ return this.#resultBuffer.join(''); } 385 386 #takeBuffer(buffer){ 387 const s = buffer.join(''); 388 buffer.length = 0; 389 return s; 390 } 391 392 takeInputBuffer(){ 393 return this.#takeBuffer(this.#inputBuffer); 394 } 395 takeResultBuffer(){ 396 return this.#takeBuffer(this.#resultBuffer); 397 } 398 399 nullValue(){ 400 return (0==arguments.length) 401 ? this.#nullView 402 : (this.#nullView = ''+arguments[0]); 403 } 404 405 outputColumnNames(){ 406 return (0==arguments.length) 407 ? this.#emitColNames 408 : (this.#emitColNames = !!arguments[0]); 409 } 410 411 currentDbId(){ 412 return (0==arguments.length) 413 ? this.#db.iCurrentDb 414 : (this.#affirmDbId(arguments[0]).#db.iCurrentDb = arguments[0]); 415 } 416 417 #affirmDbId(id){ 418 if(id<0 || id>=this.#db.list.length){ 419 toss(SQLTesterException, "Database index ",id," is out of range."); 420 } 421 return this; 422 } 423 424 currentDb(...args){ 425 if( 0!=args.length ){ 426 this.#affirmDbId(id).#db.iCurrentDb = id; 427 } 428 return this.#db.currentDb(); 429 } 430 431 getDbById(id){ 432 return this.#affirmDbId(id).#db.list[id]; 433 } 434 435 getCurrentDb(){ return this.#db.list[this.#db.iCurrentDb]; } 436 437 438 closeDb(id) { 439 if( 0==arguments.length ){ 440 id = this.#db.iCurrentDb; 441 } 442 const pDb = this.#affirmDbId(id).#db.list[id]; 443 if( pDb ){ 444 sqlite3.capi.sqlite3_close_v2(pDb); 445 this.#db.list[id] = null; 446 } 447 } 448 449 closeAllDbs(){ 450 for(let i = 0; i 0){ 480 rc = this.#runInitSql(pDb); 481 } 482 if( 0!=rc ){ 483 sqlite3.SQLite3Error.toss( 484 rc, 485 "sqlite3 result code",rc+":", 486 (pDb ? sqlite3.capi.sqlite3_errmsg(pDb) 487 : sqlite3.capi.sqlite3_errstr(rc)) 488 ); 489 } 490 return this.#db.list[this.#db.iCurrentDb] = pDb; 491 }catch(e){ 492 sqlite3.capi.sqlite3_close_v2(pDb); 493 throw e; 494 } 495 } 496 497 addTestScript(ts){ 498 if( 2===arguments.length ){ 499 ts = new TestScript(arguments[0], arguments[1]); 500 }else if(ts instanceof Uint8Array){ 501 ts = new TestScript('', ts); 502 }else if('string' === typeof arguments[1]){ 503 ts = new TestScript('', Util.utf8Encode(arguments[1])); 504 } 505 if( !(ts instanceof TestScript) ){ 506 Util.toss(SQLTesterException, "Invalid argument type for addTestScript()"); 507 } 508 this.#aScripts.push(ts); 509 return this; 510 } 511 512 runTests(){ 513 this.outln("SQLite version ", sqlite3.capi.sqlite3_libversion()," with ", 514 sqlite3.wasm.ptr.size, "-byte WASM pointers"); 515 const tStart = (new Date()).getTime(); 516 let isVerbose = this.verbosity(); 517 this.metrics.failedScripts.length = 0; 518 this.metrics.nTotalTest = 0; 519 this.metrics.nTestFile = 0; 520 for(const ts of this.#aScripts){ 521 this.reset(); 522 ++this.metrics.nTestFile; 523 let threw = false; 524 const timeStart = (new Date()).getTime(); 525 let msgTail = ''; 526 try{ 527 ts.run(this); 528 }catch(e){ 529 if(e instanceof SQLTesterException){ 530 threw = true; 531 this.outln("πŸ”₯EXCEPTION: ",e); 532 this.metrics.failedScripts.push({script: ts.filename(), message:e.toString()}); 533 if( this.#keepGoing ){ 534 this.outln("Continuing anyway because of the keep-going option."); 535 }else if( e.isFatal() ){ 536 throw e; 537 } 538 }else{ 539 throw e; 540 } 541 }finally{ 542 const timeEnd = (new Date()).getTime(); 543 this.out("🏁", (threw ? "❌" : "βœ…"), " ", 544 this.metrics.nTest, " test(s) in ", 545 (timeEnd-timeStart),"ms. "); 546 const mod = ts.moduleName(); 547 if( mod ){ 548 this.out( "[",mod,"] " ); 549 } 550 this.outln(ts.filename()); 551 } 552 } 553 const tEnd = (new Date()).getTime(); 554 Util.unlink(this.#db.initialDbName); 555 this.outln("Took ",(tEnd-tStart),"ms. Test count = ", 556 this.metrics.nTotalTest,", script count = ", 557 this.#aScripts.length,( 558 this.metrics.failedScripts.length 559 ? ", failed scripts = "+this.metrics.failedScripts.length 560 : "" 561 ) 562 ); 563 return this; 564 } 565 566 #setupInitialDb(){ 567 if( !this.#db.list[0] ){ 568 Util.unlink(this.#db.initialDbName); 569 this.openDb(0, this.#db.initialDbName, true); 570 }else{ 571 this.#outer.outln("WARNING: setupInitialDb() was unexpectedly ", 572 "triggered while it is opened."); 573 } 574 } 575 576 #escapeSqlValue(v){ 577 if( !v ) return "{}"; 578 if( !Rx.special.test(v) ){ 579 return v /* no escaping needed */; 580 } 581 if( !Rx.squiggly.test(v) ){ 582 return "{"+v+"}"; 583 } 584 const sb = ["\""]; 585 const n = v.length; 586 for(let i = 0; i < n; ++i){ 587 const ch = v.charAt(i); 588 switch(ch){ 589 case '\\': sb.push("\\\\"); break; 590 case '"': sb.push("\\\""); break; 591 default:{ 592 //verbose("CHAR ",(int)ch," ",ch," octal=",String.format("\\%03o", (int)ch)); 593 const ccode = ch.charCodeAt(i); 594 if( ccode < 32 ) sb.push('\\',ccode.toString(8),'o'); 595 else sb.push(ch); 596 break; 597 } 598 } 599 } 600 sb.push("\""); 601 return sb.join(''); 602 } 603 604 #appendDbErr(pDb, sb, rc){ 605 sb.push(sqlite3.capi.sqlite3_js_rc_str(rc), ' '); 606 const msg = this.#escapeSqlValue(sqlite3.capi.sqlite3_errmsg(pDb)); 607 if( '{' === msg.charAt(0) ){ 608 sb.push(msg); 609 }else{ 610 sb.push('{', msg, '}'); 611 } 612 } 613 614 #checkDbRc(pDb,rc){ 615 sqlite3.oo1.DB.checkRc(pDb, rc); 616 } 617 618 execSql(pDb, throwOnError, appendMode, rowMode, sql){ 619 if( !pDb && !this.#db.list[0] ){ 620 this.#setupInitialDb(); 621 } 622 if( !pDb ) pDb = this.#db.currentDb(); 623 const wasm = sqlite3.wasm, capi = sqlite3.capi; 624 sql = (sql instanceof Uint8Array) 625 ? sql 626 : Util.utf8Encode(capi.sqlite3_js_sql_to_string(sql)); 627 const self = this; 628 const sb = (ResultBufferMode.NONE===appendMode) ? null : this.#resultBuffer; 629 let rc = 0; 630 wasm.scopedAllocCall(function(){ 631 let sqlByteLen = Number(sql.byteLength); 632 const ppStmt = wasm.scopedAlloc( 633 (2 * wasm.ptr.size) /* output (sqlite3_stmt**) arg and pzTail */ 634 + (sqlByteLen + 1/* SQL + NUL */) 635 ); 636 const pzTail = wasm.ptr.add(ppStmt, wasm.ptr.size) /* final arg to sqlite3_prepare_v2() */; 637 let pSql = wasm.ptr.add(pzTail, wasm.ptr.size); 638 const pSqlEnd = wasm.ptr.add(pSql, sqlByteLen); 639 wasm.heap8().set(sql, Number(pSql)); 640 wasm.poke8(pSqlEnd, 0/*NUL terminator*/); 641 let pos = 0, n = 1, spacing = 0; 642 while( pSql && wasm.peek8(pSql) ){ 643 wasm.pokePtr([ppStmt, pzTail], 0); 644 rc = capi.sqlite3_prepare_v3( 645 pDb, pSql, sqlByteLen, 0, ppStmt, pzTail 646 ); 647 if( 0!==rc ){ 648 if(throwOnError){ 649 throw new DbException(self, pDb, rc); 650 }else if( sb ){ 651 self.#appendDbErr(pDb, sb, rc); 652 } 653 break; 654 } 655 const pStmt = wasm.peekPtr(ppStmt); 656 pSql = wasm.peekPtr(pzTail); 657 sqlByteLen = Number(pSqlEnd - pSql); 658 if(!pStmt) continue /* only whitespace or comments */; 659 if( sb ){ 660 const nCol = capi.sqlite3_column_count(pStmt); 661 let colName, val; 662 while( capi.SQLITE_ROW === (rc = capi.sqlite3_step(pStmt)) ) { 663 for( let i=0; i < nCol; ++i ){ 664 if( spacing++ > 0 ) sb.push(' '); 665 if( self.#emitColNames ){ 666 colName = capi.sqlite3_column_name(pStmt, i); 667 switch(appendMode){ 668 case ResultBufferMode.ASIS: sb.push( colName ); break; 669 case ResultBufferMode.ESCAPED: 670 sb.push( self.#escapeSqlValue(colName) ); 671 break; 672 default: 673 self.toss("Unhandled ResultBufferMode."); 674 } 675 sb.push(' '); 676 } 677 val = capi.sqlite3_column_text(pStmt, i); 678 if( null===val ){ 679 sb.push( self.#nullView ); 680 continue; 681 } 682 switch(appendMode){ 683 case ResultBufferMode.ASIS: sb.push( val ); break; 684 case ResultBufferMode.ESCAPED: 685 sb.push( self.#escapeSqlValue(val) ); 686 break; 687 } 688 }/* column loop */ 689 if( ResultRowMode.NEWLINE === rowMode ){ 690 spacing = 0; 691 sb.push('\n'); 692 } 693 }/* row loop */ 694 }else{ // no output but possibly other side effects 695 while( capi.SQLITE_ROW === (rc = capi.sqlite3_step(pStmt)) ) {} 696 } 697 capi.sqlite3_finalize(pStmt); 698 if( capi.SQLITE_ROW===rc || capi.SQLITE_DONE===rc) rc = 0; 699 else if( rc!=0 ){ 700 if( sb ){ 701 self.#appendDbErr(pDb, sb, rc); 702 } 703 break; 704 } 705 }/* SQL script loop */; 706 })/*scopedAllocCall()*/; 707 return rc; 708 } 709 710 }/*SQLTester*/ 711 712 class Command { 713 constructor(){ 714 } 715 716 process(sqlTester,testScript,argv){ 717 SQLTesterException.toss("process() must be overridden"); 718 } 719 720 argcCheck(testScript,argv,min,max){ 721 const argc = argv.length-1; 722 if(argc=0 && argc>max)){ 723 if( min==max ){ 724 testScript.toss(argv[0]," requires exactly ",min," argument(s)"); 725 }else if(max>0){ 726 testScript.toss(argv[0]," requires ",min,"-",max," arguments."); 727 }else{ 728 testScript.toss(argv[0]," requires at least ",min," arguments."); 729 } 730 } 731 } 732 } 733 734 class Cursor { 735 src; 736 sb = []; 737 pos = 0; 738 //! Current line number. Starts at 0 for internal reasons and will 739 // line up with 1-based reality once parsing starts. 740 lineNo = 0 /* yes, zero */; 741 //! Putback value for this.pos. 742 putbackPos = 0; 743 //! Putback line number 744 putbackLineNo = 0; 745 //! Peeked-to pos, used by peekLine() and consumePeeked(). 746 peekedPos = 0; 747 //! Peeked-to line number. 748 peekedLineNo = 0; 749 750 constructor(){ 751 } 752 753 //! Restore parsing state to the start of the stream. 754 rewind(){ 755 this.sb.length = this.pos = this.lineNo 756 = this.putbackPos = this.putbackLineNo 757 = this.peekedPos = this.peekedLineNo = 0; 758 } 759 } 760 761 class TestScript { 762 #cursor = new Cursor(); 763 #moduleName = null; 764 #filename = null; 765 #testCaseName = null; 766 #outer = new Outer().outputPrefix( ()=>this.getOutputPrefix()+': ' ); 767 768 constructor(...args){ 769 let content, filename; 770 if( 2 == args.length ){ 771 filename = args[0]; 772 content = args[1]; 773 }else if( 1 == args.length ){ 774 if(args[0] instanceof Object){ 775 const o = args[0]; 776 filename = o.name; 777 content = o.content; 778 }else{ 779 content = args[0]; 780 } 781 } 782 if(!(content instanceof Uint8Array)){ 783 if('string' === typeof content){ 784 content = Util.utf8Encode(content); 785 }else if((content instanceof ArrayBuffer) 786 ||(content instanceof Array)){ 787 content = new Uint8Array(content); 788 }else{ 789 toss(Error, "Invalid content type for TestScript constructor."); 790 } 791 } 792 this.#filename = filename; 793 this.#cursor.src = content; 794 } 795 796 moduleName(){ 797 return (0==arguments.length) 798 ? this.#moduleName : (this.#moduleName = arguments[0]); 799 } 800 801 testCaseName(){ 802 return (0==arguments.length) 803 ? this.#testCaseName : (this.#testCaseName = arguments[0]); 804 } 805 filename(){ 806 return (0==arguments.length) 807 ? this.#filename : (this.#filename = arguments[0]); 808 } 809 810 getOutputPrefix() { 811 let rc = "["+(this.#moduleName || '')+"]"; 812 if( this.#testCaseName ) rc += "["+this.#testCaseName+"]"; 813 if( this.#filename ) rc += '['+this.#filename+']'; 814 return rc + " line "+ this.#cursor.lineNo; 815 } 816 817 reset(){ 818 this.#testCaseName = null; 819 this.#cursor.rewind(); 820 return this; 821 } 822 823 toss(...args){ 824 throw new TestScriptFailed(this,...args); 825 } 826 827 verbose1(...args){ return this.#outer.verboseN(1,args); } 828 verbose2(...args){ return this.#outer.verboseN(2,args); } 829 verbose3(...args){ return this.#outer.verboseN(3,args); } 830 verbosity(...args){ 831 const rc = this.#outer.verbosity(...args); 832 return args.length ? this : rc; 833 } 834 835 #checkRequiredProperties(tester, props){ 836 if(true) return false; 837 let nOk = 0; 838 for(const rp of props){ 839 this.verbose2("REQUIRED_PROPERTIES: ",rp); 840 switch(rp){ 841 case "RECURSIVE_TRIGGERS": 842 tester.appendDbInitSql("pragma recursive_triggers=on;"); 843 ++nOk; 844 break; 845 case "TEMPSTORE_FILE": 846 /* This _assumes_ that the lib is built with SQLITE_TEMP_STORE=1 or 2, 847 which we just happen to know is the case */ 848 tester.appendDbInitSql("pragma temp_store=1;"); 849 ++nOk; 850 break; 851 case "TEMPSTORE_MEM": 852 /* This _assumes_ that the lib is built with SQLITE_TEMP_STORE=1 or 2, 853 which we just happen to know is the case */ 854 tester.appendDbInitSql("pragma temp_store=0;"); 855 ++nOk; 856 break; 857 case "AUTOVACUUM": 858 tester.appendDbInitSql("pragma auto_vacuum=full;"); 859 ++nOk; 860 break; 861 case "INCRVACUUM": 862 tester.appendDbInitSql("pragma auto_vacuum=incremental;"); 863 ++nOk; 864 break; 865 default: 866 break; 867 } 868 } 869 return props.length == nOk; 870 } 871 872 #checkForDirective(tester,line){ 873 if(line.startsWith("#")){ 874 throw new IncompatibleDirective(this, "C-preprocessor input: "+line); 875 }else if(line.startsWith("---")){ 876 throw new IncompatibleDirective(this, "triple-dash: ",line); 877 } 878 let m = Rx.scriptModuleName.exec(line); 879 if( m ){ 880 this.#moduleName = m[1]; 881 return; 882 } 883 m = Rx.requiredProperties.exec(line); 884 if( m ){ 885 const rp = m[1]; 886 if( !this.#checkRequiredProperties( tester, rp.split(/\s+/).filter(v=>!!v) ) ){ 887 throw new IncompatibleDirective(this, "REQUIRED_PROPERTIES: "+rp); 888 } 889 } 890 891 m = Rx.mixedModuleName.exec(line); 892 if( m ){ 893 throw new IncompatibleDirective(this, m[1]+": "+m[3]); 894 } 895 if( line.indexOf("\n|")>=0 ){ 896 throw new IncompatibleDirective(this, "newline-pipe combination."); 897 } 898 899 } 900 901 #getCommandArgv(line){ 902 const m = Rx.command.exec(line); 903 return m ? m[1].trim().split(/\s+/) : null; 904 } 905 906 907 #isCommandLine(line, checkForImpl){ 908 let m = Rx.command.exec(line); 909 if( m && checkForImpl ){ 910 m = !!CommandDispatcher.getCommandByName(m[2]); 911 } 912 return !!m; 913 } 914 915 fetchCommandBody(tester){ 916 const sb = []; 917 let line; 918 while( (null !== (line = this.peekLine())) ){ 919 this.#checkForDirective(tester, line); 920 if( this.#isCommandLine(line, true) ) break; 921 sb.push(line,"\n"); 922 this.consumePeeked(); 923 } 924 line = sb.join(''); 925 return !!line.trim() ? line : null; 926 } 927 928 run(tester){ 929 this.reset(); 930 this.#outer.verbosity( tester.verbosity() ); 931 this.#outer.logger( tester.outer().logger() ); 932 let line, directive, argv = []; 933 while( null != (line = this.getLine()) ){ 934 this.verbose3("run() input line: ",line); 935 this.#checkForDirective(tester, line); 936 argv = this.#getCommandArgv(line); 937 if( argv ){ 938 this.#processCommand(tester, argv); 939 continue; 940 } 941 tester.appendInput(line,true); 942 } 943 return true; 944 } 945 946 #processCommand(tester, argv){ 947 this.verbose2("processCommand(): ",argv[0], " ", Util.argvToString(argv)); 948 if(this.#outer.verbosity()>1){ 949 const input = tester.getInputText(); 950 this.verbose3("processCommand() input buffer = ",input); 951 } 952 CommandDispatcher.dispatch(tester, this, argv); 953 } 954 955 getLine(){ 956 const cur = this.#cursor; 957 if( cur.pos==cur.src.byteLength ){ 958 return null/*EOF*/; 959 } 960 cur.putbackPos = cur.pos; 961 cur.putbackLineNo = cur.lineNo; 962 cur.sb.length = 0; 963 let b = 0, prevB = 0, i = cur.pos; 964 let doBreak = false; 965 let nChar = 0 /* number of bytes in the aChar char */; 966 const end = cur.src.byteLength; 967 for(; i < end && !doBreak; ++i){ 968 b = cur.src[i]; 969 switch( b ){ 970 case 13/*CR*/: continue; 971 case 10/*NL*/: 972 ++cur.lineNo; 973 if(cur.sb.length>0) doBreak = true; 974 // Else it's an empty string 975 break; 976 default:{ 977 /* Multi-byte chars need to be gathered up and appended at 978 one time so that we can get them as string objects. */ 979 nChar = 1; 980 switch( b & 0xF0 ){ 981 case 0xC0: nChar = 2; break; 982 case 0xE0: nChar = 3; break; 983 case 0xF0: nChar = 4; break; 984 default: 985 if( b > 127 ) this.toss("Invalid character (#"+b+")."); 986 break; 987 } 988 if( 1==nChar ){ 989 cur.sb.push(String.fromCharCode(b)); 990 }else{ 991 const aChar = [] /* multi-byte char buffer */; 992 for(let x = 0; (x < nChar) && (i+x < end); ++x) aChar[x] = cur.src[i+x]; 993 cur.sb.push( 994 Util.utf8Decode( new Uint8Array(aChar) ) 995 ); 996 i += nChar-1; 997 } 998 break; 999 } 1000 } 1001 } 1002 cur.pos = i; 1003 const rv = cur.sb.join(''); 1004 if( i==cur.src.byteLength && 0==rv.length ){ 1005 return null /* EOF */; 1006 } 1007 return rv; 1008 }/*getLine()*/ 1009 1010 /** 1011 Fetches the next line then resets the cursor to its pre-call 1012 state. consumePeeked() can be used to consume this peeked line 1013 without having to re-parse it. 1014 */ 1015 peekLine(){ 1016 const cur = this.#cursor; 1017 const oldPos = cur.pos; 1018 const oldPB = cur.putbackPos; 1019 const oldPBL = cur.putbackLineNo; 1020 const oldLine = cur.lineNo; 1021 try { 1022 return this.getLine(); 1023 }finally{ 1024 cur.peekedPos = cur.pos; 1025 cur.peekedLineNo = cur.lineNo; 1026 cur.pos = oldPos; 1027 cur.lineNo = oldLine; 1028 cur.putbackPos = oldPB; 1029 cur.putbackLineNo = oldPBL; 1030 } 1031 } 1032 1033 1034 /** 1035 Only valid after calling peekLine() and before calling getLine(). 1036 This places the cursor to the position it would have been at had 1037 the peekLine() had been fetched with getLine(). 1038 */ 1039 consumePeeked(){ 1040 const cur = this.#cursor; 1041 cur.pos = cur.peekedPos; 1042 cur.lineNo = cur.peekedLineNo; 1043 } 1044 1045 /** 1046 Restores the cursor to the position it had before the previous 1047 call to getLine(). 1048 */ 1049 putbackLine(){ 1050 const cur = this.#cursor; 1051 cur.pos = cur.putbackPos; 1052 cur.lineNo = cur.putbackLineNo; 1053 } 1054 1055 }/*TestScript*/; 1056 1057 //! --close command 1058 class CloseDbCommand extends Command { 1059 process(t, ts, argv){ 1060 this.argcCheck(ts,argv,0,1); 1061 let id; 1062 if(argv.length>1){ 1063 const arg = argv[1]; 1064 if( "all" === arg ){ 1065 t.closeAllDbs(); 1066 return; 1067 } 1068 else{ 1069 id = parseInt(arg); 1070 } 1071 }else{ 1072 id = t.currentDbId(); 1073 } 1074 t.closeDb(id); 1075 } 1076 } 1077 1078 //! --column-names command 1079 class ColumnNamesCommand extends Command { 1080 process( st, ts, argv ){ 1081 this.argcCheck(ts,argv,1); 1082 st.outputColumnNames( !!parseInt(argv[1]) ); 1083 } 1084 } 1085 1086 //! --db command 1087 class DbCommand extends Command { 1088 process(t, ts, argv){ 1089 this.argcCheck(ts,argv,1); 1090 t.currentDbId( parseInt(argv[1]) ); 1091 } 1092 } 1093 1094 //! --glob command 1095 class GlobCommand extends Command { 1096 #negate = false; 1097 constructor(negate=false){ 1098 super(); 1099 this.#negate = negate; 1100 } 1101 1102 process(t, ts, argv){ 1103 this.argcCheck(ts,argv,1,-1); 1104 t.incrementTestCounter(); 1105 const sql = t.takeInputBuffer(); 1106 let rc = t.execSql(null, true, ResultBufferMode.ESCAPED, 1107 ResultRowMode.ONELINE, sql); 1108 const result = t.getResultText(); 1109 const sArgs = Util.argvToString(argv); 1110 //t2.verbose2(argv[0]," rc = ",rc," result buffer:\n", result,"\nargs:\n",sArgs); 1111 const glob = Util.argvToString(argv); 1112 rc = Util.strglob(glob, result); 1113 if( (this.#negate && 0===rc) || (!this.#negate && 0!==rc) ){ 1114 ts.toss(argv[0], " mismatch: ", glob," vs input: ",result); 1115 } 1116 } 1117 } 1118 1119 //! --notglob command 1120 class NotGlobCommand extends GlobCommand { 1121 constructor(){super(true);} 1122 } 1123 1124 //! --open command 1125 class OpenDbCommand extends Command { 1126 #createIfNeeded = false; 1127 constructor(createIfNeeded=false){ 1128 super(); 1129 this.#createIfNeeded = createIfNeeded; 1130 } 1131 process(t, ts, argv){ 1132 this.argcCheck(ts,argv,1); 1133 t.openDb(argv[1], this.#createIfNeeded); 1134 } 1135 } 1136 1137 //! --new command 1138 class NewDbCommand extends OpenDbCommand { 1139 constructor(){ super(true); } 1140 } 1141 1142 //! Placeholder dummy/no-op commands 1143 class NoopCommand extends Command { 1144 process(t, ts, argv){} 1145 } 1146 1147 //! --null command 1148 class NullCommand extends Command { 1149 process(st, ts, argv){ 1150 this.argcCheck(ts,argv,1); 1151 st.nullValue( argv[1] ); 1152 } 1153 } 1154 1155 //! --print command 1156 class PrintCommand extends Command { 1157 process(st, ts, argv){ 1158 st.out(ts.getOutputPrefix(),': '); 1159 if( 1==argv.length ){ 1160 st.out( st.getInputText() ); 1161 }else{ 1162 st.outln( Util.argvToString(argv) ); 1163 } 1164 } 1165 } 1166 1167 //! --result command 1168 class ResultCommand extends Command { 1169 #bufferMode; 1170 constructor(resultBufferMode = ResultBufferMode.ESCAPED){ 1171 super(); 1172 this.#bufferMode = resultBufferMode; 1173 } 1174 process(t, ts, argv){ 1175 this.argcCheck(ts,argv,0,-1); 1176 t.incrementTestCounter(); 1177 const sql = t.takeInputBuffer(); 1178 //ts.verbose2(argv[0]," SQL =\n",sql); 1179 t.execSql(null, false, this.#bufferMode, ResultRowMode.ONELINE, sql); 1180 const result = t.getResultText().trim(); 1181 const sArgs = argv.length>1 ? Util.argvToString(argv) : ""; 1182 if( result !== sArgs ){ 1183 t.outln(argv[0]," FAILED comparison. Result buffer:\n", 1184 result,"\nExpected result:\n",sArgs); 1185 ts.toss(argv[0]+" comparison failed."); 1186 } 1187 } 1188 } 1189 1190 //! --json command 1191 class JsonCommand extends ResultCommand { 1192 constructor(){ super(ResultBufferMode.ASIS); } 1193 } 1194 1195 //! --run command 1196 class RunCommand extends Command { 1197 process(t, ts, argv){ 1198 this.argcCheck(ts,argv,0,1); 1199 const pDb = (1==argv.length) 1200 ? t.currentDb() : t.getDbById( parseInt(argv[1]) ); 1201 const sql = t.takeInputBuffer(); 1202 const rc = t.execSql(pDb, false, ResultBufferMode.NONE, 1203 ResultRowMode.ONELINE, sql); 1204 if( 0!==rc && t.verbosity()>0 ){ 1205 const msg = sqlite3.capi.sqlite3_errmsg(pDb); 1206 ts.verbose2(argv[0]," non-fatal command error #",rc,": ", 1207 msg,"\nfor SQL:\n",sql); 1208 } 1209 } 1210 } 1211 1212 //! --tableresult command 1213 class TableResultCommand extends Command { 1214 #jsonMode; 1215 constructor(jsonMode=false){ 1216 super(); 1217 this.#jsonMode = jsonMode; 1218 } 1219 process(t, ts, argv){ 1220 this.argcCheck(ts,argv,0); 1221 t.incrementTestCounter(); 1222 let body = ts.fetchCommandBody(t); 1223 if( null===body ) ts.toss("Missing ",argv[0]," body."); 1224 body = body.trim(); 1225 if( !body.endsWith("\n--end") ){ 1226 ts.toss(argv[0], " must be terminated with --end\\n"); 1227 }else{ 1228 body = body.substring(0, body.length-6); 1229 } 1230 const globs = body.split(/\s*\n\s*/); 1231 if( globs.length < 1 ){ 1232 ts.toss(argv[0], " requires 1 or more ", 1233 (this.#jsonMode ? "json snippets" : "globs"),"."); 1234 } 1235 const sql = t.takeInputBuffer(); 1236 t.execSql(null, true, 1237 this.#jsonMode ? ResultBufferMode.ASIS : ResultBufferMode.ESCAPED, 1238 ResultRowMode.NEWLINE, sql); 1239 const rbuf = t.getResultText().trim(); 1240 const res = rbuf.split(/\r?\n/); 1241 if( res.length !== globs.length ){ 1242 ts.toss(argv[0], " failure: input has ", res.length, 1243 " row(s) but expecting ",globs.length); 1244 } 1245 for(let i = 0; i < res.length; ++i){ 1246 const glob = globs[i].replaceAll(/\s+/g," ").trim(); 1247 //ts.verbose2(argv[0]," <<",glob,">> vs <<",res[i],">>"); 1248 if( this.#jsonMode ){ 1249 if( glob!==res[i] ){ 1250 ts.toss(argv[0], " json <<",glob, ">> does not match: <<", 1251 res[i],">>"); 1252 } 1253 }else if( 0!=Util.strglob(glob, res[i]) ){ 1254 ts.toss(argv[0], " glob <<",glob,">> does not match: <<",res[i],">>"); 1255 } 1256 } 1257 } 1258 } 1259 1260 //! --json-block command 1261 class JsonBlockCommand extends TableResultCommand { 1262 constructor(){ super(true); } 1263 } 1264 1265 //! --testcase command 1266 class TestCaseCommand extends Command { 1267 process(tester, script, argv){ 1268 this.argcCheck(script, argv,1); 1269 script.testCaseName(argv[1]); 1270 tester.clearResultBuffer(); 1271 tester.clearInputBuffer(); 1272 } 1273 } 1274 1275 1276 //! --verbosity command 1277 class VerbosityCommand extends Command { 1278 process(t, ts, argv){ 1279 this.argcCheck(ts,argv,1); 1280 ts.verbosity( parseInt(argv[1]) ); 1281 } 1282 } 1283 1284 class CommandDispatcher { 1285 static map = newObj(); 1286 1287 static getCommandByName(name){ 1288 let rv = CommandDispatcher.map[name]; 1289 if( rv ) return rv; 1290 switch(name){ 1291 case "close": rv = new CloseDbCommand(); break; 1292 case "column-names": rv = new ColumnNamesCommand(); break; 1293 case "db": rv = new DbCommand(); break; 1294 case "glob": rv = new GlobCommand(); break; 1295 case "json": rv = new JsonCommand(); break; 1296 case "json-block": rv = new JsonBlockCommand(); break; 1297 case "new": rv = new NewDbCommand(); break; 1298 case "notglob": rv = new NotGlobCommand(); break; 1299 case "null": rv = new NullCommand(); break; 1300 case "oom": rv = new NoopCommand(); break; 1301 case "open": rv = new OpenDbCommand(); break; 1302 case "print": rv = new PrintCommand(); break; 1303 case "result": rv = new ResultCommand(); break; 1304 case "run": rv = new RunCommand(); break; 1305 case "tableresult": rv = new TableResultCommand(); break; 1306 case "testcase": rv = new TestCaseCommand(); break; 1307 case "verbosity": rv = new VerbosityCommand(); break; 1308 } 1309 if( rv ){ 1310 CommandDispatcher.map[name] = rv; 1311 } 1312 return rv; 1313 } 1314 1315 static dispatch(tester, testScript, argv){ 1316 const cmd = CommandDispatcher.getCommandByName(argv[0]); 1317 if( !cmd ){ 1318 toss(UnknownCommand,testScript,argv[0]); 1319 } 1320 cmd.process(tester, testScript, argv); 1321 } 1322 }/*CommandDispatcher*/ 1323 1324 const namespace = newObj({ 1325 Command, 1326 DbException, 1327 IncompatibleDirective, 1328 Outer, 1329 SQLTester, 1330 SQLTesterException, 1331 TestScript, 1332 TestScriptFailed, 1333 UnknownCommand, 1334 Util, 1335 sqlite3 1336 }); 1337 1338 export {namespace as default};