Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created September 16, 2015 03:39
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/32daf56e98904562b52d to your computer and use it in GitHub Desktop.
Save nolanlawson/32daf56e98904562b52d to your computer and use it in GitHub Desktop.
Repro WebKit IndexedDB wrong key order bug
<body>
<h1> Repro WebKit wrong key order bug</h1>
<p>If you see the text <strong>There is a bug</strong>, then there's a bug.</p>
<pre id="display">
</pre>
<script>
document.addEventListener('DOMContentLoaded', function () {
var dbname = 'test-wrong-key-order';
function log(msg) {
document.getElementById("display").innerHTML += msg + "\n";
}
var loadedOnce = !!localStorage.loadedOnce;
localStorage.loadedOnce = "true";
var req = indexedDB.open(dbname + "1");
req.onupgradeneeded = function (e) {
var db = e.target.result;
if (e.oldVersion === 1) {
return;
}
db.createObjectStore('store', {keyPath: 'primaryKey'})
.createIndex('secondaryKey', 'secondaryKey');
var txn = e.currentTarget.transaction;
};
req.onsuccess = function (e) {
var db = e.target.result;
var txn = db.transaction('store', 'readwrite');
if (!loadedOnce) {
txn.objectStore('store').put({primaryKey: "a11", secondaryKey: 0});
txn.objectStore('store').put({primaryKey: "b11", secondaryKey: 0});
txn.objectStore('store').put({primaryKey: "c1", secondaryKey: 0});
txn.objectStore('store').put({primaryKey: "c2", secondaryKey: 0});
txn.objectStore('store').put({primaryKey: "c3", secondaryKey: 0});
}
txn.oncomplete = function () {
var txn = db.transaction('store', 'readonly');
var req = txn.objectStore('store').index('secondaryKey').openKeyCursor();
var primaryKeys = [];
var secondaryKeys = [];
req.onsuccess = function (e) {
var cursor = e.target.result;
if (!cursor) {
return;
}
primaryKeys.push(cursor.primaryKey);
secondaryKeys.push(cursor.key);
cursor.continue();
};
txn.oncomplete = function () {
if (!loadedOnce) {
window.location.reload()
} else {
log('primaryKeys:\n' + JSON.stringify(primaryKeys, null, ' '));
log('')
log('secondaryKeys:\n' + JSON.stringify(secondaryKeys));
var sorted = primaryKeys.slice().sort()
function checkBug() {
for (var i = 0; i < sorted.length; i++) {
if (sorted[i] !== primaryKeys[i]) {
return true;
}
return false;
}
}
if (checkBug()) {
log('\nThere is a bug.');
log('The sorted list and the actual list are not the same.');
} else {
log('\nThe bug was not reproduced.');
log('The sorted list and the actual list are the same.');
}
}
};
};
};
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment