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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. lastInsertRowId: true,
  107. countChanges: sqConfig.bigIntEnabled ? 64 : true
  108. }, function(ev){
  109. ev = ev.result;
  110. T.assert(0===ev.resultRows.length)
  111. .assert(0===ev.columnNames.length)
  112. .assert(sqConfig.bigIntEnabled
  113. ? (3n===ev.changeCount)
  114. : (3===ev.changeCount))
  115. .assert('bigint'===typeof ev.lastInsertRowId)
  116. .assert(ev.lastInsertRowId>=3);
  117. });
  118. await wtest('exec',{
  119. sql: 'select a a, b b from t order by a',
  120. resultRows: [], columnNames: [],
  121. }, function(ev){
  122. ev = ev.result;
  123. T.assert(3===ev.resultRows.length)
  124. .assert(1===ev.resultRows[0][0])
  125. .assert(6===ev.resultRows[2][1])
  126. .assert(2===ev.columnNames.length)
  127. .assert('b'===ev.columnNames[1]);
  128. });
  129. await wtest('exec',{
  130. sql: 'select a a, b b from t order by a',
  131. resultRows: [], columnNames: [],
  132. rowMode: 'object',
  133. countChanges: true
  134. }, function(ev){
  135. ev = ev.result;
  136. T.assert(3===ev.resultRows.length)
  137. .assert(1===ev.resultRows[0].a)
  138. .assert(6===ev.resultRows[2].b)
  139. .assert(0===ev.changeCount);
  140. });
  141. await wtest(
  142. 'exec',
  143. {sql:'intentional_error'},
  144. mustNotReach
  145. ).catch((e)=>{
  146. warn("Intentional error:",e);
  147. });
  148. await wtest('exec',{
  149. sql:'select 1 union all select 3',
  150. resultRows: []
  151. }, function(ev){
  152. ev = ev.result;
  153. T.assert(2 === ev.resultRows.length)
  154. .assert(1 === ev.resultRows[0][0])
  155. .assert(3 === ev.resultRows[1][0])
  156. .assert(undefined === ev.changeCount);
  157. });
  158. const resultRowTest1 = function f(ev){
  159. if(undefined === f.counter) f.counter = 0;
  160. if(null === ev.rowNumber){
  161. /* End of result set. */
  162. T.assert(undefined === ev.row)
  163. .assert(2===ev.columnNames.length)
  164. .assert('a'===ev.columnNames[0])
  165. .assert('B'===ev.columnNames[1]);
  166. }else{
  167. T.assert(ev.rowNumber > 0);
  168. ++f.counter;
  169. }
  170. log("exec() result row:",ev);
  171. T.assert(null === ev.rowNumber || 'number' === typeof ev.row.B);
  172. };
  173. await wtest('exec',{
  174. sql: 'select a a, b B from t order by a limit 3',
  175. callback: resultRowTest1,
  176. rowMode: 'object'
  177. }, function(ev){
  178. T.assert(3===resultRowTest1.counter);
  179. resultRowTest1.counter = 0;
  180. });
  181. const resultRowTest2 = function f(ev){
  182. if(null === ev.rowNumber){
  183. /* End of result set. */
  184. T.assert(undefined === ev.row)
  185. .assert(1===ev.columnNames.length)
  186. .assert('a'===ev.columnNames[0])
  187. }else{
  188. T.assert(ev.rowNumber > 0);
  189. f.counter = ev.rowNumber;
  190. }
  191. log("exec() result row:",ev);
  192. T.assert(null === ev.rowNumber || 'number' === typeof ev.row);
  193. };
  194. await wtest('exec',{
  195. sql: 'select a a from t limit 3',
  196. callback: resultRowTest2,
  197. rowMode: 0
  198. }, function(ev){
  199. T.assert(3===resultRowTest2.counter);
  200. });
  201. const resultRowTest3 = function f(ev){
  202. if(null === ev.rowNumber){
  203. T.assert(3===ev.columnNames.length)
  204. .assert('foo'===ev.columnNames[0])
  205. .assert('bar'===ev.columnNames[1])
  206. .assert('baz'===ev.columnNames[2]);
  207. }else{
  208. f.counter = ev.rowNumber;
  209. T.assert('number' === typeof ev.row);
  210. }
  211. };
  212. await wtest('exec',{
  213. sql: "select 'foo' foo, a bar, 'baz' baz from t limit 2",
  214. callback: resultRowTest3,
  215. columnNames: [],
  216. rowMode: '$bar'
  217. }, function(ev){
  218. log("exec() result row:",ev);
  219. T.assert(2===resultRowTest3.counter);
  220. });
  221. await wtest('exec',{
  222. sql:[
  223. 'pragma foreign_keys=0;',
  224. // ^^^ arbitrary query with no result columns
  225. 'select a, b from t order by a desc; select a from t;'
  226. // exec() only honors SELECT results from the first
  227. // statement with result columns (regardless of whether
  228. // it has any rows).
  229. ],
  230. rowMode: 1,
  231. resultRows: []
  232. },function(ev){
  233. const rows = ev.result.resultRows;
  234. T.assert(3===rows.length).
  235. assert(6===rows[0]);
  236. });
  237. await wtest('exec',{sql: 'delete from t where a>3'});
  238. await wtest('exec',{
  239. sql: 'select count(a) from t',
  240. resultRows: []
  241. },function(ev){
  242. ev = ev.result;
  243. T.assert(1===ev.resultRows.length)
  244. .assert(2===ev.resultRows[0][0]);
  245. });
  246. await wtest('export', function(ev){
  247. ev = ev.result;
  248. T.assert('string' === typeof ev.filename)
  249. .assert(ev.byteArray instanceof Uint8Array)
  250. .assert(ev.byteArray.length > 1024)
  251. .assert('application/x-sqlite3' === ev.mimetype);
  252. });
  253. /***** close() tests must come last. *****/
  254. await wtest('close',{},function(ev){
  255. T.assert('string' === typeof ev.result.filename);
  256. });
  257. await wtest('close', (ev)=>{
  258. T.assert(undefined === ev.result.filename);
  259. }).finally(()=>logHtml('',"That's all, folks!"));
  260. }/*runTests2()*/;
  261. runTests();
  262. })();