-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsql-wasm-debug.js
6876 lines (6326 loc) · 237 KB
/
sql-wasm-debug.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
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
// We are modularizing this manually because the current modularize setting in Emscripten has some issues:
// https://github.com/kripken/emscripten/issues/5820
// In addition, When you use emcc's modularization, it still expects to export a global object called `Module`,
// which is able to be used/called before the WASM is loaded.
// The modularization below exports a promise that loads and resolves to the actual sql.js module.
// That way, this module can't be used before the WASM is finished loading.
// We are going to define a function that a user will call to start loading initializing our Sql.js library
// However, that function might be called multiple times, and on subsequent calls, we don't actually want it to instantiate a new instance of the Module
// Instead, we want to return the previously loaded module
// TODO: Make this not declare a global if used in the browser
var initSqlJsPromise = undefined;
var initSqlJs = function (moduleConfig) {
if (initSqlJsPromise){
return initSqlJsPromise;
}
// If we're here, we've never called this function before
initSqlJsPromise = new Promise(function (resolveModule, reject) {
// We are modularizing this manually because the current modularize setting in Emscripten has some issues:
// https://github.com/kripken/emscripten/issues/5820
// The way to affect the loading of emcc compiled modules is to create a variable called `Module` and add
// properties to it, like `preRun`, `postRun`, etc
// We are using that to get notified when the WASM has finished loading.
// Only then will we return our promise
// If they passed in a moduleConfig object, use that
// Otherwise, initialize Module to the empty object
var Module = typeof moduleConfig !== 'undefined' ? moduleConfig : {};
// EMCC only allows for a single onAbort function (not an array of functions)
// So if the user defined their own onAbort function, we remember it and call it
var originalOnAbortFunction = Module['onAbort'];
Module['onAbort'] = function (errorThatCausedAbort) {
reject(new Error(errorThatCausedAbort));
if (originalOnAbortFunction){
originalOnAbortFunction(errorThatCausedAbort);
}
};
Module['postRun'] = Module['postRun'] || [];
Module['postRun'].push(function () {
// When Emscripted calls postRun, this promise resolves with the built Module
resolveModule(Module);
});
// There is a section of code in the emcc-generated code below that looks like this:
// (Note that this is lowercase `module`)
// if (typeof module !== 'undefined') {
// module['exports'] = Module;
// }
// When that runs, it's going to overwrite our own modularization export efforts in shell-post.js!
// The only way to tell emcc not to emit it is to pass the MODULARIZE=1 or MODULARIZE_INSTANCE=1 flags,
// but that carries with it additional unnecessary baggage/bugs we don't want either.
// So, we have three options:
// 1) We undefine `module`
// 2) We remember what `module['exports']` was at the beginning of this function and we restore it later
// 3) We write a script to remove those lines of code as part of the Make process.
//
// Since those are the only lines of code that care about module, we will undefine it. It's the most straightforward
// of the options, and has the side effect of reducing emcc's efforts to modify the module if its output were to change in the future.
// That's a nice side effect since we're handling the modularization efforts ourselves
module = undefined;
// The emcc-generated code and shell-post.js code goes below,
// meaning that all of it runs inside of this promise. If anything throws an exception, our promise will abort
// include: shell.js
// The Module object: Our interface to the outside world. We import
// and export values on it. There are various ways Module can be used:
// 1. Not defined. We create it here
// 2. A function parameter, function(moduleArg) => Promise<Module>
// 3. pre-run appended it, var Module = {}; ..generated code..
// 4. External script tag defines var Module.
// We need to check if Module already exists (e.g. case 3 above).
// Substitution will be replaced with actual code on later stage of the build,
// this way Closure Compiler will not mangle it (e.g. case 4. above).
// Note that if you want to run closure, and also to use Module
// after the generated code, you will need to define var Module = {};
// before the code. Then that object will be used in the code, and you
// can continue to use Module afterwards as well.
var Module = typeof Module != 'undefined' ? Module : {};
// Determine the runtime environment we are in. You can customize this by
// setting the ENVIRONMENT setting at compile time (see settings.js).
// Attempt to auto-detect the environment
var ENVIRONMENT_IS_WEB = typeof window == 'object';
var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function';
// N.b. Electron.js environment is simultaneously a NODE-environment, but
// also a web environment.
var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
if (Module['ENVIRONMENT']) {
throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)');
}
if (ENVIRONMENT_IS_NODE) {
// `require()` is no-op in an ESM module, use `createRequire()` to construct
// the require()` function. This is only necessary for multi-environment
// builds, `-sENVIRONMENT=node` emits a static import declaration instead.
// TODO: Swap all `require()`'s with `import()`'s?
}
// --pre-jses are emitted after the Module integration code, so that they can
// refer to Module (if they choose; they can also define Module)
// include: /github/workspace/src/api.js
/* global
FS
HEAP8
Module
_malloc
_free
getValue
intArrayFromString
setValue
stackAlloc
stackRestore
stackSave
UTF8ToString
stringToUTF8
lengthBytesUTF8
allocate
ALLOC_NORMAL
allocateUTF8OnStack
removeFunction
addFunction
*/
"use strict";
/**
* @typedef {{Database:Database, Statement:Statement}} SqlJs
* @property {Database} Database A class that represents an SQLite database
* @property {Statement} Statement The prepared statement class
*/
/**
* @typedef {{locateFile:function(string):string}} SqlJsConfig
* @property {function(string):string} locateFile
* a function that returns the full path to a resource given its file name
* @see https://emscripten.org/docs/api_reference/module.html
*/
/**
* Asynchronously initializes sql.js
* @function initSqlJs
* @param {SqlJsConfig} config module inititialization parameters
* @returns {SqlJs}
* @example
* initSqlJs({
* locateFile: name => '/path/to/assets/' + name
* }).then(SQL => {
* const db = new SQL.Database();
* const result = db.exec("select 'hello world'");
* console.log(result);
* })
*/
/**
* @module SqlJs
*/
// Wait for preRun to run, and then finish our initialization
Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
// Declare toplevel variables
// register, used for temporary stack values
var apiTemp = stackAlloc(4);
var cwrap = Module["cwrap"];
// Null pointer
var NULL = 0;
// SQLite enum
var SQLITE_OK = 0;
var SQLITE_ROW = 100;
var SQLITE_DONE = 101;
var SQLITE_INTEGER = 1;
var SQLITE_FLOAT = 2;
var SQLITE_TEXT = 3;
var SQLITE_BLOB = 4;
// var - Encodings, used for registering functions.
var SQLITE_UTF8 = 1;
// var - cwrap function
var sqlite3_open = cwrap("sqlite3_open", "number", ["string", "number"]);
var sqlite3_close_v2 = cwrap("sqlite3_close_v2", "number", ["number"]);
var sqlite3_exec = cwrap(
"sqlite3_exec",
"number",
["number", "string", "number", "number", "number"]
);
var sqlite3_changes = cwrap("sqlite3_changes", "number", ["number"]);
var sqlite3_prepare_v2 = cwrap(
"sqlite3_prepare_v2",
"number",
["number", "string", "number", "number", "number"]
);
var sqlite3_sql = cwrap("sqlite3_sql", "string", ["number"]);
var sqlite3_normalized_sql = cwrap(
"sqlite3_normalized_sql",
"string",
["number"]
);
var sqlite3_prepare_v2_sqlptr = cwrap(
"sqlite3_prepare_v2",
"number",
["number", "number", "number", "number", "number"]
);
var sqlite3_bind_text = cwrap(
"sqlite3_bind_text",
"number",
["number", "number", "number", "number", "number"]
);
var sqlite3_bind_blob = cwrap(
"sqlite3_bind_blob",
"number",
["number", "number", "number", "number", "number"]
);
var sqlite3_bind_double = cwrap(
"sqlite3_bind_double",
"number",
["number", "number", "number"]
);
var sqlite3_bind_int = cwrap(
"sqlite3_bind_int",
"number",
["number", "number", "number"]
);
var sqlite3_bind_parameter_index = cwrap(
"sqlite3_bind_parameter_index",
"number",
["number", "string"]
);
var sqlite3_step = cwrap("sqlite3_step", "number", ["number"]);
var sqlite3_errmsg = cwrap("sqlite3_errmsg", "string", ["number"]);
var sqlite3_column_count = cwrap(
"sqlite3_column_count",
"number",
["number"]
);
var sqlite3_data_count = cwrap("sqlite3_data_count", "number", ["number"]);
var sqlite3_column_double = cwrap(
"sqlite3_column_double",
"number",
["number", "number"]
);
var sqlite3_column_text = cwrap(
"sqlite3_column_text",
"string",
["number", "number"]
);
var sqlite3_column_blob = cwrap(
"sqlite3_column_blob",
"number",
["number", "number"]
);
var sqlite3_column_bytes = cwrap(
"sqlite3_column_bytes",
"number",
["number", "number"]
);
var sqlite3_column_type = cwrap(
"sqlite3_column_type",
"number",
["number", "number"]
);
var sqlite3_column_name = cwrap(
"sqlite3_column_name",
"string",
["number", "number"]
);
var sqlite3_reset = cwrap("sqlite3_reset", "number", ["number"]);
var sqlite3_clear_bindings = cwrap(
"sqlite3_clear_bindings",
"number",
["number"]
);
var sqlite3_finalize = cwrap("sqlite3_finalize", "number", ["number"]);
var sqlite3_create_function_v2 = cwrap(
"sqlite3_create_function_v2",
"number",
[
"number",
"string",
"number",
"number",
"number",
"number",
"number",
"number",
"number"
]
);
var sqlite3_value_type = cwrap("sqlite3_value_type", "number", ["number"]);
var sqlite3_value_bytes = cwrap(
"sqlite3_value_bytes",
"number",
["number"]
);
var sqlite3_value_text = cwrap("sqlite3_value_text", "string", ["number"]);
var sqlite3_value_blob = cwrap("sqlite3_value_blob", "number", ["number"]);
var sqlite3_value_double = cwrap(
"sqlite3_value_double",
"number",
["number"]
);
var sqlite3_result_double = cwrap(
"sqlite3_result_double",
"",
["number", "number"]
);
var sqlite3_result_null = cwrap(
"sqlite3_result_null",
"",
["number"]
);
var sqlite3_result_text = cwrap(
"sqlite3_result_text",
"",
["number", "string", "number", "number"]
);
var sqlite3_result_blob = cwrap(
"sqlite3_result_blob",
"",
["number", "number", "number", "number"]
);
var sqlite3_result_int = cwrap(
"sqlite3_result_int",
"",
["number", "number"]
);
var sqlite3_result_error = cwrap(
"sqlite3_result_error",
"",
["number", "string", "number"]
);
// https://www.sqlite.org/c3ref/aggregate_context.html
// void *sqlite3_aggregate_context(sqlite3_context*, int nBytes)
var sqlite3_aggregate_context = cwrap(
"sqlite3_aggregate_context",
"number",
["number", "number"]
);
var registerExtensionFunctions = cwrap(
"RegisterExtensionFunctions",
"number",
["number"]
);
/**
* @classdesc
* Represents a prepared statement.
* Prepared statements allow you to have a template sql string,
* that you can execute multiple times with different parameters.
*
* You can't instantiate this class directly, you have to use a
* {@link Database} object in order to create a statement.
*
* **Warnings**
* 1. When you close a database (using db.close()), all
* its statements are closed too and become unusable.
* 1. After calling db.prepare() you must manually free the assigned memory
* by calling Statement.free(). Failure to do this will cause subsequent
* 'DROP TABLE ...' statements to fail with 'Uncaught Error: database table
* is locked'.
*
* Statements can't be created by the API user directly, only by
* Database::prepare
*
* @see Database.html#prepare-dynamic
* @see https://en.wikipedia.org/wiki/Prepared_statement
*
* @constructs Statement
* @memberof module:SqlJs
* @param {number} stmt1 The SQLite statement reference
* @param {Database} db The database from which this statement was created
*/
function Statement(stmt1, db) {
this.stmt = stmt1;
this.db = db;
// Index of the leftmost parameter is 1
this.pos = 1;
// Pointers to allocated memory, that need to be freed
// when the statemend is destroyed
this.allocatedmem = [];
}
/** @typedef {string|number|null|Uint8Array} Database.SqlValue */
/** @typedef {
Array<Database.SqlValue>|Object<string, Database.SqlValue>|null
} Statement.BindParams
*/
/** Bind values to the parameters, after having reseted the statement.
* If values is null, do nothing and return true.
*
* SQL statements can have parameters,
* named *'?', '?NNN', ':VVV', '@VVV', '$VVV'*,
* where NNN is a number and VVV a string.
* This function binds these parameters to the given values.
*
* *Warning*: ':', '@', and '$' are included in the parameters names
*
* ## Value types
* Javascript type | SQLite type
* -----------------| -----------
* number | REAL, INTEGER
* boolean | INTEGER
* string | TEXT
* Array, Uint8Array| BLOB
* null | NULL
*
* @example <caption>Bind values to named parameters</caption>
* var stmt = db.prepare(
* "UPDATE test SET a=@newval WHERE id BETWEEN $mini AND $maxi"
* );
* stmt.bind({$mini:10, $maxi:20, '@newval':5});
*
* @example <caption>Bind values to anonymous parameters</caption>
* // Create a statement that contains parameters like '?', '?NNN'
* var stmt = db.prepare("UPDATE test SET a=? WHERE id BETWEEN ? AND ?");
* // Call Statement.bind with an array as parameter
* stmt.bind([5, 10, 20]);
*
* @see http://www.sqlite.org/datatype3.html
* @see http://www.sqlite.org/lang_expr.html#varparam
* @param {Statement.BindParams} values The values to bind
* @return {boolean} true if it worked
* @throws {String} SQLite Error
*/
Statement.prototype["bind"] = function bind(values) {
if (!this.stmt) {
throw "Statement closed";
}
this["reset"]();
if (Array.isArray(values)) return this.bindFromArray(values);
if (values != null && typeof values === "object") {
return this.bindFromObject(values);
}
return true;
};
/** Execute the statement, fetching the the next line of result,
that can be retrieved with {@link Statement.get}.
@return {boolean} true if a row of result available
@throws {String} SQLite Error
*/
Statement.prototype["step"] = function step() {
if (!this.stmt) {
throw "Statement closed";
}
this.pos = 1;
var ret = sqlite3_step(this.stmt);
switch (ret) {
case SQLITE_ROW:
return true;
case SQLITE_DONE:
return false;
default:
throw this.db.handleError(ret);
}
};
/*
Internal methods to retrieve data from the results of a statement
that has been executed
*/
Statement.prototype.getNumber = function getNumber(pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
return sqlite3_column_double(this.stmt, pos);
};
Statement.prototype.getBigInt = function getBigInt(pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
var text = sqlite3_column_text(this.stmt, pos);
if (typeof BigInt !== "function") {
throw new Error("BigInt is not supported");
}
/* global BigInt */
return BigInt(text);
};
Statement.prototype.getString = function getString(pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
return sqlite3_column_text(this.stmt, pos);
};
Statement.prototype.getBlob = function getBlob(pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
var size = sqlite3_column_bytes(this.stmt, pos);
var ptr = sqlite3_column_blob(this.stmt, pos);
var result = new Uint8Array(size);
for (var i = 0; i < size; i += 1) {
result[i] = HEAP8[ptr + i];
}
return result;
};
/** Get one row of results of a statement.
If the first parameter is not provided, step must have been called before.
@param {Statement.BindParams} [params] If set, the values will be bound
to the statement before it is executed
@return {Array<Database.SqlValue>} One row of result
@example
<caption>Print all the rows of the table test to the console</caption>
var stmt = db.prepare("SELECT * FROM test");
while (stmt.step()) console.log(stmt.get());
<caption>Enable BigInt support</caption>
var stmt = db.prepare("SELECT * FROM test");
while (stmt.step()) console.log(stmt.get(null, {useBigInt: true}));
*/
Statement.prototype["get"] = function get(params, config) {
config = config || {};
if (params != null && this["bind"](params)) {
this["step"]();
}
var results1 = [];
var ref = sqlite3_data_count(this.stmt);
for (var field = 0; field < ref; field += 1) {
switch (sqlite3_column_type(this.stmt, field)) {
case SQLITE_INTEGER:
var getfunc = config["useBigInt"]
? this.getBigInt(field)
: this.getNumber(field);
results1.push(getfunc);
break;
case SQLITE_FLOAT:
results1.push(this.getNumber(field));
break;
case SQLITE_TEXT:
results1.push(this.getString(field));
break;
case SQLITE_BLOB:
results1.push(this.getBlob(field));
break;
default:
results1.push(null);
}
}
return results1;
};
/** Get the list of column names of a row of result of a statement.
@return {Array<string>} The names of the columns
@example
var stmt = db.prepare(
"SELECT 5 AS nbr, x'616200' AS data, NULL AS null_value;"
);
stmt.step(); // Execute the statement
console.log(stmt.getColumnNames());
// Will print ['nbr','data','null_value']
*/
Statement.prototype["getColumnNames"] = function getColumnNames() {
var results1 = [];
var ref = sqlite3_column_count(this.stmt);
for (var i = 0; i < ref; i += 1) {
results1.push(sqlite3_column_name(this.stmt, i));
}
return results1;
};
/** Get one row of result as a javascript object, associating column names
with their value in the current row.
@param {Statement.BindParams} [params] If set, the values will be bound
to the statement, and it will be executed
@return {Object<string, Database.SqlValue>} The row of result
@see {@link Statement.get}
@example
var stmt = db.prepare(
"SELECT 5 AS nbr, x'010203' AS data, NULL AS null_value;"
);
stmt.step(); // Execute the statement
console.log(stmt.getAsObject());
// Will print {nbr:5, data: Uint8Array([1,2,3]), null_value:null}
*/
Statement.prototype["getAsObject"] = function getAsObject(params, config) {
var values = this["get"](params, config);
var names = this["getColumnNames"]();
var rowObject = {};
for (var i = 0; i < names.length; i += 1) {
var name = names[i];
rowObject[name] = values[i];
}
return rowObject;
};
/** Get the SQL string used in preparing this statement.
@return {string} The SQL string
*/
Statement.prototype["getSQL"] = function getSQL() {
return sqlite3_sql(this.stmt);
};
/** Get the SQLite's normalized version of the SQL string used in
preparing this statement. The meaning of "normalized" is not
well-defined: see {@link https://sqlite.org/c3ref/expanded_sql.html
the SQLite documentation}.
@example
db.run("create table test (x integer);");
stmt = db.prepare("select * from test where x = 42");
// returns "SELECT*FROM test WHERE x=?;"
@return {string} The normalized SQL string
*/
Statement.prototype["getNormalizedSQL"] = function getNormalizedSQL() {
return sqlite3_normalized_sql(this.stmt);
};
/** Shorthand for bind + step + reset
Bind the values, execute the statement, ignoring the rows it returns,
and resets it
@param {Statement.BindParams} [values] Value to bind to the statement
*/
Statement.prototype["run"] = function run(values) {
if (values != null) {
this["bind"](values);
}
this["step"]();
return this["reset"]();
};
Statement.prototype.bindString = function bindString(string, pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
var bytes = intArrayFromString(string);
var strptr = allocate(bytes, ALLOC_NORMAL);
this.allocatedmem.push(strptr);
this.db.handleError(sqlite3_bind_text(
this.stmt,
pos,
strptr,
bytes.length - 1,
0
));
return true;
};
Statement.prototype.bindBlob = function bindBlob(array, pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
var blobptr = allocate(array, ALLOC_NORMAL);
this.allocatedmem.push(blobptr);
this.db.handleError(sqlite3_bind_blob(
this.stmt,
pos,
blobptr,
array.length,
0
));
return true;
};
Statement.prototype.bindNumber = function bindNumber(num, pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
var bindfunc = (
num === (num | 0)
? sqlite3_bind_int
: sqlite3_bind_double
);
this.db.handleError(bindfunc(this.stmt, pos, num));
return true;
};
Statement.prototype.bindNull = function bindNull(pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
return sqlite3_bind_blob(this.stmt, pos, 0, 0, 0) === SQLITE_OK;
};
Statement.prototype.bindValue = function bindValue(val, pos) {
if (pos == null) {
pos = this.pos;
this.pos += 1;
}
switch (typeof val) {
case "string":
return this.bindString(val, pos);
case "number":
return this.bindNumber(val + 0, pos);
case "bigint":
// BigInt is not fully supported yet at WASM level.
return this.bindString(val.toString(), pos);
case "boolean":
return this.bindNumber(val + 0, pos);
case "object":
if (val === null) {
return this.bindNull(pos);
}
if (val.length != null) {
return this.bindBlob(val, pos);
}
break;
default:
break;
}
throw (
"Wrong API use : tried to bind a value of an unknown type ("
+ val + ")."
);
};
/** Bind names and values of an object to the named parameters of the
statement
@param {Object<string, Database.SqlValue>} valuesObj
@private
@nodoc
*/
Statement.prototype.bindFromObject = function bindFromObject(valuesObj) {
var that = this;
Object.keys(valuesObj).forEach(function each(name) {
var num = sqlite3_bind_parameter_index(that.stmt, name);
if (num !== 0) {
that.bindValue(valuesObj[name], num);
}
});
return true;
};
/** Bind values to numbered parameters
@param {Array<Database.SqlValue>} values
@private
@nodoc
*/
Statement.prototype.bindFromArray = function bindFromArray(values) {
for (var num = 0; num < values.length; num += 1) {
this.bindValue(values[num], num + 1);
}
return true;
};
/** Reset a statement, so that its parameters can be bound to new values
It also clears all previous bindings, freeing the memory used
by bound parameters.
*/
Statement.prototype["reset"] = function reset() {
this["freemem"]();
return (
sqlite3_clear_bindings(this.stmt) === SQLITE_OK
&& sqlite3_reset(this.stmt) === SQLITE_OK
);
};
/** Free the memory allocated during parameter binding */
Statement.prototype["freemem"] = function freemem() {
var mem;
while ((mem = this.allocatedmem.pop()) !== undefined) {
_free(mem);
}
};
/** Free the memory used by the statement
@return {boolean} true in case of success
*/
Statement.prototype["free"] = function free() {
var res;
this["freemem"]();
res = sqlite3_finalize(this.stmt) === SQLITE_OK;
delete this.db.statements[this.stmt];
this.stmt = NULL;
return res;
};
/**
* @classdesc
* An iterator over multiple SQL statements in a string,
* preparing and returning a Statement object for the next SQL
* statement on each iteration.
*
* You can't instantiate this class directly, you have to use a
* {@link Database} object in order to create a statement iterator
*
* {@see Database#iterateStatements}
*
* @example
* // loop over and execute statements in string sql
* for (let statement of db.iterateStatements(sql) {
* statement.step();
* // get results, etc.
* // do not call statement.free() manually, each statement is freed
* // before the next one is parsed
* }
*
* // capture any bad query exceptions with feedback
* // on the bad sql
* let it = db.iterateStatements(sql);
* try {
* for (let statement of it) {
* statement.step();
* }
* } catch(e) {
* console.log(
* `The SQL string "${it.getRemainingSQL()}" ` +
* `contains the following error: ${e}`
* );
* }
*
* @implements {Iterator<Statement>}
* @implements {Iterable<Statement>}
* @constructs StatementIterator
* @memberof module:SqlJs
* @param {string} sql A string containing multiple SQL statements
* @param {Database} db The database from which this iterator was created
*/
function StatementIterator(sql, db) {
this.db = db;
var sz = lengthBytesUTF8(sql) + 1;
this.sqlPtr = _malloc(sz);
if (this.sqlPtr === null) {
throw new Error("Unable to allocate memory for the SQL string");
}
stringToUTF8(sql, this.sqlPtr, sz);
this.nextSqlPtr = this.sqlPtr;
this.nextSqlString = null;
this.activeStatement = null;
}
/**
* @typedef {{ done:true, value:undefined } |
* { done:false, value:Statement}}
* StatementIterator.StatementIteratorResult
* @property {Statement} value the next available Statement
* (as returned by {@link Database.prepare})
* @property {boolean} done true if there are no more available statements
*/
/** Prepare the next available SQL statement
@return {StatementIterator.StatementIteratorResult}
@throws {String} SQLite error or invalid iterator error
*/
StatementIterator.prototype["next"] = function next() {
if (this.sqlPtr === null) {
return { done: true };
}
if (this.activeStatement !== null) {
this.activeStatement["free"]();
this.activeStatement = null;
}
if (!this.db.db) {
this.finalize();
throw new Error("Database closed");
}
var stack = stackSave();
var pzTail = stackAlloc(4);
setValue(apiTemp, 0, "i32");
setValue(pzTail, 0, "i32");
try {
this.db.handleError(sqlite3_prepare_v2_sqlptr(
this.db.db,
this.nextSqlPtr,
-1,
apiTemp,
pzTail
));
this.nextSqlPtr = getValue(pzTail, "i32");
var pStmt = getValue(apiTemp, "i32");
if (pStmt === NULL) {
this.finalize();
return { done: true };
}
this.activeStatement = new Statement(pStmt, this.db);
this.db.statements[pStmt] = this.activeStatement;
return { value: this.activeStatement, done: false };
} catch (e) {
this.nextSqlString = UTF8ToString(this.nextSqlPtr);
this.finalize();
throw e;
} finally {
stackRestore(stack);
}
};
StatementIterator.prototype.finalize = function finalize() {
_free(this.sqlPtr);
this.sqlPtr = null;
};
/** Get any un-executed portions remaining of the original SQL string
@return {String}
*/
StatementIterator.prototype["getRemainingSQL"] = function getRemainder() {
// iff an exception occurred, we set the nextSqlString
if (this.nextSqlString !== null) return this.nextSqlString;
// otherwise, convert from nextSqlPtr
return UTF8ToString(this.nextSqlPtr);
};
/* implement Iterable interface */
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
StatementIterator.prototype[Symbol.iterator] = function iterator() {
return this;
};
}
/** @classdesc
* Represents an SQLite database
* @constructs Database
* @memberof module:SqlJs
* Open a new database either by creating a new one or opening an existing
* one stored in the byte array passed in first argument
* @param {Array<number>} data An array of bytes representing
* an SQLite database file
*/
function Database(data) {
this.filename = "dbfile_" + (0xffffffff * Math.random() >>> 0);
if (data != null) {
FS.createDataFile("/", this.filename, data, true, true);
}
this.handleError(sqlite3_open(this.filename, apiTemp));
this.db = getValue(apiTemp, "i32");
registerExtensionFunctions(this.db);
// A list of all prepared statements of the database
this.statements = {};
// A list of all user function of the database
// (created by create_function call)
this.functions = {};
}
/** Execute an SQL query, ignoring the rows it returns.
@param {string} sql a string containing some SQL text to execute
@param {Statement.BindParams} [params] When the SQL statement contains
placeholders, you can pass them in here. They will be bound to the statement
before it is executed. If you use the params argument, you **cannot**
provide an sql string that contains several statements (separated by `;`)
@example
// Insert values in a table
db.run(
"INSERT INTO test VALUES (:age, :name)",
{ ':age' : 18, ':name' : 'John' }
);
@return {Database} The database object (useful for method chaining)
*/
Database.prototype["run"] = function run(sql, params) {
if (!this.db) {
throw "Database closed";
}
if (params) {
var stmt = this["prepare"](sql, params);
try {
stmt["step"]();
} finally {
stmt["free"]();
}
} else {
this.handleError(sqlite3_exec(this.db, sql, 0, 0, apiTemp));
}
return this;
};
/**
* @typedef {{
columns:Array<string>,
values:Array<Array<Database.SqlValue>>
}} Database.QueryExecResult
* @property {Array<string>} columns the name of the columns of the result
* (as returned by {@link Statement.getColumnNames})
* @property {
* Array<Array<Database.SqlValue>>
* } values one array per row, containing
* the column values
*/
/** Execute an SQL query, and returns the result.
*