1. 1// MIT License
2. 1//
3. 1// Copyright (c) 2021 Kai Zhu
4. 1//
5. 1// Permission is hereby granted, free of charge, to any person obtaining a copy
6. 1// of this software and associated documentation files (the "Software"), to deal
7. 1// in the Software without restriction, including without limitation the rights
8. 1// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9. 1// copies of the Software, and to permit persons to whom the Software is
10. 1// furnished to do so, subject to the following conditions:
11. 1//
12. 1// The above copyright notice and this permission notice shall be included in
13. 1// all copies or substantial portions of the Software.
14. 1//
15. 1// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16. 1// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17. 1// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18. 1// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19. 1// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20. 1// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21. 1// SOFTWARE.
22. 1
23. 1
24. 1/*jslint beta, bitwise, name, node*/
25. 1/*global FinalizationRegistry*/
26. 1"use strict";
27. 1
28. 1const JSBATON_ARGC = 8;
29. 1const JSBATON_OFFSET_ALL = 256;
30. 1const JSBATON_OFFSET_ARGV = 128;
31. 1const JSBATON_OFFSET_BUFV = 192;
32. 1// const JSBATON_OFFSET_ERRMSG = 48;
33. 1const JSBATON_OFFSET_FUNCNAME = 8;
34. 1const JS_MAX_SAFE_INTEGER = 0x1f_ffff_ffff_ffff;
35. 1const JS_MIN_SAFE_INTEGER = -0x1f_ffff_ffff_ffff;
36. 1const SIZEOF_BLOB_MAX = 1_000_000_000;
37. 1// const SIZEOF_ERRMSG = 80;
38. 1const SIZEOF_FUNCNAME = 16;
39. 1const SQLITE_DATATYPE_BLOB = 0x04;
40. 1const SQLITE_DATATYPE_EXTERNALBUFFER = 0x71;
41. 1const SQLITE_DATATYPE_FLOAT = 0x02;
42. 1const SQLITE_DATATYPE_INTEGER = 0x01;
43. 1const SQLITE_DATATYPE_INTEGER_0 = 0x00;
44. 1const SQLITE_DATATYPE_INTEGER_1 = 0x21;
45. 1const SQLITE_DATATYPE_NULL = 0x05;
46. 1const SQLITE_DATATYPE_TEXT = 0x03;
47. 1const SQLITE_DATATYPE_TEXT_0 = 0x13;
48. 1const SQLITE_RESPONSETYPE_LASTBLOB = 1;
49. 1const SQLITE_RESPONSETYPE_LASTVALUE = 2;
50. 1
51. 1const FILENAME_DBTMP = "/tmp/__dbtmp1"; //jslint-ignore-line
52. 1
53. 1const LGBM_DTYPE_FLOAT32 = 0; /* float32 (single precision float)*/
54. 1const LGBM_DTYPE_FLOAT64 = 1; /* float64 (double precision float)*/
55. 1const LGBM_DTYPE_INT32 = 2; /* int32*/
56. 1const LGBM_DTYPE_INT64 = 3; /* int64*/
57. 1const LGBM_FEATURE_IMPORTANCE_GAIN = 1; /* Gain type of feature importance*/
58. 1const LGBM_FEATURE_IMPORTANCE_SPLIT = 0;/* Split type of feature importance*/
59. 1const LGBM_MATRIX_TYPE_CSC = 1; /* CSC sparse matrix type*/
60. 1const LGBM_MATRIX_TYPE_CSR = 0; /* CSR sparse matrix type*/
61. 1const LGBM_PREDICT_CONTRIB = 3; /* Predict feature contributions (SHAP values)*/
62. 1const LGBM_PREDICT_LEAF_INDEX = 2; /* Predict leaf index*/
63. 1const LGBM_PREDICT_NORMAL = 0; /* Normal prediction w/ transform (if needed)*/
64. 1const LGBM_PREDICT_RAW_SCORE = 1; /* Predict raw score*/
65. 1const SQLITE_OPEN_AUTOPROXY = 0x00000020; /* VFS only */
66. 1const SQLITE_OPEN_CREATE = 0x00000004; /* Ok for sqlite3_open_v2() */
67. 1const SQLITE_OPEN_DELETEONCLOSE = 0x00000008; /* VFS only */
68. 1const SQLITE_OPEN_EXCLUSIVE = 0x00000010; /* VFS only */
69. 1const SQLITE_OPEN_FULLMUTEX = 0x00010000; /* Ok for sqlite3_open_v2() */
70. 1const SQLITE_OPEN_MAIN_DB = 0x00000100; /* VFS only */
71. 1const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; /* VFS only */
72. 1const SQLITE_OPEN_MEMORY = 0x00000080; /* Ok for sqlite3_open_v2() */
73. 1const SQLITE_OPEN_NOFOLLOW = 0x01000000; /* Ok for sqlite3_open_v2() */
74. 1const SQLITE_OPEN_NOMUTEX = 0x00008000; /* Ok for sqlite3_open_v2() */
75. 1const SQLITE_OPEN_PRIVATECACHE = 0x00040000; /* Ok for sqlite3_open_v2() */
76. 1const SQLITE_OPEN_READONLY = 0x00000001; /* Ok for sqlite3_open_v2() */
77. 1const SQLITE_OPEN_READWRITE = 0x00000002; /* Ok for sqlite3_open_v2() */
78. 1const SQLITE_OPEN_SHAREDCACHE = 0x00020000; /* Ok for sqlite3_open_v2() */
79. 1const SQLITE_OPEN_SUBJOURNAL = 0x00002000; /* VFS only */
80. 1const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000; /* VFS only */
81. 1const SQLITE_OPEN_TEMP_DB = 0x00000200; /* VFS only */
82. 1const SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; /* VFS only */
83. 1const SQLITE_OPEN_TRANSIENT_DB = 0x00000400; /* VFS only */
84. 1const SQLITE_OPEN_URI = 0x00000040; /* Ok for sqlite3_open_v2() */
85. 1const SQLITE_OPEN_WAL = 0x00080000; /* VFS only */
86. 1
87. 1let DB_EXEC_PROFILE_DICT = {};
88. 1let DB_EXEC_PROFILE_MODE;
89. 1let DB_EXEC_PROFILE_SQL_LENGTH;
90. 1let DB_STATE = {};
91. 1let IS_BROWSER;
92. 1let SQLMATH_EXE;
93. 1let SQLMATH_NODE;
94. 1let cModule;
95. 1let cModulePath;
96. 1let consoleError = console.error;
97. 1let dbFinalizationRegistry;
98. 1// init debugInline
99. 1let debugInline = (function () {
100. 3 let __consoleError = function () {
101. 3 return;
102. 3 };
103. 1 function debug(...argv) {
104. 1
105. 1// This function will print <argv> to stderr and then return <argv>[0].
106. 1
107. 1 __consoleError("\n\ndebugInline");
108. 1 __consoleError(...argv);
109. 1 __consoleError("\n");
110. 1 return argv[0];
111. 1 }
112. 1 debug(); // Coverage-hack.
113. 1 __consoleError = console.error; //jslint-ignore-line
114. 1 return debug;
115. 1}());
116. 1let moduleChildProcess;
117. 1let moduleChildProcessSpawn;
118. 1let moduleCrypto;
119. 1let moduleFs;
120. 1let moduleFsInitResolveList;
121. 1let modulePath;
122. 1let moduleUrl;
123. 1let {
124. 1 npm_config_mode_debug,
125. 1 npm_config_mode_setup,
126. 1 npm_config_mode_test
127. 1} = typeof process === "object" && process?.env;
128. 1let sqlMessageDict = {}; // dict of web-worker-callbacks
129. 1let sqlMessageId = 0;
130. 1let sqlWorker;
131. 1let version = "v2026.3.1";
132. 1
133. 86async function assertErrorThrownAsync(asyncFunc, regexp) {
134. 86
135. 86// This function will assert calling <asyncFunc> throws an error.
136. 86
137. 86 let err;
138. 86 try {
139. 1 await asyncFunc();
140. 85 } catch (errCaught) {
141. 85 err = errCaught;
142. 85 }
143. 86 assertOrThrow(err, "No error thrown.");
144. 86 assertOrThrow(
145. 83 !regexp || new RegExp(regexp).test(err.message),
146. 86 err
147. 86 );
148. 86}
149. 1
150. 14016function assertInt64(val) {
151. 14016 // This function will assert <val> is within range of c99-signed-long-long.
152. 14016 val = BigInt(val);
153. 14016 if (!(
154. 14009 -9_223_372_036_854_775_808n <= val && val <= 9_223_372_036_854_775_807n
155. 14 )) {
156. 14 throw new Error(
157. 14 `integer ${val} outside signed-64-bit inclusive-range`
158. 14 + " -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807"
159. 14 );
160. 14 }
161. 14016}
162. 1
163. 4930function assertJsonEqual(aa, bb, message) {
164. 4930
165. 4930// This function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>).
166. 4930
167. 4930 aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa), undefined, 1);
168. 4930 bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb), undefined, 1);
169. 3 if (aa !== bb) {
170. 3 throw new Error(
171. 3 "\n" + aa + "\n!==\n" + bb
172. 3 + (
173. 3 typeof message === "string"
174. 3 ? " - " + message
175. 3 : message
176. 3 ? " - " + JSON.stringify(message)
177. 3 : ""
178. 3 )
179. 3 );
180. 3 }
181. 4930}
182. 1
183. 4function assertNumericalEqual(aa, bb, message) {
184. 4
185. 4// This function will assert aa - bb <= Number.EPSILON.
186. 4
187. 4 assertOrThrow(aa, "value cannot be 0 or falsy");
188. 2 if (!(Math.abs((aa - bb) / Math.max(aa, bb)) <= 256 * Number.EPSILON)) {
189. 2 throw new Error(
190. 2 JSON.stringify(aa) + " != " + JSON.stringify(bb) + (
191. 2 message
192. 2 ? " - " + message
193. 2 : ""
194. 2 )
195. 2 );
196. 2 }
197. 4}
198. 1
199. 49203function assertOrThrow(condition, message) {
200. 49203
201. 49203// This function will throw <message> if <condition> is falsy.
202. 49203
203. 70 if (!condition) {
204. 70 throw (
205. 70 (!message || typeof message === "string")
206. 70 ? new Error(String(message).slice(0, 2048))
207. 70 : message
208. 70 );
209. 70 }
210. 49203}
211. 1
212. 15async function childProcessSpawn2(command, args, option) {
213. 15
214. 15// This function will run child_process.spawn as a promise.
215. 15
216. 15 return await new Promise(function (resolve, reject) {
217. 15 let bufList = [[], [], []];
218. 15 let child;
219. 15 let {
220. 15 modeCapture,
221. 15 modeDebug,
222. 15 stdio = []
223. 15 } = option;
224. 1 if (modeDebug) {
225. 1 consoleError(
226. 1 `childProcessSpawn2 - ${command} ${JSON.stringify(args)}`
227. 1 );
228. 1 }
229. 15 child = moduleChildProcessSpawn(
230. 15 command,
231. 15 args,
232. 15 Object.assign({}, option, {
233. 15 stdio: [
234. 15 "ignore",
235. 15 (
236. 15 modeCapture
237. 1 ? "pipe"
238. 14 : stdio[1]
239. 15 ),
240. 15 (
241. 15 modeCapture
242. 1 ? "pipe"
243. 14 : stdio[2]
244. 15 )
245. 15 ]
246. 15 })
247. 15 );
248. 1 if (modeCapture) {
249. 1 [
250. 1 child.stdin, child.stdout, child.stderr
251. 3 ].forEach(function (pipe, ii) {
252. 1 if (ii === 0) {
253. 1 return;
254. 2 }
255. 2 pipe.on("data", function (chunk) {
256. 2 bufList[ii].push(chunk);
257. 2 if (stdio[ii] !== "ignore") {
258. 2 switch (ii) {
259. 2 case 1:
260. 2 process.stdout.write(chunk);
261. 2 break;
262. 2 case 2:
263. 2 process.stderr.write(chunk);
264. 2 break;
265. 2 }
266. 2 }
267. 2 });
268. 2 });
269. 1 }
270. 15 child.on("exit", function (exitCode) {
271. 15 let resolve0 = resolve;
272. 15 let stderr;
273. 15 let stdout;
274. 15 // coverage-hack
275. 15 if (exitCode || npm_config_mode_test) {
276. 15 resolve = reject;
277. 15 }
278. 15 // coverage-hack
279. 15 if (npm_config_mode_test) {
280. 15 resolve = resolve0;
281. 15 }
282. 15 [
283. 15 stdout, stderr
284. 30 ] = bufList.slice(1).map(function (buf) {
285. 30 return (
286. 30 typeof modeCapture === "string"
287. 2 ? Buffer.concat(buf).toString(modeCapture)
288. 28 : Buffer.concat(buf)
289. 30 );
290. 30 });
291. 15 resolve([
292. 15 exitCode, stdout, stderr
293. 15 ]);
294. 15 });
295. 15 });
296. 15}
297. 1
298. 7async function ciBuildExt({
299. 7 process
300. 7}) {
301. 7
302. 7// This function will build sqlmath from c.
303. 7
304. 7 let binNodegyp;
305. 7 let exitCode;
306. 7 binNodegyp = modulePath.resolve(
307. 7 modulePath.dirname(process.execPath || ""),
308. 7 "node_modules/npm/node_modules/node-gyp/bin/node-gyp.js"
309. 7 ).replace("/bin/node_modules/", "/lib/node_modules/");
310. 7 if (!noop(
311. 7 await fsExistsUnlessTest(cModulePath)
312. 7 )) {
313. 7 await ciBuildExt1NodejsConfigure({
314. 7 binNodegyp,
315. 7 process
316. 7 });
317. 7 }
318. 7 consoleError(
319. 7 `ciBuildExt2Nodejs - linking lib ${modulePath.resolve(cModulePath)}`
320. 7 );
321. 7 [
322. 7 exitCode
323. 7 ] = await childProcessSpawn2(
324. 7 "sh",
325. 7 [
326. 7 "-c",
327. 7 (`
328. 7(set -e
329. 7 # rebuild binding
330. 7 rm -rf build/Release/obj/SRC_SQLMATH_CUSTOM/
331. 7 node "${binNodegyp}" build --release
332. 7 # node "${binNodegyp}" build --release --loglevel=verbose
333. 7 mv build/Release/binding.node "${cModulePath}"
334. 7 mv build/Release/shell "${SQLMATH_EXE}"
335. 7 # ugly-hack - win32-sqlite-shell doesn't like nodejs-builtin-zlib,
336. 7 # so link with external-zlib.
337. 7 if (uname | grep -q "MING\\|MSYS")
338. 7 then
339. 7 rm -f ${SQLMATH_EXE}
340. 7 python setup.py exe_link \
341. 7 ./build/Release/SRC_SQLITE_BASE.lib \
342. 7 ./build/Release/SRC_SQLMATH_CUSTOM.lib \
343. 7 ./build/Release/obj/shell/sqlmath_external_sqlite.obj \
344. 7 ./zlib.v1.3.1.vcpkg.x64-windows-static.lib \
345. 7 \
346. 7 -ltcg \
347. 7 -nologo \
348. 7 -out:${SQLMATH_EXE} \
349. 7 -subsystem:console
350. 7 fi
351. 7)
352. 7 `)
353. 7 ],
354. 7 {modeDebug: npm_config_mode_debug, stdio: ["ignore", 1, 2]}
355. 7 );
356. 7 assertOrThrow(!exitCode, `ciBuildExt - exitCode=${exitCode}`);
357. 7}
358. 1
359. 7async function ciBuildExt1NodejsConfigure({
360. 7 binNodegyp
361. 7 // process
362. 7}) {
363. 7
364. 7// This function will setup posix/win32 env for building c-extension.
365. 7
366. 7 let cflagWallList = [];
367. 7 let cflagWnoList = [];
368. 7 String(
369. 7 await fsReadFileUnlessTest(".ci.sh", "utf8", (`
370. 7SQLMATH_CFLAG_WALL_LIST=" \\
371. 7"
372. 7SQLMATH_CFLAG_WNO_LIST=" \\
373. 7"
374. 7 `))
375. 7 ).replace((
376. 7 /(SQLMATH_CFLAG_WALL_LIST|SQLMATH_CFLAG_WNO_LIST)=" \\([\S\s]*?)"/g
377. 14 ), function (ignore, cflagType, cflagList) {
378. 14 cflagList = cflagList.split(/[\s\\]/).filter(noop);
379. 14 switch (cflagType) {
380. 7 case "SQLMATH_CFLAG_WALL_LIST":
381. 7 cflagWallList = cflagList;
382. 7 break;
383. 7 case "SQLMATH_CFLAG_WNO_LIST":
384. 7 cflagWnoList = cflagList;
385. 7 break;
386. 14 }
387. 14 return "";
388. 14 });
389. 7 consoleError(`ciBuildExt1Nodejs - configure binding.gyp`);
390. 7 await fsWriteFileUnlessTest("binding.gyp", JSON.stringify({
391. 7 "target_defaults": {
392. 7 "cflags": cflagWallList,
393. 7// https://github.com/nodejs/node-gyp/blob/v10.3.1/gyp/pylib/gyp/MSVSSettings.py
394. 7 "msvs_settings": {
395. 7 "VCCLCompilerTool": {
396. 7 "WarnAsError": 1,
397. 7 "WarningLevel": 4
398. 7 }
399. 7 },
400. 7 "xcode_settings": {
401. 7 "OTHER_CFLAGS": cflagWallList
402. 7 }
403. 7 },
404. 7 "targets": [
405. 7 {
406. 7 "cflags": cflagWnoList,
407. 7 "defines": [
408. 7 "SRC_SQLITE_BASE_C2"
409. 7 ],
410. 7 "msvs_settings": {
411. 7 "VCCLCompilerTool": {
412. 7 "WarnAsError": 1,
413. 7 "WarningLevel": 2
414. 7 }
415. 7 },
416. 7 "sources": [
417. 7 "sqlmath_external_sqlite.c"
418. 7 ],
419. 7 "target_name": "SRC_SQLITE_BASE",
420. 7 "type": "static_library",
421. 7 "xcode_settings": {
422. 7 "OTHER_CFLAGS": cflagWnoList
423. 7 }
424. 7 },
425. 7 {
426. 7 "defines": [
427. 7 "SRC_SQLMATH_BASE_C2",
428. 7 "SRC_SQLMATH_CUSTOM_C2"
429. 7 ],
430. 7 "dependencies": [
431. 7 "SRC_SQLITE_BASE"
432. 7 ],
433. 7 "sources": [
434. 7 "sqlmath_base.c",
435. 7 "sqlmath_custom.c"
436. 7 ],
437. 7 "target_name": "SRC_SQLMATH_CUSTOM",
438. 7 "type": "static_library"
439. 7 },
440. 7 {
441. 7 "defines": [
442. 7 "SRC_SQLMATH_NODEJS_C2"
443. 7 ],
444. 7 "dependencies": [
445. 7 "SRC_SQLMATH_CUSTOM"
446. 7 ],
447. 7 "sources": [
448. 7 "sqlmath_base.c"
449. 7 ],
450. 7 "target_name": "binding"
451. 7 },
452. 7 {
453. 7 "conditions": [
454. 7 [
455. 7 "OS==\"win\"",
456. 7 {},
457. 7 {
458. 7 "libraries": [
459. 7 "-lz"
460. 7 ]
461. 7 }
462. 7 ]
463. 7 ],
464. 7 "defines": [
465. 7 "SRC_SQLITE_SHELL_C2"
466. 7 ],
467. 7 "dependencies": [
468. 7 "SRC_SQLMATH_CUSTOM"
469. 7 ],
470. 7 "sources": [
471. 7 "sqlmath_external_sqlite.c"
472. 7 ],
473. 7 "target_name": "shell",
474. 7 "type": "executable"
475. 7 }
476. 7 ]
477. 7 }, undefined, 4) + "\n");
478. 7 await childProcessSpawn2(
479. 7 "sh",
480. 7 [
481. 7 "-c",
482. 7 (`
483. 7(set -e
484. 7 # node "${binNodegyp}" clean
485. 7 node "${binNodegyp}" configure
486. 7)
487. 7 `)
488. 7 ],
489. 7 {modeDebug: npm_config_mode_debug, stdio: ["ignore", 1, 2]}
490. 7 );
491. 7}
492. 1
493. 3912async function dbCallAsync(baton, argList, mode, db) {
494. 3912
495. 3912// This function will call c-function dbXxx() with given <funcname>
496. 3912// and return [<baton>, ...argList].
497. 3912
498. 3912 let errStack;
499. 3912 let funcname;
500. 3912 let id;
501. 3912 let profileObj;
502. 3912 let profileStart;
503. 3912 let result;
504. 3912 let sql;
505. 3912 let timeElapsed;
506. 3912 // If argList contains <db>, then mark it as busy.
507. 2025 if (mode === "modeDbExec" || mode === "modeDbFile") {
508. 1902 // init db
509. 1902 db = argList[0];
510. 1902 assertOrThrow(
511. 1902 db.busy >= 0,
512. 1902 `dbCallAsync - invalid db.busy = ${db.busy}`
513. 1902 );
514. 1902 db.ii = (db.ii + 1) % db.connPool.length;
515. 1902 db.ptr = db.connPool[db.ii][0];
516. 1902 // increment db.busy
517. 1902 db.busy += 1;
518. 1902 // init profileObj
519. 1902 if (DB_EXEC_PROFILE_MODE && mode === "modeDbExec") {
520. 1902 profileStart = Date.now();
521. 1902 sql = String(argList[1]);
522. 1902 // sql-hash - remove comment
523. 1902 sql = sql.replace((/(?:^|\s+?)--.*/gm), "");
524. 1902 // sql-hash - remove vowel
525. 1902 sql = sql.replace((/[aeiou]\b/gi), "\u0000$&");
526. 1902 sql = sql.replace((/([bcdfghjklmnpqrstvwxyz])[aeiou]+/gi), "$1");
527. 1902 sql = sql.replace((/\u0000([aeiou])\b/gi), "$1");
528. 1902 // sql-hash - remove underscore
529. 1902 sql = sql.replace((/_+/g), "");
530. 1902 // sql-hash - truncate long text
531. 1902 sql = sql.replace((/(\S{16})\S+/g), "$1");
532. 1902 // sql-hash - remove whitespace
533. 1902 sql = sql.replace((/\s+/g), " ");
534. 1902 sql = sql.trim().slice(0, DB_EXEC_PROFILE_SQL_LENGTH);
535. 1902 DB_EXEC_PROFILE_DICT[sql] = DB_EXEC_PROFILE_DICT[sql] || {
536. 1902 busy: 0,
537. 1902 count: 0,
538. 1902 sql,
539. 1902 timeElapsed: 0
540. 1902 };
541. 1902 profileObj = DB_EXEC_PROFILE_DICT[sql];
542. 1902 // increment profileObj.busy
543. 1902 profileObj.busy += 1;
544. 1902 profileObj.count += 1;
545. 1902 }
546. 1902 try {
547. 1902 return await dbCallAsync(
548. 1902 baton,
549. 1902 [
550. 1902 db.ptr,
551. 1902 ...argList.slice(1)
552. 1902 ],
553. 1902 undefined,
554. 1902 db
555. 1902 );
556. 1902 } finally {
557. 1902 // decrement db.busy
558. 1902 db.busy -= 1;
559. 1902 assertOrThrow(
560. 1902 db.busy >= 0,
561. 1902 `dbCallAsync - invalid db.busy = ${db.busy}`
562. 1902 );
563. 1902 // update profileObj
564. 1902 if (profileObj) {
565. 1902 // decrement profileObj.busy
566. 1902 profileObj.busy -= 1;
567. 1902 assertOrThrow(
568. 1902 profileObj.busy >= 0,
569. 1902 `dbCallAsync - invalid profileObj.busy = ${profileObj.busy}`
570. 1902 );
571. 1902 if (profileObj.busy === 0) {
572. 1902 profileObj.timeElapsed += Date.now() - profileStart;
573. 1902 }
574. 1902 }
575. 1902 }
576. 2010 }
577. 2010 // copy argList to avoid side-effect
578. 2010 argList = [...argList];
579. 2010 assertOrThrow(
580. 2010 argList.length <= JSBATON_ARGC,
581. 2010 `dbCallAsync - argList.length must be less than than ${JSBATON_ARGC}`
582. 2010 );
583. 2010 // pad argList to length JSBATON_ARGC
584. 6221 while (argList.length < JSBATON_ARGC) {
585. 6221 argList.push(0n);
586. 6221 }
587. 2010 // serialize js-value to c-value
588. 15942 argList = argList.map(function (val, argi) {
589. 15941 if (val === null || val === undefined) {
590. 2010 val = 0;
591. 2010 }
592. 15942 switch (typeof val) {
593. 8039 case "bigint":
594. 9929 case "boolean":
595. 13984 case "number":
596. 13984 // check for min/max safe-integer
597. 13984 assertOrThrow(
598. 13984 (
599. 13984 (JS_MIN_SAFE_INTEGER <= val && val <= JS_MAX_SAFE_INTEGER)
600. 13984 || typeof val === "bigint"
601. 13984 ),
602. 13984 (
603. 13984 "dbCallAsync - "
604. 13984 + "non-bigint-integer must be within inclusive-range"
605. 13984 + ` ${JS_MIN_SAFE_INTEGER} to ${JS_MAX_SAFE_INTEGER}`
606. 13984 )
607. 13984 );
608. 13984 val = BigInt(val);
609. 13984 assertInt64(val);
610. 13984 baton.setBigInt64(JSBATON_OFFSET_ARGV + argi * 8, val, true);
611. 13984 return val;
612. 15942 // case "object":
613. 15942 // break;
614. 2010 case "string":
615. 2010 baton = jsbatonSetValue(baton, argi, (
616. 2010 val.endsWith("\u0000")
617. 2010 ? val
618. 2010 // append null-terminator to string
619. 2010 : val + "\u0000"
620. 2010 ));
621. 2010 return;
622. 2010 }
623. 2010 assertOrThrow(
624. 2010 !ArrayBuffer.isView(val) || val.byteOffset === 0,
625. 15942 (
626. 15942 "dbCallAsync - argList cannot contain arraybuffer-views"
627. 15942 + " with non-zero byteOffset"
628. 15942 )
629. 15942 );
630. 2010 if (isExternalBuffer(val)) {
631. 2010 return val;
632. 2010 }
633. 2010 throw new Error(`dbCallAsync - invalid arg-type "${typeof val}"`);
634. 2010 });
635. 2010 // assert byteOffset === 0
636. 17883 [baton, ...argList].forEach(function (arg) {
637. 2010 assertOrThrow(!ArrayBuffer.isView(arg) || arg.byteOffset === 0, arg);
638. 17883 });
639. 2010 // extract funcname
640. 2010 funcname = new TextDecoder().decode(
641. 2010 new DataView(baton.buffer, JSBATON_OFFSET_FUNCNAME, SIZEOF_FUNCNAME)
642. 2010 ).replace((/\u0000/g), "");
643. 2010 // preserve stack-trace
644. 2010 errStack = new Error().stack.replace((/.*$/m), "");
645. 2010 try {
646. 2010
647. 2010// Dispatch to nodejs-napi.
648. 2010
649. 2010 if (!IS_BROWSER) {
650. 1985 await cModule._jspromiseCreate(baton.buffer, argList, funcname);
651. 1985 // prepend baton to argList
652. 1985 return [baton, ...argList];
653. 1985 }
654. 2
655. 2// Dispatch to web-worker.
656. 2
657. 2 // increment sqlMessageId
658. 2 sqlMessageId += 1;
659. 2 id = sqlMessageId;
660. 2 // postMessage to web-worker
661. 2 sqlWorker.postMessage(
662. 2 {
663. 2 FILENAME_DBTMP,
664. 2 JSBATON_OFFSET_ALL,
665. 2 JSBATON_OFFSET_BUFV,
666. 2 argList,
667. 2 baton,
668. 2 funcname,
669. 2 id
670. 2 },
671. 2 // transfer arraybuffer without copying
672. 2 [baton.buffer, ...argList.filter(isExternalBuffer)]
673. 2 );
674. 2 // init timeElapsed
675. 2 timeElapsed = Date.now();
676. 2 // await result from web-worker
677. 2 result = await new Promise(function (resolve) {
678. 2 sqlMessageDict[id] = resolve;
679. 2 });
680. 2 // cleanup sqlMessageDict
681. 2 delete sqlMessageDict[id];
682. 2 // debug slow postMessage
683. 2 timeElapsed = Date.now() - timeElapsed;
684. 2 if (timeElapsed > 500 || funcname === "testTimeElapsed") {
685. 1 consoleError(
686. 1 "sqlMessagePost - "
687. 1 + JSON.stringify({funcname, timeElapsed})
688. 1 + errStack
689. 1 );
690. 2 }
691. 2 assertOrThrow(!result.errmsg, result.errmsg);
692. 2 // prepend baton to argList
693. 2 return [result.baton, ...result.argList];
694. 55 } catch (err) {
695. 55 // debug db.filename
696. 55 if (db?.filename2 || db?.filename) {
697. 55 err.message += ` (from ${db?.filename2 || db?.filename})`;
698. 55 }
699. 55 err.stack += errStack;
700. 55 assertOrThrow(undefined, err);
701. 55 }
702. 3912}
703. 1
704. 3async function dbCloseAsync(db) {
705. 3
706. 3// This function will close sqlite-database-connection <db>.
707. 3
708. 3 // prevent segfault - do not close db if actions are pending
709. 3 assertOrThrow(
710. 3 db.busy === 0,
711. 3 `dbCloseAsync - cannot close db with ${db.busy} actions pending`
712. 3 );
713. 3 // cleanup connPool
714. 1 await Promise.all(db.connPool.map(async function (ptr) {
715. 1 let val = ptr[0];
716. 1 ptr[0] = 0n;
717. 1 await dbCallAsync(
718. 1 jsbatonCreate("_dbClose"),
719. 1 [
720. 1 val,
721. 1 db.filename
722. 1 ]
723. 1 );
724. 1 }));
725. 1}
726. 1
727. 58function dbExecAndReturnLastBlob(option) {
728. 58
729. 58// This function will exec <sql> in <db>,
730. 58// and return last-value retrieved from execution as raw blob/buffer.
731. 58
732. 58 return dbExecAsync(Object.assign({
733. 58 responseType: "lastblob"
734. 58 }, option));
735. 58}
736. 1
737. 115async function dbExecAndReturnLastRow(option) {
738. 115
739. 115// This function will exec <sql> in <db>,
740. 115// and return last-row or empty-object.
741. 115
742. 101 let result = await dbExecAsync(option);
743. 101 result = result[result.length - 1] || [];
744. 1 result = result[result.length - 1] || {};
745. 115 return result;
746. 115}
747. 1
748. 65async function dbExecAndReturnLastTable(option) {
749. 65
750. 65// This function will exec <sql> in <db>,
751. 65// and return last-table or empty-list.
752. 65
753. 65 let result = await dbExecAsync(option);
754. 1 result = result[result.length - 1] || [];
755. 65 return result;
756. 65}
757. 1
758. 1184function dbExecAndReturnLastValue(option) {
759. 1184
760. 1184// This function will exec <sql> in <db>,
761. 1184// and return last-json-value.
762. 1184
763. 1184 return dbExecAsync(Object.assign({
764. 1184 responseType: "lastvalue"
765. 1184 }, option));
766. 1184}
767. 1
768. 1900async function dbExecAsync({
769. 1900 bindList = [],
770. 1900 db,
771. 1900 modeNoop,
772. 1900 responseType,
773. 1900 sql
774. 1900}) {
775. 1900
776. 1900// This function will exec <sql> in <db> and return <result>.
777. 1900
778. 1900 let baton = jsbatonCreate("_dbExec");
779. 1900 let bindByKey = !Array.isArray(bindList);
780. 1900 let bufi = [0];
781. 1900 let referenceList = [];
782. 1900 let result;
783. 1 if (modeNoop) {
784. 1 return;
785. 1899 }
786. 1899 if (bindByKey) {
787. 1347 Object.entries(bindList).forEach(function ([key, val]) {
788. 1347 baton = jsbatonSetValue(baton, undefined, `:${key}\u0000`);
789. 1347 baton = jsbatonSetValue(
790. 1347 baton,
791. 1347 undefined,
792. 1347 val,
793. 1347 bufi,
794. 1347 referenceList
795. 1347 );
796. 1347 });
797. 1235 } else {
798. 664 bindList.forEach(function (val) {
799. 664 baton = jsbatonSetValue(
800. 664 baton,
801. 664 undefined,
802. 664 val,
803. 664 bufi,
804. 664 referenceList
805. 664 );
806. 664 });
807. 1887 }
808. 1887 [
809. 1887 baton, ...result
810. 1887 ] = await dbCallAsync(
811. 1887 baton,
812. 1887 [
813. 1887 // 0. db
814. 1887 db,
815. 1887 // 1. sql
816. 1887 String(sql) + "\n;\nPRAGMA noop",
817. 1887 // 2. bindList.length
818. 1887 (
819. 1887 bindByKey
820. 1887 ? Object.keys(bindList).length
821. 652 : bindList.length
822. 1900 ),
823. 1900 // 3. bindByKey
824. 1900 bindByKey,
825. 1900 // 4. responseType
826. 1900 (
827. 1900 responseType === "lastblob"
828. 56 ? SQLITE_RESPONSETYPE_LASTBLOB
829. 1831 : responseType === "lastvalue"
830. 1831 ? SQLITE_RESPONSETYPE_LASTVALUE
831. 1831 : 0
832. 1900 )
833. 1900 ],
834. 1900 "modeDbExec"
835. 1832 );
836. 1832 result = result[0];
837. 1832 if (!IS_BROWSER) {
838. 1832 result = cModule._jsbatonStealCbuffer(
839. 1832 baton.buffer,
840. 1832 0,
841. 1832 Number(
842. 1832 responseType !== "arraybuffer" && responseType !== "lastblob"
843. 1832 )
844. 1832 );
845. 1832 }
846. 1832 switch (responseType) {
847. 1832 case "arraybuffer":
848. 110 case "lastblob":
849. 110 break;
850. 1236 case "lastvalue":
851. 1403 case "list":
852. 1403 result = jsonParseArraybuffer(result);
853. 1403 break;
854. 319 default:
855. 345 result = jsonParseArraybuffer(result).map(function (table) {
856. 345 let colList = table.shift();
857. 13913 return table.map(function (row) {
858. 13913 let dict = {};
859. 43338 colList.forEach(function (key, ii) {
860. 43338 dict[key] = row[ii];
861. 43338 });
862. 13913 return dict;
863. 13913 });
864. 345 });
865. 1832 }
866. 1832 return result;
867. 1832}
868. 1
869. 2function dbExecProfile({
870. 2 limit = 20,
871. 2 lineLength = 80,
872. 2 modeInit,
873. 2 sqlLength = 256
874. 2}) {
875. 2
876. 2// This function will profile dbExecAsync.
877. 2
878. 2 let result;
879. 1 if (modeInit && !DB_EXEC_PROFILE_MODE) {
880. 1 DB_EXEC_PROFILE_MODE = Date.now();
881. 1 DB_EXEC_PROFILE_SQL_LENGTH = sqlLength;
882. 1 process.on("exit", function () {
883. 1 console.error(dbExecProfile({
884. 1 limit,
885. 1 lineLength
886. 1 }));
887. 1 });
888. 1 return;
889. 1 }
890. 1 result = Object.values(DB_EXEC_PROFILE_DICT);
891. 1414 result.sort(function (aa, bb) {
892. 406 return ((bb.timeElapsed - aa.timeElapsed) || (bb.count - aa.count));
893. 1414 });
894. 20 result = result.slice(0, limit).map(function ({
895. 20 count,
896. 20 sql,
897. 20 timeElapsed
898. 20 }, ii) {
899. 20 return String(
900. 20 `${Number(ii + 1).toFixed(0).padStart(2, " ")}.`
901. 20 + ` ${timeElapsed.toFixed(0).padStart(4)}`
902. 20 + ` ${count.toFixed(0).padStart(3)}`
903. 20 + " " + JSON.stringify(sql)
904. 20 ).slice(0, lineLength);
905. 20 }).join("\n");
906. 1 result = (
907. 1 `\ndbExecProfile:\n`
908. 1 + ` # time cnt sql\n`
909. 1 + `${result}\n`
910. 1 );
911. 1 return result;
912. 1}
913. 1
914. 17async function dbFileLoadAsync({
915. 17 db,
916. 17 dbData,
917. 17 filename,
918. 17 modeNoop,
919. 17 modeSave = 0
920. 17}) {
921. 17
922. 17// This function will load <filename> to <db>.
923. 17
924. 17 let filename2;
925. 15 async function _dbFileLoad() {
926. 15 dbData = await dbCallAsync(
927. 15 jsbatonCreate("_dbFileLoad"),
928. 15 [
929. 15 // 0. sqlite3 * pInMemory
930. 15 db,
931. 15 // 1. char *zFilename
932. 15 filename,
933. 15 // 2. const int isSave
934. 15 modeSave,
935. 15 // 3. undefined
936. 15 undefined,
937. 15 // 4. dbData - same position as dbOpenAsync
938. 15 dbData
939. 15 ],
940. 15 "modeDbFile"
941. 15 );
942. 15 }
943. 1 if (modeNoop) {
944. 1 return;
945. 16 }
946. 16 if (IS_BROWSER) {
947. 1 filename = FILENAME_DBTMP;
948. 16 }
949. 16 assertOrThrow(
950. 16 typeof filename === "string" && filename,
951. 17 `invalid filename ${filename}`
952. 17 );
953. 17 db.filename2 = filename;
954. 17 // Save to tmpfile and then atomically-rename to actual-filename.
955. 15 if (moduleFs && modeSave) {
956. 13 filename2 = filename;
957. 13 filename = modulePath.join(
958. 13 modulePath.dirname(filename),
959. 13 `.dbFileSaveAsync.${moduleCrypto.randomUUID()}`
960. 13 );
961. 13 try {
962. 13 await _dbFileLoad();
963. 13 await moduleFs.promises.rename(filename, filename2);
964. 13 } finally {
965. 13 await moduleFs.promises.unlink(filename).catch(noop);
966. 13 }
967. 13 } else {
968. 2 await _dbFileLoad();
969. 15 }
970. 15 return dbData[1 + 0];
971. 15}
972. 1
973. 14async function dbFileSaveAsync({
974. 14 db,
975. 14 dbData,
976. 14 filename,
977. 14 modeNoop
978. 14}) {
979. 14
980. 14// This function will save <db> to <filename>.
981. 14
982. 14 return await dbFileLoadAsync({
983. 14 db,
984. 14 dbData,
985. 14 filename,
986. 14 modeNoop,
987. 14 modeSave: 1
988. 14 });
989. 14}
990. 1
991. 56async function dbNoopAsync(...argList) {
992. 56
993. 56// This function will do nothing except return <argList>.
994. 56
995. 56 return await dbCallAsync(
996. 56 jsbatonCreate("_dbNoop"),
997. 56 argList
998. 56 );
999. 56}
1000. 1
1001. 32async function dbOpenAsync({
1002. 32 afterFinalization,
1003. 32 dbData,
1004. 32 filename = ":memory:",
1005. 32 flags,
1006. 32 threadCount = 1,
1007. 32 timeoutBusy = 5000
1008. 32}) {
1009. 32
1010. 32// This function will open and return sqlite-database-connection <db>.
1011. 32
1012. 32// int sqlite3_open_v2(
1013. 32// const char *filename, /* Database filename (UTF-8) */
1014. 32// sqlite3 **ppDb, /* OUT: SQLite db handle */
1015. 32// int flags, /* Flags */
1016. 32// const char *zVfs /* Name of VFS module to use */
1017. 32// );
1018. 32 let connPool;
1019. 32 let db = {busy: 0, filename, ii: 0};
1020. 32 assertOrThrow(typeof filename === "string", `invalid filename ${filename}`);
1021. 32 assertOrThrow(
1022. 1 !dbData || isExternalBuffer(dbData),
1023. 32 "dbData must be ArrayBuffer"
1024. 32 );
1025. 32 connPool = await Promise.all(Array.from(new Array(
1026. 32 threadCount
1027. 32 ), async function () {
1028. 32 let [ptr] = await dbCallAsync(
1029. 32 jsbatonCreate("_dbOpen"),
1030. 32 [
1031. 32 // 0. const char *filename, Database filename (UTF-8)
1032. 32 filename,
1033. 32 // 1. sqlite3 **ppDb, OUT: SQLite db handle
1034. 32 undefined,
1035. 32 // 2. int flags, Flags
1036. 32 flags ?? (
1037. 32 SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI
1038. 32 ),
1039. 32 // 3. const char *zVfs Name of VFS module to use
1040. 32 undefined,
1041. 32 // 4. wasm-only - arraybuffer of raw sqlite-database
1042. 32 dbData
1043. 32 ]
1044. 32 );
1045. 32 ptr = [ptr.getBigInt64(JSBATON_OFFSET_ARGV + 0, true)];
1046. 32 dbFinalizationRegistry.register(db, {afterFinalization, ptr});
1047. 32 return ptr;
1048. 32 }));
1049. 32 db.connPool = connPool;
1050. 1 if (!IS_BROWSER && !DB_STATE.init) {
1051. 1 DB_STATE.init = true;
1052. 1 await Promise.all([
1053. 1 // PRAGMA busy_timeout
1054. 1 dbExecAsync({
1055. 1 db,
1056. 1 sql: (`
1057. 1PRAGMA busy_timeout = ${timeoutBusy};
1058. 1 `)
1059. 1 }),
1060. 1 // LGBM_DLOPEN
1061. 1 (async function () {
1062. 1 let libLgbm;
1063. 1 libLgbm = process.platform;
1064. 1 libLgbm = libLgbm.replace("darwin", "lib_lightgbm.dylib");
1065. 1 libLgbm = libLgbm.replace("win32", "lib_lightgbm.dll");
1066. 1 libLgbm = libLgbm.replace(process.platform, "lib_lightgbm.so");
1067. 1 libLgbm = `${import.meta.dirname}/sqlmath/${libLgbm}`;
1068. 1 await moduleFs.promises.access(
1069. 1 libLgbm
1070. 1 ).then(async function () {
1071. 1 await dbExecAsync({
1072. 1 db,
1073. 1 sql: (`
1074. 1SELECT LGBM_DLOPEN('${libLgbm}');
1075. 1 `)
1076. 1 });
1077. 1 DB_STATE.lgbm = true;
1078. 1 }).catch(noop);
1079. 1 }())
1080. 1 ]);
1081. 1 }
1082. 32 return db;
1083. 32}
1084. 1
1085. 47async function dbTableImportAsync({
1086. 47 db,
1087. 47 filename,
1088. 47 headerMissing,
1089. 47 mode,
1090. 47 tableName,
1091. 47 textData
1092. 47}) {
1093. 47// This function will create table from imported csv/json <textData>.
1094. 47 let colList;
1095. 47 let rowList;
1096. 47 let rowidList;
1097. 47 let tmp;
1098. 42 if (filename) {
1099. 42 textData = await moduleFs.promises.readFile(filename, "utf8");
1100. 42 }
1101. 47 switch (mode) {
1102. 2 case "csv":
1103. 2 rowList = jsonRowListFromCsv({
1104. 2 csv: textData
1105. 2 });
1106. 2 break;
1107. 43 case "tsv":
1108. 43 rowList = [];
1109. 99001 textData.trimEnd().replace((/.+/g), function (line) {
1110. 99001 rowList.push(line.split("\t"));
1111. 99001 });
1112. 43 break;
1113. 47 // case "json":
1114. 2 default:
1115. 2 rowList = JSON.parse(textData);
1116. 47 }
1117. 1 if (!(typeof rowList === "object" && rowList)) {
1118. 1 rowList = [];
1119. 1 }
1120. 47 // normalize rowList to list
1121. 1 if (!Array.isArray(rowList)) {
1122. 1 rowidList = [];
1123. 2 rowList = Object.entries(rowList).map(function ([
1124. 2 key, val
1125. 2 ]) {
1126. 2 rowidList.push(key);
1127. 2 return val;
1128. 2 });
1129. 1 }
1130. 47 // headerMissing
1131. 42 if (headerMissing && (rowList.length > 0 && Array.isArray(rowList[0]))) {
1132. 714 rowList.unshift(Array.from(rowList[0]).map(function (ignore, ii) {
1133. 714 return String(ii + 1);
1134. 714 }));
1135. 42 }
1136. 47 // normalize rowList[ii] to list
1137. 1 if (rowList.length === 0) {
1138. 1 rowList.push([
1139. 1 "undefined"
1140. 1 ]);
1141. 1 }
1142. 1 if (!Array.isArray(rowList[0])) {
1143. 1 colList = Array.from(
1144. 1 new Set(
1145. 2 rowList.map(function (obj) {
1146. 2 return Object.keys(obj);
1147. 2 }).flat()
1148. 1 )
1149. 1 );
1150. 2 rowList = rowList.map(function (obj) {
1151. 4 return colList.map(function (key) {
1152. 4 return obj[key];
1153. 4 });
1154. 2 });
1155. 1 rowList.unshift(colList);
1156. 1 }
1157. 47 // init colList
1158. 47 colList = rowList.shift();
1159. 47 // preserve rowid
1160. 1 if (rowidList) {
1161. 1 colList.unshift("rowid");
1162. 2 rowList.forEach(function (row, ii) {
1163. 2 row.unshift(rowidList[ii]);
1164. 2 });
1165. 1 }
1166. 47 // normalize colList
1167. 47 tmp = new Set();
1168. 723 colList = colList.map(function (colName) {
1169. 723 let colName2;
1170. 723 let duplicate = 0;
1171. 723 colName = colName.trim();
1172. 723 colName = colName.replace((/\W/g), "_");
1173. 723 colName = colName.replace((/^[^A-Z_a-z]|^$/gm), "_$&");
1174. 724 while (true) {
1175. 724 duplicate += 1;
1176. 724 colName2 = (
1177. 724 duplicate === 1
1178. 724 ? colName
1179. 724 : colName + "_" + duplicate
1180. 724 );
1181. 724 if (!tmp.has(colName2)) {
1182. 724 tmp.add(colName2);
1183. 724 return colName2;
1184. 724 }
1185. 724 }
1186. 723 });
1187. 47 // create dbtable from rowList
1188. 47 await dbExecAsync({
1189. 47 bindList: {
1190. 47 rowList: JSON.stringify(rowList)
1191. 47 },
1192. 47 db,
1193. 47 sql: (
1194. 47 rowList.length === 0
1195. 3 ? `CREATE TABLE ${tableName} (${colList.join(",")});`
1196. 44 : (
1197. 44 `CREATE TABLE ${tableName} AS SELECT `
1198. 719 + colList.map(function (colName, ii) {
1199. 719 return "value->>" + ii + " AS " + colName;
1200. 719 }).join(",")
1201. 44 + " FROM JSON_EACH($rowList);"
1202. 44 )
1203. 47 )
1204. 47 });
1205. 47}
1206. 1
1207. 2async function fsCopyFileUnlessTest(file1, file2, mode) {
1208. 2
1209. 2// This function will copy <file1> to <file2> unless <npm_config_mode_test> = 1.
1210. 2
1211. 1 if (npm_config_mode_test && mode !== "force") {
1212. 1 return;
1213. 1 }
1214. 1 await moduleFs.promises.copyFile(file1, file2, mode | 0);
1215. 1}
1216. 1
1217. 10async function fsExistsUnlessTest(file, mode) {
1218. 10
1219. 10// This function will test if <file> exists unless <npm_config_mode_test> = 1.
1220. 10
1221. 8 if (npm_config_mode_test && mode !== "force") {
1222. 8 return false;
1223. 8 }
1224. 2 try {
1225. 2 await moduleFs.promises.access(file);
1226. 1 return true;
1227. 1 } catch (ignore) {
1228. 1 return false;
1229. 1 }
1230. 10}
1231. 1
1232. 22async function fsReadFileUnlessTest(file, mode, defaultData) {
1233. 22
1234. 22// This function will read <data> from <file> unless <npm_config_mode_test> = 1.
1235. 22
1236. 8 if (npm_config_mode_test && mode !== "force") {
1237. 8 return defaultData;
1238. 14 }
1239. 14 return await moduleFs.promises.readFile(
1240. 14 file,
1241. 14 mode && mode.replace("force", "utf8")
1242. 22 );
1243. 22}
1244. 1
1245. 10async function fsWriteFileUnlessTest(file, data, mode) {
1246. 10
1247. 10// This function will write <data> to <file> unless <npm_config_mode_test> = 1.
1248. 10
1249. 9 if (npm_config_mode_test && mode !== "force") {
1250. 9 return;
1251. 9 }
1252. 1 await moduleFs.promises.writeFile(file, data);
1253. 1}
1254. 1
1255. 31function isExternalBuffer(buf) {
1256. 31
1257. 31// This function will check if <buf> is ArrayBuffer.
1258. 31
1259. 17 return buf && buf.constructor === ArrayBuffer;
1260. 31}
1261. 1
1262. 2023function jsbatonCreate(funcname) {
1263. 2023
1264. 2023// This function will create buffer <baton>.
1265. 2023
1266. 2023 let baton = new DataView(new ArrayBuffer(JSBATON_OFFSET_ALL));
1267. 2023 // init nallc, nused
1268. 2023 baton.setInt32(4, JSBATON_OFFSET_ALL, true);
1269. 2023 // copy funcname into baton
1270. 2023 new Uint8Array(
1271. 2023 baton.buffer,
1272. 2023 baton.byteOffset + JSBATON_OFFSET_FUNCNAME,
1273. 2023 SIZEOF_FUNCNAME - 1
1274. 2023 ).set(new TextEncoder().encode(funcname));
1275. 2023 return baton;
1276. 2023}
1277. 1
1278. 24function jsbatonGetInt64(baton, argi) {
1279. 24
1280. 24// This function will return int64-value from <baton> at <argi>.
1281. 24
1282. 24 return baton.getBigInt64(JSBATON_OFFSET_ARGV + argi * 8, true);
1283. 24}
1284. 1
1285. 9function jsbatonGetString(baton, argi) {
1286. 9
1287. 9// This function will return string-value from <baton> at <argi>.
1288. 9
1289. 9 let offset = baton.getInt32(JSBATON_OFFSET_ARGV + argi * 8, true);
1290. 9 return new TextDecoder().decode(new Uint8Array(
1291. 9 baton.buffer,
1292. 9 baton.byteOffset + offset + 1 + 4,
1293. 9 // remove null-terminator from string
1294. 9 baton.getInt32(offset + 1, true) - 1
1295. 9 ));
1296. 9}
1297. 1
1298. 5154function jsbatonSetValue(baton, argi, val, bufi, referenceList) {
1299. 5154
1300. 5154// This function will set <val> to buffer <baton>.
1301. 5154
1302. 5154 let nn;
1303. 5154 let nused;
1304. 5154 let tmp;
1305. 5154 let vsize;
1306. 5154 let vtype;
1307. 5154/*
1308. 5154#define SQLITE_DATATYPE_BLOB 0x04
1309. 5154#define SQLITE_DATATYPE_EXTERNALBUFFER 0x71
1310. 5154#define SQLITE_DATATYPE_FLOAT 0x02
1311. 5154#define SQLITE_DATATYPE_INTEGER 0x01
1312. 5154#define SQLITE_DATATYPE_INTEGER_0 0x00
1313. 5154#define SQLITE_DATATYPE_INTEGER_1 0x21
1314. 5154#define SQLITE_DATATYPE_NULL 0x05
1315. 5154#define SQLITE_DATATYPE_TEXT 0x03
1316. 5154#define SQLITE_DATATYPE_TEXT_0 0x13
1317. 5154 // 1. 0.bigint
1318. 5154 // 2. 0.boolean
1319. 5154 // 3. 0.function
1320. 5154 // 4. 0.number
1321. 5154 // 5. 0.object
1322. 5154 // 6. 0.string
1323. 5154 // 7. 0.symbol
1324. 5154 // 8. 0.undefined
1325. 5154 // 9. 1.bigint
1326. 5154 // 10. 1.boolean
1327. 5154 // 11. 1.function
1328. 5154 // 12. 1.number
1329. 5154 // 13. 1.object
1330. 5154 // 14. 1.string
1331. 5154 // 15. 1.symbol
1332. 5154 // 16. 1.undefined
1333. 5154 // 17. 1.buffer
1334. 5154 // 18. 1.externalbuffer
1335. 5154*/
1336. 5154 // 10. 1.boolean
1337. 5130 if (val === 1 || val === 1n) {
1338. 30 val = true;
1339. 30 }
1340. 5154 switch (
1341. 5154 val
1342. 4773 ? "1." + typeof(val)
1343. 381 : "0." + typeof(val)
1344. 5154 ) {
1345. 5154 // 1. 0.bigint
1346. 24 case "0.bigint":
1347. 5154 // 2. 0.boolean
1348. 30 case "0.boolean":
1349. 5154 // 4. 0.number
1350. 250 case "0.number":
1351. 250 if (Number.isNaN(val)) {
1352. 250 vtype = SQLITE_DATATYPE_NULL;
1353. 250 vsize = 0;
1354. 250 break;
1355. 250 }
1356. 250 vtype = SQLITE_DATATYPE_INTEGER_0;
1357. 250 vsize = 0;
1358. 250 break;
1359. 5154 // 3. 0.function
1360. 5154 // case "0.function":
1361. 5154 // 5. 0.object
1362. 98 case "0.object":
1363. 5154 // 7. 0.symbol
1364. 98 case "0.symbol":
1365. 5154 // 8. 0.undefined
1366. 105 case "0.undefined":
1367. 5154 // 11. 1.function
1368. 119 case "1.function":
1369. 5154 // 15. 1.symbol
1370. 125 case "1.symbol":
1371. 125 // 16. 1.undefined
1372. 125 // case "1.undefined":
1373. 125 vtype = SQLITE_DATATYPE_NULL;
1374. 125 vsize = 0;
1375. 125 break;
1376. 5154 // 6. 0.string
1377. 26 case "0.string":
1378. 26 vtype = SQLITE_DATATYPE_TEXT_0;
1379. 26 vsize = 0;
1380. 26 break;
1381. 5154 // 9. 1.bigint
1382. 42 case "1.bigint":
1383. 42 vtype = SQLITE_DATATYPE_INTEGER;
1384. 42 vsize = 8;
1385. 42 break;
1386. 5154 // 10. 1.boolean
1387. 36 case "1.boolean":
1388. 36 vtype = SQLITE_DATATYPE_INTEGER_1;
1389. 36 vsize = 0;
1390. 36 break;
1391. 5154 // 12. 1.number
1392. 561 case "1.number":
1393. 561 vtype = SQLITE_DATATYPE_FLOAT;
1394. 561 vsize = 8;
1395. 561 break;
1396. 5154 // 14. 1.string
1397. 4032 case "1.string":
1398. 4032 val = new TextEncoder().encode(val);
1399. 4032 vtype = SQLITE_DATATYPE_TEXT;
1400. 4032 vsize = 4 + val.byteLength;
1401. 4032 break;
1402. 5154 // 13. 1.object
1403. 82 default:
1404. 82 // 18. 1.externalbuffer
1405. 82 if (val.constructor === ArrayBuffer) {
1406. 82 assertOrThrow(
1407. 82 !IS_BROWSER,
1408. 82 "external ArrayBuffer cannot be passed directly to wasm"
1409. 82 );
1410. 82 vtype = SQLITE_DATATYPE_EXTERNALBUFFER;
1411. 82 vsize = 4;
1412. 82 break;
1413. 82 }
1414. 82 // 17. 1.buffer
1415. 82 if (ArrayBuffer.isView(val)) {
1416. 82 if (val.byteLength === 0) {
1417. 82 vtype = SQLITE_DATATYPE_NULL;
1418. 82 vsize = 0;
1419. 82 break;
1420. 82 }
1421. 82 vtype = SQLITE_DATATYPE_BLOB;
1422. 82 vsize = 4 + val.byteLength;
1423. 82 break;
1424. 82 }
1425. 82 // 13. 1.object
1426. 82 val = new TextEncoder().encode(
1427. 82 typeof val.toJSON === "function"
1428. 82 ? val.toJSON()
1429. 82 : JSON.stringify(val)
1430. 82 );
1431. 82 vtype = SQLITE_DATATYPE_TEXT;
1432. 82 vsize = 4 + val.byteLength;
1433. 5154 }
1434. 5154 nused = baton.getInt32(4, true);
1435. 5154 nn = nused + 1 + vsize;
1436. 5154 assertOrThrow(
1437. 5154 nn <= 0xffff_ffff,
1438. 5154 "jsbaton cannot exceed 0x7fff_ffff / 2,147,483,647 bytes"
1439. 5154 );
1440. 5154 // exponentially grow baton as needed
1441. 2136 if (baton.byteLength < nn) {
1442. 2136 tmp = baton;
1443. 2136 baton = new DataView(new ArrayBuffer(
1444. 2136 Math.min(2 ** Math.ceil(Math.log2(nn)), 0x7fff_ffff)
1445. 2136 ));
1446. 2136 // update nallc
1447. 2136 baton.setInt32(0, baton.byteLength, true);
1448. 2136 // copy old-baton into new-baton
1449. 2136 new Uint8Array(baton.buffer, baton.byteOffset, nused).set(
1450. 2136 new Uint8Array(tmp.buffer, tmp.byteOffset, nused)
1451. 2136 );
1452. 2136 }
1453. 5154 // push vtype - 1-byte
1454. 5154 baton.setUint8(nused, vtype);
1455. 5154 // update nused
1456. 5154 baton.setInt32(4, nused + 1 + vsize, true);
1457. 5154 // handle blob-value
1458. 5154 switch (vtype) {
1459. 30 case SQLITE_DATATYPE_BLOB:
1460. 4090 case SQLITE_DATATYPE_TEXT:
1461. 4090 // set argv[ii] to blob/text location
1462. 4090 if (argi !== undefined) {
1463. 4090 baton.setInt32(JSBATON_OFFSET_ARGV + argi * 8, nused, true);
1464. 4090 }
1465. 4090 vsize -= 4;
1466. 4090 assertOrThrow(
1467. 4090 0 <= vsize && vsize <= SIZEOF_BLOB_MAX,
1468. 4090 (
1469. 4090 "sqlite-blob byte-length must be within inclusive-range"
1470. 4090 + ` 0 to ${SIZEOF_BLOB_MAX}`
1471. 4090 )
1472. 4090 );
1473. 4090 // push vsize - 4-byte
1474. 4090 baton.setInt32(nused + 1, vsize, true);
1475. 4090 // push SQLITE-BLOB/TEXT - vsize-byte
1476. 4090 new Uint8Array(
1477. 4090 baton.buffer,
1478. 4090 baton.byteOffset + nused + 1 + 4,
1479. 4090 vsize
1480. 4090 ).set(new Uint8Array(val.buffer, val.byteOffset, vsize));
1481. 4090 break;
1482. 12 case SQLITE_DATATYPE_EXTERNALBUFFER:
1483. 12 vsize = val.byteLength;
1484. 12 assertOrThrow(
1485. 12 0 <= vsize && vsize <= SIZEOF_BLOB_MAX,
1486. 12 (
1487. 12 "sqlite-blob byte-length must be within inclusive-range"
1488. 12 + ` 0 to ${SIZEOF_BLOB_MAX}`
1489. 12 )
1490. 12 );
1491. 12 assertOrThrow(
1492. 12 bufi[0] < JSBATON_ARGC,
1493. 12 `cannot pass more than ${JSBATON_ARGC} arraybuffers`
1494. 12 );
1495. 12 // push externalbuffer - 4-byte
1496. 12 baton.setInt32(nused + 1, bufi[0], true);
1497. 12 // set buffer
1498. 12 cModule._jsbatonSetArraybuffer(baton.buffer, bufi[0], val);
1499. 12 // increment bufi
1500. 12 bufi[0] += 1;
1501. 12 // add buffer to reference_list to prevent gc during db_call.
1502. 12 referenceList.push(val);
1503. 12 break;
1504. 561 case SQLITE_DATATYPE_FLOAT:
1505. 561 // push SQLITE-REAL - 8-byte
1506. 561 baton.setFloat64(nused + 1, val, true);
1507. 561 break;
1508. 42 case SQLITE_DATATYPE_INTEGER:
1509. 42 assertInt64(val);
1510. 42 // push SQLITE-INTEGER - 8-byte
1511. 42 baton.setBigInt64(nused + 1, val, true);
1512. 42 break;
1513. 5142 }
1514. 5142 return baton;
1515. 5142}
1516. 1
1517. 1723function jsonParseArraybuffer(buf) {
1518. 1723
1519. 1723// This function will JSON.parse arraybuffer <buf>.
1520. 1723
1521. 1723 return JSON.parse(
1522. 1723 (
1523. 1723 IS_BROWSER
1524. 1 ? new TextDecoder().decode(buf)
1525. 1722 : buf
1526. 1723 )
1527. 1 || "null"
1528. 1723 );
1529. 1723}
1530. 1
1531. 2function jsonRowListFromCsv({
1532. 2 csv
1533. 2}) {
1534. 2// This function will convert <csv>-text to json list-of-list.
1535. 2//
1536. 2// https://tools.ietf.org/html/rfc4180#section-2
1537. 2// Definition of the CSV Format
1538. 2// While there are various specifications and implementations for the
1539. 2// CSV format (for ex. [4], [5], [6] and [7]), there is no formal
1540. 2// specification in existence, which allows for a wide variety of
1541. 2// interpretations of CSV files. This section documents the format that
1542. 2// seems to be followed by most implementations:
1543. 2//
1544. 2// 1. Each record is located on a separate line, delimited by a line
1545. 2// break (CRLF). For example:
1546. 2// aaa,bbb,ccc CRLF
1547. 2// zzz,yyy,xxx CRLF
1548. 2//
1549. 2// 2. The last record in the file may or may not have an ending line
1550. 2// break. For example:
1551. 2// aaa,bbb,ccc CRLF
1552. 2// zzz,yyy,xxx
1553. 2//
1554. 2// 3. There maybe an optional header line appearing as the first line
1555. 2// of the file with the same format as normal record lines. This
1556. 2// header will contain names corresponding to the fields in the file
1557. 2// and should contain the same number of fields as the records in
1558. 2// the rest of the file (the presence or absence of the header line
1559. 2// should be indicated via the optional "header" parameter of this
1560. 2// MIME type). For example:
1561. 2// field_name,field_name,field_name CRLF
1562. 2// aaa,bbb,ccc CRLF
1563. 2// zzz,yyy,xxx CRLF
1564. 2//
1565. 2// 4. Within the header and each record, there may be one or more
1566. 2// fields, separated by commas. Each line should contain the same
1567. 2// number of fields throughout the file. Spaces are considered part
1568. 2// of a field and should not be ignored. The last field in the
1569. 2// record must not be followed by a comma. For example:
1570. 2// aaa,bbb,ccc
1571. 2//
1572. 2// 5. Each field may or may not be enclosed in double quotes (however
1573. 2// some programs, such as Microsoft Excel, do not use double quotes
1574. 2// at all). If fields are not enclosed with double quotes, then
1575. 2// double quotes may not appear inside the fields. For example:
1576. 2// "aaa","bbb","ccc" CRLF
1577. 2// zzz,yyy,xxx
1578. 2//
1579. 2// 6. Fields containing line breaks (CRLF), double quotes, and commas
1580. 2// should be enclosed in double-quotes. For example:
1581. 2// "aaa","b CRLF
1582. 2// bb","ccc" CRLF
1583. 2// zzz,yyy,xxx
1584. 2//
1585. 2// 7. If double-quotes are used to enclose fields, then a double-quote
1586. 2// appearing inside a field must be escaped by preceding it with
1587. 2// another double quote. For example:
1588. 2// "aaa","b""bb","ccc"
1589. 2 let match;
1590. 2 let quote;
1591. 2 let rgx;
1592. 2 let row;
1593. 2 let rowList;
1594. 2 let val;
1595. 2 // normalize "\r\n" to "\n"
1596. 2 csv = csv.trimEnd().replace((
1597. 2 /\r\n?/gu
1598. 2 ), "\n") + "\n";
1599. 2 rgx = (
1600. 2 /(.*?)(""|"|,|\n)/gu
1601. 2 );
1602. 2 rowList = [];
1603. 2 // reset row
1604. 2 row = [];
1605. 2 val = "";
1606. 28 while (true) {
1607. 28 match = rgx.exec(csv);
1608. 28 if (!match) {
1609. 28// 2. The last record in the file may or may not have an ending line
1610. 28// break. For example:
1611. 28// aaa,bbb,ccc CRLF
1612. 28// zzz,yyy,xxx
1613. 28 if (!row.length) {
1614. 28 break;
1615. 28 }
1616. 28 // // if eof missing crlf, then mock it
1617. 28 // rgx.lastIndex = csv.length;
1618. 28 // match = [
1619. 28 // "\n", "", "\n"
1620. 28 // ];
1621. 28 }
1622. 28 // build val
1623. 28 val += match[1];
1624. 28 if (match[2] === "\"") {
1625. 28// 5. Each field may or may not be enclosed in double quotes (however
1626. 28// some programs, such as Microsoft Excel, do not use double quotes
1627. 28// at all). If fields are not enclosed with double quotes, then
1628. 28// double quotes may not appear inside the fields. For example:
1629. 28// "aaa","bbb","ccc" CRLF
1630. 28// zzz,yyy,xxx
1631. 28 quote = !quote;
1632. 28 } else if (quote) {
1633. 28// 7. If double-quotes are used to enclose fields, then a double-quote
1634. 28// appearing inside a field must be escaped by preceding it with
1635. 28// another double quote. For example:
1636. 28// "aaa","b""bb","ccc"
1637. 28 if (match[2] === "\"\"") {
1638. 28 val += "\"";
1639. 28// 6. Fields containing line breaks (CRLF), double quotes, and commas
1640. 28// should be enclosed in double-quotes. For example:
1641. 28// "aaa","b CRLF
1642. 28// bb","ccc" CRLF
1643. 28// zzz,yyy,xxx
1644. 28 } else {
1645. 28 val += match[2];
1646. 28 }
1647. 28 } else if (match[2] === ",") {
1648. 28// 4. Within the header and each record, there may be one or more
1649. 28// fields, separated by commas. Each line should contain the same
1650. 28// number of fields throughout the file. Spaces are considered part
1651. 28// of a field and should not be ignored. The last field in the
1652. 28// record must not be followed by a comma. For example:
1653. 28// aaa,bbb,ccc
1654. 28 // delimit val
1655. 28 row.push(val);
1656. 28 val = "";
1657. 28 } else if (match[2] === "\n") {
1658. 28// 1. Each record is located on a separate line, delimited by a line
1659. 28// break (CRLF). For example:
1660. 28// aaa,bbb,ccc CRLF
1661. 28// zzz,yyy,xxx CRLF
1662. 28 // delimit val
1663. 28 row.push(val);
1664. 28 val = "";
1665. 28 // append row
1666. 28 rowList.push(row);
1667. 28 // reset row
1668. 28 row = [];
1669. 28 }
1670. 28 }
1671. 2 // // append val
1672. 2 // if (val) {
1673. 2 // row.push(val);
1674. 2 // }
1675. 2 // // append row
1676. 2 // if (row.length) {
1677. 2 // rowList.push(row);
1678. 2 // }
1679. 2 return rowList;
1680. 2}
1681. 1
1682. 1function listOrEmptyList(list) {
1683. 1
1684. 1// This function will return <list> or empty-list if falsy.
1685. 1
1686. 1 return list || [];
1687. 1}
1688. 1
1689. 8async function moduleFsInit() {
1690. 8
1691. 8// This function will import nodejs builtin-modules if they have not yet been
1692. 8// imported.
1693. 8
1694. 8// State 3 - Modules already imported.
1695. 8
1696. 6 if (moduleFs !== undefined) {
1697. 6 return;
1698. 6 }
1699. 2
1700. 2// State 2 - Wait while modules are importing.
1701. 2
1702. 2 if (moduleFsInitResolveList !== undefined) {
1703. 1 return new Promise(function (resolve) {
1704. 1 moduleFsInitResolveList.push(resolve);
1705. 1 });
1706. 1 }
1707. 1
1708. 1// State 1 - Start importing modules.
1709. 1
1710. 1 moduleFsInitResolveList = [];
1711. 1 [
1712. 1 moduleChildProcess,
1713. 1 moduleCrypto,
1714. 1 moduleFs,
1715. 1 modulePath,
1716. 1 moduleUrl
1717. 1 ] = await Promise.all([
1718. 1 import("child_process"),
1719. 1 import("crypto"),
1720. 1 import("fs"),
1721. 1 import("path"),
1722. 1 import("url")
1723. 1 ]);
1724. 1 while (moduleFsInitResolveList.length > 0) {
1725. 1 moduleFsInitResolveList.shift()();
1726. 1 }
1727. 1 SQLMATH_NODE = `_sqlmath.napi6_${process.platform}_${process.arch}.node`;
1728. 1 SQLMATH_EXE = (
1729. 1 `_sqlmath.shell_${process.platform}_${process.arch}`
1730. 1 + process.platform.replace(
1731. 1 "win32",
1732. 1 ".exe"
1733. 1 ).replace(
1734. 1 process.platform,
1735. 1 ""
1736. 1 )
1737. 1 );
1738. 1}
1739. 1
1740. 263function noop(val) {
1741. 263
1742. 263// This function will do nothing except return <val>.
1743. 263
1744. 263 return val;
1745. 263}
1746. 1
1747. 42774function objectDeepCopyWithKeysSorted(obj) {
1748. 42774
1749. 42774// This function will recursively deep-copy <obj> with keys sorted.
1750. 42774
1751. 42774 let sorted;
1752. 28326 if (typeof obj !== "object" || !obj) {
1753. 28326 return obj;
1754. 28326 }
1755. 14448
1756. 14448// Recursively deep-copy list with child-keys sorted.
1757. 14448
1758. 14448 if (Array.isArray(obj)) {
1759. 2202 return obj.map(objectDeepCopyWithKeysSorted);
1760. 12246 }
1761. 12246
1762. 12246// Recursively deep-copy obj with keys sorted.
1763. 12246
1764. 12246 sorted = Object.create(null);
1765. 13714 Object.keys(obj).sort().forEach(function (key) {
1766. 13714 sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
1767. 13714 });
1768. 12246 return sorted;
1769. 12246}
1770. 1
1771. 3async function sqlmathInit() {
1772. 3
1773. 3// This function will init sqlmath.
1774. 3
1775. 3 let moduleModule;
1776. 3 dbFinalizationRegistry = (
1777. 3 dbFinalizationRegistry
1778. 18 ) || new FinalizationRegistry(function ({afterFinalization, ptr}) {
1779. 18
1780. 18// This function will auto-close any open sqlite3-db-pointer,
1781. 18// after its js-wrapper has been garbage-collected.
1782. 18
1783. 18 dbCallAsync(
1784. 18 jsbatonCreate("_dbClose"),
1785. 18 [
1786. 18 ptr[0]
1787. 18 ]
1788. 18 );
1789. 1 if (afterFinalization) {
1790. 1 afterFinalization();
1791. 1 }
1792. 18 });
1793. 3
1794. 3// Feature-detect nodejs.
1795. 3
1796. 3 if (
1797. 3 typeof process !== "object"
1798. 3 || typeof process?.versions?.node !== "string"
1799. 3 || cModule
1800. 1 ) {
1801. 1 return;
1802. 2 }
1803. 2
1804. 2// Init moduleFs.
1805. 2
1806. 2 await moduleFsInit();
1807. 2 moduleFsInit(); // coverage-hack
1808. 2 moduleChildProcessSpawn = moduleChildProcess.spawn;
1809. 2
1810. 2// Init moduleFs.
1811. 2
1812. 2 await moduleFsInit();
1813. 2 moduleFsInit(); // coverage-hack
1814. 2 moduleChildProcessSpawn = moduleChildProcess.spawn;
1815. 2 cModulePath = moduleUrl.fileURLToPath(import.meta.url).replace(
1816. 2 (/\bsqlmath\.mjs$/),
1817. 2 SQLMATH_NODE
1818. 2 );
1819. 2
1820. 2// Import napi c-addon.
1821. 2
1822. 2 if (!npm_config_mode_setup) {
1823. 2 moduleModule = await import("module");
1824. 2 if (!cModule) {
1825. 2 cModule = moduleModule.createRequire(cModulePath);
1826. 2 cModule = cModule(cModulePath);
1827. 2 }
1828. 2 }
1829. 2 if (npm_config_mode_test) {
1830. 2
1831. 2// Mock consoleError.
1832. 2
1833. 2 consoleError = noop;
1834. 2
1835. 2// Mock moduleChildProcessSpawn.
1836. 2
1837. 15 moduleChildProcessSpawn = function () {
1838. 15 let child = {
1839. 15 end: noop,
1840. 17 on: function (onType, resolve) {
1841. 17 switch (onType) {
1842. 2 case "data":
1843. 2 resolve(Buffer.alloc(0));
1844. 2 return;
1845. 15 default:
1846. 15 resolve(0);
1847. 17 }
1848. 17 },
1849. 15 setEncoding: noop,
1850. 15 write: noop
1851. 15 };
1852. 15 child.stderr = child;
1853. 15 child.stdin = child;
1854. 15 child.stdout = child;
1855. 15 return child;
1856. 15 };
1857. 2 }
1858. 3}
1859. 1
1860. 1function sqlmathWebworkerInit({
1861. 1 db,
1862. 1 modeTest
1863. 1}) {
1864. 1
1865. 1// This function will init sqlmath web-worker.
1866. 1
1867. 1// Feature-detect browser.
1868. 1
1869. 1 let Worker = globalThis.Worker;
1870. 1 IS_BROWSER = true;
1871. 1 if (modeTest) {
1872. 1 Worker = function () {
1873. 1 return;
1874. 1 };
1875. 1 }
1876. 1 sqlWorker = new Worker("sqlmath_wasm.js");
1877. 2 sqlWorker.onmessage = function ({
1878. 2 data
1879. 2 }) {
1880. 2 sqlMessageDict[data.id](data);
1881. 2 };
1882. 1 if (modeTest) {
1883. 2 sqlWorker.postMessage = function (data) {
1884. 2 setTimeout(function () {
1885. 2 sqlWorker.onmessage({data});
1886. 2 });
1887. 2 };
1888. 1 // test dbCallAsync handling-behavior
1889. 1 dbCallAsync(
1890. 1 jsbatonCreate("testTimeElapsed"),
1891. 1 [
1892. 1 true
1893. 1 ]
1894. 1 );
1895. 1 // test dbFileLoadAsync handling-behavior
1896. 1 dbFileLoadAsync({db, filename: "aa", modeTest});
1897. 1 // test jsonParseArraybuffer handling-behavior
1898. 1 jsonParseArraybuffer(new TextEncoder().encode("0"));
1899. 1 // revert IS_BROWSER
1900. 1 IS_BROWSER = undefined;
1901. 1 }
1902. 1}
1903. 1
1904. 1function waitAsync(timeout) {
1905. 1
1906. 1// This function will wait <timeout> ms.
1907. 1
1908. 1 return new Promise(function (resolve) {
1909. 1 setTimeout(resolve, timeout * !npm_config_mode_test);
1910. 1 });
1911. 1}
1912. 1
1913. 1sqlmathInit(); // coverage-hack
1914. 1await sqlmathInit();
1915. 1sqlmathInit(); // coverage-hack
1916. 1
1917. 1export {
1918. 1 DB_EXEC_PROFILE_DICT,
1919. 1 DB_STATE,
1920. 1 LGBM_DTYPE_FLOAT32,
1921. 1 LGBM_DTYPE_FLOAT64,
1922. 1 LGBM_DTYPE_INT32,
1923. 1 LGBM_DTYPE_INT64,
1924. 1 LGBM_FEATURE_IMPORTANCE_GAIN,
1925. 1 LGBM_FEATURE_IMPORTANCE_SPLIT,
1926. 1 LGBM_MATRIX_TYPE_CSC,
1927. 1 LGBM_MATRIX_TYPE_CSR,
1928. 1 LGBM_PREDICT_CONTRIB,
1929. 1 LGBM_PREDICT_LEAF_INDEX,
1930. 1 LGBM_PREDICT_NORMAL,
1931. 1 LGBM_PREDICT_RAW_SCORE,
1932. 1 SQLITE_OPEN_AUTOPROXY,
1933. 1 SQLITE_OPEN_CREATE,
1934. 1 SQLITE_OPEN_DELETEONCLOSE,
1935. 1 SQLITE_OPEN_EXCLUSIVE,
1936. 1 SQLITE_OPEN_FULLMUTEX,
1937. 1 SQLITE_OPEN_MAIN_DB,
1938. 1 SQLITE_OPEN_MAIN_JOURNAL,
1939. 1 SQLITE_OPEN_MEMORY,
1940. 1 SQLITE_OPEN_NOFOLLOW,
1941. 1 SQLITE_OPEN_NOMUTEX,
1942. 1 SQLITE_OPEN_PRIVATECACHE,
1943. 1 SQLITE_OPEN_READONLY,
1944. 1 SQLITE_OPEN_READWRITE,
1945. 1 SQLITE_OPEN_SHAREDCACHE,
1946. 1 SQLITE_OPEN_SUBJOURNAL,
1947. 1 SQLITE_OPEN_SUPER_JOURNAL,
1948. 1 SQLITE_OPEN_TEMP_DB,
1949. 1 SQLITE_OPEN_TEMP_JOURNAL,
1950. 1 SQLITE_OPEN_TRANSIENT_DB,
1951. 1 SQLITE_OPEN_URI,
1952. 1 SQLITE_OPEN_WAL,
1953. 1 SQLMATH_EXE,
1954. 1 SQLMATH_NODE,
1955. 1 assertErrorThrownAsync,
1956. 1 assertInt64,
1957. 1 assertJsonEqual,
1958. 1 assertNumericalEqual,
1959. 1 assertOrThrow,
1960. 1 childProcessSpawn2,
1961. 1 ciBuildExt,
1962. 1 dbCloseAsync,
1963. 1 dbExecAndReturnLastBlob,
1964. 1 dbExecAndReturnLastRow,
1965. 1 dbExecAndReturnLastTable,
1966. 1 dbExecAndReturnLastValue,
1967. 1 dbExecAsync,
1968. 1 dbExecProfile,
1969. 1 dbFileLoadAsync,
1970. 1 dbFileSaveAsync,
1971. 1 dbNoopAsync,
1972. 1 dbOpenAsync,
1973. 1 dbTableImportAsync,
1974. 1 debugInline,
1975. 1 fsCopyFileUnlessTest,
1976. 1 fsExistsUnlessTest,
1977. 1 fsReadFileUnlessTest,
1978. 1 fsWriteFileUnlessTest,
1979. 1 jsbatonGetInt64,
1980. 1 jsbatonGetString,
1981. 1 listOrEmptyList,
1982. 1 noop,
1983. 1 objectDeepCopyWithKeysSorted,
1984. 1 sqlmathWebworkerInit,
1985. 1 version,
1986. 1 waitAsync
1987. 1};
1988. 1