forked from superfeedr/indexeddb-backbonejs-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-indexeddb.js
576 lines (501 loc) · 25.4 KB
/
backbone-indexeddb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
(function () { /*global _: false, Backbone: false */
// Generate four random hex digits.
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
if(typeof exports !== 'undefined'){
_ = require('underscore');
Backbone = require('backbone');
}
// Naming is a mess!
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB ;
var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" }; // No prefix in moz
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ; // No prefix in moz
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.mozIDBCursor || window.msIDBCursor ;
// Driver object
// That's the interesting part.
// There is a driver for each schema provided. The schema is a te combination of name (for the database), a version as well as migrations to reach that
// version of the database.
function Driver(schema, ready, nolog) {
this.schema = schema;
this.ready = ready;
this.error = null;
this.transactions = []; // Used to list all transactions and keep track of active ones.
this.db = null;
this.nolog = nolog;
this.supportOnUpgradeNeeded = false;
var lastMigrationPathVersion = _.last(this.schema.migrations).version;
if (!this.nolog) debugLog("opening database " + this.schema.id + " in version #" + lastMigrationPathVersion);
this.dbRequest = indexedDB.open(this.schema.id,lastMigrationPathVersion); //schema version need to be an unsigned long
this.launchMigrationPath = function(dbVersion) {
var clonedMigrations = _.clone(schema.migrations);
this.migrate(clonedMigrations, dbVersion, {
success: function () {
this.ready();
}.bind(this),
error: function () {
this.error = "Database not up to date. " + dbVersion + " expected was " + lastMigrationPathVersion;
}.bind(this)
});
};
this.dbRequest.onblocked = function(event){
if (!this.nolog) debugLog("blocked");
}
this.dbRequest.onsuccess = function (e) {
this.db = e.target.result; // Attach the connection ot the queue.
if(!this.supportOnUpgradeNeeded)
{
var currentIntDBVersion = (parseInt(this.db.version) || 0); // we need convert beacuse chrome store in integer and ie10 DP4+ in int;
var lastMigrationInt = (parseInt(lastMigrationPathVersion) || 0); // And make sure we compare numbers with numbers.
if (currentIntDBVersion === lastMigrationInt) { //if support new event onupgradeneeded will trigger the ready function
// No migration to perform!
this.ready();
} else if (currentIntDBVersion < lastMigrationInt ) {
// We need to migrate up to the current migration defined in the database
this.launchMigrationPath(currentIntDBVersion);
} else {
// Looks like the IndexedDB is at a higher version than the current driver schema.
this.error = "Database version is greater than current code " + currentIntDBVersion + " expected was " + lastMigrationInt;
}
};
}.bind(this);
this.dbRequest.onerror = function (e) {
// Failed to open the database
this.error = "Couldn't not connect to the database"
}.bind(this);
this.dbRequest.onabort = function (e) {
// Failed to open the database
this.error = "Connection to the database aborted"
}.bind(this);
this.dbRequest.onupgradeneeded = function(iDBVersionChangeEvent){
this.db =iDBVersionChangeEvent.target.transaction.db;
this.supportOnUpgradeNeeded = true;
if (!this.nolog) debugLog("onupgradeneeded = " + iDBVersionChangeEvent.oldVersion + " => " + iDBVersionChangeEvent.newVersion);
this.launchMigrationPath(iDBVersionChangeEvent.oldVersion);
}.bind(this);
}
function debugLog(str) {
if (typeof window !== "undefined" && typeof window.console !== "undefined" && typeof window.console.log !== "undefined") {
window.console.log(str);
}
else if(console.log !== "undefined") {
console.log(str)
}
}
// Driver Prototype
Driver.prototype = {
// Tracks transactions. Mostly for debugging purposes. TO-IMPROVE
_track_transaction: function(transaction) {
this.transactions.push(transaction);
function removeIt() {
var idx = this.transactions.indexOf(transaction);
if (idx !== -1) {this.transactions.splice(idx); }
};
transaction.oncomplete = removeIt.bind(this);
transaction.onabort = removeIt.bind(this);
transaction.onerror = removeIt.bind(this);
},
// Performs all the migrations to reach the right version of the database.
migrate: function (migrations, version, options) {
if (!this.nolog) debugLog("Starting migrations from " + version);
this._migrate_next(migrations, version, options);
},
// Performs the next migrations. This method is private and should probably not be called.
_migrate_next: function (migrations, version, options) {
if (!this.nolog) debugLog("_migrate_next begin version from #" + version);
var that = this;
var migration = migrations.shift();
if (migration) {
if (!version || version < migration.version) {
// We need to apply this migration-
if (typeof migration.before == "undefined") {
migration.before = function (next) {
next();
};
}
if (typeof migration.after == "undefined") {
migration.after = function (next) {
next();
};
}
// First, let's run the before script
if (!this.nolog) debugLog("_migrate_next begin before version #" + migration.version);
migration.before(function () {
if (!this.nolog) debugLog("_migrate_next done before version #" + migration.version);
var continueMigration = function (e) {
if (!this.nolog) debugLog("_migrate_next continueMigration version #" + migration.version);
var transaction = this.dbRequest.transaction || versionRequest.result;
if (!this.nolog) debugLog("_migrate_next begin migrate version #" + migration.version);
migration.migrate(transaction, function () {
if (!this.nolog) debugLog("_migrate_next done migrate version #" + migration.version);
// Migration successfully appliedn let's go to the next one!
if (!this.nolog) debugLog("_migrate_next begin after version #" + migration.version);
migration.after(function () {
if (!this.nolog) debugLog("_migrate_next done after version #" + migration.version);
if (!this.nolog) debugLog("Migrated to " + migration.version);
//last modification occurred, need finish
if(migrations.length ==0) {
/*if(this.supportOnUpgradeNeeded){
debugLog("Done migrating");
// No more migration
options.success();
}
else{*/
if (!this.nolog) debugLog("_migrate_next setting transaction.oncomplete to finish version #" + migration.version);
transaction.oncomplete = function() {
if (!that.nolog) debugLog("_migrate_next done transaction.oncomplete version #" + migration.version);
if (!that.nolog) debugLog("Done migrating");
// No more migration
options.success();
}
//}
}
else
{
if (!this.nolog) debugLog("_migrate_next setting transaction.oncomplete to recursive _migrate_next version #" + migration.version);
transaction.oncomplete = function() {
if (!this.nolog) debugLog("_migrate_next end from version #" + version + " to " + migration.version);
that._migrate_next(migrations, version, options);
}
}
}.bind(this));
}.bind(this));
}.bind(this);
if(!this.supportOnUpgradeNeeded){
if (!this.nolog) debugLog("_migrate_next begin setVersion version #" + migration.version);
var versionRequest = this.db.setVersion(migration.version);
versionRequest.onsuccess = continueMigration;
versionRequest.onerror = options.error;
}
else {
continueMigration();
}
}.bind(this));
} else {
// No need to apply this migration
if (!this.nolog) debugLog("Skipping migration " + migration.version);
this._migrate_next(migrations, version, options);
}
}
},
// This is the main method, called by the ExecutionQueue when the driver is ready (database open and migration performed)
execute: function (storeName, method, object, options) {
if (!this.nolog) debugLog("execute : " + method + " on " + storeName + " for " + object.id);
switch (method) {
case "create":
this.create(storeName, object, options);
break;
case "read":
if (object.id || object.cid) {
this.read(storeName, object, options); // It's a model
} else {
this.query(storeName, object, options); // It's a collection
}
break;
case "update":
this.update(storeName, object, options); // We may want to check that this is not a collection. TOFIX
break;
case "delete":
if (object.id || object.cid) {
this.delete(storeName, object, options);
} else {
this.clear(storeName, object, options);
}
break;
default:
// Hum what?
}
},
// Writes the json to the storeName in db. It is a create operations, which means it will fail if the key already exists
// options are just success and error callbacks.
create: function (storeName, object, options) {
var writeTransaction = this.db.transaction([storeName], 'readwrite');
//this._track_transaction(writeTransaction);
var store = writeTransaction.objectStore(storeName);
var json = object.toJSON();
var writeRequest;
if (json.id === undefined) json.id = guid();
if (json.id === null) delete json.id;
if (!store.keyPath)
writeRequest = store.add(json, json.id);
else
writeRequest = store.add(json);
writeRequest.onerror = function (e) {
options.error(e);
};
writeRequest.onsuccess = function (e) {
options.success(json);
};
},
// Writes the json to the storeName in db. It is an update operation, which means it will overwrite the value if the key already exist
// options are just success and error callbacks.
update: function (storeName, object, options) {
var writeTransaction = this.db.transaction([storeName], 'readwrite');
//this._track_transaction(writeTransaction);
var store = writeTransaction.objectStore(storeName);
var json = object.toJSON();
var writeRequest;
if (!json.id) json.id = guid();
if (!store.keyPath)
writeRequest = store.put(json, json.id);
else
writeRequest = store.put(json);
writeRequest.onerror = function (e) {
options.error(e);
};
writeRequest.onsuccess = function (e) {
options.success(json);
};
},
// Reads from storeName in db with json.id if it's there of with any json.xxxx as long as xxx is an index in storeName
read: function (storeName, object, options) {
var readTransaction = this.db.transaction([storeName], "readonly");
this._track_transaction(readTransaction);
var store = readTransaction.objectStore(storeName);
var json = object.toJSON();
var getRequest = null;
if (json.id) {
getRequest = store.get(json.id);
} else {
// We need to find which index we have
_.each(store.indexNames, function (key, index) {
index = store.index(key);
if (json[index.keyPath] && !getRequest) {
getRequest = index.get(json[index.keyPath]);
}
});
}
if (getRequest) {
getRequest.onsuccess = function (event) {
if (event.target.result) {
options.success(event.target.result);
} else {
options.error("Not Found");
}
};
getRequest.onerror = function () {
options.error("Not Found"); // We couldn't find the record.
}
} else {
options.error("Not Found"); // We couldn't even look for it, as we don't have enough data.
}
},
// Deletes the json.id key and value in storeName from db.
delete: function (storeName, object, options) {
var deleteTransaction = this.db.transaction([storeName], 'readwrite');
//this._track_transaction(deleteTransaction);
var store = deleteTransaction.objectStore(storeName);
var json = object.toJSON();
var deleteRequest = store.delete(json.id);
deleteRequest.onsuccess = function (event) {
options.success(null);
};
deleteRequest.onerror = function (event) {
options.error("Not Deleted");
};
},
// Clears all records for storeName from db.
clear: function (storeName, object, options) {
var deleteTransaction = this.db.transaction([storeName], "readwrite");
//this._track_transaction(deleteTransaction);
var store = deleteTransaction.objectStore(storeName);
var deleteRequest = store.clear();
deleteRequest.onsuccess = function (event) {
options.success(null);
};
deleteRequest.onerror = function (event) {
options.error("Not Cleared");
};
},
// Performs a query on storeName in db.
// options may include :
// - conditions : value of an index, or range for an index
// - range : range for the primary key
// - limit : max number of elements to be yielded
// - offset : skipped items.
query: function (storeName, collection, options) {
var elements = [];
var skipped = 0, processed = 0;
var queryTransaction = this.db.transaction([storeName], "readonly");
//this._track_transaction(queryTransaction);
var readCursor = null;
var store = queryTransaction.objectStore(storeName);
var index = null,
lower = null,
upper = null,
bounds = null;
if (options.conditions) {
// We have a condition, we need to use it for the cursor
_.each(store.indexNames, function (key) {
if (!readCursor) {
index = store.index(key);
if (options.conditions[index.keyPath] instanceof Array) {
lower = options.conditions[index.keyPath][0] > options.conditions[index.keyPath][1] ? options.conditions[index.keyPath][1] : options.conditions[index.keyPath][0];
upper = options.conditions[index.keyPath][0] > options.conditions[index.keyPath][1] ? options.conditions[index.keyPath][0] : options.conditions[index.keyPath][1];
bounds = IDBKeyRange.bound(lower, upper, true, true);
if (options.conditions[index.keyPath][0] > options.conditions[index.keyPath][1]) {
// Looks like we want the DESC order
readCursor = index.openCursor(bounds, window.IDBCursor.PREV);
} else {
// We want ASC order
readCursor = index.openCursor(bounds, window.IDBCursor.NEXT);
}
} else if (options.conditions[index.keyPath] != undefined) {
bounds = IDBKeyRange.only(options.conditions[index.keyPath]);
readCursor = index.openCursor(bounds);
}
}
});
} else {
// No conditions, use the index
if (options.range) {
lower = options.range[0] > options.range[1] ? options.range[1] : options.range[0];
upper = options.range[0] > options.range[1] ? options.range[0] : options.range[1];
bounds = IDBKeyRange.bound(lower, upper);
if (options.range[0] > options.range[1]) {
readCursor = store.openCursor(bounds, window.IDBCursor.PREV);
} else {
readCursor = store.openCursor(bounds, window.IDBCursor.NEXT);
}
} else {
readCursor = store.openCursor();
}
}
if (typeof (readCursor) == "undefined" || !readCursor) {
options.error("No Cursor");
} else {
readCursor.onerror = function(e){
options.error("readCursor error", e);
};
// Setup a handler for the cursor’s `success` event:
readCursor.onsuccess = function (e) {
var cursor = e.target.result;
if (!cursor) {
if (options.addIndividually || options.clear) {
// nothing!
// We need to indicate that we're done. But, how?
collection.trigger("reset");
} else {
options.success(elements); // We're done. No more elements.
}
}
else {
// Cursor is not over yet.
if (options.limit && processed >= options.limit) {
// Yet, we have processed enough elements. So, let's just skip.
if (bounds && options.conditions[index.keyPath]) {
cursor.continue(options.conditions[index.keyPath][1] + 1); /* We need to 'terminate' the cursor cleany, by moving to the end */
} else {
cursor.continue(); /* We need to 'terminate' the cursor cleany, by moving to the end */
}
}
else if (options.offset && options.offset > skipped) {
skipped++;
cursor.continue(); /* We need to Moving the cursor forward */
} else {
// This time, it looks like it's good!
if (options.addIndividually) {
collection.add(cursor.value);
} else if (options.clear) {
var deleteRequest = store.delete(cursor.value.id);
deleteRequest.onsuccess = function (event) {
elements.push(cursor.value);
};
deleteRequest.onerror = function (event) {
elements.push(cursor.value);
};
} else {
elements.push(cursor.value);
}
processed++;
cursor.continue();
}
}
};
}
},
close :function(){
if(this.db){
this.db.close()
; }
}
};
// ExecutionQueue object
// The execution queue is an abstraction to buffer up requests to the database.
// It holds a "driver". When the driver is ready, it just fires up the queue and executes in sync.
function ExecutionQueue(schema,next,nolog) {
this.driver = new Driver(schema, this.ready.bind(this), nolog);
this.started = false;
this.stack = [];
this.version = _.last(schema.migrations).version;
this.next = next;
}
// ExecutionQueue Prototype
ExecutionQueue.prototype = {
// Called when the driver is ready
// It just loops over the elements in the queue and executes them.
ready: function () {
this.started = true;
_.each(this.stack, function (message) {
this.execute(message);
}.bind(this));
this.next();
},
// Executes a given command on the driver. If not started, just stacks up one more element.
execute: function (message) {
if (this.started) {
this.driver.execute(message[1].storeName, message[0], message[1], message[2]); // Upon messages, we execute the query
} else {
this.stack.push(message);
}
},
close : function(){
this.driver.close();
}
};
// Method used by Backbone for sync of data with data store. It was initially designed to work with "server side" APIs, This wrapper makes
// it work with the local indexedDB stuff. It uses the schema attribute provided by the object.
// The wrapper keeps an active Executuon Queue for each "schema", and executes querues agains it, based on the object type (collection or
// single model), but also the method... etc.
// Keeps track of the connections
var Databases = {};
function sync(method, object, options) {
if(method=="closeall"){
_.each(Databases,function(database){
database.close();
});
// Clean up active databases object.
Databases = {}
return;
}
var schema = object.database;
if (Databases[schema.id]) {
if(Databases[schema.id].version != _.last(schema.migrations).version){
Databases[schema.id].close();
delete Databases[schema.id];
}
}
var next = function(){
Databases[schema.id].execute([method, object, options]);
};
if (!Databases[schema.id]) {
Databases[schema.id] = new ExecutionQueue(schema,next,schema.nolog);
}else
{
next();
}
};
if(typeof exports == 'undefined'){
Backbone.ajaxSync = Backbone.sync;
Backbone.sync = sync;
}
else {
exports.sync = sync;
exports.debugLog = debugLog;
}
//window.addEventListener("unload",function(){Backbone.sync("closeall")})
})();