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 / demo-worker1.js

348 lines · 11873 bytes Raw Blame History
1/*
2 2022-05-22
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 A basic test script for sqlite3-worker1.js.
14
15 Note that the wrapper interface demonstrated in
16 demo-worker1-promiser.js is much easier to use from client code, as it
17 lacks the message-passing acrobatics demonstrated in this file.
18*/
19'use strict';
20(function(){
21 const T = globalThis.SqliteTestUtil;
22 const SW = new Worker("jswasm/sqlite3-worker1.js");
23 const DbState = {
24 id: undefined
25 };
26 const eOutput = document.querySelector('#test-output');
27 const log = console.log.bind(console);
28 const logHtml = function(cssClass,...args){
29 log.apply(this, args);
30 const ln = document.createElement('div');
31 if(cssClass) ln.classList.add(cssClass);
32 ln.append(document.createTextNode(args.join(' ')));
33 eOutput.append(ln);
34 };
35 const warn = console.warn.bind(console);
36 const error = console.error.bind(console);
37 const toss = (...args)=>{throw new Error(args.join(' '))};
38
39 SW.onerror = function(event){
40 error("onerror",event);
41 };
42
43 let startTime;
44
45 /**
46 A queue for callbacks which are to be run in response to async
47 DB commands. See the notes in runTests() for why we need
48 this. The event-handling plumbing of this file requires that
49 any DB command which includes a `messageId` property also have
50 a queued callback entry, as the existence of that property in
51 response payloads is how it knows whether or not to shift an
52 entry off of the queue.
53 */
54 const MsgHandlerQueue = {
55 queue: [],
56 id: 0,
57 push: function(type,callback){
58 this.queue.push(callback);
59 return type + '-' + (++this.id);
60 },
61 shift: function(){
62 return this.queue.shift();
63 }
64 };
65
66 const testCount = ()=>{
67 logHtml("","Total test count:",T.counter+". Total time =",(performance.now() - startTime),"ms");
68 };
69
70 const logEventResult = function(ev){
71 const evd = ev.result;
72 logHtml(evd.errorClass ? 'error' : '',
73 "runOneTest",ev.messageId,"Worker time =",
74 (ev.workerRespondTime - ev.workerReceivedTime),"ms.",
75 "Round-trip event time =",
76 (performance.now() - ev.departureTime),"ms.",
77 (evd.errorClass ? evd.message : "")//, JSON.stringify(evd)
78 );
79 };
80
81 const runOneTest = function(eventType, eventArgs, callback){
82 T.assert(eventArgs && 'object'===typeof eventArgs);
83 /* ^^^ that is for the testing and messageId-related code, not
84 a hard requirement of all of the Worker-exposed APIs. */
85 const messageId = MsgHandlerQueue.push(eventType,function(ev){
86 logEventResult(ev);
87 if(callback instanceof Function){
88 callback(ev);
89 testCount();
90 }
91 });
92 const msg = {
93 type: eventType,
94 args: eventArgs,
95 dbId: DbState.id,
96 messageId: messageId,
97 departureTime: performance.now()
98 };
99 log("Posting",eventType,"message to worker dbId="+(DbState.id||'default')+':',msg);
100 SW.postMessage(msg);
101 };
102
103 /** Methods which map directly to onmessage() event.type keys.
104 They get passed the inbound event.data. */
105 const dbMsgHandler = {
106 open: function(ev){
107 DbState.id = ev.dbId;
108 log("open result",ev);
109 },
110 exec: function(ev){
111 log("exec result",ev);
112 },
113 export: function(ev){
114 log("export result",ev);
115 },
116 error: function(ev){
117 error("ERROR from the worker:",ev);
118 logEventResult(ev);
119 },
120 resultRowTest1: function f(ev){
121 if(undefined === f.counter) f.counter = 0;
122 if(null === ev.rowNumber){
123 /* End of result set. */
124 T.assert(undefined === ev.row)
125 .assert(Array.isArray(ev.columnNames))
126 .assert(ev.columnNames.length);
127 }else{
128 T.assert(ev.rowNumber > 0);
129 ++f.counter;
130 }
131 //log("exec() result row:",ev);
132 T.assert(null === ev.rowNumber || 'number' === typeof ev.row.b);
133 }
134 };
135
136 /**
137 "The problem" now is that the test results are async. We
138 know, however, that the messages posted to the worker will
139 be processed in the order they are passed to it, so we can
140 create a queue of callbacks to handle them. The problem
141 with that approach is that it's not error-handling
142 friendly, in that an error can cause us to bypass a result
143 handler queue entry. We have to perform some extra
144 acrobatics to account for that.
145
146 Problem #2 is that we cannot simply start posting events: we
147 first have to post an 'open' event, wait for it to respond, and
148 collect its db ID before continuing. If we don't wait, we may
149 well fire off 10+ messages before the open actually responds.
150 */
151 const runTests2 = function(){
152 const mustNotReach = ()=>{
153 throw new Error("This is not supposed to be reached.");
154 };
155 runOneTest('exec',{
156 sql: ["create table t(a,b);",
157 "insert into t(a,b) values(1,2),(3,4),(5,6)"
158 ],
159 lastInsertRowId: true,
160 resultRows: [], columnNames: []
161 }, function(ev){
162 ev = ev.result;
163 T.assert(0===ev.resultRows.length)
164 .assert(0===ev.columnNames.length)
165 .assert('bigint'===typeof ev.lastInsertRowId)
166 .assert(ev.lastInsertRowId>=3);
167 });
168 runOneTest('exec',{
169 sql: 'select a a, b b from t order by a',
170 resultRows: [], columnNames: [], saveSql:[]
171 }, function(ev){
172 ev = ev.result;
173 T.assert(3===ev.resultRows.length)
174 .assert(1===ev.resultRows[0][0])
175 .assert(6===ev.resultRows[2][1])
176 .assert(2===ev.columnNames.length)
177 .assert('b'===ev.columnNames[1]);
178 });
179 //if(1){ error("Returning prematurely for testing."); return; }
180 runOneTest('exec',{
181 sql: 'select a a, b b from t order by a',
182 resultRows: [], columnNames: [],
183 rowMode: 'object'
184 }, function(ev){
185 ev = ev.result;
186 T.assert(3===ev.resultRows.length)
187 .assert(1===ev.resultRows[0].a)
188 .assert(6===ev.resultRows[2].b)
189 });
190 runOneTest('exec',{sql:'intentional_error'}, mustNotReach);
191 // Ensure that the message-handler queue survives ^^^ that error...
192 runOneTest('exec',{
193 sql:'select 1',
194 resultRows: [],
195 //rowMode: 'array', // array is the default in the Worker interface
196 }, function(ev){
197 ev = ev.result;
198 T.assert(1 === ev.resultRows.length)
199 .assert(1 === ev.resultRows[0][0]);
200 });
201 runOneTest('exec',{
202 sql: 'select a a, b b from t order by a',
203 callback: 'resultRowTest1',
204 rowMode: 'object'
205 }, function(ev){
206 T.assert(3===dbMsgHandler.resultRowTest1.counter);
207 dbMsgHandler.resultRowTest1.counter = 0;
208 });
209 runOneTest('exec',{
210 sql:[
211 "pragma foreign_keys=0;",
212 // ^^^ arbitrary query with no result columns
213 "select a, b from t order by a desc;",
214 "select a from t;"
215 // exec() only honors SELECT results from the first
216 // statement with result columns (regardless of whether
217 // it has any rows).
218 ],
219 rowMode: 1,
220 resultRows: []
221 },function(ev){
222 const rows = ev.result.resultRows;
223 T.assert(3===rows.length).
224 assert(6===rows[0]);
225 });
226 runOneTest('exec',{sql: 'delete from t where a>3'});
227 runOneTest('exec',{
228 sql: 'select count(a) from t',
229 resultRows: []
230 },function(ev){
231 ev = ev.result;
232 T.assert(1===ev.resultRows.length)
233 .assert(2===ev.resultRows[0][0]);
234 });
235 runOneTest('export',{}, function(ev){
236 ev = ev.result;
237 log("export result:",ev);
238 T.assert('string' === typeof ev.filename)
239 .assert(ev.byteArray instanceof Uint8Array)
240 .assert(ev.byteArray.length > 1024)
241 .assert('application/x-sqlite3' === ev.mimetype);
242 });
243 /***** close() tests must come last. *****/
244 runOneTest('close',{unlink:true},function(ev){
245 ev = ev.result;
246 T.assert('string' === typeof ev.filename);
247 });
248 runOneTest('close',{unlink:true},function(ev){
249 ev = ev.result;
250 T.assert(undefined === ev.filename);
251 logHtml('warning',"This is the final test.");
252 });
253 logHtml('warning',"Finished posting tests. Waiting on async results.");
254 };
255
256 const runTests = function(){
257 /**
258 Design decision time: all remaining tests depend on the 'open'
259 command having succeeded. In order to support multiple DBs, the
260 upcoming commands ostensibly have to know the ID of the DB they
261 want to talk to. We have two choices:
262
263 1) We run 'open' and wait for its response, which contains the
264 db id.
265
266 2) We have the Worker automatically use the current "default
267 db" (the one which was most recently opened) if no db id is
268 provided in the message. When we do this, the main thread may
269 well fire off _all_ of the test messages before the 'open'
270 actually responds, but because the messages are handled on a
271 FIFO basis, those after the initial 'open' will pick up the
272 "default" db. However, if the open fails, then all pending
273 messages (until next next 'open', at least) except for 'close'
274 will fail and we have no way of cancelling them once they've
275 been posted to the worker.
276
277 Which approach we use below depends on the boolean value of
278 waitForOpen.
279 */
280 const waitForOpen = 1,
281 simulateOpenError = 0 /* if true, the remaining tests will
282 all barf if waitForOpen is
283 false. */;
284 logHtml('',
285 "Sending 'open' message and",(waitForOpen ? "" : "NOT ")+
286 "waiting for its response before continuing.");
287 startTime = performance.now();
288 runOneTest('open', {
289 filename:'testing2.sqlite3',
290 simulateError: simulateOpenError
291 }, function(ev){
292 log("open result",ev);
293 T.assert('testing2.sqlite3'===ev.result.filename)
294 .assert(ev.dbId)
295 .assert(ev.messageId)
296 .assert('string' === typeof ev.result.vfs);
297 DbState.id = ev.dbId;
298 if(waitForOpen) setTimeout(runTests2, 0);
299 });
300 if(!waitForOpen) runTests2();
301 };
302
303 SW.onmessage = function(ev){
304 if(!ev.data || 'object'!==typeof ev.data){
305 warn("Unknown sqlite3-worker message type:",ev);
306 return;
307 }
308 ev = ev.data/*expecting a nested object*/;
309 //log("main window onmessage:",ev);
310 if(ev.result && ev.messageId){
311 /* We're expecting a queued-up callback handler. */
312 const f = MsgHandlerQueue.shift();
313 if('error'===ev.type){
314 dbMsgHandler.error(ev);
315 return;
316 }
317 T.assert(f instanceof Function);
318 f(ev);
319 return;
320 }
321 switch(ev.type){
322 case 'sqlite3-api':
323 switch(ev.result){
324 case 'worker1-ready':
325 log("Message:",ev);
326 globalThis.sqlite3TestModule.setStatus(null);
327 runTests();
328 return;
329 default:
330 warn("Unknown sqlite3-api message type:",ev);
331 return;
332 }
333 default:
334 if(dbMsgHandler.hasOwnProperty(ev.type)){
335 try{dbMsgHandler[ev.type](ev);}
336 catch(err){
337 error("Exception while handling db result message",
338 ev,":",err);
339 }
340 return;
341 }
342 warn("Unknown sqlite3-api message type:",ev);
343 }
344 };
345 log("Init complete, but async init bits may still be running.");
346 log("Installing Worker into global scope SW for dev purposes.");
347 globalThis.SW = SW;
348})();