This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSqlite.jsm
1680 lines (1512 loc) · 54.6 KB
/
Sqlite.jsm
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var EXPORTED_SYMBOLS = ["Sqlite"];
// The maximum time to wait before considering a transaction stuck and rejecting
// it. (Note that the minimum amount of time we wait is 20% less than this, see
// the `_getTimeoutPromise` method on `ConnectionData` for details).
const TRANSACTIONS_QUEUE_TIMEOUT_MS = 300000; // 5 minutes
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
Services: "resource://gre/modules/Services.jsm",
OS: "resource://gre/modules/osfile.jsm",
Log: "resource://gre/modules/Log.jsm",
FileUtils: "resource://gre/modules/FileUtils.jsm",
PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
});
XPCOMUtils.defineLazyServiceGetter(
this,
"FinalizationWitnessService",
"@mozilla.org/toolkit/finalizationwitness;1",
"nsIFinalizationWitnessService"
);
// Regular expression used by isInvalidBoundLikeQuery
var likeSqlRegex = /\bLIKE\b\s(?![@:?])/i;
// Counts the number of created connections per database basename(). This is
// used for logging to distinguish connection instances.
var connectionCounters = new Map();
// Tracks identifiers of wrapped connections, that are Storage connections
// opened through mozStorage and then wrapped by Sqlite.jsm to use its syntactic
// sugar API. Since these connections have an unknown origin, we use this set
// to differentiate their behavior.
var wrappedConnections = new Set();
/**
* Once `true`, reject any attempt to open or close a database.
*/
var isClosed = false;
var Debugging = {
// Tests should fail if a connection auto closes. The exception is
// when finalization itself is tested, in which case this flag
// should be set to false.
failTestsOnAutoClose: true,
};
/**
* Helper function to check whether LIKE is implemented using proper bindings.
*
* @param sql
* (string) The SQL query to be verified.
* @return boolean value telling us whether query was correct or not
*/
function isInvalidBoundLikeQuery(sql) {
return likeSqlRegex.test(sql);
}
// Displays a script error message
function logScriptError(message) {
let consoleMessage = Cc["@mozilla.org/scripterror;1"].createInstance(
Ci.nsIScriptError
);
let stack = new Error();
consoleMessage.init(
message,
stack.fileName,
null,
stack.lineNumber,
0,
Ci.nsIScriptError.errorFlag,
"component javascript"
);
Services.console.logMessage(consoleMessage);
// This `Promise.reject` will cause tests to fail. The debugging
// flag can be used to suppress this for tests that explicitly
// test auto closes.
if (Debugging.failTestsOnAutoClose) {
Promise.reject(new Error(message));
}
}
/**
* Gets connection identifier from its database file name.
*
* @param fileName
* A database file string name.
* @return the connection identifier.
*/
function getIdentifierByFileName(fileName) {
let number = connectionCounters.get(fileName) || 0;
connectionCounters.set(fileName, number + 1);
return fileName + "#" + number;
}
/**
* Barriers used to ensure that Sqlite.jsm is shutdown after all
* its clients.
*/
XPCOMUtils.defineLazyGetter(this, "Barriers", () => {
let Barriers = {
/**
* Public barrier that clients may use to add blockers to the
* shutdown of Sqlite.jsm. Triggered by profile-before-change.
* Once all blockers of this barrier are lifted, we close the
* ability to open new connections.
*/
shutdown: new AsyncShutdown.Barrier(
"Sqlite.jsm: wait until all clients have completed their task"
),
/**
* Private barrier blocked by connections that are still open.
* Triggered after Barriers.shutdown is lifted and `isClosed` is
* set to `true`.
*/
connections: new AsyncShutdown.Barrier(
"Sqlite.jsm: wait until all connections are closed"
),
};
/**
* Observer for the event which is broadcasted when the finalization
* witness `_witness` of `OpenedConnection` is garbage collected.
*
* The observer is passed the connection identifier of the database
* connection that is being finalized.
*/
let finalizationObserver = function(subject, topic, identifier) {
let connectionData = ConnectionData.byId.get(identifier);
if (connectionData === undefined) {
logScriptError(
"Error: Attempt to finalize unknown Sqlite connection: " +
identifier +
"\n"
);
return;
}
ConnectionData.byId.delete(identifier);
logScriptError(
"Warning: Sqlite connection '" +
identifier +
"' was not properly closed. Auto-close triggered by garbage collection.\n"
);
connectionData.close();
};
Services.obs.addObserver(finalizationObserver, "sqlite-finalization-witness");
/**
* Ensure that Sqlite.jsm:
* - informs its clients before shutting down;
* - lets clients open connections during shutdown, if necessary;
* - waits for all connections to be closed before shutdown.
*/
AsyncShutdown.profileBeforeChange.addBlocker(
"Sqlite.jsm shutdown blocker",
async function() {
await Barriers.shutdown.wait();
// At this stage, all clients have had a chance to open (and close)
// their databases. Some previous close operations may still be pending,
// so we need to wait until they are complete before proceeding.
// Prevent any new opening.
isClosed = true;
// Now, wait until all databases are closed
await Barriers.connections.wait();
// Everything closed, no finalization events to catch
Services.obs.removeObserver(
finalizationObserver,
"sqlite-finalization-witness"
);
},
function status() {
if (isClosed) {
// We are waiting for the connections to close. The interesting
// status is therefore the list of connections still pending.
return {
description: "Waiting for connections to close",
state: Barriers.connections.state,
};
}
// We are still in the first stage: waiting for the barrier
// to be lifted. The interesting status is therefore that of
// the barrier.
return {
description: "Waiting for the barrier to be lifted",
state: Barriers.shutdown.state,
};
}
);
return Barriers;
});
/**
* Connection data with methods necessary for closing the connection.
*
* To support auto-closing in the event of garbage collection, this
* data structure contains all the connection data of an opened
* connection and all of the methods needed for sucessfully closing
* it.
*
* By putting this information in its own separate object, it is
* possible to store an additional reference to it without preventing
* a garbage collection of a finalization witness in
* OpenedConnection. When the witness detects a garbage collection,
* this object can be used to close the connection.
*
* This object contains more methods than just `close`. When
* OpenedConnection needs to use the methods in this object, it will
* dispatch its method calls here.
*/
function ConnectionData(connection, identifier, options = {}) {
this._log = Log.repository.getLoggerWithMessagePrefix(
"Sqlite.Connection",
identifier + ": "
);
this._log.info("Opened");
this._dbConn = connection;
// This is a unique identifier for the connection, generated through
// getIdentifierByFileName. It may be used for logging or as a key in Maps.
this._identifier = identifier;
this._open = true;
this._cachedStatements = new Map();
this._anonymousStatements = new Map();
this._anonymousCounter = 0;
// A map from statement index to mozIStoragePendingStatement, to allow for
// canceling prior to finalizing the mozIStorageStatements.
this._pendingStatements = new Map();
// Increments for each executed statement for the life of the connection.
this._statementCounter = 0;
// Increments whenever we request a unique operation id.
this._operationsCounter = 0;
if ("defaultTransactionType" in options) {
this.defaultTransactionType = options.defaultTransactionType;
} else {
this.defaultTransactionType = convertStorageTransactionType(
this._dbConn.defaultTransactionType
);
}
this._hasInProgressTransaction = false;
// Manages a chain of transactions promises, so that new transactions
// always happen in queue to the previous ones. It never rejects.
this._transactionQueue = Promise.resolve();
this._idleShrinkMS = options.shrinkMemoryOnConnectionIdleMS;
if (this._idleShrinkMS) {
this._idleShrinkTimer = Cc["@mozilla.org/timer;1"].createInstance(
Ci.nsITimer
);
// We wait for the first statement execute to start the timer because
// shrinking now would not do anything.
}
// Deferred whose promise is resolved when the connection closing procedure
// is complete.
this._deferredClose = PromiseUtils.defer();
this._closeRequested = false;
// An AsyncShutdown barrier used to make sure that we wait until clients
// are done before shutting down the connection.
this._barrier = new AsyncShutdown.Barrier(
`${this._identifier}: waiting for clients`
);
Barriers.connections.client.addBlocker(
this._identifier + ": waiting for shutdown",
this._deferredClose.promise,
() => ({
identifier: this._identifier,
isCloseRequested: this._closeRequested,
hasDbConn: !!this._dbConn,
hasInProgressTransaction: this._hasInProgressTransaction,
pendingStatements: this._pendingStatements.size,
statementCounter: this._statementCounter,
})
);
// We avoid creating a timer every transaction that exists solely as a safety
// check (e.g. one that never should fire) by reusing it if it's sufficiently
// close to when the previous promise was created (see bug 1442353 and
// `_getTimeoutPromise` for more info).
this._timeoutPromise = null;
// The last timestamp when we should consider using `this._timeoutPromise`.
this._timeoutPromiseExpires = 0;
}
/**
* Map of connection identifiers to ConnectionData objects
*
* The connection identifier is a human-readable name of the
* database. Used by finalization witnesses to be able to close opened
* connections on garbage collection.
*
* Key: _identifier of ConnectionData
* Value: ConnectionData object
*/
ConnectionData.byId = new Map();
ConnectionData.prototype = Object.freeze({
/**
* Run a task, ensuring that its execution will not be interrupted by shutdown.
*
* As the operations of this module are asynchronous, a sequence of operations,
* or even an individual operation, can still be pending when the process shuts
* down. If any of this operations is a write, this can cause data loss, simply
* because the write has not been completed (or even started) by shutdown.
*
* To avoid this risk, clients are encouraged to use `executeBeforeShutdown` for
* any write operation, as follows:
*
* myConnection.executeBeforeShutdown("Bookmarks: Removing a bookmark",
* async function(db) {
* // The connection will not be closed and shutdown will not proceed
* // until this task has completed.
*
* // `db` exposes the same API as `myConnection` but provides additional
* // logging support to help debug hard-to-catch shutdown timeouts.
*
* await db.execute(...);
* }));
*
* @param {string} name A human-readable name for the ongoing operation, used
* for logging and debugging purposes.
* @param {function(db)} task A function that takes as argument a Sqlite.jsm
* db and returns a Promise.
*/
executeBeforeShutdown(parent, name, task) {
if (!name) {
throw new TypeError("Expected a human-readable name as first argument");
}
if (typeof task != "function") {
throw new TypeError("Expected a function as second argument");
}
if (this._closeRequested) {
throw new Error(
`${
this._identifier
}: cannot execute operation ${name}, the connection is already closing`
);
}
// Status, used for AsyncShutdown crash reports.
let status = {
// The latest command started by `task`, either as a
// sql string, or as one of "<not started>" or "<closing>".
command: "<not started>",
// `true` if `command` was started but not completed yet.
isPending: false,
};
// An object with the same API as `this` but with
// additional logging. To keep logging simple, we
// assume that `task` is not running several queries
// concurrently.
let loggedDb = Object.create(parent, {
execute: {
value: async (sql, ...rest) => {
status.isPending = true;
status.command = sql;
try {
return await this.execute(sql, ...rest);
} finally {
status.isPending = false;
}
},
},
close: {
value: async () => {
status.isPending = false;
status.command = "<close>";
try {
return await this.close();
} finally {
status.isPending = false;
}
},
},
executeCached: {
value: async (sql, ...rest) => {
status.isPending = false;
status.command = sql;
try {
return await this.executeCached(sql, ...rest);
} finally {
status.isPending = false;
}
},
},
});
let promiseResult = task(loggedDb);
if (
!promiseResult ||
typeof promiseResult != "object" ||
!("then" in promiseResult)
) {
throw new TypeError("Expected a Promise");
}
let key = `${this._identifier}: ${name} (${this._getOperationId()})`;
let promiseComplete = promiseResult.catch(() => {});
this._barrier.client.addBlocker(key, promiseComplete, {
fetchState: () => status,
});
return (async () => {
try {
return await promiseResult;
} finally {
this._barrier.client.removeBlocker(key, promiseComplete);
}
})();
},
close() {
this._closeRequested = true;
if (!this._dbConn) {
return this._deferredClose.promise;
}
this._log.debug("Request to close connection.");
this._clearIdleShrinkTimer();
return this._barrier.wait().then(() => {
if (!this._dbConn) {
return undefined;
}
return this._finalize();
});
},
clone(readOnly = false) {
this.ensureOpen();
this._log.debug("Request to clone connection.");
let options = {
connection: this._dbConn,
readOnly,
};
if (this._idleShrinkMS) {
options.shrinkMemoryOnConnectionIdleMS = this._idleShrinkMS;
}
return cloneStorageConnection(options);
},
_getOperationId() {
return this._operationsCounter++;
},
_finalize() {
this._log.debug("Finalizing connection.");
// Cancel any pending statements.
for (let [, /* k */ statement] of this._pendingStatements) {
statement.cancel();
}
this._pendingStatements.clear();
// We no longer need to track these.
this._statementCounter = 0;
// Next we finalize all active statements.
for (let [, /* k */ statement] of this._anonymousStatements) {
statement.finalize();
}
this._anonymousStatements.clear();
for (let [, /* k */ statement] of this._cachedStatements) {
statement.finalize();
}
this._cachedStatements.clear();
// This guards against operations performed between the call to this
// function and asyncClose() finishing. See also bug 726990.
this._open = false;
// We must always close the connection at the Sqlite.jsm-level, not
// necessarily at the mozStorage-level.
let markAsClosed = () => {
this._log.info("Closed");
// Now that the connection is closed, no need to keep
// a blocker for Barriers.connections.
Barriers.connections.client.removeBlocker(this._deferredClose.promise);
this._deferredClose.resolve();
};
if (wrappedConnections.has(this._identifier)) {
wrappedConnections.delete(this._identifier);
this._dbConn = null;
markAsClosed();
} else {
this._log.debug("Calling asyncClose().");
this._dbConn.asyncClose(markAsClosed);
this._dbConn = null;
}
return this._deferredClose.promise;
},
executeCached(sql, params = null, onRow = null) {
this.ensureOpen();
if (!sql) {
throw new Error("sql argument is empty.");
}
let statement = this._cachedStatements.get(sql);
if (!statement) {
statement = this._dbConn.createAsyncStatement(sql);
this._cachedStatements.set(sql, statement);
}
this._clearIdleShrinkTimer();
return new Promise((resolve, reject) => {
try {
this._executeStatement(sql, statement, params, onRow).then(
result => {
this._startIdleShrinkTimer();
resolve(result);
},
error => {
this._startIdleShrinkTimer();
reject(error);
}
);
} catch (ex) {
this._startIdleShrinkTimer();
throw ex;
}
});
},
execute(sql, params = null, onRow = null) {
if (typeof sql != "string") {
throw new Error("Must define SQL to execute as a string: " + sql);
}
this.ensureOpen();
let statement = this._dbConn.createAsyncStatement(sql);
let index = this._anonymousCounter++;
this._anonymousStatements.set(index, statement);
this._clearIdleShrinkTimer();
let onFinished = () => {
this._anonymousStatements.delete(index);
statement.finalize();
this._startIdleShrinkTimer();
};
return new Promise((resolve, reject) => {
try {
this._executeStatement(sql, statement, params, onRow).then(
rows => {
onFinished();
resolve(rows);
},
error => {
onFinished();
reject(error);
}
);
} catch (ex) {
onFinished();
throw ex;
}
});
},
get transactionInProgress() {
return this._open && this._hasInProgressTransaction;
},
executeTransaction(func, type) {
if (type == OpenedConnection.prototype.TRANSACTION_DEFAULT) {
type = this.defaultTransactionType;
} else if (!OpenedConnection.TRANSACTION_TYPES.includes(type)) {
throw new Error("Unknown transaction type: " + type);
}
this.ensureOpen();
this._log.debug("Beginning transaction");
let promise = this._transactionQueue.then(() => {
if (this._closeRequested) {
throw new Error("Transaction canceled due to a closed connection.");
}
let transactionPromise = (async () => {
// At this point we should never have an in progress transaction, since
// they are enqueued.
if (this._hasInProgressTransaction) {
console.error(
"Unexpected transaction in progress when trying to start a new one."
);
}
this._hasInProgressTransaction = true;
try {
// We catch errors in statement execution to detect nested transactions.
try {
await this.execute("BEGIN " + type + " TRANSACTION");
} catch (ex) {
// Unfortunately, if we are wrapping an existing connection, a
// transaction could have been started by a client of the same
// connection that doesn't use Sqlite.jsm (e.g. C++ consumer).
// The best we can do is proceed without a transaction and hope
// things won't break.
if (wrappedConnections.has(this._identifier)) {
this._log.warn(
"A new transaction could not be started cause the wrapped connection had one in progress",
ex
);
// Unmark the in progress transaction, since it's managed by
// some other non-Sqlite.jsm client. See the comment above.
this._hasInProgressTransaction = false;
} else {
this._log.warn(
"A transaction was already in progress, likely a nested transaction",
ex
);
throw ex;
}
}
let result;
try {
result = await func();
} catch (ex) {
// It's possible that the exception has been caused by trying to
// close the connection in the middle of a transaction.
if (this._closeRequested) {
this._log.warn(
"Connection closed while performing a transaction",
ex
);
} else {
this._log.warn("Error during transaction. Rolling back", ex);
// If we began a transaction, we must rollback it.
if (this._hasInProgressTransaction) {
try {
await this.execute("ROLLBACK TRANSACTION");
} catch (inner) {
this._log.warn("Could not roll back transaction", inner);
}
}
}
// Rethrow the exception.
throw ex;
}
// See comment above about connection being closed during transaction.
if (this._closeRequested) {
this._log.warn(
"Connection closed before committing the transaction."
);
throw new Error(
"Connection closed before committing the transaction."
);
}
// If we began a transaction, we must commit it.
if (this._hasInProgressTransaction) {
try {
await this.execute("COMMIT TRANSACTION");
} catch (ex) {
this._log.warn("Error committing transaction", ex);
throw ex;
}
}
return result;
} finally {
this._hasInProgressTransaction = false;
}
})();
// If a transaction yields on a never resolved promise, or is mistakenly
// nested, it could hang the transactions queue forever. Thus we timeout
// the execution after a meaningful amount of time, to ensure in any case
// we'll proceed after a while.
let timeoutPromise = this._getTimeoutPromise();
return Promise.race([transactionPromise, timeoutPromise]);
});
// Atomically update the queue before anyone else has a chance to enqueue
// further transactions.
this._transactionQueue = promise.catch(ex => {
console.error(ex);
});
// Make sure that we do not shutdown the connection during a transaction.
this._barrier.client.addBlocker(
`Transaction (${this._getOperationId()})`,
this._transactionQueue
);
return promise;
},
shrinkMemory() {
this._log.info("Shrinking memory usage.");
let onShrunk = this._clearIdleShrinkTimer.bind(this);
return this.execute("PRAGMA shrink_memory").then(onShrunk, onShrunk);
},
discardCachedStatements() {
let count = 0;
for (let [, /* k */ statement] of this._cachedStatements) {
++count;
statement.finalize();
}
this._cachedStatements.clear();
this._log.debug("Discarded " + count + " cached statements.");
return count;
},
interrupt() {
this._log.info("Trying to interrupt.");
this.ensureOpen();
this._dbConn.interrupt();
},
/**
* Helper method to bind parameters of various kinds through
* reflection.
*/
_bindParameters(statement, params) {
if (!params) {
return;
}
function bindParam(obj, key, val) {
let isBlob =
val && typeof val == "object" && val.constructor.name == "Uint8Array";
let args = [key, val];
if (isBlob) {
args.push(val.length);
}
let methodName = `bind${isBlob ? "Blob" : ""}By${
typeof key == "number" ? "Index" : "Name"
}`;
obj[methodName](...args);
}
if (Array.isArray(params)) {
// It's an array of separate params.
if (params.length && typeof params[0] == "object" && params[0] !== null) {
let paramsArray = statement.newBindingParamsArray();
for (let p of params) {
let bindings = paramsArray.newBindingParams();
for (let [key, value] of Object.entries(p)) {
bindParam(bindings, key, value);
}
paramsArray.addParams(bindings);
}
statement.bindParameters(paramsArray);
return;
}
// Indexed params.
for (let i = 0; i < params.length; i++) {
bindParam(statement, i, params[i]);
}
return;
}
// Named params.
if (params && typeof params == "object") {
for (let k in params) {
bindParam(statement, k, params[k]);
}
return;
}
throw new Error(
"Invalid type for bound parameters. Expected Array or " +
"object. Got: " +
params
);
},
_executeStatement(sql, statement, params, onRow) {
if (statement.state != statement.MOZ_STORAGE_STATEMENT_READY) {
throw new Error("Statement is not ready for execution.");
}
if (onRow && typeof onRow != "function") {
throw new Error("onRow must be a function. Got: " + onRow);
}
this._bindParameters(statement, params);
let index = this._statementCounter++;
let deferred = PromiseUtils.defer();
let userCancelled = false;
let errors = [];
let rows = [];
let handledRow = false;
// Don't incur overhead for serializing params unless the messages go
// somewhere.
if (this._log.level <= Log.Level.Trace) {
let msg = "Stmt #" + index + " " + sql;
if (params) {
msg += " - " + JSON.stringify(params);
}
this._log.trace(msg);
} else {
this._log.debug("Stmt #" + index + " starting");
}
let self = this;
let pending = statement.executeAsync({
handleResult(resultSet) {
// .cancel() may not be immediate and handleResult() could be called
// after a .cancel().
for (
let row = resultSet.getNextRow();
row && !userCancelled;
row = resultSet.getNextRow()
) {
if (!onRow) {
rows.push(row);
continue;
}
handledRow = true;
try {
onRow(row, () => {
userCancelled = true;
pending.cancel();
});
} catch (e) {
self._log.warn("Exception when calling onRow callback", e);
}
}
},
handleError(error) {
self._log.info(
"Error when executing SQL (" + error.result + "): " + error.message
);
errors.push(error);
},
handleCompletion(reason) {
self._log.debug("Stmt #" + index + " finished.");
self._pendingStatements.delete(index);
switch (reason) {
case Ci.mozIStorageStatementCallback.REASON_FINISHED:
case Ci.mozIStorageStatementCallback.REASON_CANCELED:
// If there is an onRow handler, we always instead resolve to a
// boolean indicating whether the onRow handler was called or not.
let result = onRow ? handledRow : rows;
deferred.resolve(result);
break;
case Ci.mozIStorageStatementCallback.REASON_ERROR:
let error = new Error(
"Error(s) encountered during statement execution: " +
errors.map(e => e.message).join(", ")
);
error.errors = errors;
// Forward the error result in some cases, for example if there is
// a single error, or if there is corruption.
if (errors.length == 1 && errors[0].result) {
error.result = errors[0].result;
} else if (
errors.some(e => e.result == Cr.NS_ERROR_FILE_CORRUPTED)
) {
error.result = Cr.NS_ERROR_FILE_CORRUPTED;
}
deferred.reject(error);
break;
default:
deferred.reject(
new Error("Unknown completion reason code: " + reason)
);
break;
}
},
});
this._pendingStatements.set(index, pending);
return deferred.promise;
},
ensureOpen() {
if (!this._open) {
throw new Error("Connection is not open.");
}
},
_clearIdleShrinkTimer() {
if (!this._idleShrinkTimer) {
return;
}
this._idleShrinkTimer.cancel();
},
_startIdleShrinkTimer() {
if (!this._idleShrinkTimer) {
return;
}
this._idleShrinkTimer.initWithCallback(
this.shrinkMemory.bind(this),
this._idleShrinkMS,
this._idleShrinkTimer.TYPE_ONE_SHOT
);
},
// Returns a promise that will resolve after a time comprised between 80% of
// `TRANSACTIONS_QUEUE_TIMEOUT_MS` and `TRANSACTIONS_QUEUE_TIMEOUT_MS`. Use
// this promise instead of creating several individual timers to reduce the
// overhead due to timers (see bug 1442353).
_getTimeoutPromise() {
if (this._timeoutPromise && Cu.now() <= this._timeoutPromiseExpires) {
return this._timeoutPromise;
}
let timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
// Clear out this._timeoutPromise if it hasn't changed since we set it.
if (this._timeoutPromise == timeoutPromise) {
this._timeoutPromise = null;
}
reject(
new Error(
"Transaction timeout, most likely caused by unresolved pending work."
)
);
}, TRANSACTIONS_QUEUE_TIMEOUT_MS);
});
this._timeoutPromise = timeoutPromise;
this._timeoutPromiseExpires =
Cu.now() + TRANSACTIONS_QUEUE_TIMEOUT_MS * 0.2;
return this._timeoutPromise;
},
});
/**
* Opens a connection to a SQLite database.
*
* The following parameters can control the connection:
*
* path -- (string) The filesystem path of the database file to open. If the
* file does not exist, a new database will be created.
*
* sharedMemoryCache -- (bool) Whether multiple connections to the database
* share the same memory cache. Sharing the memory cache likely results
* in less memory utilization. However, sharing also requires connections
* to obtain a lock, possibly making database access slower. Defaults to
* true.
*
* shrinkMemoryOnConnectionIdleMS -- (integer) If defined, the connection
* will attempt to minimize its memory usage after this many
* milliseconds of connection idle. The connection is idle when no
* statements are executing. There is no default value which means no
* automatic memory minimization will occur. Please note that this is
* *not* a timer on the idle service and this could fire while the
* application is active.
*
* readOnly -- (bool) Whether to open the database with SQLITE_OPEN_READONLY
* set. If used, writing to the database will fail. Defaults to false.
*
* ignoreLockingMode -- (bool) Whether to ignore locks on the database held