-
Notifications
You must be signed in to change notification settings - Fork 61
/
sqlite-api.js
870 lines (772 loc) · 25.5 KB
/
sqlite-api.js
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
// Copyright 2021 Roy T. Hashimoto. All Rights Reserved.
import * as SQLite from './sqlite-constants.js';
export * from './sqlite-constants.js';
const MAX_INT64 = 0x7fffffffffffffffn;
const MIN_INT64 = -0x8000000000000000n;
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
export class SQLiteError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
const async = true;
/**
* Builds a Javascript API from the Emscripten module. This API is still
* low-level and closely corresponds to the C API exported by the module,
* but differs in some specifics like throwing exceptions on errors.
* @param {*} Module SQLite Emscripten module
* @returns {SQLiteAPI}
*/
export function Factory(Module) {
/** @type {SQLiteAPI} */ const sqlite3 = {};
Module.retryOps = [];
const sqliteFreeAddress = Module._getSqliteFree();
// Allocate some space for 32-bit returned values.
const tmp = Module._malloc(8);
const tmpPtr = [tmp, tmp + 4];
// Convert a JS string to a C string. sqlite3_malloc is used to allocate
// memory (use sqlite3_free to deallocate).
function createUTF8(s) {
if (typeof s !== 'string') return 0;
const utf8 = new TextEncoder().encode(s);
const zts = Module._sqlite3_malloc(utf8.byteLength + 1);
Module.HEAPU8.set(utf8, zts);
Module.HEAPU8[zts + utf8.byteLength] = 0;
return zts;
}
/**
* Concatenate 32-bit numbers into a 64-bit (signed) BigInt.
* @param {number} lo32
* @param {number} hi32
* @returns {bigint}
*/
function cvt32x2ToBigInt(lo32, hi32) {
return (BigInt(hi32) << 32n) | (BigInt(lo32) & 0xffffffffn);
}
/**
* Concatenate 32-bit numbers and return as number or BigInt, depending
* on the value.
* @param {number} lo32
* @param {number} hi32
* @returns {number|bigint}
*/
const cvt32x2AsSafe = (function() {
const hiMax = BigInt(Number.MAX_SAFE_INTEGER) >> 32n;
const hiMin = BigInt(Number.MIN_SAFE_INTEGER) >> 32n;
return function(lo32, hi32) {
if (hi32 > hiMax || hi32 < hiMin) {
// Can't be expressed as a Number so use BigInt.
return cvt32x2ToBigInt(lo32, hi32);
} else {
// Combine the upper and lower 32-bit numbers. The complication is
// that lo32 is a signed integer which makes manipulating its bits
// a little tricky - the sign bit gets handled separately.
return (hi32 * 0x100000000) + (lo32 & 0x7fffffff) - (lo32 & 0x80000000);
}
}
})();
const databases = new Set();
function verifyDatabase(db) {
if (!databases.has(db)) {
throw new SQLiteError('not a database', SQLite.SQLITE_MISUSE);
}
}
const mapStmtToDB = new Map();
function verifyStatement(stmt) {
if (!mapStmtToDB.has(stmt)) {
throw new SQLiteError('not a statement', SQLite.SQLITE_MISUSE);
}
}
sqlite3.bind_collection = function(stmt, bindings) {
verifyStatement(stmt);
const isArray = Array.isArray(bindings);
const nBindings = sqlite3.bind_parameter_count(stmt);
for (let i = 1; i <= nBindings; ++i) {
const key = isArray ? i - 1 : sqlite3.bind_parameter_name(stmt, i);
const value = bindings[key];
if (value !== undefined) {
sqlite3.bind(stmt, i, value);
}
}
return SQLite.SQLITE_OK;
};
sqlite3.bind = function(stmt, i, value) {
verifyStatement(stmt);
switch (typeof value) {
case 'number':
if (value === (value | 0)) {
return sqlite3.bind_int(stmt, i, value);
} else {
return sqlite3.bind_double(stmt, i, value);
}
case 'string':
return sqlite3.bind_text(stmt, i, value);
default:
if (value instanceof Uint8Array || Array.isArray(value)) {
return sqlite3.bind_blob(stmt, i, value);
} else if (value === null) {
return sqlite3.bind_null(stmt, i);
} else if (typeof value === 'bigint') {
return sqlite3.bind_int64(stmt, i, value);
} else if (value === undefined) {
// Existing binding (or NULL) will be used.
return SQLite.SQLITE_NOTICE;
} else {
console.warn('unknown binding converted to null', value);
return sqlite3.bind_null(stmt, i);
}
}
};
sqlite3.bind_blob = (function() {
const fname = 'sqlite3_bind_blob';
const f = Module.cwrap(fname, ...decl('nnnnn:n'));
return function(stmt, i, value) {
verifyStatement(stmt);
// @ts-ignore
const byteLength = value.byteLength ?? value.length;
const ptr = Module._sqlite3_malloc(byteLength);
Module.HEAPU8.subarray(ptr).set(value);
const result = f(stmt, i, ptr, byteLength, sqliteFreeAddress);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.bind_parameter_count = (function() {
const fname = 'sqlite3_bind_parameter_count';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(stmt) {
verifyStatement(stmt);
const result = f(stmt);
return result;
};
})();
sqlite3.bind_double = (function() {
const fname = 'sqlite3_bind_double';
const f = Module.cwrap(fname, ...decl('nnn:n'));
return function(stmt, i, value) {
verifyStatement(stmt);
const result = f(stmt, i, value);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.bind_int = (function() {
const fname = 'sqlite3_bind_int';
const f = Module.cwrap(fname, ...decl('nnn:n'));
return function(stmt, i, value) {
verifyStatement(stmt);
if (value > 0x7fffffff || value < -0x80000000) return SQLite.SQLITE_RANGE;
const result = f(stmt, i, value);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.bind_int64 = (function() {
const fname = 'sqlite3_bind_int64';
const f = Module.cwrap(fname, ...decl('nnnn:n'));
return function(stmt, i, value) {
verifyStatement(stmt);
if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;
const lo32 = value & 0xffffffffn;
const hi32 = value >> 32n;
const result = f(stmt, i, Number(lo32), Number(hi32));
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.bind_null = (function() {
const fname = 'sqlite3_bind_null';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, i) {
verifyStatement(stmt);
const result = f(stmt, i);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.bind_parameter_name = (function() {
const fname = 'sqlite3_bind_parameter_name';
const f = Module.cwrap(fname, ...decl('n:s'));
return function(stmt, i) {
verifyStatement(stmt);
const result = f(stmt, i);
return result;
};
})();
sqlite3.bind_text = (function() {
const fname = 'sqlite3_bind_text';
const f = Module.cwrap(fname, ...decl('nnnnn:n'));
return function(stmt, i, value) {
verifyStatement(stmt);
const ptr = createUTF8(value);
const result = f(stmt, i, ptr, -1, sqliteFreeAddress);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.changes = (function() {
const fname = 'sqlite3_changes';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(db) {
verifyDatabase(db);
const result = f(db);
return result;
};
})();
sqlite3.close = (function() {
const fname = 'sqlite3_close';
const f = Module.cwrap(fname, ...decl('n:n'), { async });
return async function(db) {
verifyDatabase(db);
const result = await f(db);
databases.delete(db);
return check(fname, result, db);
};
})();
sqlite3.column = function(stmt, iCol) {
verifyStatement(stmt);
const type = sqlite3.column_type(stmt, iCol);
switch (type) {
case SQLite.SQLITE_BLOB:
return sqlite3.column_blob(stmt, iCol);
case SQLite.SQLITE_FLOAT:
return sqlite3.column_double(stmt, iCol);
case SQLite.SQLITE_INTEGER:
const lo32 = sqlite3.column_int(stmt, iCol);
const hi32 = Module.getTempRet0();
return cvt32x2AsSafe(lo32, hi32);
case SQLite.SQLITE_NULL:
return null;
case SQLite.SQLITE_TEXT:
return sqlite3.column_text(stmt, iCol);
default:
throw new SQLiteError('unknown type', type);
}
};
sqlite3.column_blob = (function() {
const fname = 'sqlite3_column_blob';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const nBytes = sqlite3.column_bytes(stmt, iCol);
const address = f(stmt, iCol);
const result = Module.HEAPU8.subarray(address, address + nBytes);
return result;
};
})();
sqlite3.column_bytes = (function() {
const fname = 'sqlite3_column_bytes';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.column_count = (function() {
const fname = 'sqlite3_column_count';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(stmt) {
verifyStatement(stmt);
const result = f(stmt);
return result;
};
})();
sqlite3.column_double = (function() {
const fname = 'sqlite3_column_double';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.column_int = (function() {
// Retrieve int64 but use only the lower 32 bits. The upper 32-bits are
// accessible with Module.getTempRet0().
const fname = 'sqlite3_column_int64';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.column_int64 = (function() {
const fname = 'sqlite3_column_int64';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const lo32 = f(stmt, iCol);
const hi32 = Module.getTempRet0();
const result = cvt32x2ToBigInt(lo32, hi32);
return result;
};
})();
sqlite3.column_name = (function() {
const fname = 'sqlite3_column_name';
const f = Module.cwrap(fname, ...decl('nn:s'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.column_names = function(stmt) {
const columns = [];
const nColumns = sqlite3.column_count(stmt);
for (let i = 0; i < nColumns; ++i) {
columns.push(sqlite3.column_name(stmt, i));
}
return columns;
};
sqlite3.column_text = (function() {
const fname = 'sqlite3_column_text';
const f = Module.cwrap(fname, ...decl('nn:s'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.column_type = (function() {
const fname = 'sqlite3_column_type';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(stmt, iCol) {
verifyStatement(stmt);
const result = f(stmt, iCol);
return result;
};
})();
sqlite3.create_function = function(db, zFunctionName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) {
verifyDatabase(db);
// Convert SQLite callback arguments to JavaScript-friendly arguments.
function adapt(f) {
return f instanceof AsyncFunction ?
(async (ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n))) :
((ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n)));
}
const result = Module.create_function(
db,
zFunctionName,
nArg,
eTextRep,
pApp,
xFunc && adapt(xFunc),
xStep && adapt(xStep),
xFinal);
return check('sqlite3_create_function', result, db);
};
sqlite3.data_count = (function() {
const fname = 'sqlite3_data_count';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(stmt) {
verifyStatement(stmt);
const result = f(stmt);
return result;
};
})();
sqlite3.exec = async function(db, sql, callback) {
for await (const stmt of sqlite3.statements(db, sql)) {
let columns;
while (await sqlite3.step(stmt) === SQLite.SQLITE_ROW) {
if (callback) {
columns = columns ?? sqlite3.column_names(stmt);
const row = sqlite3.row(stmt);
await callback(row, columns);
}
}
}
return SQLite.SQLITE_OK;
};
sqlite3.finalize = (function() {
const fname = 'sqlite3_finalize';
const f = Module.cwrap(fname, ...decl('n:n'), { async });
return async function(stmt) {
const result = await f(stmt);
mapStmtToDB.delete(stmt)
// Don't throw on error here. Typically the error has already been
// thrown and finalize() is part of the cleanup.
return result;
};
})();
sqlite3.get_autocommit = (function() {
const fname = 'sqlite3_get_autocommit';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(db) {
const result = f(db);
return result;
};
})();
sqlite3.libversion = (function() {
const fname = 'sqlite3_libversion';
const f = Module.cwrap(fname, ...decl(':s'));
return function() {
const result = f();
return result;
};
})();
sqlite3.libversion_number = (function() {
const fname = 'sqlite3_libversion_number';
const f = Module.cwrap(fname, ...decl(':n'));
return function() {
const result = f();
return result;
};
})();
sqlite3.limit = (function() {
const fname = 'sqlite3_limit';
const f = Module.cwrap(fname, ...decl('nnn:n'));
return function(db, id, newVal) {
const result = f(db, id, newVal);
return result;
};
})();
sqlite3.open_v2 = (function() {
const fname = 'sqlite3_open_v2';
const f = Module.cwrap(fname, ...decl('snnn:n'), { async });
return async function(zFilename, flags, zVfs) {
flags = flags || SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE;
zVfs = createUTF8(zVfs);
try {
// Allow retry operations.
const rc = await retry(() => f(zFilename, tmpPtr[0], flags, zVfs));
const db = Module.getValue(tmpPtr[0], '*');
databases.add(db);
Module.ccall('RegisterExtensionFunctions', 'void', ['number'], [db]);
check(fname, rc);
return db;
} finally {
Module._sqlite3_free(zVfs);
}
};
})();
sqlite3.progress_handler = function(db, nProgressOps, handler, userData) {
verifyDatabase(db);
Module.progress_handler(db, nProgressOps, handler, userData);
};;
sqlite3.reset = (function() {
const fname = 'sqlite3_reset';
const f = Module.cwrap(fname, ...decl('n:n'), { async });
return async function(stmt) {
verifyStatement(stmt);
const result = await f(stmt);
return check(fname, result, mapStmtToDB.get(stmt));
};
})();
sqlite3.result = function(context, value) {
switch (typeof value) {
case 'number':
if (value === (value | 0)) {
sqlite3.result_int(context, value);
} else {
sqlite3.result_double(context, value);
}
break;
case 'string':
sqlite3.result_text(context, value);
break;
default:
if (value instanceof Uint8Array || Array.isArray(value)) {
sqlite3.result_blob(context, value);
} else if (value === null) {
sqlite3.result_null(context);
} else if (typeof value === 'bigint') {
return sqlite3.result_int64(context, value);
} else {
console.warn('unknown result converted to null', value);
sqlite3.result_null(context);
}
break;
}
};
sqlite3.result_blob = (function() {
const fname = 'sqlite3_result_blob';
const f = Module.cwrap(fname, ...decl('nnnn:n'));
return function(context, value) {
// @ts-ignore
const byteLength = value.byteLength ?? value.length;
const ptr = Module._sqlite3_malloc(byteLength);
Module.HEAPU8.subarray(ptr).set(value);
f(context, ptr, byteLength, sqliteFreeAddress); // void return
};
})();
sqlite3.result_double = (function() {
const fname = 'sqlite3_result_double';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(context, value) {
f(context, value); // void return
};
})();
sqlite3.result_int = (function() {
const fname = 'sqlite3_result_int';
const f = Module.cwrap(fname, ...decl('nn:n'));
return function(context, value) {
f(context, value); // void return
};
})();
sqlite3.result_int64 = (function() {
const fname = 'sqlite3_result_int64';
const f = Module.cwrap(fname, ...decl('nnn:n'));
return function(context, value) {
if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;
const lo32 = value & 0xffffffffn;
const hi32 = value >> 32n;
f(context, Number(lo32), Number(hi32)); // void return
};
})();
sqlite3.result_null = (function() {
const fname = 'sqlite3_result_null';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(context) {
f(context); // void return
};
})();
sqlite3.result_text = (function() {
const fname = 'sqlite3_result_text';
const f = Module.cwrap(fname, ...decl('nnnn:n'));
return function(context, value) {
const ptr = createUTF8(value);
f(context, ptr, -1, sqliteFreeAddress); // void return
};
})();
sqlite3.row = function(stmt) {
const row = [];
const nColumns = sqlite3.data_count(stmt);
for (let i = 0; i < nColumns; ++i) {
const value = sqlite3.column(stmt, i);
// Copy blob if aliasing volatile WebAssembly memory. This avoids an
// unnecessary copy if users monkey patch column_blob to copy.
// @ts-ignore
row.push(value?.buffer === Module.HEAPU8.buffer ? value.slice() : value);
}
return row;
};
sqlite3.set_authorizer = function(db, xAuth, pApp) {
verifyDatabase(db);
// Convert SQLite callback arguments to JavaScript-friendly arguments.
function cvtArgs(_, iAction, p3, p4, p5, p6) {
return [
_,
iAction,
Module.UTF8ToString(p3),
Module.UTF8ToString(p4),
Module.UTF8ToString(p5),
Module.UTF8ToString(p6)
];
};
function adapt(f) {
return f instanceof AsyncFunction ?
(async (_, iAction, p3, p4, p5, p6) => f(cvtArgs(_, iAction, p3, p4, p5, p6))) :
((_, iAction, p3, p4, p5, p6) => f(cvtArgs(_, iAction, p3, p4, p5, p6)));
}
const result = Module.set_authorizer(db, adapt(xAuth), pApp);
return check('sqlite3_set_authorizer', result, db);
};;
sqlite3.sql = (function() {
const fname = 'sqlite3_sql';
const f = Module.cwrap(fname, ...decl('n:s'));
return function(stmt) {
verifyStatement(stmt);
const result = f(stmt);
return result;
};
})();
sqlite3.statements = function(db, sql, options = {}) {
const prepare = Module.cwrap(
'sqlite3_prepare_v3',
'number',
['number', 'number', 'number', 'number', 'number', 'number'],
{ async: true });
return (async function*() {
const onFinally = [];
try {
// Encode SQL string to UTF-8.
const utf8 = new TextEncoder().encode(sql);
// Copy encoded string to WebAssembly memory. The SQLite docs say
// zero-termination is a minor optimization so add room for that.
// Also add space for the statement handle and SQL tail pointer.
const allocSize = utf8.byteLength - (utf8.byteLength % 4) + 12;
const pzHead = Module._sqlite3_malloc(allocSize);
const pzEnd = pzHead + utf8.byteLength + 1;
onFinally.push(() => Module._sqlite3_free(pzHead));
Module.HEAPU8.set(utf8, pzHead);
Module.HEAPU8[pzEnd - 1] = 0;
// Use extra space for the statement handle and SQL tail pointer.
const pStmt = pzHead + allocSize - 8;
const pzTail = pzHead + allocSize - 4;
// Ensure that statement handles are not leaked.
let stmt;
function maybeFinalize() {
if (stmt && !options.unscoped) {
sqlite3.finalize(stmt);
}
stmt = 0;
}
onFinally.push(maybeFinalize);
// Loop over statements.
Module.setValue(pzTail, pzHead, '*');
do {
// Reclaim resources for the previous iteration.
maybeFinalize();
// Call sqlite3_prepare_v3() for the next statement.
// Allow retry operations.
const zTail = Module.getValue(pzTail, '*');
const rc = await retry(() => {
return prepare(
db,
zTail,
pzEnd - pzTail,
options.flags || 0,
pStmt,
pzTail);
});
if (rc !== SQLite.SQLITE_OK) {
check('sqlite3_prepare_v3', rc, db);
}
stmt = Module.getValue(pStmt, '*');
if (stmt) {
mapStmtToDB.set(stmt, db);
yield stmt;
}
} while (stmt);
} finally {
while (onFinally.length) {
onFinally.pop()();
}
}
})();
};
sqlite3.step = (function() {
const fname = 'sqlite3_step';
const f = Module.cwrap(fname, ...decl('n:n'), { async });
return async function(stmt) {
verifyStatement(stmt);
// Allow retry operations.
const rc = await retry(() => f(stmt));
return check(fname, rc, mapStmtToDB.get(stmt), [SQLite.SQLITE_ROW, SQLite.SQLITE_DONE]);
};
})();
sqlite3.value = function(pValue) {
const type = sqlite3.value_type(pValue);
switch (type) {
case SQLite.SQLITE_BLOB:
return sqlite3.value_blob(pValue);
case SQLite.SQLITE_FLOAT:
return sqlite3.value_double(pValue);
case SQLite.SQLITE_INTEGER:
const lo32 = sqlite3.value_int(pValue);
const hi32 = Module.getTempRet0();
return cvt32x2AsSafe(lo32, hi32);
case SQLite.SQLITE_NULL:
return null;
case SQLite.SQLITE_TEXT:
return sqlite3.value_text(pValue);
default:
throw new SQLiteError('unknown type', type);
}
};
sqlite3.value_blob = (function() {
const fname = 'sqlite3_value_blob';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const nBytes = sqlite3.value_bytes(pValue);
const address = f(pValue);
const result = Module.HEAPU8.subarray(address, address + nBytes);
return result;
};
})();
sqlite3.value_bytes = (function() {
const fname = 'sqlite3_value_bytes';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const result = f(pValue);
return result;
};
})();
sqlite3.value_double = (function() {
const fname = 'sqlite3_value_double';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const result = f(pValue);
return result;
};
})();
sqlite3.value_int = (function() {
const fname = 'sqlite3_value_int64';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const result = f(pValue);
return result;
};
})();
sqlite3.value_int64 = (function() {
const fname = 'sqlite3_value_int64';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const lo32 = f(pValue);
const hi32 = Module.getTempRet0();
const result = cvt32x2ToBigInt(lo32, hi32);
return result;
};
})();
sqlite3.value_text = (function() {
const fname = 'sqlite3_value_text';
const f = Module.cwrap(fname, ...decl('n:s'));
return function(pValue) {
const result = f(pValue);
return result;
};
})();
sqlite3.value_type = (function() {
const fname = 'sqlite3_value_type';
const f = Module.cwrap(fname, ...decl('n:n'));
return function(pValue) {
const result = f(pValue);
return result;
};
})();
sqlite3.vfs_register = function(vfs, makeDefault) {
const result = Module.vfs_register(vfs, makeDefault);
return check('sqlite3_vfs_register', result);
};
function check(fname, result, db = null, allowed = [SQLite.SQLITE_OK]) {
if (allowed.includes(result)) return result;
const message = db ?
Module.ccall('sqlite3_errmsg', 'string', ['number'], [db]) :
fname;
throw new SQLiteError(message, result);
}
// This function is used to automatically retry failed calls that
// have pending retry operations that should allow the retry to
// succeed.
async function retry(f) {
let rc;
do {
// Wait for all pending retry operations to complete. This is
// normally empty on the first loop iteration.
if (Module.retryOps.length) {
await Promise.all(Module.retryOps);
Module.retryOps = [];
}
rc = await f();
// Retry on failure with new pending retry operations.
} while (rc && Module.retryOps.length);
return rc;
}
return sqlite3;
}
// Helper function to use a more compact signature specification.
function decl(s) {
const result = [];
const m = s.match(/([ns@]*):([nsv@])/);
switch (m[2]) {
case 'n': result.push('number'); break;
case 's': result.push('string'); break;
case 'v': result.push(null); break;
}
const args = [];
for (let c of m[1]) {
switch (c) {
case 'n': args.push('number'); break;
case 's': args.push('string'); break;
}
}
result.push(args);
return result;
}