demo-worker1-promiser.c-pp.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. 2022-08-23
  3. The author disclaims copyright to this source code. In place of a
  4. legal notice, here is a blessing:
  5. * May you do good and not evil.
  6. * May you find forgiveness for yourself and forgive others.
  7. * May you share freely, never taking more than you give.
  8. ***********************************************************************
  9. Demonstration of the sqlite3 Worker API #1 Promiser: a Promise-based
  10. proxy for for the sqlite3 Worker #1 API.
  11. */
  12. //#if target=es6-module
  13. import {default as promiserFactory} from "./jswasm/sqlite3-worker1-promiser.mjs";
  14. //#else
  15. "use strict";
  16. const promiserFactory = globalThis.sqlite3Worker1Promiser.v2;
  17. delete globalThis.sqlite3Worker1Promiser;
  18. //#endif
  19. (async function(){
  20. const T = globalThis.SqliteTestUtil;
  21. const eOutput = document.querySelector('#test-output');
  22. const warn = console.warn.bind(console);
  23. const error = console.error.bind(console);
  24. const log = console.log.bind(console);
  25. const logHtml = async function(cssClass,...args){
  26. log.apply(this, args);
  27. const ln = document.createElement('div');
  28. if(cssClass) ln.classList.add(cssClass);
  29. ln.append(document.createTextNode(args.join(' ')));
  30. eOutput.append(ln);
  31. };
  32. let startTime;
  33. const testCount = async ()=>{
  34. logHtml("","Total test count:",T.counter+". Total time =",(performance.now() - startTime),"ms");
  35. };
  36. const promiserConfig = {
  37. //#ifnot target=es6-module
  38. /**
  39. The v1 interfaces uses an onready function. The v2 interface optionally
  40. accepts one but does not require it. If provided, it is called _before_
  41. the promise is resolved, and the promise is rejected if onready() throws.
  42. */
  43. onready: function(f){
  44. /* f === the function returned by promiserFactory().
  45. Ostensibly (f === workerPromise) but this function is
  46. called before the promiserFactory() Promise resolves, so
  47. before workerPromise is set. */
  48. console.warn("This is the v2 interface - you don't need an onready() function.");
  49. },
  50. //#endif
  51. debug: 1 ? undefined : (...args)=>console.debug('worker debug',...args),
  52. onunhandled: function(ev){
  53. error("Unhandled worker message:",ev.data);
  54. },
  55. onerror: function(ev){
  56. error("worker1 error:",ev);
  57. }
  58. };
  59. const workerPromise = await promiserFactory(promiserConfig)
  60. .then((func)=>{
  61. console.log("Init complete. Starting tests momentarily.");
  62. globalThis.sqlite3TestModule.setStatus(null)/*hide the HTML-side is-loading spinner*/;
  63. return func;
  64. });
  65. const wtest = async function(msgType, msgArgs, callback){
  66. if(2===arguments.length && 'function'===typeof msgArgs){
  67. callback = msgArgs;
  68. msgArgs = undefined;
  69. }
  70. const p = 1
  71. ? workerPromise({type: msgType, args:msgArgs})
  72. : workerPromise(msgType, msgArgs);
  73. return callback ? p.then(callback).finally(testCount) : p;
  74. };
  75. let sqConfig;
  76. const runTests = async function(){
  77. const dbFilename = '/testing2.sqlite3';
  78. startTime = performance.now();
  79. await wtest('config-get', (ev)=>{
  80. const r = ev.result;
  81. log('sqlite3.config subset:', r);
  82. T.assert('boolean' === typeof r.bigIntEnabled);
  83. sqConfig = r;
  84. });
  85. logHtml('',
  86. "Sending 'open' message and waiting for its response before continuing...");
  87. await wtest('open', {
  88. filename: dbFilename,
  89. simulateError: 0 /* if true, fail the 'open' */,
  90. }, function(ev){
  91. const r = ev.result;
  92. log("then open result",r);
  93. T.assert(ev.dbId === r.dbId)
  94. .assert(ev.messageId)
  95. .assert('string' === typeof r.vfs);
  96. promiserConfig.dbId = ev.dbId;
  97. }).then(runTests2);
  98. };
  99. const runTests2 = async function(){
  100. const mustNotReach = ()=>toss("This is not supposed to be reached.");
  101. await wtest('exec',{
  102. sql: ["create table t(a,b)",
  103. "insert into t(a,b) values(1,2),(3,4),(5,6)"
  104. ].join(';'),
  105. resultRows: [], columnNames: [],
  106. countChanges: sqConfig.bigIntEnabled ? 64 : true
  107. }, function(ev){
  108. ev = ev.result;
  109. T.assert(0===ev.resultRows.length)
  110. .assert(0===ev.columnNames.length)
  111. .assert(sqConfig.bigIntEnabled
  112. ? (3n===ev.changeCount)
  113. : (3===ev.changeCount));
  114. });
  115. await wtest('exec',{
  116. sql: 'select a a, b b from t order by a',
  117. resultRows: [], columnNames: [],
  118. }, function(ev){
  119. ev = ev.result;
  120. T.assert(3===ev.resultRows.length)
  121. .assert(1===ev.resultRows[0][0])
  122. .assert(6===ev.resultRows[2][1])
  123. .assert(2===ev.columnNames.length)
  124. .assert('b'===ev.columnNames[1]);
  125. });
  126. await wtest('exec',{
  127. sql: 'select a a, b b from t order by a',
  128. resultRows: [], columnNames: [],
  129. rowMode: 'object',
  130. countChanges: true
  131. }, function(ev){
  132. ev = ev.result;
  133. T.assert(3===ev.resultRows.length)
  134. .assert(1===ev.resultRows[0].a)
  135. .assert(6===ev.resultRows[2].b)
  136. .assert(0===ev.changeCount);
  137. });
  138. await wtest(
  139. 'exec',
  140. {sql:'intentional_error'},
  141. mustNotReach
  142. ).catch((e)=>{
  143. warn("Intentional error:",e);
  144. });
  145. await wtest('exec',{
  146. sql:'select 1 union all select 3',
  147. resultRows: []
  148. }, function(ev){
  149. ev = ev.result;
  150. T.assert(2 === ev.resultRows.length)
  151. .assert(1 === ev.resultRows[0][0])
  152. .assert(3 === ev.resultRows[1][0])
  153. .assert(undefined === ev.changeCount);
  154. });
  155. const resultRowTest1 = function f(ev){
  156. if(undefined === f.counter) f.counter = 0;
  157. if(null === ev.rowNumber){
  158. /* End of result set. */
  159. T.assert(undefined === ev.row)
  160. .assert(2===ev.columnNames.length)
  161. .assert('a'===ev.columnNames[0])
  162. .assert('B'===ev.columnNames[1]);
  163. }else{
  164. T.assert(ev.rowNumber > 0);
  165. ++f.counter;
  166. }
  167. log("exec() result row:",ev);
  168. T.assert(null === ev.rowNumber || 'number' === typeof ev.row.B);
  169. };
  170. await wtest('exec',{
  171. sql: 'select a a, b B from t order by a limit 3',
  172. callback: resultRowTest1,
  173. rowMode: 'object'
  174. }, function(ev){
  175. T.assert(3===resultRowTest1.counter);
  176. resultRowTest1.counter = 0;
  177. });
  178. const resultRowTest2 = function f(ev){
  179. if(null === ev.rowNumber){
  180. /* End of result set. */
  181. T.assert(undefined === ev.row)
  182. .assert(1===ev.columnNames.length)
  183. .assert('a'===ev.columnNames[0])
  184. }else{
  185. T.assert(ev.rowNumber > 0);
  186. f.counter = ev.rowNumber;
  187. }
  188. log("exec() result row:",ev);
  189. T.assert(null === ev.rowNumber || 'number' === typeof ev.row);
  190. };
  191. await wtest('exec',{
  192. sql: 'select a a from t limit 3',
  193. callback: resultRowTest2,
  194. rowMode: 0
  195. }, function(ev){
  196. T.assert(3===resultRowTest2.counter);
  197. });
  198. const resultRowTest3 = function f(ev){
  199. if(null === ev.rowNumber){
  200. T.assert(3===ev.columnNames.length)
  201. .assert('foo'===ev.columnNames[0])
  202. .assert('bar'===ev.columnNames[1])
  203. .assert('baz'===ev.columnNames[2]);
  204. }else{
  205. f.counter = ev.rowNumber;
  206. T.assert('number' === typeof ev.row);
  207. }
  208. };
  209. await wtest('exec',{
  210. sql: "select 'foo' foo, a bar, 'baz' baz from t limit 2",
  211. callback: resultRowTest3,
  212. columnNames: [],
  213. rowMode: '$bar'
  214. }, function(ev){
  215. log("exec() result row:",ev);
  216. T.assert(2===resultRowTest3.counter);
  217. });
  218. await wtest('exec',{
  219. sql:[
  220. 'pragma foreign_keys=0;',
  221. // ^^^ arbitrary query with no result columns
  222. 'select a, b from t order by a desc; select a from t;'
  223. // exec() only honors SELECT results from the first
  224. // statement with result columns (regardless of whether
  225. // it has any rows).
  226. ],
  227. rowMode: 1,
  228. resultRows: []
  229. },function(ev){
  230. const rows = ev.result.resultRows;
  231. T.assert(3===rows.length).
  232. assert(6===rows[0]);
  233. });
  234. await wtest('exec',{sql: 'delete from t where a>3'});
  235. await wtest('exec',{
  236. sql: 'select count(a) from t',
  237. resultRows: []
  238. },function(ev){
  239. ev = ev.result;
  240. T.assert(1===ev.resultRows.length)
  241. .assert(2===ev.resultRows[0][0]);
  242. });
  243. await wtest('export', function(ev){
  244. ev = ev.result;
  245. T.assert('string' === typeof ev.filename)
  246. .assert(ev.byteArray instanceof Uint8Array)
  247. .assert(ev.byteArray.length > 1024)
  248. .assert('application/x-sqlite3' === ev.mimetype);
  249. });
  250. /***** close() tests must come last. *****/
  251. await wtest('close',{},function(ev){
  252. T.assert('string' === typeof ev.result.filename);
  253. });
  254. await wtest('close', (ev)=>{
  255. T.assert(undefined === ev.result.filename);
  256. }).finally(()=>logHtml('',"That's all, folks!"));
  257. }/*runTests2()*/;
  258. runTests();
  259. })();