Bug 1885602 - Part 5: Implement navigating to the SUMO help topic from the menu heade...
[gecko.git] / toolkit / modules / Sqlite.sys.mjs
blobb1f48c28be669143b97f80f0adce0dddf463c3c8
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 /**
6  * PRIVACY WARNING
7  * ===============
8  *
9  * Database file names can be exposed through telemetry and in crash reports on
10  * the https://crash-stats.mozilla.org site, to allow recognizing the affected
11  * database.
12  * if your database name may contain privacy sensitive information, e.g. an
13  * URL origin, you should use openDatabaseWithFileURL and pass an explicit
14  * TelemetryFilename to it. That name will be used both for telemetry and for
15  * thread names in crash reports.
16  * If you have different needs (e.g. using the javascript module or an async
17  * connection from the main thread) please coordinate with the mozStorage peers.
18  */
20 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
22 import { setTimeout } from "resource://gre/modules/Timer.sys.mjs";
24 const lazy = {};
26 ChromeUtils.defineESModuleGetters(
27   lazy,
28   {
29     AsyncShutdown: "resource://gre/modules/AsyncShutdown.sys.mjs",
30     FileUtils: "resource://gre/modules/FileUtils.sys.mjs",
31   },
32   { global: "contextual" }
35 XPCOMUtils.defineLazyServiceGetter(
36   lazy,
37   "FinalizationWitnessService",
38   "@mozilla.org/toolkit/finalizationwitness;1",
39   "nsIFinalizationWitnessService"
42 // Regular expression used by isInvalidBoundLikeQuery
43 var likeSqlRegex = /\bLIKE\b\s(?![@:?])/i;
45 // Counts the number of created connections per database basename(). This is
46 // used for logging to distinguish connection instances.
47 var connectionCounters = new Map();
49 // Tracks identifiers of wrapped connections, that are Storage connections
50 // opened through mozStorage and then wrapped by Sqlite.sys.mjs to use its syntactic
51 // sugar API.  Since these connections have an unknown origin, we use this set
52 // to differentiate their behavior.
53 var wrappedConnections = new Set();
55 /**
56  * Once `true`, reject any attempt to open or close a database.
57  */
58 function isClosed() {
59   // If Barriers have not been initialized yet, just trust AppStartup.
60   if (
61     typeof Object.getOwnPropertyDescriptor(lazy, "Barriers").get == "function"
62   ) {
63     // It's still possible to open new connections at profile-before-change, so
64     // use the next phase here, as a fallback.
65     return Services.startup.isInOrBeyondShutdownPhase(
66       Ci.nsIAppStartup.SHUTDOWN_PHASE_XPCOMWILLSHUTDOWN
67     );
68   }
69   return lazy.Barriers.shutdown.client.isClosed;
72 var Debugging = {
73   // Tests should fail if a connection auto closes.  The exception is
74   // when finalization itself is tested, in which case this flag
75   // should be set to false.
76   failTestsOnAutoClose: true,
79 /**
80  * Helper function to check whether LIKE is implemented using proper bindings.
81  *
82  * @param sql
83  *        (string) The SQL query to be verified.
84  * @return boolean value telling us whether query was correct or not
85  */
86 function isInvalidBoundLikeQuery(sql) {
87   return likeSqlRegex.test(sql);
90 // Displays a script error message
91 function logScriptError(message) {
92   let consoleMessage = Cc["@mozilla.org/scripterror;1"].createInstance(
93     Ci.nsIScriptError
94   );
95   let stack = new Error();
96   consoleMessage.init(
97     message,
98     stack.fileName,
99     null,
100     stack.lineNumber,
101     0,
102     Ci.nsIScriptError.errorFlag,
103     "component javascript"
104   );
105   Services.console.logMessage(consoleMessage);
107   // This `Promise.reject` will cause tests to fail.  The debugging
108   // flag can be used to suppress this for tests that explicitly
109   // test auto closes.
110   if (Debugging.failTestsOnAutoClose) {
111     Promise.reject(new Error(message));
112   }
116  * Gets connection identifier from its database file name.
118  * @param fileName
119  *        A database file string name.
120  * @return the connection identifier.
121  */
122 function getIdentifierByFileName(fileName) {
123   let number = connectionCounters.get(fileName) || 0;
124   connectionCounters.set(fileName, number + 1);
125   return fileName + "#" + number;
129  * Convert mozIStorageError to common NS_ERROR_*
130  * The conversion is mostly based on the one in
131  * mozStoragePrivateHelpers::ConvertResultCode, plus a few additions.
133  * @param {integer} result a mozIStorageError result code.
134  * @returns {integer} an NS_ERROR_* result code.
135  */
136 function convertStorageErrorResult(result) {
137   switch (result) {
138     case Ci.mozIStorageError.PERM:
139     case Ci.mozIStorageError.AUTH:
140     case Ci.mozIStorageError.CANTOPEN:
141       return Cr.NS_ERROR_FILE_ACCESS_DENIED;
142     case Ci.mozIStorageError.LOCKED:
143       return Cr.NS_ERROR_FILE_IS_LOCKED;
144     case Ci.mozIStorageError.READONLY:
145       return Cr.NS_ERROR_FILE_READ_ONLY;
146     case Ci.mozIStorageError.ABORT:
147     case Ci.mozIStorageError.INTERRUPT:
148       return Cr.NS_ERROR_ABORT;
149     case Ci.mozIStorageError.TOOBIG:
150     case Ci.mozIStorageError.FULL:
151       return Cr.NS_ERROR_FILE_NO_DEVICE_SPACE;
152     case Ci.mozIStorageError.NOMEM:
153       return Cr.NS_ERROR_OUT_OF_MEMORY;
154     case Ci.mozIStorageError.BUSY:
155       return Cr.NS_ERROR_STORAGE_BUSY;
156     case Ci.mozIStorageError.CONSTRAINT:
157       return Cr.NS_ERROR_STORAGE_CONSTRAINT;
158     case Ci.mozIStorageError.NOLFS:
159     case Ci.mozIStorageError.IOERR:
160       return Cr.NS_ERROR_STORAGE_IOERR;
161     case Ci.mozIStorageError.SCHEMA:
162     case Ci.mozIStorageError.MISMATCH:
163     case Ci.mozIStorageError.MISUSE:
164     case Ci.mozIStorageError.RANGE:
165       return Ci.NS_ERROR_UNEXPECTED;
166     case Ci.mozIStorageError.CORRUPT:
167     case Ci.mozIStorageError.EMPTY:
168     case Ci.mozIStorageError.FORMAT:
169     case Ci.mozIStorageError.NOTADB:
170       return Cr.NS_ERROR_FILE_CORRUPTED;
171     default:
172       return Cr.NS_ERROR_FAILURE;
173   }
176  * Barriers used to ensure that Sqlite.sys.mjs is shutdown after all
177  * its clients.
178  */
179 ChromeUtils.defineLazyGetter(lazy, "Barriers", () => {
180   let Barriers = {
181     /**
182      * Public barrier that clients may use to add blockers to the
183      * shutdown of Sqlite.sys.mjs. Triggered by profile-before-change.
184      * Once all blockers of this barrier are lifted, we close the
185      * ability to open new connections.
186      */
187     shutdown: new lazy.AsyncShutdown.Barrier(
188       "Sqlite.sys.mjs: wait until all clients have completed their task"
189     ),
191     /**
192      * Private barrier blocked by connections that are still open.
193      * Triggered after Barriers.shutdown is lifted and `isClosed()` returns
194      * `true`.
195      */
196     connections: new lazy.AsyncShutdown.Barrier(
197       "Sqlite.sys.mjs: wait until all connections are closed"
198     ),
199   };
201   /**
202    * Observer for the event which is broadcasted when the finalization
203    * witness `_witness` of `OpenedConnection` is garbage collected.
204    *
205    * The observer is passed the connection identifier of the database
206    * connection that is being finalized.
207    */
208   let finalizationObserver = function (subject, topic, identifier) {
209     let connectionData = ConnectionData.byId.get(identifier);
211     if (connectionData === undefined) {
212       logScriptError(
213         "Error: Attempt to finalize unknown Sqlite connection: " +
214           identifier +
215           "\n"
216       );
217       return;
218     }
220     ConnectionData.byId.delete(identifier);
221     logScriptError(
222       "Warning: Sqlite connection '" +
223         identifier +
224         "' was not properly closed. Auto-close triggered by garbage collection.\n"
225     );
226     connectionData.close();
227   };
228   Services.obs.addObserver(finalizationObserver, "sqlite-finalization-witness");
230   /**
231    * Ensure that Sqlite.sys.mjs:
232    * - informs its clients before shutting down;
233    * - lets clients open connections during shutdown, if necessary;
234    * - waits for all connections to be closed before shutdown.
235    */
236   lazy.AsyncShutdown.profileBeforeChange.addBlocker(
237     "Sqlite.sys.mjs shutdown blocker",
238     async function () {
239       await Barriers.shutdown.wait();
240       // At this stage, all clients have had a chance to open (and close)
241       // their databases. Some previous close operations may still be pending,
242       // so we need to wait until they are complete before proceeding.
243       await Barriers.connections.wait();
245       // Everything closed, no finalization events to catch
246       Services.obs.removeObserver(
247         finalizationObserver,
248         "sqlite-finalization-witness"
249       );
250     },
252     function status() {
253       if (isClosed()) {
254         // We are waiting for the connections to close. The interesting
255         // status is therefore the list of connections still pending.
256         return {
257           description: "Waiting for connections to close",
258           state: Barriers.connections.state,
259         };
260       }
262       // We are still in the first stage: waiting for the barrier
263       // to be lifted. The interesting status is therefore that of
264       // the barrier.
265       return {
266         description: "Waiting for the barrier to be lifted",
267         state: Barriers.shutdown.state,
268       };
269     }
270   );
272   return Barriers;
275 const VACUUM_CATEGORY = "vacuum-participant";
276 const VACUUM_CONTRACTID = "@sqlite.module.js/vacuum-participant;";
277 var registeredVacuumParticipants = new Map();
279 function registerVacuumParticipant(connectionData) {
280   let contractId = VACUUM_CONTRACTID + connectionData._identifier;
281   let factory = {
282     createInstance(iid) {
283       return connectionData.QueryInterface(iid);
284     },
285     QueryInterface: ChromeUtils.generateQI(["nsIFactory"]),
286   };
287   let cid = Services.uuid.generateUUID();
288   Components.manager
289     .QueryInterface(Ci.nsIComponentRegistrar)
290     .registerFactory(cid, contractId, contractId, factory);
291   Services.catMan.addCategoryEntry(
292     VACUUM_CATEGORY,
293     contractId,
294     contractId,
295     false,
296     false
297   );
298   registeredVacuumParticipants.set(contractId, { cid, factory });
301 function unregisterVacuumParticipant(connectionData) {
302   let contractId = VACUUM_CONTRACTID + connectionData._identifier;
303   let component = registeredVacuumParticipants.get(contractId);
304   if (component) {
305     Components.manager
306       .QueryInterface(Ci.nsIComponentRegistrar)
307       .unregisterFactory(component.cid, component.factory);
308     Services.catMan.deleteCategoryEntry(VACUUM_CATEGORY, contractId, false);
309   }
313  * Create a ConsoleInstance logger with a given prefix.
314  * @param {string} prefix The prefix to use when logging.
315  * @returns {ConsoleInstance} a console logger.
316  */
317 function createLoggerWithPrefix(prefix) {
318   return console.createInstance({
319     prefix: `SQLite JSM (${prefix})`,
320     maxLogLevelPref: "toolkit.sqlitejsm.loglevel",
321   });
325  * Connection data with methods necessary for closing the connection.
327  * To support auto-closing in the event of garbage collection, this
328  * data structure contains all the connection data of an opened
329  * connection and all of the methods needed for sucessfully closing
330  * it.
332  * By putting this information in its own separate object, it is
333  * possible to store an additional reference to it without preventing
334  * a garbage collection of a finalization witness in
335  * OpenedConnection. When the witness detects a garbage collection,
336  * this object can be used to close the connection.
338  * This object contains more methods than just `close`.  When
339  * OpenedConnection needs to use the methods in this object, it will
340  * dispatch its method calls here.
341  */
342 function ConnectionData(connection, identifier, options = {}) {
343   this._logger = createLoggerWithPrefix(`Connection ${identifier}`);
344   this._logger.debug("Opened");
346   this._dbConn = connection;
348   // This is a unique identifier for the connection, generated through
349   // getIdentifierByFileName.  It may be used for logging or as a key in Maps.
350   this._identifier = identifier;
352   this._open = true;
354   this._cachedStatements = new Map();
355   this._anonymousStatements = new Map();
356   this._anonymousCounter = 0;
358   // A map from statement index to mozIStoragePendingStatement, to allow for
359   // canceling prior to finalizing the mozIStorageStatements.
360   this._pendingStatements = new Map();
362   // Increments for each executed statement for the life of the connection.
363   this._statementCounter = 0;
365   // Increments whenever we request a unique operation id.
366   this._operationsCounter = 0;
368   if ("defaultTransactionType" in options) {
369     this.defaultTransactionType = options.defaultTransactionType;
370   } else {
371     this.defaultTransactionType = convertStorageTransactionType(
372       this._dbConn.defaultTransactionType
373     );
374   }
375   // Tracks whether this instance initiated a transaction.
376   this._initiatedTransaction = false;
377   // Manages a chain of transactions promises, so that new transactions
378   // always happen in queue to the previous ones.  It never rejects.
379   this._transactionQueue = Promise.resolve();
381   this._idleShrinkMS = options.shrinkMemoryOnConnectionIdleMS;
382   if (this._idleShrinkMS) {
383     this._idleShrinkTimer = Cc["@mozilla.org/timer;1"].createInstance(
384       Ci.nsITimer
385     );
386     // We wait for the first statement execute to start the timer because
387     // shrinking now would not do anything.
388   }
390   // Deferred whose promise is resolved when the connection closing procedure
391   // is complete.
392   this._deferredClose = Promise.withResolvers();
393   this._closeRequested = false;
395   // An AsyncShutdown barrier used to make sure that we wait until clients
396   // are done before shutting down the connection.
397   this._barrier = new lazy.AsyncShutdown.Barrier(
398     `${this._identifier}: waiting for clients`
399   );
401   lazy.Barriers.connections.client.addBlocker(
402     this._identifier + ": waiting for shutdown",
403     this._deferredClose.promise,
404     () => ({
405       identifier: this._identifier,
406       isCloseRequested: this._closeRequested,
407       hasDbConn: !!this._dbConn,
408       initiatedTransaction: this._initiatedTransaction,
409       pendingStatements: this._pendingStatements.size,
410       statementCounter: this._statementCounter,
411     })
412   );
414   // We avoid creating a timer for every transaction, because in most cases they
415   // are not canceled and they are only used as a timeout.
416   // Instead the timer is reused when it's sufficiently close to the previous
417   // creation time (see `_getTimeoutPromise` for more info).
418   this._timeoutPromise = null;
419   // The last timestamp when we should consider using `this._timeoutPromise`.
420   this._timeoutPromiseExpires = 0;
422   this._useIncrementalVacuum = !!options.incrementalVacuum;
423   if (this._useIncrementalVacuum) {
424     this._logger.debug("Set auto_vacuum INCREMENTAL");
425     this.execute("PRAGMA auto_vacuum = 2").catch(ex => {
426       this._logger.error("Setting auto_vacuum to INCREMENTAL failed.");
427       console.error(ex);
428     });
429   }
431   this._expectedPageSize = options.pageSize ?? 0;
432   if (this._expectedPageSize) {
433     this._logger.debug("Set page_size to " + this._expectedPageSize);
434     this.execute("PRAGMA page_size = " + this._expectedPageSize).catch(ex => {
435       this._logger.error(
436         `Setting page_size to ${this._expectedPageSize} failed.`
437       );
438       console.error(ex);
439     });
440   }
442   this._vacuumOnIdle = options.vacuumOnIdle;
443   if (this._vacuumOnIdle) {
444     this._logger.debug("Register as vacuum participant");
445     this.QueryInterface = ChromeUtils.generateQI([
446       Ci.mozIStorageVacuumParticipant,
447     ]);
448     registerVacuumParticipant(this);
449   }
453  * Map of connection identifiers to ConnectionData objects
455  * The connection identifier is a human-readable name of the
456  * database. Used by finalization witnesses to be able to close opened
457  * connections on garbage collection.
459  * Key: _identifier of ConnectionData
460  * Value: ConnectionData object
461  */
462 ConnectionData.byId = new Map();
464 ConnectionData.prototype = Object.freeze({
465   get expectedDatabasePageSize() {
466     return this._expectedPageSize;
467   },
469   get useIncrementalVacuum() {
470     return this._useIncrementalVacuum;
471   },
473   /**
474    * This should only be used by the VacuumManager component.
475    * @see unsafeRawConnection for an official (but still unsafe) API.
476    */
477   get databaseConnection() {
478     if (this._vacuumOnIdle) {
479       return this._dbConn;
480     }
481     return null;
482   },
484   onBeginVacuum() {
485     let granted = !this.transactionInProgress;
486     this._logger.debug("Begin Vacuum - " + granted ? "granted" : "denied");
487     return granted;
488   },
490   onEndVacuum(succeeded) {
491     this._logger.debug("End Vacuum - " + succeeded ? "success" : "failure");
492   },
494   /**
495    * Run a task, ensuring that its execution will not be interrupted by shutdown.
496    *
497    * As the operations of this module are asynchronous, a sequence of operations,
498    * or even an individual operation, can still be pending when the process shuts
499    * down. If any of this operations is a write, this can cause data loss, simply
500    * because the write has not been completed (or even started) by shutdown.
501    *
502    * To avoid this risk, clients are encouraged to use `executeBeforeShutdown` for
503    * any write operation, as follows:
504    *
505    * myConnection.executeBeforeShutdown("Bookmarks: Removing a bookmark",
506    *   async function(db) {
507    *     // The connection will not be closed and shutdown will not proceed
508    *     // until this task has completed.
509    *
510    *     // `db` exposes the same API as `myConnection` but provides additional
511    *     // logging support to help debug hard-to-catch shutdown timeouts.
512    *
513    *     await db.execute(...);
514    * }));
515    *
516    * @param {string} name A human-readable name for the ongoing operation, used
517    *  for logging and debugging purposes.
518    * @param {function(db)} task A function that takes as argument a Sqlite.sys.mjs
519    *  db and returns a Promise.
520    */
521   executeBeforeShutdown(parent, name, task) {
522     if (!name) {
523       throw new TypeError("Expected a human-readable name as first argument");
524     }
525     if (typeof task != "function") {
526       throw new TypeError("Expected a function as second argument");
527     }
528     if (this._closeRequested) {
529       throw new Error(
530         `${this._identifier}: cannot execute operation ${name}, the connection is already closing`
531       );
532     }
534     // Status, used for AsyncShutdown crash reports.
535     let status = {
536       // The latest command started by `task`, either as a
537       // sql string, or as one of "<not started>" or "<closing>".
538       command: "<not started>",
540       // `true` if `command` was started but not completed yet.
541       isPending: false,
542     };
544     // An object with the same API as `this` but with
545     // additional logging. To keep logging simple, we
546     // assume that `task` is not running several queries
547     // concurrently.
548     let loggedDb = Object.create(parent, {
549       execute: {
550         value: async (sql, ...rest) => {
551           status.isPending = true;
552           status.command = sql;
553           try {
554             return await this.execute(sql, ...rest);
555           } finally {
556             status.isPending = false;
557           }
558         },
559       },
560       close: {
561         value: async () => {
562           status.isPending = true;
563           status.command = "<close>";
564           try {
565             return await this.close();
566           } finally {
567             status.isPending = false;
568           }
569         },
570       },
571       executeCached: {
572         value: async (sql, ...rest) => {
573           status.isPending = true;
574           status.command = "cached: " + sql;
575           try {
576             return await this.executeCached(sql, ...rest);
577           } finally {
578             status.isPending = false;
579           }
580         },
581       },
582     });
584     let promiseResult = task(loggedDb);
585     if (
586       !promiseResult ||
587       typeof promiseResult != "object" ||
588       !("then" in promiseResult)
589     ) {
590       throw new TypeError("Expected a Promise");
591     }
592     let key = `${this._identifier}: ${name} (${this._getOperationId()})`;
593     let promiseComplete = promiseResult.catch(() => {});
594     this._barrier.client.addBlocker(key, promiseComplete, {
595       fetchState: () => status,
596     });
598     return (async () => {
599       try {
600         return await promiseResult;
601       } finally {
602         this._barrier.client.removeBlocker(key, promiseComplete);
603       }
604     })();
605   },
606   close() {
607     this._closeRequested = true;
609     if (!this._dbConn) {
610       return this._deferredClose.promise;
611     }
613     this._logger.debug("Request to close connection.");
614     this._clearIdleShrinkTimer();
616     if (this._vacuumOnIdle) {
617       this._logger.debug("Unregister as vacuum participant");
618       unregisterVacuumParticipant(this);
619     }
621     return this._barrier.wait().then(() => {
622       if (!this._dbConn) {
623         return undefined;
624       }
625       return this._finalize();
626     });
627   },
629   clone(readOnly = false) {
630     this.ensureOpen();
632     this._logger.debug("Request to clone connection.");
634     let options = {
635       connection: this._dbConn,
636       readOnly,
637     };
638     if (this._idleShrinkMS) {
639       options.shrinkMemoryOnConnectionIdleMS = this._idleShrinkMS;
640     }
642     return cloneStorageConnection(options);
643   },
644   _getOperationId() {
645     return this._operationsCounter++;
646   },
647   _finalize() {
648     this._logger.debug("Finalizing connection.");
649     // Cancel any pending statements.
650     for (let [, /* k */ statement] of this._pendingStatements) {
651       statement.cancel();
652     }
653     this._pendingStatements.clear();
655     // We no longer need to track these.
656     this._statementCounter = 0;
658     // Next we finalize all active statements.
659     for (let [, /* k */ statement] of this._anonymousStatements) {
660       statement.finalize();
661     }
662     this._anonymousStatements.clear();
664     for (let [, /* k */ statement] of this._cachedStatements) {
665       statement.finalize();
666     }
667     this._cachedStatements.clear();
669     // This guards against operations performed between the call to this
670     // function and asyncClose() finishing. See also bug 726990.
671     this._open = false;
673     // We must always close the connection at the Sqlite.sys.mjs-level, not
674     // necessarily at the mozStorage-level.
675     let markAsClosed = () => {
676       this._logger.debug("Closed");
677       // Now that the connection is closed, no need to keep
678       // a blocker for Barriers.connections.
679       lazy.Barriers.connections.client.removeBlocker(
680         this._deferredClose.promise
681       );
682       this._deferredClose.resolve();
683     };
684     if (wrappedConnections.has(this._identifier)) {
685       wrappedConnections.delete(this._identifier);
686       this._dbConn = null;
687       markAsClosed();
688     } else {
689       this._logger.debug("Calling asyncClose().");
690       try {
691         this._dbConn.asyncClose(markAsClosed);
692       } catch (ex) {
693         // If for any reason asyncClose fails, we must still remove the
694         // shutdown blockers and resolve _deferredClose.
695         markAsClosed();
696       } finally {
697         this._dbConn = null;
698       }
699     }
700     return this._deferredClose.promise;
701   },
703   executeCached(sql, params = null, onRow = null) {
704     this.ensureOpen();
706     if (!sql) {
707       throw new Error("sql argument is empty.");
708     }
710     let statement = this._cachedStatements.get(sql);
711     if (!statement) {
712       statement = this._dbConn.createAsyncStatement(sql);
713       this._cachedStatements.set(sql, statement);
714     }
716     this._clearIdleShrinkTimer();
718     return new Promise((resolve, reject) => {
719       try {
720         this._executeStatement(sql, statement, params, onRow).then(
721           result => {
722             this._startIdleShrinkTimer();
723             resolve(result);
724           },
725           error => {
726             this._startIdleShrinkTimer();
727             reject(error);
728           }
729         );
730       } catch (ex) {
731         this._startIdleShrinkTimer();
732         throw ex;
733       }
734     });
735   },
737   execute(sql, params = null, onRow = null) {
738     if (typeof sql != "string") {
739       throw new Error("Must define SQL to execute as a string: " + sql);
740     }
742     this.ensureOpen();
744     let statement = this._dbConn.createAsyncStatement(sql);
745     let index = this._anonymousCounter++;
747     this._anonymousStatements.set(index, statement);
748     this._clearIdleShrinkTimer();
750     let onFinished = () => {
751       this._anonymousStatements.delete(index);
752       statement.finalize();
753       this._startIdleShrinkTimer();
754     };
756     return new Promise((resolve, reject) => {
757       try {
758         this._executeStatement(sql, statement, params, onRow).then(
759           rows => {
760             onFinished();
761             resolve(rows);
762           },
763           error => {
764             onFinished();
765             reject(error);
766           }
767         );
768       } catch (ex) {
769         onFinished();
770         throw ex;
771       }
772     });
773   },
775   get transactionInProgress() {
776     return this._open && this._dbConn.transactionInProgress;
777   },
779   executeTransaction(func, type) {
780     // Identify the caller for debugging purposes.
781     let caller = new Error().stack
782       .split("\n", 3)
783       .pop()
784       .match(/^([^@]*@).*\/([^\/:]+)[:0-9]*$/);
785     caller = caller[1] + caller[2];
786     this._logger.debug(`Transaction (type ${type}) requested by: ${caller}`);
788     if (type == OpenedConnection.prototype.TRANSACTION_DEFAULT) {
789       type = this.defaultTransactionType;
790     } else if (!OpenedConnection.TRANSACTION_TYPES.includes(type)) {
791       throw new Error("Unknown transaction type: " + type);
792     }
793     this.ensureOpen();
795     // If a transaction yields on a never resolved promise, or is mistakenly
796     // nested, it could hang the transactions queue forever.  Thus we timeout
797     // the execution after a meaningful amount of time, to ensure in any case
798     // we'll proceed after a while.
799     let timeoutPromise = this._getTimeoutPromise();
801     let promise = this._transactionQueue.then(() => {
802       if (this._closeRequested) {
803         throw new Error("Transaction canceled due to a closed connection.");
804       }
806       let transactionPromise = (async () => {
807         // At this point we should never have an in progress transaction, since
808         // they are enqueued.
809         if (this._initiatedTransaction) {
810           this._logger.error(
811             "Unexpected transaction in progress when trying to start a new one."
812           );
813         }
814         try {
815           // We catch errors in statement execution to detect nested transactions.
816           try {
817             await this.execute("BEGIN " + type + " TRANSACTION");
818             this._logger.debug(`Begin transaction`);
819             this._initiatedTransaction = true;
820           } catch (ex) {
821             // Unfortunately, if we are wrapping an existing connection, a
822             // transaction could have been started by a client of the same
823             // connection that doesn't use Sqlite.sys.mjs (e.g. C++ consumer).
824             // The best we can do is proceed without a transaction and hope
825             // things won't break.
826             if (wrappedConnections.has(this._identifier)) {
827               this._logger.warn(
828                 "A new transaction could not be started cause the wrapped connection had one in progress",
829                 ex
830               );
831             } else {
832               this._logger.warn(
833                 "A transaction was already in progress, likely a nested transaction",
834                 ex
835               );
836               throw ex;
837             }
838           }
840           let result;
841           try {
842             result = await Promise.race([func(), timeoutPromise]);
843           } catch (ex) {
844             // It's possible that the exception has been caused by trying to
845             // close the connection in the middle of a transaction.
846             if (this._closeRequested) {
847               this._logger.warn(
848                 "Connection closed while performing a transaction",
849                 ex
850               );
851             } else {
852               // Otherwise the function didn't resolve before the timeout, or
853               // generated an unexpected error. Then we rollback.
854               if (ex.becauseTimedOut) {
855                 let caller_module = caller.split(":", 1)[0];
856                 Services.telemetry.keyedScalarAdd(
857                   "mozstorage.sqlitejsm_transaction_timeout",
858                   caller_module,
859                   1
860                 );
861                 this._logger.error(
862                   `The transaction requested by ${caller} timed out. Rolling back`,
863                   ex
864                 );
865               } else {
866                 this._logger.error(
867                   `Error during transaction requested by ${caller}. Rolling back`,
868                   ex
869                 );
870               }
871               // If we began a transaction, we must rollback it.
872               if (this._initiatedTransaction) {
873                 try {
874                   await this.execute("ROLLBACK TRANSACTION");
875                   this._initiatedTransaction = false;
876                   this._logger.debug(`Roll back transaction`);
877                 } catch (inner) {
878                   this._logger.error("Could not roll back transaction", inner);
879                 }
880               }
881             }
882             // Rethrow the exception.
883             throw ex;
884           }
886           // See comment above about connection being closed during transaction.
887           if (this._closeRequested) {
888             this._logger.warn(
889               "Connection closed before committing the transaction."
890             );
891             throw new Error(
892               "Connection closed before committing the transaction."
893             );
894           }
896           // If we began a transaction, we must commit it.
897           if (this._initiatedTransaction) {
898             try {
899               await this.execute("COMMIT TRANSACTION");
900               this._logger.debug(`Commit transaction`);
901             } catch (ex) {
902               this._logger.warn("Error committing transaction", ex);
903               throw ex;
904             }
905           }
907           return result;
908         } finally {
909           this._initiatedTransaction = false;
910         }
911       })();
913       return Promise.race([transactionPromise, timeoutPromise]);
914     });
915     // Atomically update the queue before anyone else has a chance to enqueue
916     // further transactions.
917     this._transactionQueue = promise.catch(ex => {
918       this._logger.error(ex);
919     });
921     // Make sure that we do not shutdown the connection during a transaction.
922     this._barrier.client.addBlocker(
923       `Transaction (${this._getOperationId()})`,
924       this._transactionQueue
925     );
926     return promise;
927   },
929   shrinkMemory() {
930     this._logger.debug("Shrinking memory usage.");
931     return this.execute("PRAGMA shrink_memory").finally(() => {
932       this._clearIdleShrinkTimer();
933     });
934   },
936   discardCachedStatements() {
937     let count = 0;
938     for (let [, /* k */ statement] of this._cachedStatements) {
939       ++count;
940       statement.finalize();
941     }
942     this._cachedStatements.clear();
943     this._logger.debug("Discarded " + count + " cached statements.");
944     return count;
945   },
947   interrupt() {
948     this._logger.debug("Trying to interrupt.");
949     this.ensureOpen();
950     this._dbConn.interrupt();
951   },
953   /**
954    * Helper method to bind parameters of various kinds through
955    * reflection.
956    */
957   _bindParameters(statement, params) {
958     if (!params) {
959       return;
960     }
962     function bindParam(obj, key, val) {
963       let isBlob =
964         val && typeof val == "object" && val.constructor.name == "Uint8Array";
965       let args = [key, val];
966       if (isBlob) {
967         args.push(val.length);
968       }
969       let methodName = `bind${isBlob ? "Blob" : ""}By${
970         typeof key == "number" ? "Index" : "Name"
971       }`;
972       obj[methodName](...args);
973     }
975     if (Array.isArray(params)) {
976       // It's an array of separate params.
977       if (params.length && typeof params[0] == "object" && params[0] !== null) {
978         let paramsArray = statement.newBindingParamsArray();
979         for (let p of params) {
980           let bindings = paramsArray.newBindingParams();
981           for (let [key, value] of Object.entries(p)) {
982             bindParam(bindings, key, value);
983           }
984           paramsArray.addParams(bindings);
985         }
987         statement.bindParameters(paramsArray);
988         return;
989       }
991       // Indexed params.
992       for (let i = 0; i < params.length; i++) {
993         bindParam(statement, i, params[i]);
994       }
995       return;
996     }
998     // Named params.
999     if (params && typeof params == "object") {
1000       for (let k in params) {
1001         bindParam(statement, k, params[k]);
1002       }
1003       return;
1004     }
1006     throw new Error(
1007       "Invalid type for bound parameters. Expected Array or " +
1008         "object. Got: " +
1009         params
1010     );
1011   },
1013   _executeStatement(sql, statement, params, onRow) {
1014     if (statement.state != statement.MOZ_STORAGE_STATEMENT_READY) {
1015       throw new Error("Statement is not ready for execution.");
1016     }
1018     if (onRow && typeof onRow != "function") {
1019       throw new Error("onRow must be a function. Got: " + onRow);
1020     }
1022     this._bindParameters(statement, params);
1024     let index = this._statementCounter++;
1026     let deferred = Promise.withResolvers();
1027     let userCancelled = false;
1028     let errors = [];
1029     let rows = [];
1030     let handledRow = false;
1032     // Don't incur overhead for serializing params unless the messages go
1033     // somewhere.
1034     if (this._logger.shouldLog("Trace")) {
1035       let msg = "Stmt #" + index + " " + sql;
1037       if (params) {
1038         msg += " - " + JSON.stringify(params);
1039       }
1040       this._logger.trace(msg);
1041     } else {
1042       this._logger.debug("Stmt #" + index + " starting");
1043     }
1045     let self = this;
1046     let pending = statement.executeAsync({
1047       handleResult(resultSet) {
1048         // .cancel() may not be immediate and handleResult() could be called
1049         // after a .cancel().
1050         for (
1051           let row = resultSet.getNextRow();
1052           row && !userCancelled;
1053           row = resultSet.getNextRow()
1054         ) {
1055           if (!onRow) {
1056             rows.push(row);
1057             continue;
1058           }
1060           handledRow = true;
1062           try {
1063             onRow(row, () => {
1064               userCancelled = true;
1065               pending.cancel();
1066             });
1067           } catch (e) {
1068             self._logger.warn("Exception when calling onRow callback", e);
1069           }
1070         }
1071       },
1073       handleError(error) {
1074         self._logger.warn(
1075           "Error when executing SQL (" + error.result + "): " + error.message
1076         );
1077         errors.push(error);
1078       },
1080       handleCompletion(reason) {
1081         self._logger.debug("Stmt #" + index + " finished.");
1082         self._pendingStatements.delete(index);
1084         switch (reason) {
1085           case Ci.mozIStorageStatementCallback.REASON_FINISHED:
1086           case Ci.mozIStorageStatementCallback.REASON_CANCELED:
1087             // If there is an onRow handler, we always instead resolve to a
1088             // boolean indicating whether the onRow handler was called or not.
1089             let result = onRow ? handledRow : rows;
1090             deferred.resolve(result);
1091             break;
1093           case Ci.mozIStorageStatementCallback.REASON_ERROR:
1094             let error = new Error(
1095               "Error(s) encountered during statement execution: " +
1096                 errors.map(e => e.message).join(", ")
1097             );
1098             error.errors = errors;
1100             // Forward the error result.
1101             // Corruption is the most critical one so it's handled apart.
1102             if (errors.some(e => e.result == Ci.mozIStorageError.CORRUPT)) {
1103               error.result = Cr.NS_ERROR_FILE_CORRUPTED;
1104             } else {
1105               // Just use the first error result in the other cases.
1106               error.result = convertStorageErrorResult(errors[0]?.result);
1107             }
1109             deferred.reject(error);
1110             break;
1112           default:
1113             deferred.reject(
1114               new Error("Unknown completion reason code: " + reason)
1115             );
1116             break;
1117         }
1118       },
1119     });
1121     this._pendingStatements.set(index, pending);
1122     return deferred.promise;
1123   },
1125   ensureOpen() {
1126     if (!this._open) {
1127       throw new Error("Connection is not open.");
1128     }
1129   },
1131   _clearIdleShrinkTimer() {
1132     if (!this._idleShrinkTimer) {
1133       return;
1134     }
1136     this._idleShrinkTimer.cancel();
1137   },
1139   _startIdleShrinkTimer() {
1140     if (!this._idleShrinkTimer) {
1141       return;
1142     }
1144     this._idleShrinkTimer.initWithCallback(
1145       this.shrinkMemory.bind(this),
1146       this._idleShrinkMS,
1147       this._idleShrinkTimer.TYPE_ONE_SHOT
1148     );
1149   },
1151   /**
1152    * Returns a promise that will resolve after a time comprised between 80% of
1153    * `TRANSACTIONS_TIMEOUT_MS` and `TRANSACTIONS_TIMEOUT_MS`. Use
1154    * this method instead of creating several individual timers that may survive
1155    * longer than necessary.
1156    */
1157   _getTimeoutPromise() {
1158     if (this._timeoutPromise && Cu.now() <= this._timeoutPromiseExpires) {
1159       return this._timeoutPromise;
1160     }
1161     let timeoutPromise = new Promise((resolve, reject) => {
1162       setTimeout(() => {
1163         // Clear out this._timeoutPromise if it hasn't changed since we set it.
1164         if (this._timeoutPromise == timeoutPromise) {
1165           this._timeoutPromise = null;
1166         }
1167         let e = new Error(
1168           "Transaction timeout, most likely caused by unresolved pending work."
1169         );
1170         e.becauseTimedOut = true;
1171         reject(e);
1172       }, Sqlite.TRANSACTIONS_TIMEOUT_MS);
1173     });
1174     this._timeoutPromise = timeoutPromise;
1175     this._timeoutPromiseExpires =
1176       Cu.now() + Sqlite.TRANSACTIONS_TIMEOUT_MS * 0.2;
1177     return this._timeoutPromise;
1178   },
1180   /**
1181    * Asynchronously makes a copy of the SQLite database while there may still be
1182    * open connections on it.
1183    *
1184    * @param {string} destFilePath
1185    *   The path on the local filesystem to write the database copy. Any existing
1186    *   file at this path will be overwritten.
1187    * @return Promise<undefined, nsresult>
1188    */
1189   async backupToFile(destFilePath) {
1190     if (!this._dbConn) {
1191       return Promise.reject(
1192         new Error("No opened database connection to create a backup from.")
1193       );
1194     }
1195     let destFile = await IOUtils.getFile(destFilePath);
1196     return new Promise((resolve, reject) => {
1197       this._dbConn.backupToFileAsync(destFile, result => {
1198         if (Components.isSuccessCode(result)) {
1199           resolve();
1200         } else {
1201           reject(result);
1202         }
1203       });
1204     });
1205   },
1209  * Opens a connection to a SQLite database.
1211  * The following parameters can control the connection:
1213  *   path -- (string) The filesystem path of the database file to open. If the
1214  *       file does not exist, a new database will be created.
1216  *   sharedMemoryCache -- (bool) Whether multiple connections to the database
1217  *       share the same memory cache. Sharing the memory cache likely results
1218  *       in less memory utilization. However, sharing also requires connections
1219  *       to obtain a lock, possibly making database access slower. Defaults to
1220  *       true.
1222  *   shrinkMemoryOnConnectionIdleMS -- (integer) If defined, the connection
1223  *       will attempt to minimize its memory usage after this many
1224  *       milliseconds of connection idle. The connection is idle when no
1225  *       statements are executing. There is no default value which means no
1226  *       automatic memory minimization will occur. Please note that this is
1227  *       *not* a timer on the idle service and this could fire while the
1228  *       application is active.
1230  *   readOnly -- (bool) Whether to open the database with SQLITE_OPEN_READONLY
1231  *       set. If used, writing to the database will fail. Defaults to false.
1233  *   ignoreLockingMode -- (bool) Whether to ignore locks on the database held
1234  *       by other connections. If used, implies readOnly. Defaults to false.
1235  *       USE WITH EXTREME CAUTION. This mode WILL produce incorrect results or
1236  *       return "false positive" corruption errors if other connections write
1237  *       to the DB at the same time.
1239  *   vacuumOnIdle -- (bool) Whether to register this connection to be vacuumed
1240  *       on idle by the VacuumManager component.
1241  *       If you're vacuum-ing an incremental vacuum database, ensure to also
1242  *       set incrementalVacuum to true, otherwise this will try to change it
1243  *       to full vacuum mode.
1245  *   incrementalVacuum -- (bool) if set to true auto_vacuum = INCREMENTAL will
1246  *       be enabled for the database.
1247  *       Changing auto vacuum of an already populated database requires a full
1248  *       VACUUM. You can evaluate to enable vacuumOnIdle for that.
1250  *   pageSize -- (integer) This allows to set a custom page size for the
1251  *       database. It is usually not necessary to set it, since the default
1252  *       value should be good for most consumers.
1253  *       Changing the page size of an already populated database requires a full
1254  *       VACUUM. You can evaluate to enable vacuumOnIdle for that.
1256  *   testDelayedOpenPromise -- (promise) Used by tests to delay the open
1257  *       callback handling and execute code between asyncOpen and its callback.
1259  * FUTURE options to control:
1261  *   special named databases
1262  *   pragma TEMP STORE = MEMORY
1263  *   TRUNCATE JOURNAL
1264  *   SYNCHRONOUS = full
1266  * @param options
1267  *        (Object) Parameters to control connection and open options.
1269  * @return Promise<OpenedConnection>
1270  */
1271 function openConnection(options) {
1272   let logger = createLoggerWithPrefix("ConnectionOpener");
1274   if (!options.path) {
1275     throw new Error("path not specified in connection options.");
1276   }
1278   if (isClosed()) {
1279     throw new Error(
1280       "Sqlite.sys.mjs has been shutdown. Cannot open connection to: " +
1281         options.path
1282     );
1283   }
1285   // Retains absolute paths and normalizes relative as relative to profile.
1286   let path = options.path;
1287   let file;
1288   try {
1289     file = lazy.FileUtils.File(path);
1290   } catch (ex) {
1291     // For relative paths, we will get an exception from trying to initialize
1292     // the file. We must then join this path to the profile directory.
1293     if (ex.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH) {
1294       path = PathUtils.joinRelative(
1295         Services.dirsvc.get("ProfD", Ci.nsIFile).path,
1296         options.path
1297       );
1298       file = lazy.FileUtils.File(path);
1299     } else {
1300       throw ex;
1301     }
1302   }
1304   let sharedMemoryCache =
1305     "sharedMemoryCache" in options ? options.sharedMemoryCache : true;
1307   let openedOptions = {};
1309   if ("shrinkMemoryOnConnectionIdleMS" in options) {
1310     if (!Number.isInteger(options.shrinkMemoryOnConnectionIdleMS)) {
1311       throw new Error(
1312         "shrinkMemoryOnConnectionIdleMS must be an integer. " +
1313           "Got: " +
1314           options.shrinkMemoryOnConnectionIdleMS
1315       );
1316     }
1318     openedOptions.shrinkMemoryOnConnectionIdleMS =
1319       options.shrinkMemoryOnConnectionIdleMS;
1320   }
1322   if ("defaultTransactionType" in options) {
1323     let defaultTransactionType = options.defaultTransactionType;
1324     if (!OpenedConnection.TRANSACTION_TYPES.includes(defaultTransactionType)) {
1325       throw new Error(
1326         "Unknown default transaction type: " + defaultTransactionType
1327       );
1328     }
1330     openedOptions.defaultTransactionType = defaultTransactionType;
1331   }
1333   if ("vacuumOnIdle" in options) {
1334     if (typeof options.vacuumOnIdle != "boolean") {
1335       throw new Error("Invalid vacuumOnIdle: " + options.vacuumOnIdle);
1336     }
1337     openedOptions.vacuumOnIdle = options.vacuumOnIdle;
1338   }
1340   if ("incrementalVacuum" in options) {
1341     if (typeof options.incrementalVacuum != "boolean") {
1342       throw new Error(
1343         "Invalid incrementalVacuum: " + options.incrementalVacuum
1344       );
1345     }
1346     openedOptions.incrementalVacuum = options.incrementalVacuum;
1347   }
1349   if ("pageSize" in options) {
1350     if (
1351       ![512, 1024, 2048, 4096, 8192, 16384, 32768, 65536].includes(
1352         options.pageSize
1353       )
1354     ) {
1355       throw new Error("Invalid pageSize: " + options.pageSize);
1356     }
1357     openedOptions.pageSize = options.pageSize;
1358   }
1360   let identifier = getIdentifierByFileName(PathUtils.filename(path));
1362   logger.debug("Opening database: " + path + " (" + identifier + ")");
1364   return new Promise((resolve, reject) => {
1365     let dbOpenOptions = Ci.mozIStorageService.OPEN_DEFAULT;
1366     if (sharedMemoryCache) {
1367       dbOpenOptions |= Ci.mozIStorageService.OPEN_SHARED;
1368     }
1369     if (options.readOnly) {
1370       dbOpenOptions |= Ci.mozIStorageService.OPEN_READONLY;
1371     }
1372     if (options.ignoreLockingMode) {
1373       dbOpenOptions |= Ci.mozIStorageService.OPEN_IGNORE_LOCKING_MODE;
1374       dbOpenOptions |= Ci.mozIStorageService.OPEN_READONLY;
1375     }
1377     let dbConnectionOptions = Ci.mozIStorageService.CONNECTION_DEFAULT;
1379     Services.storage.openAsyncDatabase(
1380       file,
1381       dbOpenOptions,
1382       dbConnectionOptions,
1383       async (status, connection) => {
1384         if (!connection) {
1385           logger.error(`Could not open connection to ${path}: ${status}`);
1386           let error = new Components.Exception(
1387             `Could not open connection to ${path}: ${status}`,
1388             status
1389           );
1390           reject(error);
1391           return;
1392         }
1393         logger.debug("Connection opened");
1395         if (options.testDelayedOpenPromise) {
1396           await options.testDelayedOpenPromise;
1397         }
1399         if (isClosed()) {
1400           connection.QueryInterface(Ci.mozIStorageAsyncConnection).asyncClose();
1401           reject(
1402             new Error(
1403               "Sqlite.sys.mjs has been shutdown. Cannot open connection to: " +
1404                 options.path
1405             )
1406           );
1407           return;
1408         }
1410         try {
1411           resolve(
1412             new OpenedConnection(
1413               connection.QueryInterface(Ci.mozIStorageAsyncConnection),
1414               identifier,
1415               openedOptions
1416             )
1417           );
1418         } catch (ex) {
1419           logger.error("Could not open database", ex);
1420           connection.asyncClose();
1421           reject(ex);
1422         }
1423       }
1424     );
1425   });
1429  * Creates a clone of an existing and open Storage connection.  The clone has
1430  * the same underlying characteristics of the original connection and is
1431  * returned in form of an OpenedConnection handle.
1433  * The following parameters can control the cloned connection:
1435  *   connection -- (mozIStorageAsyncConnection) The original Storage connection
1436  *       to clone.  It's not possible to clone connections to memory databases.
1438  *   readOnly -- (boolean) - If true the clone will be read-only.  If the
1439  *       original connection is already read-only, the clone will be, regardless
1440  *       of this option.  If the original connection is using the shared cache,
1441  *       this parameter will be ignored and the clone will be as privileged as
1442  *       the original connection.
1443  *   shrinkMemoryOnConnectionIdleMS -- (integer) If defined, the connection
1444  *       will attempt to minimize its memory usage after this many
1445  *       milliseconds of connection idle. The connection is idle when no
1446  *       statements are executing. There is no default value which means no
1447  *       automatic memory minimization will occur. Please note that this is
1448  *       *not* a timer on the idle service and this could fire while the
1449  *       application is active.
1452  * @param options
1453  *        (Object) Parameters to control connection and clone options.
1455  * @return Promise<OpenedConnection>
1456  */
1457 function cloneStorageConnection(options) {
1458   let logger = createLoggerWithPrefix("ConnectionCloner");
1460   let source = options && options.connection;
1461   if (!source) {
1462     throw new TypeError("connection not specified in clone options.");
1463   }
1464   if (!(source instanceof Ci.mozIStorageAsyncConnection)) {
1465     throw new TypeError("Connection must be a valid Storage connection.");
1466   }
1468   if (isClosed()) {
1469     throw new Error(
1470       "Sqlite.sys.mjs has been shutdown. Cannot clone connection to: " +
1471         source.databaseFile.path
1472     );
1473   }
1475   let openedOptions = {};
1477   if ("shrinkMemoryOnConnectionIdleMS" in options) {
1478     if (!Number.isInteger(options.shrinkMemoryOnConnectionIdleMS)) {
1479       throw new TypeError(
1480         "shrinkMemoryOnConnectionIdleMS must be an integer. " +
1481           "Got: " +
1482           options.shrinkMemoryOnConnectionIdleMS
1483       );
1484     }
1485     openedOptions.shrinkMemoryOnConnectionIdleMS =
1486       options.shrinkMemoryOnConnectionIdleMS;
1487   }
1489   let path = source.databaseFile.path;
1490   let identifier = getIdentifierByFileName(PathUtils.filename(path));
1492   logger.debug("Cloning database: " + path + " (" + identifier + ")");
1494   return new Promise((resolve, reject) => {
1495     source.asyncClone(!!options.readOnly, (status, connection) => {
1496       if (!connection) {
1497         logger.error("Could not clone connection: " + status);
1498         reject(new Error("Could not clone connection: " + status));
1499         return;
1500       }
1501       logger.debug("Connection cloned");
1503       if (isClosed()) {
1504         connection.QueryInterface(Ci.mozIStorageAsyncConnection).asyncClose();
1505         reject(
1506           new Error(
1507             "Sqlite.sys.mjs has been shutdown. Cannot open connection to: " +
1508               options.path
1509           )
1510         );
1511         return;
1512       }
1514       try {
1515         let conn = connection.QueryInterface(Ci.mozIStorageAsyncConnection);
1516         resolve(new OpenedConnection(conn, identifier, openedOptions));
1517       } catch (ex) {
1518         logger.error("Could not clone database", ex);
1519         connection.asyncClose();
1520         reject(ex);
1521       }
1522     });
1523   });
1527  * Wraps an existing and open Storage connection with Sqlite.sys.mjs API.  The
1528  * wrapped connection clone has the same underlying characteristics of the
1529  * original connection and is returned in form of an OpenedConnection handle.
1531  * Clients are responsible for closing both the Sqlite.sys.mjs wrapper and the
1532  * underlying mozStorage connection.
1534  * The following parameters can control the wrapped connection:
1536  *   connection -- (mozIStorageAsyncConnection) The original Storage connection
1537  *       to wrap.
1539  * @param options
1540  *        (Object) Parameters to control connection and wrap options.
1542  * @return Promise<OpenedConnection>
1543  */
1544 function wrapStorageConnection(options) {
1545   let logger = createLoggerWithPrefix("ConnectionWrapper");
1547   let connection = options && options.connection;
1548   if (!connection || !(connection instanceof Ci.mozIStorageAsyncConnection)) {
1549     throw new TypeError("connection not specified or invalid.");
1550   }
1552   if (isClosed()) {
1553     throw new Error(
1554       "Sqlite.sys.mjs has been shutdown. Cannot wrap connection to: " +
1555         connection.databaseFile.path
1556     );
1557   }
1559   let identifier = getIdentifierByFileName(connection.databaseFile.leafName);
1561   logger.debug("Wrapping database: " + identifier);
1562   return new Promise(resolve => {
1563     try {
1564       let conn = connection.QueryInterface(Ci.mozIStorageAsyncConnection);
1565       let wrapper = new OpenedConnection(conn, identifier);
1566       // We must not handle shutdown of a wrapped connection, since that is
1567       // already handled by the opener.
1568       wrappedConnections.add(identifier);
1569       resolve(wrapper);
1570     } catch (ex) {
1571       logger.error("Could not wrap database", ex);
1572       throw ex;
1573     }
1574   });
1578  * Handle on an opened SQLite database.
1580  * This is essentially a glorified wrapper around mozIStorageConnection.
1581  * However, it offers some compelling advantages.
1583  * The main functions on this type are `execute` and `executeCached`. These are
1584  * ultimately how all SQL statements are executed. It's worth explaining their
1585  * differences.
1587  * `execute` is used to execute one-shot SQL statements. These are SQL
1588  * statements that are executed one time and then thrown away. They are useful
1589  * for dynamically generated SQL statements and clients who don't care about
1590  * performance (either their own or wasting resources in the overall
1591  * application). Because of the performance considerations, it is recommended
1592  * to avoid `execute` unless the statement you are executing will only be
1593  * executed once or seldomly.
1595  * `executeCached` is used to execute a statement that will presumably be
1596  * executed multiple times. The statement is parsed once and stuffed away
1597  * inside the connection instance. Subsequent calls to `executeCached` will not
1598  * incur the overhead of creating a new statement object. This should be used
1599  * in preference to `execute` when a specific SQL statement will be executed
1600  * multiple times.
1602  * Instances of this type are not meant to be created outside of this file.
1603  * Instead, first open an instance of `UnopenedSqliteConnection` and obtain
1604  * an instance of this type by calling `open`.
1606  * FUTURE IMPROVEMENTS
1608  *   Ability to enqueue operations. Currently there can be race conditions,
1609  *   especially as far as transactions are concerned. It would be nice to have
1610  *   an enqueueOperation(func) API that serially executes passed functions.
1612  *   Support for SAVEPOINT (named/nested transactions) might be useful.
1614  * @param connection
1615  *        (mozIStorageConnection) Underlying SQLite connection.
1616  * @param identifier
1617  *        (string) The unique identifier of this database. It may be used for
1618  *        logging or as a key in Maps.
1619  * @param options [optional]
1620  *        (object) Options to control behavior of connection. See
1621  *        `openConnection`.
1622  */
1623 function OpenedConnection(connection, identifier, options = {}) {
1624   // Store all connection data in a field distinct from the
1625   // witness. This enables us to store an additional reference to this
1626   // field without preventing garbage collection of
1627   // OpenedConnection. On garbage collection, we will still be able to
1628   // close the database using this extra reference.
1629   this._connectionData = new ConnectionData(connection, identifier, options);
1631   // Store the extra reference in a map with connection identifier as
1632   // key.
1633   ConnectionData.byId.set(
1634     this._connectionData._identifier,
1635     this._connectionData
1636   );
1638   // Make a finalization witness. If this object is garbage collected
1639   // before its `forget` method has been called, an event with topic
1640   // "sqlite-finalization-witness" is broadcasted along with the
1641   // connection identifier string of the database.
1642   this._witness = lazy.FinalizationWitnessService.make(
1643     "sqlite-finalization-witness",
1644     this._connectionData._identifier
1645   );
1648 OpenedConnection.TRANSACTION_TYPES = ["DEFERRED", "IMMEDIATE", "EXCLUSIVE"];
1650 // Converts a `mozIStorageAsyncConnection::TRANSACTION_*` constant into the
1651 // corresponding `OpenedConnection.TRANSACTION_TYPES` constant.
1652 function convertStorageTransactionType(type) {
1653   if (!(type in OpenedConnection.TRANSACTION_TYPES)) {
1654     throw new Error("Unknown storage transaction type: " + type);
1655   }
1656   return OpenedConnection.TRANSACTION_TYPES[type];
1659 OpenedConnection.prototype = Object.freeze({
1660   TRANSACTION_DEFAULT: "DEFAULT",
1661   TRANSACTION_DEFERRED: "DEFERRED",
1662   TRANSACTION_IMMEDIATE: "IMMEDIATE",
1663   TRANSACTION_EXCLUSIVE: "EXCLUSIVE",
1665   /**
1666    * Returns a handle to the underlying `mozIStorageAsyncConnection`. This is
1667    * ⚠️ **extremely unsafe** ⚠️ because `Sqlite.sys.mjs` continues to manage the
1668    * connection's lifecycle, including transactions and shutdown blockers.
1669    * Misusing the raw connection can easily lead to data loss, memory leaks,
1670    * and errors.
1671    *
1672    * Consumers of the raw connection **must not** close or re-wrap it,
1673    * and should not run statements concurrently with `Sqlite.sys.mjs`.
1674    *
1675    * It's _much_ safer to open a `mozIStorage{Async}Connection` yourself,
1676    * and access it from JavaScript via `Sqlite.wrapStorageConnection`.
1677    * `unsafeRawConnection` is an escape hatch for cases where you can't
1678    * do that.
1679    *
1680    * Please do _not_ add new uses of `unsafeRawConnection` without review
1681    * from a storage peer.
1682    */
1683   get unsafeRawConnection() {
1684     return this._connectionData._dbConn;
1685   },
1687   /**
1688    * Returns the maximum number of bound parameters for statements executed
1689    * on this connection.
1690    *
1691    * @returns {number} The bound parameters limit.
1692    */
1693   get variableLimit() {
1694     return this.unsafeRawConnection.variableLimit;
1695   },
1697   /**
1698    * Set the the maximum number of bound parameters for statements executed
1699    * on this connection. If the passed-in value is higher than the maximum
1700    * default value, it will be silently truncated.
1701    *
1702    * @param {number} newLimit The bound parameters limit.
1703    */
1704   set variableLimit(newLimit) {
1705     this.unsafeRawConnection.variableLimit = newLimit;
1706   },
1708   /**
1709    * The integer schema version of the database.
1710    *
1711    * This is 0 if not schema version has been set.
1712    *
1713    * @return Promise<int>
1714    */
1715   getSchemaVersion(schemaName = "main") {
1716     return this.execute(`PRAGMA ${schemaName}.user_version`).then(result =>
1717       result[0].getInt32(0)
1718     );
1719   },
1721   setSchemaVersion(value, schemaName = "main") {
1722     if (!Number.isInteger(value)) {
1723       // Guarding against accidental SQLi
1724       throw new TypeError("Schema version must be an integer. Got " + value);
1725     }
1726     this._connectionData.ensureOpen();
1727     return this.execute(`PRAGMA ${schemaName}.user_version = ${value}`);
1728   },
1730   /**
1731    * Close the database connection.
1732    *
1733    * This must be performed when you are finished with the database.
1734    *
1735    * Closing the database connection has the side effect of forcefully
1736    * cancelling all active statements. Therefore, callers should ensure that
1737    * all active statements have completed before closing the connection, if
1738    * possible.
1739    *
1740    * The returned promise will be resolved once the connection is closed.
1741    * Successive calls to close() return the same promise.
1742    *
1743    * IMPROVEMENT: Resolve the promise to a closed connection which can be
1744    * reopened.
1745    *
1746    * @return Promise<>
1747    */
1748   close() {
1749     // Unless cleanup has already been done by a previous call to
1750     // `close`, delete the database entry from map and tell the
1751     // finalization witness to forget.
1752     if (ConnectionData.byId.has(this._connectionData._identifier)) {
1753       ConnectionData.byId.delete(this._connectionData._identifier);
1754       this._witness.forget();
1755     }
1756     return this._connectionData.close();
1757   },
1759   /**
1760    * Clones this connection to a new Sqlite one.
1761    *
1762    * The following parameters can control the cloned connection:
1763    *
1764    * @param readOnly
1765    *        (boolean) - If true the clone will be read-only.  If the original
1766    *        connection is already read-only, the clone will be, regardless of
1767    *        this option.  If the original connection is using the shared cache,
1768    *        this parameter will be ignored and the clone will be as privileged as
1769    *        the original connection.
1770    *
1771    * @return Promise<OpenedConnection>
1772    */
1773   clone(readOnly = false) {
1774     return this._connectionData.clone(readOnly);
1775   },
1777   executeBeforeShutdown(name, task) {
1778     return this._connectionData.executeBeforeShutdown(this, name, task);
1779   },
1781   /**
1782    * Execute a SQL statement and cache the underlying statement object.
1783    *
1784    * This function executes a SQL statement and also caches the underlying
1785    * derived statement object so subsequent executions are faster and use
1786    * less resources.
1787    *
1788    * This function optionally binds parameters to the statement as well as
1789    * optionally invokes a callback for every row retrieved.
1790    *
1791    * By default, no parameters are bound and no callback will be invoked for
1792    * every row.
1793    *
1794    * Bound parameters can be defined as an Array of positional arguments or
1795    * an object mapping named parameters to their values. If there are no bound
1796    * parameters, the caller can pass nothing or null for this argument.
1797    *
1798    * Callers are encouraged to pass objects rather than Arrays for bound
1799    * parameters because they prevent foot guns. With positional arguments, it
1800    * is simple to modify the parameter count or positions without fixing all
1801    * users of the statement. Objects/named parameters are a little safer
1802    * because changes in order alone won't result in bad things happening.
1803    *
1804    * When `onRow` is not specified, all returned rows are buffered before the
1805    * returned promise is resolved. For INSERT or UPDATE statements, this has
1806    * no effect because no rows are returned from these. However, it has
1807    * implications for SELECT statements.
1808    *
1809    * If your SELECT statement could return many rows or rows with large amounts
1810    * of data, for performance reasons it is recommended to pass an `onRow`
1811    * handler. Otherwise, the buffering may consume unacceptable amounts of
1812    * resources.
1813    *
1814    * If the second parameter of an `onRow` handler is called during execution
1815    * of the `onRow` handler, the execution of the statement is immediately
1816    * cancelled. Subsequent rows will not be processed and no more `onRow`
1817    * invocations will be made. The promise is resolved immediately.
1818    *
1819    * If an exception is thrown by the `onRow` handler, the exception is logged
1820    * and processing of subsequent rows occurs as if nothing happened. The
1821    * promise is still resolved (not rejected).
1822    *
1823    * The return value is a promise that will be resolved when the statement
1824    * has completed fully.
1825    *
1826    * The promise will be rejected with an `Error` instance if the statement
1827    * did not finish execution fully. The `Error` may have an `errors` property.
1828    * If defined, it will be an Array of objects describing individual errors.
1829    * Each object has the properties `result` and `message`. `result` is a
1830    * numeric error code and `message` is a string description of the problem.
1831    *
1832    * @param name
1833    *        (string) The name of the registered statement to execute.
1834    * @param params optional
1835    *        (Array or object) Parameters to bind.
1836    * @param onRow optional
1837    *        (function) Callback to receive each row from result.
1838    */
1839   executeCached(sql, params = null, onRow = null) {
1840     if (isInvalidBoundLikeQuery(sql)) {
1841       throw new Error("Please enter a LIKE clause with bindings");
1842     }
1843     return this._connectionData.executeCached(sql, params, onRow);
1844   },
1846   /**
1847    * Execute a one-shot SQL statement.
1848    *
1849    * If you find yourself feeding the same SQL string in this function, you
1850    * should *not* use this function and instead use `executeCached`.
1851    *
1852    * See `executeCached` for the meaning of the arguments and extended usage info.
1853    *
1854    * @param sql
1855    *        (string) SQL to execute.
1856    * @param params optional
1857    *        (Array or Object) Parameters to bind to the statement.
1858    * @param onRow optional
1859    *        (function) Callback to receive result of a single row.
1860    */
1861   execute(sql, params = null, onRow = null) {
1862     if (isInvalidBoundLikeQuery(sql)) {
1863       throw new Error("Please enter a LIKE clause with bindings");
1864     }
1865     return this._connectionData.execute(sql, params, onRow);
1866   },
1868   /**
1869    * The default behavior for transactions run on this connection.
1870    */
1871   get defaultTransactionType() {
1872     return this._connectionData.defaultTransactionType;
1873   },
1875   /**
1876    * Whether a transaction is currently in progress.
1877    *
1878    * Note that this is true if a transaction is active on the connection,
1879    * regardless of whether it was started by `Sqlite.sys.mjs` or another consumer.
1880    * See the explanation above `mozIStorageConnection.transactionInProgress` for
1881    * why this distinction matters.
1882    */
1883   get transactionInProgress() {
1884     return this._connectionData.transactionInProgress;
1885   },
1887   /**
1888    * Perform a transaction.
1889    *
1890    * *****************************************************************************
1891    * YOU SHOULD _NEVER_ NEST executeTransaction CALLS FOR ANY REASON, NOR
1892    * DIRECTLY, NOR THROUGH OTHER PROMISES.
1893    * FOR EXAMPLE, NEVER DO SOMETHING LIKE:
1894    *   await executeTransaction(async function () {
1895    *     ...some_code...
1896    *     await executeTransaction(async function () { // WRONG!
1897    *       ...some_code...
1898    *     })
1899    *     await someCodeThatExecuteTransaction(); // WRONG!
1900    *     await neverResolvedPromise; // WRONG!
1901    *   });
1902    * NESTING CALLS WILL BLOCK ANY FUTURE TRANSACTION UNTIL A TIMEOUT KICKS IN.
1903    * *****************************************************************************
1904    *
1905    * A transaction is specified by a user-supplied function that is an
1906    * async function. The function receives this connection instance as its argument.
1907    *
1908    * The supplied function is expected to return promises. These are often
1909    * promises created by calling `execute` and `executeCached`. If the
1910    * generator is exhausted without any errors being thrown, the
1911    * transaction is committed. If an error occurs, the transaction is
1912    * rolled back.
1913    *
1914    * The returned value from this function is a promise that will be resolved
1915    * once the transaction has been committed or rolled back. The promise will
1916    * be resolved to whatever value the supplied function resolves to. If
1917    * the transaction is rolled back, the promise is rejected.
1918    *
1919    * @param func
1920    *        (function) What to perform as part of the transaction.
1921    * @param type optional
1922    *        One of the TRANSACTION_* constants attached to this type.
1923    */
1924   executeTransaction(func, type = this.TRANSACTION_DEFAULT) {
1925     return this._connectionData.executeTransaction(() => func(this), type);
1926   },
1928   /**
1929    * Whether a table exists in the database (both persistent and temporary tables).
1930    *
1931    * @param name
1932    *        (string) Name of the table.
1933    *
1934    * @return Promise<bool>
1935    */
1936   tableExists(name) {
1937     return this.execute(
1938       "SELECT name FROM (SELECT * FROM sqlite_master UNION ALL " +
1939         "SELECT * FROM sqlite_temp_master) " +
1940         "WHERE type = 'table' AND name=?",
1941       [name]
1942     ).then(function onResult(rows) {
1943       return Promise.resolve(!!rows.length);
1944     });
1945   },
1947   /**
1948    * Whether a named index exists (both persistent and temporary tables).
1949    *
1950    * @param name
1951    *        (string) Name of the index.
1952    *
1953    * @return Promise<bool>
1954    */
1955   indexExists(name) {
1956     return this.execute(
1957       "SELECT name FROM (SELECT * FROM sqlite_master UNION ALL " +
1958         "SELECT * FROM sqlite_temp_master) " +
1959         "WHERE type = 'index' AND name=?",
1960       [name]
1961     ).then(function onResult(rows) {
1962       return Promise.resolve(!!rows.length);
1963     });
1964   },
1966   /**
1967    * Free up as much memory from the underlying database connection as possible.
1968    *
1969    * @return Promise<>
1970    */
1971   shrinkMemory() {
1972     return this._connectionData.shrinkMemory();
1973   },
1975   /**
1976    * Discard all cached statements.
1977    *
1978    * Note that this relies on us being non-interruptible between
1979    * the insertion or retrieval of a statement in the cache and its
1980    * execution: we finalize all statements, which is only safe if
1981    * they will not be executed again.
1982    *
1983    * @return (integer) the number of statements discarded.
1984    */
1985   discardCachedStatements() {
1986     return this._connectionData.discardCachedStatements();
1987   },
1989   /**
1990    * Interrupts pending database operations returning at the first opportunity.
1991    * Statement execution will throw an NS_ERROR_ABORT failure.
1992    * Can only be used on read-only connections.
1993    */
1994   interrupt() {
1995     this._connectionData.interrupt();
1996   },
1998   /**
1999    * Asynchronously makes a copy of the SQLite database while there may still be
2000    * open connections on it.
2001    *
2002    * @param {string} destFilePath
2003    *   The path on the local filesystem to write the database copy. Any existing
2004    *   file at this path will be overwritten.
2005    * @return Promise<undefined, nsresult>
2006    */
2007   backup(destFilePath) {
2008     return this._connectionData.backupToFile(destFilePath);
2009   },
2012 export var Sqlite = {
2013   // The maximum time to wait before considering a transaction stuck and
2014   // issuing a ROLLBACK, see `executeTransaction`. Could be modified by tests.
2015   TRANSACTIONS_TIMEOUT_MS: 300000, // 5 minutes
2017   openConnection,
2018   cloneStorageConnection,
2019   wrapStorageConnection,
2020   /**
2021    * Shutdown barrier client. May be used by clients to perform last-minute
2022    * cleanup prior to the shutdown of this module.
2023    *
2024    * See the documentation of AsyncShutdown.Barrier.prototype.client.
2025    */
2026   get shutdown() {
2027     return lazy.Barriers.shutdown.client;
2028   },
2029   failTestsOnAutoClose(enabled) {
2030     Debugging.failTestsOnAutoClose = enabled;
2031   },