-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsqlmath.mjs
More file actions
1723 lines (1690 loc) · 54.3 KB
/
Copy pathsqlmath.mjs
File metadata and controls
1723 lines (1690 loc) · 54.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*jslint beta, bitwise, name, node*/
"use strict";
import {
Blob
} from "buffer";
import {
createRequire
} from "module";
import jslint from "./jslint.mjs";
let {
assertErrorThrownAsync,
assertJsonEqual,
assertOrThrow,
debugInline,
noop
} = jslint;
let local = Object.assign({}, jslint);
function assertNumericalEqual(aa, bb, message) {
// This function will assert aa - bb <= Number.EPSILON
assertOrThrow(aa, "value cannot be 0 or falsy");
if (!(Math.abs(aa - bb) <= Number.EPSILON)) {
throw new Error(
JSON.stringify(aa) + " != " + JSON.stringify(bb) + (
message
? " - " + message
: ""
)
);
}
}
/*
file sqlmath.js
*/
(function () {
let JSBATON_ARGC = 16;
// let SIZEOF_MESSAGE_DEFAULT = 768;
let SQLITE_MAX_LENGTH2 = 1000000000;
let SQLITE_OPEN_AUTOPROXY = 0x00000020; /* VFS only */
let SQLITE_OPEN_CREATE = 0x00000004; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_DELETEONCLOSE = 0x00000008; /* VFS only */
let SQLITE_OPEN_EXCLUSIVE = 0x00000010; /* VFS only */
let SQLITE_OPEN_FULLMUTEX = 0x00010000; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_MAIN_DB = 0x00000100; /* VFS only */
let SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; /* VFS only */
let SQLITE_OPEN_MEMORY = 0x00000080; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_NOFOLLOW = 0x01000000; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_NOMUTEX = 0x00008000; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_PRIVATECACHE = 0x00040000; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_READONLY = 0x00000001; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_READWRITE = 0x00000002; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_SHAREDCACHE = 0x00020000; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_SUBJOURNAL = 0x00002000; /* VFS only */
let SQLITE_OPEN_SUPER_JOURNAL = 0x00004000; /* VFS only */
let SQLITE_OPEN_TEMP_DB = 0x00000200; /* VFS only */
let SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; /* VFS only */
let SQLITE_OPEN_TRANSIENT_DB = 0x00000400; /* VFS only */
let SQLITE_OPEN_URI = 0x00000040; /* Ok for sqlite3_open_v2() */
let SQLITE_OPEN_WAL = 0x00080000; /* VFS only */
let addon;
let dbDict = new WeakMap();
let requireCjs = createRequire(import.meta.url);
let testList;
// private map of sqlite-database-connections
function cCall(func, argList) {
// this function will serialize <argList> to a c <baton>,
// suitable for passing into napi
let baton = new BigInt64Array(2048);
let errStack;
let result;
// serialize js-args to c-args
argList = argList.map(function (arg, ii) {
switch (typeof arg) {
case "bigint":
case "boolean":
case "number":
try {
baton[ii] = BigInt(arg);
} catch (ignore) {
return;
}
break;
// case "object":
// break;
case "string":
// append null-terminator to string
arg = new TextEncoder().encode(arg + "\u0000");
break;
}
if (ArrayBuffer.isView(arg)) {
baton[ii] = BigInt(arg.byteLength);
return new DataView(
arg.buffer,
arg.byteOffset,
arg.byteLength
);
}
return arg;
});
// pad argList to length = JSBATON_ARGC
argList = argList.concat(
Array.from(new Array(JSBATON_ARGC))
).slice(0, JSBATON_ARGC);
// prepend baton to argList
argList.unshift(baton);
// call napi with func and argList
result = addon[func](argList);
if (typeof result?.catch === "function") {
errStack = new Error().stack.replace((
/.*$/m
), "");
return result.catch(function (err) {
err.stack += errStack;
throw err;
});
}
return result;
}
function dbCallAsync(func, db, argList) {
// this function will call <func> using <db>
db = dbDeref(db);
// increment db.busy
db.busy += 1;
return cCall(func, [
db.ptr
].concat(argList)).finally(function () {
// decrement db.busy
db.busy -= 1;
assertOrThrow(db.busy >= 0, "invalid db.busy " + db.busy);
});
}
async function dbCloseAsync({
db
}) {
// this function will close sqlite-database-connection <db>
let __db = dbDeref(db);
// prevent segfault - do not close db if actions are pending
assertOrThrow(
__db.busy === 0,
"db cannot close with " + __db.busy + " actions pending"
);
// cleanup connPool
await Promise.all(__db.connPool.map(async function (ptr) {
let val = ptr[0];
ptr[0] = 0n;
await cCall("__dbCloseAsync", [
val
]);
}));
dbDict.delete(db);
}
function dbDeref(db) {
// this function will get private-object mapped to <db>
let __db = dbDict.get(db);
assertOrThrow(__db?.connPool[0] > 0, "invalid or closed db");
assertOrThrow(__db.busy >= 0, "invalid db.busy " + __db.busy);
__db.ii = (__db.ii + 1) % __db.connPool.length;
__db.ptr = __db.connPool[__db.ii][0];
assertOrThrow(__db.ptr > 0n, "invalid or closed db");
return __db;
}
async function dbExecAsync({
bindList = [],
db,
responseType,
rowList,
sql
}) {
// this function will exec <sql> in <db> and return <result>
let bindByKey = !Array.isArray(bindList);
let bindListLength = (
Array.isArray(bindList)
? bindList.length
: Object.keys(bindList).length
);
let result;
let serialize = jsToSqlSerializer();
if (rowList) {
await dbTableInsertAsync({
db,
rowList
});
}
Object.entries(bindList).forEach(function ([
key, val
]) {
if (bindByKey) {
serialize(":" + key + "\u0000");
}
serialize(val);
});
result = await dbCallAsync("__dbExecAsync", db, [
String(sql) + "\n;\nPRAGMA noop",
bindListLength,
serialize.bufResult,
bindByKey,
(
responseType === "lastBlob"
? 1
: responseType === "lastMatrixDouble"
? 2
: 0
)
].concat(serialize.bufSharedList));
result = result[1];
switch (responseType) {
case "arraybuffer":
case "lastBlob":
return result;
case "lastMatrixDouble":
return new Float64Array(result);
case "list":
return JSON.parse(new TextDecoder().decode(result));
default:
result = JSON.parse(new TextDecoder().decode(result));
return result.map(function (rowList) {
let colList = rowList.shift();
return rowList.map(function (row) {
let dict = {};
colList.forEach(function (key, ii) {
dict[key] = row[ii];
});
return dict;
});
});
}
}
function dbGetLastBlobAsync({
bindList = [],
db,
sql
}) {
// this function will exec <sql> in <db> and return last value retrieved
// from execution as raw blob/buffer
return dbExecAsync({
bindList,
db,
responseType: "lastBlob",
sql
});
}
function dbGetLastMatrixDouble({
bindList = [],
db,
sql
}) {
// this function will exec <sql> in <db> and return last SELECT-statement
// from execution as row x col matrix of doubles
return dbExecAsync({
bindList,
db,
responseType: "lastMatrixDouble",
sql
});
}
async function dbMemoryLoadAsync({
db,
filename
}) {
// This function will load <filename> to <db>
assertOrThrow(filename, "invalid filename " + filename);
await dbCallAsync("__dbMemoryLoadOrSave", db, [
String(filename), 0
]);
}
async function dbMemorySaveAsync({
db,
filename
}) {
// This function will save <db> to <filename>
assertOrThrow(filename, "invalid filename " + filename);
await dbCallAsync("__dbMemoryLoadOrSave", db, [
String(filename), 1
]);
}
async function dbOpenAsync({
filename,
flags,
threadCount = 1
}) {
// this function will open and return sqlite-database-connection <db>
// int sqlite3_open_v2(
// const char *filename, /* Database filename (UTF-8) */
// sqlite3 **ppDb, /* OUT: SQLite db handle */
// int flags, /* Flags */
// const char *zVfs /* Name of VFS module to use */
// );
let connPool;
let db = {};
assertOrThrow(
typeof filename === "string",
"invalid filename " + filename
);
connPool = await Promise.all(Array.from(new Array(
threadCount
), async function () {
let finalizer;
let ptr = await cCall("__dbOpenAsync", [
String(filename), undefined, flags ?? (
SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI
), undefined
]);
ptr = ptr[0][0];
finalizer = new BigInt64Array(addon.__dbFinalizerCreate());
finalizer[0] = BigInt(ptr);
return finalizer;
}));
dbDict.set(db, {
busy: 0,
connPool,
ii: 0,
ptr: 0n
});
return db;
}
async function dbTableInsertAsync({
colList,
colListPriority,
csv,
db,
rowList,
tableName = "tmp1"
}) {
// this function will create-or-replace temp <tablename> with <rowList>
let serialize = jsToSqlSerializer();
let sqlCreateTable;
let sqlInsertRow;
// normalize and validate tableName
tableName = "temp." + JSON.stringify(tableName.replace((
/^temp\./
), ""));
assertOrThrow((
/^temp\."[A-Z_a-z][0-9A-Z_a-z]*?"$/
).test(tableName), "invalid tableName " + tableName);
// parse csv
if (!rowList && csv) {
rowList = jsonRowListFromCsv({
csv
});
}
rowList = jsonRowListNormalize({
colList,
colListPriority,
rowList
});
colList = rowList.shift();
sqlCreateTable = (
"DROP TABLE IF EXISTS " + tableName + ";"
+ "CREATE TEMP TABLE " + tableName + "(" + colList.join(",") + ");"
);
sqlInsertRow = (
"INSERT INTO " + tableName + " VALUES("
+ ",?".repeat(colList.length).slice(1) + ");"
);
rowList.forEach(function (row) {
row.forEach(serialize);
});
await dbCallAsync("__dbTableInsertAsync", db, [
String(sqlCreateTable),
String(sqlInsertRow),
serialize.bufResult,
colList.length,
rowList.length
]);
}
function jsToSqlSerializer() {
// this function will return another function that serializes javascript <val>
// to <bufResult> as sqlite-values
let BIGINT64_MAX = 2n ** 63n - 1n;
let BIGINT64_MIN = -(2n ** 63n - 1n);
let SQLITE_DATATYPE_BLOB = 0x04;
// let SQLITE_DATATYPE_BLOB_0 = 0x14;
let SQLITE_DATATYPE_FLOAT = 0x02;
// let SQLITE_DATATYPE_FLOAT_0 = 0x12;
let SQLITE_DATATYPE_INTEGER = 0x01;
let SQLITE_DATATYPE_INTEGER_0 = 0x11;
let SQLITE_DATATYPE_INTEGER_1 = 0x21;
let SQLITE_DATATYPE_NULL = 0x05;
let SQLITE_DATATYPE_SHAREDARRAYBUFFER = -0x01;
let SQLITE_DATATYPE_TEXT = 0x03;
let SQLITE_DATATYPE_TEXT_0 = 0x13;
let bufResult = new DataView(new ArrayBuffer(2048));
let bufSharedList = [];
let offset = 0;
function bufferAppendDatatype(datatype, byteLength) {
// this function will grow <bufResult> by <bytelength> and append <datatype>
let nn = offset + 1 + byteLength;
let tmp;
// exponentially grow bufResult as needed
if (bufResult.byteLength < nn) {
assertOrThrow(nn <= SQLITE_MAX_LENGTH2, (
"sqlite - string or blob exceeds size limit of "
+ SQLITE_MAX_LENGTH2 + " bytes"
));
tmp = bufResult;
bufResult = new DataView(new ArrayBuffer(
Math.min(2 ** Math.ceil(Math.log2(nn)), SQLITE_MAX_LENGTH2)
));
// copy tmp to bufResult with offset
bufferSetBuffer(bufResult, tmp, 0);
// save bufResult
serialize.bufResult = bufResult;
}
bufResult.setUint8(offset, datatype);
offset += 1;
}
function bufferSetBigint64(offset, val) {
// this function will set bigint <val> to buffer <bufResult> at <offset>
assertOrThrow(
BIGINT64_MIN <= val && val <= BIGINT64_MAX,
(
"The value of \"value\" is out of range."
+ " It must be >= -(2n ** 63n) and < 2n ** 63n."
)
);
bufResult.setBigInt64(offset, val, true);
}
function bufferSetBuffer(aa, bb, offset) {
// this function will set buffer <bb> to buffer <aa> at <offset>
if (typeof bb === "string") {
bb = new TextEncoder().encode(bb);
}
aa = new Uint8Array(aa.buffer, aa.byteOffset, aa.byteLength);
bb = new Uint8Array(bb.buffer, bb.byteOffset, bb.byteLength);
aa.set(bb, offset);
return bb.byteLength;
}
function serialize(val) {
// this function will write to <bufResult>, <val> at given <offset>
let byteLength = 0;
/*
#define SQLITE_DATATYPE_BLOB 0x04
#define SQLITE_DATATYPE_BLOB_0 0x14
#define SQLITE_DATATYPE_FLOAT 0x02
#define SQLITE_DATATYPE_FLOAT_0 0x12
#define SQLITE_DATATYPE_INTEGER 0x01
#define SQLITE_DATATYPE_INTEGER_0 0x11
#define SQLITE_DATATYPE_INTEGER_1 0x21
#define SQLITE_DATATYPE_NULL 0x05
#define SQLITE_DATATYPE_TEXT 0x03
#define SQLITE_DATATYPE_TEXT_0 0x13
// 1. false.bigint
// 2. false.boolean
// 3. false.function
// 4. false.number
// 5. false.object
// 6. false.string
// 7. false.symbol
// 8. false.undefined
// 11. true.bigint
// 12. true.boolean
// 13. true.function
// 14. true.number
// 15. true.object
// 16. true.string
// 17. true.symbol
// 18. true.undefined
*/
// -1. SharedArrayBuffer
if (val && val.constructor === SharedArrayBuffer) {
assertOrThrow(
bufSharedList.length <= 0.5 * JSBATON_ARGC,
(
"too many SharedArrayBuffer's " + bufSharedList.length
+ " > " + (0.5 * JSBATON_ARGC)
)
);
bufferAppendDatatype(SQLITE_DATATYPE_SHAREDARRAYBUFFER, 0);
bufSharedList.push(new DataView(val));
return;
}
// 12. true.boolean
if (val === 1 || val === 1n || val === true) {
bufferAppendDatatype(SQLITE_DATATYPE_INTEGER_1, 0);
return;
}
switch (Boolean(val) + "." + typeof(val)) {
// 1. false.bigint
case "false.bigint":
// 2. false.boolean
case "false.boolean":
// 4. false.number
case "false.number":
bufferAppendDatatype(SQLITE_DATATYPE_INTEGER_0, 0);
return;
// 3. false.function
// case "false.function":
// 5. false.object
case "false.object":
// 7. false.symbol
// case "false.symbol":
// 8. false.undefined
case "false.undefined":
// 13. true.function
case "true.function":
// 17. true.symbol
case "true.symbol":
// 18. true.undefined
// case "true.undefined":
bufferAppendDatatype(SQLITE_DATATYPE_NULL, 0);
return;
// 6. false.string
case "false.string":
bufferAppendDatatype(SQLITE_DATATYPE_TEXT_0, 0);
return;
// 11. true.bigint
case "true.bigint":
bufferAppendDatatype(SQLITE_DATATYPE_INTEGER, 8);
bufferSetBigint64(offset, val);
offset += 8;
return;
// 14. true.number
case "true.number":
bufferAppendDatatype(SQLITE_DATATYPE_FLOAT, 8);
bufResult.setFloat64(offset, val, true);
offset += 8;
return;
// 16. true.string
case "true.string":
byteLength = new Blob([
val
]).size;
bufferAppendDatatype(SQLITE_DATATYPE_TEXT, 8 + byteLength);
bufferSetBigint64(offset, BigInt(byteLength));
offset += 8;
offset += bufferSetBuffer(bufResult, val, offset);
return;
// 15. true.object
default:
assertOrThrow(
val && typeof val === "object",
"invalid data " + (typeof val) + " " + val
);
// write buffer
if (ArrayBuffer.isView(val)) {
if (val.byteLength === 0) {
bufferAppendDatatype(SQLITE_DATATYPE_NULL, 0);
return;
}
bufferAppendDatatype(
SQLITE_DATATYPE_BLOB,
8 + val.byteLength
);
bufferSetBigint64(offset, BigInt(val.byteLength));
offset += 8;
// copy val to bufResult with offset
bufferSetBuffer(bufResult, val, offset);
offset += val.byteLength;
return;
}
// write JSON.stringify(val)
val = String(
typeof val.toJSON === "function"
? val.toJSON()
: JSON.stringify(val)
);
byteLength = new Blob([
val
]).size;
bufferAppendDatatype(SQLITE_DATATYPE_TEXT, 8 + byteLength);
bufferSetBigint64(offset, BigInt(byteLength));
offset += 8;
offset += bufferSetBuffer(bufResult, val, offset);
}
}
// save bufResult
serialize.bufResult = bufResult;
// save bufSharedList
serialize.bufSharedList = bufSharedList;
return serialize;
}
function jsonRowListFromCsv({
csv
}) {
// this function will convert <csv>-text to json list-of-list
/*
https://tools.ietf.org/html/rfc4180#section-2
Definition of the CSV Format
While there are various specifications and implementations for the
CSV format (for ex. [4], [5], [6] and [7]), there is no formal
specification in existence, which allows for a wide variety of
interpretations of CSV files. This section documents the format that
seems to be followed by most implementations:
1. Each record is located on a separate line, delimited by a line
break (CRLF). For example:
aaa,bbb,ccc CRLF
zzz,yyy,xxx CRLF
2. The last record in the file may or may not have an ending line
break. For example:
aaa,bbb,ccc CRLF
zzz,yyy,xxx
3. There maybe an optional header line appearing as the first line
of the file with the same format as normal record lines. This
header will contain names corresponding to the fields in the file
and should contain the same number of fields as the records in
the rest of the file (the presence or absence of the header line
should be indicated via the optional "header" parameter of this
MIME type). For example:
field_name,field_name,field_name CRLF
aaa,bbb,ccc CRLF
zzz,yyy,xxx CRLF
4. Within the header and each record, there may be one or more
fields, separated by commas. Each line should contain the same
number of fields throughout the file. Spaces are considered part
of a field and should not be ignored. The last field in the
record must not be followed by a comma. For example:
aaa,bbb,ccc
5. Each field may or may not be enclosed in double quotes (however
some programs, such as Microsoft Excel, do not use double quotes
at all). If fields are not enclosed with double quotes, then
double quotes may not appear inside the fields. For example:
"aaa","bbb","ccc" CRLF
zzz,yyy,xxx
6. Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes. For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
7. If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:
"aaa","b""bb","ccc"
*/
let match;
let quote = false;
let rgx = (
/(.*?)(""|"|,|\n)/g
);
let row = [];
let rowList = [];
let val = "";
// normalize "\r\n" to "\n"
csv = csv.replace((
/\r\n?/g
), "\n");
/*
2. The last record in the file may or may not have an ending line
break. For example:
aaa,bbb,ccc CRLF
zzz,yyy,xxx
*/
if (csv[csv.length - 1] !== "\n") {
csv += "\n";
}
while (true) {
match = rgx.exec(csv);
if (!match) {
return rowList;
}
// build val
val += match[1];
match = match[2];
switch (quote + "." + match) {
case "false.,":
/*
4. Within the header and each record, there may be one or more
fields, separated by commas. Each line should contain the same
number of fields throughout the file. Spaces are considered part
of a field and should not be ignored. The last field in the
record must not be followed by a comma. For example:
aaa,bbb,ccc
*/
// delimit val
row.push(val);
val = "";
break;
case "false.\"":
case "true.\"":
/*
5. Each field may or may not be enclosed in double quotes (however
some programs, such as Microsoft Excel, do not use double quotes
at all). If fields are not enclosed with double quotes, then
double quotes may not appear inside the fields. For example:
"aaa","bbb","ccc" CRLF
zzz,yyy,xxx
*/
assertOrThrow(quote || val === "", (
"invalid csv - naked double-quote in unquoted-string "
+ JSON.stringify(val + "\"")
));
quote = !quote;
break;
// backtrack for naked-double-double-quote
case "false.\"\"":
quote = true;
rgx.lastIndex -= 1;
break;
case "false.\n":
case "false.\r\n":
/*
1. Each record is located on a separate line, delimited by a line
break (CRLF). For example:
aaa,bbb,ccc CRLF
zzz,yyy,xxx CRLF
*/
// delimit val
row.push(val);
val = "";
// append row
rowList.push(row);
// reset row
row = [];
break;
case "true.\"\"":
/*
7. If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:
"aaa","b""bb","ccc"
*/
val += "\"";
break;
default:
/*
6. Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes. For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
*/
assertOrThrow(quote, (
"invalid csv - illegal character in unquoted-string "
+ JSON.stringify(match)
));
val += match;
}
}
}
function jsonRowListNormalize({
colList,
colListPriority,
rowList
}) {
// this function will normalize <rowList> with given <colList>
let colDict = {};
if (!(rowList?.length > 0)) {
throw new Error("invalid rowList " + JSON.stringify(rowList));
}
// convert list-of-dict to list-of-list
if (!Array.isArray(rowList[0])) {
colList = new Map(Array.from(
colList || []
).map(function (key, ii) {
return [
key, ii
];
}));
rowList = rowList.map(function (row) {
Object.keys(row).forEach(function (key) {
if (!colList.has(key)) {
colList.set(key, colList.size);
}
});
return Array.from(colList.keys()).map(function (key) {
return row[key];
});
});
colList = Array.from(colList.keys());
}
if (!colList) {
colList = rowList[0];
rowList = rowList.slice(1);
}
if (!(colList?.length > 0)) {
throw new Error("invalid colList " + JSON.stringify(colList));
}
colList = colList.map(function (key) {
// sanitize column-name
key = String(key).replace((
/^[^A-Z_a-z]/
), "c_" + key);
key = key.replace((
/[^0-9A-Z_a-z]/g
), "_");
// for duplicate column-name, add ordinal _2, _3, _4, ...
colDict[key] = colDict[key] || 0;
colDict[key] += 1;
if (colDict[key] > 1) {
key += "_" + colDict[key];
}
return key;
});
// normalize rowList
rowList = rowList.map(function (row) {
return (
row.length === colList.length
? row
: colList.map(function (ignore, ii) {
return row[ii];
})
);
});
if (!colListPriority) {
rowList.unshift(colList);
return rowList;
}
// sort colList by colListPriority
colListPriority = new Map([].concat(
colListPriority,
colList
).map(function (key) {
return [
key, colList.indexOf(key)
];
}).filter(function ([
ignore, ii
]) {
return ii >= 0;
}));
colList = Array.from(colListPriority.keys());
colListPriority = Array.from(colListPriority.values());
rowList = rowList.map(function (row) {
return colListPriority.map(function (ii) {
return row[ii];
});
});
rowList.unshift(colList);
return rowList;
}
function testAll() {
// this function will run all tests
testList.forEach(function (testFunc) {
testFunc();
});
}
function testAssertXxx() {
// this function will test assertXxx's handling-behavior
// test assertNumericalEqual's handling-behavior
assertNumericalEqual(1, 1);
assertErrorThrownAsync(function () {
assertNumericalEqual(0, 0);
}, "value cannot be 0 or falsy");
assertErrorThrownAsync(function () {
assertNumericalEqual(1, 2);
}, "1 != 2");
assertErrorThrownAsync(function () {
assertNumericalEqual(1, 2, "aa");
}, "aa");
}
function testCcall() {
// this function will test cCall's handling-behavior
[
[-0, "0"],
[-Infinity, "0"],
[0, "0"],
[1 / 0, "0"],
[Infinity, "0"],
[false, "0"],
[null, "0"],
[true, "1"],
[undefined, "0"],
[{}, "0"]
].forEach(async function ([
aa, bb
]) {
let cc;
cc = String(
await cCall("noopAsync", [
aa
])
)[0][0];
assertOrThrow(bb === cc, [aa, bb, cc]);
cc = String(cCall("noopSync", [
aa
]))[0][0];
assertOrThrow(bb === cc, [aa, bb, cc]);
});
}
async function testDbBind() {
// this function will test db's bind handling-behavior
let db = await dbOpenAsync({
filename: ":memory:"
});
async function testDbGetLastBlobAsync(val) {
return await dbGetLastBlobAsync({
bindList: [
val
],
db,
sql: "SELECT 1, 2, 3; SELECT 1, 2, ?"
});
}
// test bigint-error handling-behavior
noop([
-(2n ** 63n),
2n ** 63n
]).forEach(function (val) {
assertErrorThrownAsync(testDbGetLastBlobAsync.bind(undefined, val));
});
// test datatype handling-behavior
[
// -1. SharedArrayBuffer
// new SharedArrayBuffer(0), null,
// 1. bigint
-0n, -0,
-0x7fffffffffffffffn, "-9223372036854775807",
-1n, -1,
-2n, -2,
0n, 0,
0x7fffffffffffffffn, "9223372036854775807",
1n, 1,
2n, 2,
// 2. boolean
false, 0,
true, 1,
// 3. function
noop, null,
// 4. number
-0, 0,
-1 / 0, null,
-1e-999, 0,
-1e999, null,
-2, -2,
-Infinity, null,
-NaN, 0,
0, 0,
1 / 0, null,
1e-999, 0,
1e999, null,
2, 2,
Infinity, null,
NaN, 0,
// 5. object
new Uint8Array(0), null,
new TextEncoder().encode(""), null,
new TextEncoder().encode("\u0000"), null,
new TextEncoder().encode("\u0000\u{1f600}\u0000"), null,
[], "[]",
new Date(0), "1970-01-01T00:00:00.000Z",
new RegExp(), "{}",
null, null,
{}, "{}",
// 6. string
"", "",
"0", "0",
"1", "1",
"2", "2",
"\u0000", "\u0000",
"\u0000\u{1f600}\u0000", "\u0000\u{1f600}\u0000",
"a".repeat(9999), "a".repeat(9999),
// 7. symbol
Symbol(), null,
// 8. undefined
undefined, null
].forEach(function (aa, ii, list) {
let bb = list[ii + 1];
if (ii % 2 === 1) {
return;
}
ii *= 0.5;
// test dbGetLastBlobAsync's bind handling-behavior
[
aa
].forEach(async function (aa) {
let cc = String(bb);
let dd = new TextDecoder().decode(
await testDbGetLastBlobAsync(aa)
);
switch (typeof(aa)) {
case "bigint":
aa = Number(aa);
break;
case "function":
case "symbol":
case "undefined":
cc = "";
break;
case "number":
switch (aa) {
case -2:
cc = "-2.0";
break;
case -Infinity:
cc = "-Inf";
break;
case 2:
cc = "2.0";