Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created October 12, 2014 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/1afe3b5e98e4111c67c4 to your computer and use it in GitHub Desktop.
Save nolanlawson/1afe3b5e98e4111c67c4 to your computer and use it in GitHub Desktop.
IndexedDB test keyPath vs. unique index
<html>
<body>
<h1>IndexedDB test keyPath vs. unique index</h1>
<pre id="display"></pre>
<script src="index.js"></script>
</body>
</html>
(function () {
'use strict';
function log(str) {
document.getElementById('display').innerHTML += '\n' + str;
}
function deleteFirst(cb) {
var req = indexedDB.deleteDatabase('first');
req.onsuccess = cb;
req.onerror = cb;
}
function deleteSecond(cb) {
var req = indexedDB.deleteDatabase('first');
req.onsuccess = cb;
req.onerror = cb;
}
function testWithKeyPath(cb) {
log('\ntesting with a normal keyPath');
var req = indexedDB.open('first', 1);
req.onupgradeneeded = function(e) {
var db = e.target.result;
if (e.oldVersion < 1) {
db.createObjectStore('docs', {keyPath : 'id'})
.createIndex('someOtherId', 'someOtherId', {unique: true});
}
};
req.onsuccess = function (e) {
var db = e.target.result;
var txn = db.transaction(['docs'], 'readwrite');
var store = txn.objectStore('docs');
store.put({id: 'foo', someOtherId: 'bar'}).onsuccess = function () {
var putReq = store.put({id: 'foo', someOtherId: 'quux'});
putReq.onsuccess = function() {
log('oh hey, it let me overwrite the existing key');
};
putReq.onerror = function(e) {
log('nope, didn\'t let me overwrite the existing key: ' + JSON.stringify(e.error));
};
};
txn.oncomplete = cb;
}
}
function testWithUniqueIndex(cb) {
log('\ntesting with a unique index');
var req = indexedDB.open('first', 1);
req.onupgradeneeded = function(e) {
var db = e.target.result;
if (e.oldVersion < 1) {
db.createObjectStore('docs', {keyPath : 'id'});
}
};
req.onsuccess = function (e) {
var db = e.target.result;
var txn = db.transaction(['docs'], 'readwrite');
var store = txn.objectStore('docs');
store.put({id: 'hey', someOtherId: 'ya'}).onsuccess = function () {
var putReq = store.put({id: 'sup', someOtherId: 'ya'});
putReq.onsuccess = function() {
log('oh hey, it let me overwrite the existing key');
};
putReq.onerror = function(e) {
log('nope, didn\'t let me overwrite the existing key: ' + JSON.stringify(e.target.error));
};
};
txn.oncomplete = cb;
}
}
deleteFirst(function() {
deleteSecond(function() {
testWithKeyPath(function() {
testWithUniqueIndex(function() {
log('\ndone');
});
});
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment