summaryrefslogtreecommitdiffstats
path: root/dom/base/IndexedDBHelper.jsm
blob: ccb992d70a7ff70dd5083971b3f4e123b81f16b5 (plain)
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
/* 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 DEBUG = 0;
var debug;
if (DEBUG) {
  debug = function(s) {
    dump("-*- IndexedDBHelper: " + s + "\n");
  };
} else {
  debug = function(s) {};
}

var EXPORTED_SYMBOLS = ["IndexedDBHelper"];

Cu.importGlobalProperties(["indexedDB"]);

ChromeUtils.defineModuleGetter(
  this,
  "Services",
  "resource://gre/modules/Services.jsm"
);

function getErrorName(err) {
  return (err && err.name) || "UnknownError";
}

function IndexedDBHelper() {}

IndexedDBHelper.prototype = {
  // Close the database
  close: function close() {
    if (this._db) {
      this._db.close();
      this._db = null;
    }
  },

  /**
   * Open a new database.
   * User has to provide upgradeSchema.
   *
   * @param successCb
   *        Success callback to call once database is open.
   * @param failureCb
   *        Error callback to call when an error is encountered.
   */
  open: function open(aCallback) {
    if (aCallback && !this._waitForOpenCallbacks.has(aCallback)) {
      this._waitForOpenCallbacks.add(aCallback);
      if (this._waitForOpenCallbacks.size !== 1) {
        return;
      }
    }

    let self = this;
    let invokeCallbacks = err => {
      for (let callback of self._waitForOpenCallbacks) {
        callback(err);
      }
      self._waitForOpenCallbacks.clear();
    };

    if (DEBUG) {
      debug("Try to open database:" + self.dbName + " " + self.dbVersion);
    }
    let req;
    try {
      req = indexedDB.open(this.dbName, this.dbVersion);
    } catch (e) {
      if (DEBUG) {
        debug("Error opening database: " + self.dbName);
      }
      Services.tm.dispatchToMainThread(() => invokeCallbacks(getErrorName(e)));
      return;
    }
    req.onsuccess = function(event) {
      if (DEBUG) {
        debug("Opened database:" + self.dbName + " " + self.dbVersion);
      }
      self._db = event.target.result;
      self._db.onversionchange = function(event) {
        if (DEBUG) {
          debug("WARNING: DB modified from a different window.");
        }
      };
      invokeCallbacks();
    };

    req.onupgradeneeded = function(aEvent) {
      if (DEBUG) {
        debug(
          "Database needs upgrade:" +
            self.dbName +
            aEvent.oldVersion +
            aEvent.newVersion
        );
        debug(
          "Correct new database version:" +
            (aEvent.newVersion == this.dbVersion)
        );
      }

      let _db = aEvent.target.result;
      self.upgradeSchema(
        req.transaction,
        _db,
        aEvent.oldVersion,
        aEvent.newVersion
      );
    };
    req.onerror = function(aEvent) {
      if (DEBUG) {
        debug("Failed to open database: " + self.dbName);
      }
      invokeCallbacks(getErrorName(aEvent.target.error));
    };
    req.onblocked = function(aEvent) {
      if (DEBUG) {
        debug("Opening database request is blocked.");
      }
    };
  },

  /**
   * Use the cached DB or open a new one.
   *
   * @param successCb
   *        Success callback to call.
   * @param failureCb
   *        Error callback to call when an error is encountered.
   */
  ensureDB: function ensureDB(aSuccessCb, aFailureCb) {
    if (this._db) {
      if (DEBUG) {
        debug("ensureDB: already have a database, returning early.");
      }
      if (aSuccessCb) {
        Services.tm.dispatchToMainThread(aSuccessCb);
      }
      return;
    }
    this.open(aError => {
      if (aError) {
        aFailureCb && aFailureCb(aError);
      } else {
        aSuccessCb && aSuccessCb();
      }
    });
  },

  /**
   * Start a new transaction.
   *
   * @param txn_type
   *        Type of transaction (e.g. "readwrite")
   * @param store_name
   *        The object store you want to be passed to the callback
   * @param callback
   *        Function to call when the transaction is available. It will
   *        be invoked with the transaction and the `store' object store.
   * @param successCb
   *        Success callback to call on a successful transaction commit.
   *        The result is stored in txn.result (in the callback function).
   * @param failureCb
   *        Error callback to call when an error is encountered.
   */
  newTxn: function newTxn(
    txn_type,
    store_name,
    callback,
    successCb,
    failureCb
  ) {
    this.ensureDB(() => {
      if (DEBUG) {
        debug("Starting new transaction" + txn_type);
      }
      let txn;
      try {
        txn = this._db.transaction(
          Array.isArray(store_name) ? store_name : this.dbStoreNames,
          txn_type
        );
      } catch (e) {
        if (DEBUG) {
          debug("Error starting transaction: " + this.dbName);
        }
        failureCb(getErrorName(e));
        return;
      }
      if (DEBUG) {
        debug("Retrieving object store: " + this.dbName);
      }
      let stores;
      if (Array.isArray(store_name)) {
        stores = [];
        for (let i = 0; i < store_name.length; ++i) {
          stores.push(txn.objectStore(store_name[i]));
        }
      } else {
        stores = txn.objectStore(store_name);
      }

      txn.oncomplete = function() {
        if (DEBUG) {
          debug("Transaction complete. Returning to callback.");
        }
        /*
         * txn.result property is not part of the transaction object returned
         * by this._db.transaction method called above.
         * The property is expected to be set in the callback function.
         * However, it can happen that the property is not set for some reason,
         * so we have to check if the property exists before calling the
         * success callback.
         */
        if (successCb) {
          if ("result" in txn) {
            successCb(txn.result);
          } else {
            successCb();
          }
        }
      };

      txn.onabort = function() {
        if (DEBUG) {
          debug("Caught error on transaction");
        }
        /*
         * txn.error property is part of the transaction object returned by
         * this._db.transaction method called above.
         * The attribute is defined in IDBTranscation WebIDL interface.
         * It may be null.
         */
        if (failureCb) {
          failureCb(getErrorName(txn.error));
        }
      };
      callback(txn, stores);
    }, failureCb);
  },

  /**
   * Initialize the DB. Does not call open.
   *
   * @param aDBName
   *        DB name for the open call.
   * @param aDBVersion
   *        Current DB version. User has to implement upgradeSchema.
   * @param aDBStoreName
   *        ObjectStore that is used.
   */
  initDBHelper: function initDBHelper(aDBName, aDBVersion, aDBStoreNames) {
    this.dbName = aDBName;
    this.dbVersion = aDBVersion;
    this.dbStoreNames = aDBStoreNames;
    // Cache the database.
    this._db = null;
    this._waitForOpenCallbacks = new Set();
  },
};