Debian Codegraph @

dojox/store/db/IndexedDB.js

raw symbols SCIP
1 define(['dojo/_base/declare', 'dojo/_base/lang', 'dojo/Deferred', 'dojo/when', 'dojo/promise/all', 'dojo/store/util/SimpleQueryEngine', 'dojo/store/util/QueryResults'],
2 function(declare, lang, Deferred, when, all, SimpleQueryEngine, QueryResults){
3
4 function makePromise(request) {
5 var deferred = new Deferred();
6 request.onsuccess = function(event) {
7 deferred.resolve(event.target.result);
8 };
9 request.onerror = function() {
10 request.error.message = request.webkitErrorMessage;
11 deferred.reject(request.error);
12 };
13 return deferred.promise;
14 }
15
16 // we keep a queue of cursors, so we can prioritize the traversal of result sets
17 var cursorQueue = [];
18 var maxConcurrent = 1;
19 var cursorsRunning = 0;
20 var wildcardRe = /(.*)\*$/;
21 function queueCursor(cursor, priority, retry) {
22 // process the cursor queue, possibly submitting a cursor for continuation
23 if (cursorsRunning || cursorQueue.length) {
24 // actively processing
25 if (cursor) {
26 // add to queue
27 cursorQueue.push({cursor: cursor, priority: priority, retry: retry});
28 // keep the queue in priority order
29 cursorQueue.sort(function(a, b) {
30 return a.priority > b.priority ? 1 : -1;
31 });
32 }
33 if (cursorsRunning >= maxConcurrent) {
34 return;
35 }
36 var cursorObject = cursorQueue.pop();
37 cursor = cursorObject && cursorObject.cursor;
38 }//else nothing in the queue, just shortcut directly to continuing the cursor
39 if (cursor) {
40 try {
41 // submit the continuation of the highest priority cursor
42 cursor['continue']();
43 cursorsRunning++;
44 } catch(e) {
45 if ((e.name === 'TransactionInactiveError' || e.name === 0) && cursorObject) { // == 0 is IndexedDBShim
46 // if the cursor has been interrupted we usually need to create a new transaction,
47 // handing control back to the query/filter function to open the cursor again
48 cursorObject.retry();
49 } else {
50 throw e;
51 }
52 }
53 }
54 }
55 function yes(){
56 return true;
57 }
58
59 // a query results API based on a source with a filter method that is expected to be called only once. All iterative methods are
60 // implemented in terms of forEach that will call the filter only once and subsequently use the promised results.
61 // will also copy the `total` property as well.
62 function queryFromFilter(source) {
63 var promisedResults, started, callbacks = [];
64 // this is the main iterative function that will ensure we will only do a low level iteratation of the result set once.
65 function forEach(callback, thisObj) {
66 if (started) {
67 // we have already iterated the query results, just hook into the existing promised results
68 callback && promisedResults.then(function(results) {
69 results.forEach(callback, thisObj);
70 });
71 } else {
72 // first call, start the filter iterator, getting the results as a promise, so we can connect to that each subsequent time
73 callback && callbacks.push(callback);
74 if(!promisedResults){
75 promisedResults = source.filter(function(value) {
76 started = true;
77 for(var i = 0, l = callbacks.length; i < l; i++){
78 callbacks[i].call(thisObj, value);
79 }
80 return true;
81 });
82 }
83 }
84 return promisedResults;
85 }
86
87 return {
88 total: source.total,
89 filter: function(callback, thisObj) {
90 var done;
91 return forEach(function(value) {
92 if (!done) {
93 done = !callback.call(thisObj, value);
94 }
95 });
96 },
97 forEach: forEach,
98 map: function(callback, thisObj) {
99 var mapped = [];
100 return forEach(function(value) {
101 mapped.push(callback.call(thisObj, value));
102 }).then(function() {
103 return mapped;
104 });
105 },
106 then: function(callback, errback) {
107 return forEach().then(callback, errback);
108 }
109 };
110 }
111
112 var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
113 return declare(null, {
114 // summary:
115 // This is a basic store for IndexedDB. It implements dojo/store/api/Store.
116
117 constructor: function(options) {
118 // summary:
119 // This is a basic store for IndexedDB.
120 // options:
121 // This provides any configuration information that will be mixed into the store
122
123 declare.safeMixin(this, options);
124 var store = this;
125 var dbConfig = this.dbConfig;
126 this.indices = dbConfig.stores[this.storeName];
127 this.cachedCount = {};
128 for (var index in store.indices) {
129 var value = store.indices[index];
130 if (typeof value === 'number') {
131 store.indices[index] = {
132 preference: value
133 };
134 }
135 }
136 this.db = this.db || dbConfig.db;
137
138 if (!this.db) {
139 var openRequest = dbConfig.openRequest;
140 if (!openRequest) {
141 openRequest = dbConfig.openRequest = window.indexedDB.open(dbConfig.name || 'dojo-db',
142 parseInt(dbConfig.version, 10));
143 openRequest.onupgradeneeded = function() {
144 var db = store.db = openRequest.result;
145 for (var storeName in dbConfig.stores) {
146 var storeConfig = dbConfig.stores[storeName];
147 if (!db.objectStoreNames.contains(storeName)) {
148 var idProperty = storeConfig.idProperty || 'id';
149 var idbStore = db.createObjectStore(storeName, {
150 keyPath: idProperty,
151 autoIncrement: storeConfig[idProperty] &&
152 storeConfig[idProperty].autoIncrement || false
153 });
154 } else {
155 idbStore = openRequest.transaction.objectStore(storeName);
156 }
157 for (var index in storeConfig) {
158 if (!idbStore.indexNames.contains(index) && index !== 'autoIncrement' &&
159 storeConfig[index].indexed !== false) {
160 idbStore.createIndex(index, index, storeConfig[index]);
161 }
162 }
163 }
164 };
165 dbConfig.available = makePromise(openRequest);
166 }
167 this.available = dbConfig.available.then(function(db){
168 return store.db = db;
169 });
170 }
171 },
172
173 // idProperty: String
174 // Indicates the property to use as the identity property. The values of this
175 // property should be unique.
176 idProperty: 'id',
177
178 storeName: '',
179
180 // indices:
181 // a hash of the preference of indices, indices that are likely to have very
182 // unique values should have the highest numbers
183 // as a reference, sorting is always set at 1, so properties that are higher than
184 // one will trigger filtering with index and then sort the whole set.
185 // we recommend setting boolean values at 0.1.
186 indices: {
187 /*
188 property: {
189 preference: 1,
190 multiEntry: true
191 }
192 */
193 },
194
195 queryEngine: SimpleQueryEngine,
196
197 transaction: function() {
198 var store = this;
199 this._currentTransaction = null;// get rid of the last transaction
200 return {
201 abort: function() {
202 store._currentTransaction.abort();
203 },
204 commit: function() {
205 // noop, idb does auto-commits
206 store._currentTransaction = null;// get rid of the last transaction
207 }
208 }
209 },
210
211 _getTransaction: function() {
212 if (!this._currentTransaction) {
213 this._currentTransaction = this.db.transaction([this.storeName], 'readwrite');
214 var store = this;
215 this._currentTransaction.oncomplete = function() {
216 // null it out so we will use a new one next time
217 store._currentTransaction = null;
218 };
219 this._currentTransaction.onerror = function(error) {
220 console.error(error);
221 };
222 }
223 return this._currentTransaction;
224 },
225
226 _callOnStore: function(method, args, index, returnRequest) {
227 // calls a method on the IndexedDB store
228 var store = this;
229 return when(this.available, function callOnStore() {
230 var currentTransaction = store._currentTransaction;
231 if (currentTransaction) {
232 var allowRetry = true;
233 } else {
234 currentTransaction = store._getTransaction();
235 }
236 var request, idbStore;
237 if (allowRetry) {
238 try {
239 idbStore = currentTransaction.objectStore(store.storeName);
240 if (index) {
241 idbStore = idbStore.index(index);
242 }
243 request = idbStore[method].apply(idbStore, args);
244 } catch(e) {
245 if (e.name === 'TransactionInactiveError' || e.name === 'InvalidStateError') {
246 store._currentTransaction = null;
247 //retry
248 return callOnStore();
249 } else {
250 throw e;
251 }
252 }
253 } else {
254 idbStore = currentTransaction.objectStore(store.storeName);
255 if (index) {
256 idbStore = idbStore.index(index);
257 }
258 request = idbStore[method].apply(idbStore, args);
259 }
260 return returnRequest ? request : makePromise(request);
261 });
262 },
263
264 get: function(id) {
265 // summary:
266 // Retrieves an object by its identity.
267 // id: Number
268 // The identity to use to lookup the object
269 // options: Object?
270 // returns: dojo//Deferred
271
272 return this._callOnStore('get',[id]);
273 },
274
275 getIdentity: function(object) {
276 // summary:
277 // Returns an object's identity
278 // object: Object
279 // The object to get the identity from
280 // returns: Number
281
282 return object[this.idProperty];
283 },
284
285 put: function(object, options) {
286 // summary:
287 // Stores an object.
288 // object: Object
289 // The object to store.
290 // options: __PutDirectives?
291 // Additional metadata for storing the data. Includes an "id"
292 // property if a specific id is to be used.
293 // returns: dojo/Deferred
294
295 options = options || {};
296 this.cachedCount = {}; // clear the count cache
297 return this._callOnStore(options.overwrite === false ? 'add' : 'put',[object]);
298 },
299
300 add: function(object, options) {
301 // summary:
302 // Adds an object.
303 // object: Object
304 // The object to store.
305 // options: __PutDirectives?
306 // Additional metadata for storing the data. Includes an "id"
307 // property if a specific id is to be used.
308 // returns: dojo/Deferred
309
310 options = options || {};
311 options.overwrite = false;
312 return this.put(object, options);
313 },
314
315 remove: function(id) {
316 // summary:
317 // Deletes an object by its identity.
318 // id: Number
319 // The identity to use to delete the object
320 // returns: dojo/Deferred
321
322 this.cachedCount = {}; // clear the count cache
323 return this._callOnStore('delete', [id]);
324 },
325
326 query: function(query, options) {
327 // summary:
328 // Queries the store for objects.
329 // query: Object
330 // The query to use for retrieving objects from the store.
331 // options: __QueryOptions?
332 // The optional arguments to apply to the resultset.
333 // returns: dojo/store/api/Store.QueryResults
334 // The results of the query, extended with iterative methods.
335
336 options = options || {};
337 var start = options.start || 0;
338 var count = options.count || Infinity;
339 var sortOption = options.sort;
340 var store = this;
341
342 // an array, do a union
343 if (query.forEach) {
344 var sortOptions = {sort: sortOption};
345 var sorter = this.queryEngine({}, sortOptions);
346 var totals = [];
347 var collectedCount = 0;
348 var inCount = 0;
349 return queryFromFilter({
350 total: {
351 then: function() {
352 // do it lazily again
353 return all(totals).then(function(totals) {
354 return totals.reduce(function(a, b) {
355 return a + b;
356 }) * collectedCount / (inCount || 1);
357 }).then.apply(this, arguments);
358 }
359 },
360 filter: function(callback, thisObj) {
361 var index = 0;
362 var queues = [];
363 var done;
364 var collected = {};
365 var results = [];
366 // wait for all the union segments to complete
367 return all(query.map(function(part, i) {
368 var queue = queues[i] = [];
369 function addToQueue(object) {
370 // to the queue that is kept for each individual query for merge sorting
371 queue.push(object);
372 var nextInQueues = []; // so we can index of the selected choice
373 var toMerge = [];
374 while(queues.every(function(queue) {
375 if (queue.length > 0) {
376 var next = queue[0];
377 if (next) {
378 toMerge.push(next);
379 }
380 return nextInQueues.push(next);
381 }
382 })){
383 if (index >= start + count || toMerge.length === 0) {
384 done = true;
385 return; // exit filter loop
386 }
387 var nextSelected = sorter(toMerge)[0];
388 // shift it off the selected queue
389 queues[nextInQueues.indexOf(nextSelected)].shift();
390 if (index++ >= start) {
391 results.push(nextSelected);
392 if (!callback.call(thisObj, nextSelected)) {
393 done = true;
394 return;
395 }
396 }
397 nextInQueues = [];// reset
398 toMerge = [];
399 }
400 return true;
401
402 }
403 var queryResults = store.query(part, sortOptions);
404 totals[i] = queryResults.total;
405 return queryResults.filter(function(object) {
406 if (done) {
407 return;
408 }
409 var id = store.getIdentity(object);
410 inCount++;
411 if (id in collected) {
412 return true;
413 }
414 collectedCount++;
415 collected[id] = true;
416 return addToQueue(object);
417 }).then(function(results) {
418 // null signifies the end of this particular query result
419 addToQueue(null);
420 return results;
421 });
422 })).then(function() {
423 return results;
424 });
425 }
426 });
427 }
428
429 var keyRange;
430 var alreadySearchedProperty;
431 var queryId = JSON.stringify(query) + '-' + JSON.stringify(options.sort);
432 var advance;
433 var bestIndex, bestIndexQuality = 0;
434 var indexTries = 0;
435 var filterValue;
436
437 function tryIndex(indexName, quality, factor) {
438 indexTries++;
439 var indexDefinition = store.indices[indexName];
440 if (indexDefinition && indexDefinition.indexed !== false) {
441 quality = quality || indexDefinition.preference * (factor || 1) || 0.001;
442 if (quality > bestIndexQuality) {
443 bestIndexQuality = quality;
444 bestIndex = indexName;
445 return true;
446 }
447 }
448 indexTries++;
449 }
450
451 for (var i in query) {
452 // test all the filters as possible indices to drive the query
453 filterValue = query[i];
454 var range = false;
455 var wildcard, newFilterValue = null;
456
457 if (typeof filterValue === 'boolean') {
458 // can't use booleans as filter keys
459 continue;
460 }
461
462 if (filterValue) {
463 if (filterValue.from || filterValue.to) {
464 range = true;
465 (function(from, to) {
466 // convert a to/from object to a testable object with a keyrange
467 newFilterValue = {
468 test: function(value) {
469 return !from || from <= value &&
470 (!to || to >= value);
471 },
472 keyRange: from ?
473 to ?
474 IDBKeyRange.bound(from, to, filterValue.excludeFrom, filterValue.excludeTo) :
475 IDBKeyRange.lowerBound(from, filterValue.excludeFrom) :
476 IDBKeyRange.upperBound(to, filterValue.excludeTo)
477 };
478 })(filterValue.from, filterValue.to);
479 } else if (typeof filterValue === 'object' && filterValue.contains) {
480 // contains is for matching any value in a given array to any value in the target indices array
481 // this expects a multiEntry: true index
482 (function(contains) {
483 var keyRange, first = contains[0];
484
485 var wildcard = first && first.match && first.match(wildcardRe);
486 if (wildcard) {
487 first = wildcard[1];
488 keyRange = IDBKeyRange.bound(first, first + '~');
489 } else {
490 keyRange = IDBKeyRange.only(first);
491 }
492 newFilterValue = {
493 test: function(value) {
494 return contains.every(function(item) {
495 var wildcard = item && item.match && item.match(wildcardRe);
496 if (wildcard) {
497 item = wildcard[1];
498 return value && value.some(function(part) {
499 return part.slice(0, item.length) === item;
500 });
501 }
502 return value && value.indexOf(item) > -1;
503 } );
504 },
505 keyRange: keyRange
506 };
507 })(filterValue.contains);
508 } else if((wildcard = filterValue.match && filterValue.match(wildcardRe))) {
509 // wildcard matching
510 var matchStart = wildcard[1];
511 newFilterValue = new RegExp('^' + matchStart);
512 newFilterValue.keyRange = IDBKeyRange.bound(matchStart, matchStart + '~');
513 }
514 }
515 if (newFilterValue) {
516 query[i] = newFilterValue;
517 }
518 tryIndex(i, null, range ? 0.1 : 1);
519 }
520 var descending;
521 if (sortOption) {
522 // this isn't necessarily the best heuristic to determine the best index
523 var mainSort = sortOption[0];
524 if (mainSort.attribute === bestIndex || tryIndex(mainSort.attribute, 1)) {
525 descending = mainSort.descending;
526 } else {
527 // we need to sort afterwards now
528 var postSorting = true;
529 // we have to retrieve everything in this case
530 start = 0;
531 count = Infinity;
532 }
533 }
534 var cursorRequestArgs;
535 if (bestIndex) {
536 if (bestIndex in query) {
537 // we are filtering
538 filterValue = query[bestIndex];
539 if (filterValue && (filterValue.keyRange)) {
540 keyRange = filterValue.keyRange;
541 } else {
542 keyRange = IDBKeyRange.only(filterValue);
543 }
544 alreadySearchedProperty = bestIndex;
545 } else {
546 keyRange = null;
547 }
548 cursorRequestArgs = [keyRange, descending ? 'prev' : 'next'];
549 } else {
550 // no index, no arguments required
551 cursorRequestArgs = [];
552 }
553 // console.log("using index", bestIndex);
554 var cachedPosition = store.cachedPosition;
555 if (cachedPosition && cachedPosition.queryId === queryId &&
556 cachedPosition.offset < start && indexTries > 1) {
557 advance = cachedPosition.preFilterOffset + 1;
558 // make a new copy, so we don't have concurrency issues
559 store.cachedPosition = cachedPosition = lang.mixin({}, cachedPosition);
560 } else {
561 // cache of the position, tracking our traversal progress
562 cachedPosition = store.cachedPosition = {
563 offset: -1,
564 preFilterOffset: -1,
565 queryId: queryId
566 };
567 if (indexTries < 2) {
568 // can skip to advance
569 cachedPosition.offset = cachedPosition.preFilterOffset = (advance = start) - 1;
570 }
571 }
572 var filter = this.queryEngine(query);
573 // this is adjusted so we can compute the total more accurately
574 var filteredResults = {
575 total: {
576 then: function(callback) {
577 // make this a lazy promise, only executing if we need to
578 var cachedCount = store.cachedCount[queryId];
579 if (cachedCount){
580 return callback(adjustTotal(cachedCount));
581 } else {
582 var countPromise = (keyRange ? store._callOnStore('count', [keyRange], bestIndex) : store._callOnStore('count'));
583 return (this.then = countPromise.then(adjustTotal)).then.apply(this, arguments);
584 }
585 function adjustTotal(total) {
586 // we estimate the total count base on the matching rate
587 store.cachedCount[queryId] = total;
588 return Math.round((cachedPosition.offset + 1.01) / (cachedPosition.preFilterOffset + 1.01) * total);
589 }
590 }
591 },
592 filter: function(callback, thisObj) {
593 // this is main implementation of the the query results traversal, forEach and map use this method
594 var deferred = new Deferred();
595 var all = [];
596 function openCursor() {
597 // get the cursor
598 when(store._callOnStore('openCursor', cursorRequestArgs, bestIndex, true), function(cursorRequest) {
599 // this will be called for each iteration in the traversal
600 cursorsRunning++;
601 cursorRequest.onsuccess = function(event) {
602 cursorsRunning--;
603 var cursor = event.target.result;
604 if (cursor) {
605 if (advance) {
606 // we can advance through and wait for the completion
607 cursor.advance(advance);
608 cursorsRunning++;
609 advance = false;
610 return;
611 }
612 cachedPosition.preFilterOffset++;
613 try {
614 var item = cursor.value;
615 if (options.join) {
616 item = options.join(item);
617 }
618 return when(item, function(item) {
619 if (filter.matches(item)) {
620 cachedPosition.offset++;
621 if (cachedPosition.offset >= start) { // make sure we are after the start
622 all.push(item);
623 if (!callback.call(thisObj, item) || cachedPosition.offset >= start + count - 1) {
624 // finished
625 cursorRequest.lastCursor = cursor;
626 deferred.resolve(all);
627 queueCursor();
628 return;
629 }
630 }
631 }
632 // submit our cursor to the priority queue for continuation, now or when our turn comes up
633 return queueCursor(cursor, options.priority, function() {
634 // retry function, that we provide to the queue to use if the cursor can't be continued due to interruption
635 // if called, open the cursor again, and continue from our current position
636 advance = cachedPosition.preFilterOffset;
637 openCursor();
638 });
639 });
640 } catch(e) {
641 deferred.reject(e);
642 }
643 } else {
644 deferred.resolve(all);
645 }
646 // let any other cursors start executing now
647 queueCursor();
648 };
649 cursorRequest.onerror = function(error) {
650 cursorsRunning--;
651 deferred.reject(error);
652 queueCursor();
653 };
654 });
655 }
656 openCursor();
657 return deferred.promise;
658 }
659 };
660
661 if (postSorting) {
662 // we are using the index to do filtering, so we are going to have to sort the entire list
663 var sorter = this.queryEngine({}, options);
664 var sortedResults = lang.delegate(filteredResults.filter(yes).then(function(results) {
665 return sorter(results);
666 }));
667 sortedResults.total = filteredResults.total;
668 return new QueryResults(sortedResults);
669 }
670 return options.rawResults ? filteredResults : queryFromFilter(filteredResults);
671 }
672 });
673
674 });