Skip to content

Instantly share code, notes, and snippets.

@kilbot
Last active Feb 29, 2016
Embed
What would you like to do?
Repro Safari IndexedDB autoIncrement bug
<body>
<h1>Repro Safari IndexedDB autoIncrement bug</h1>
<div id="logger"></div>
<script>
var dbname = 'time_' + Date.now() + '_';
function log(msg) {
document.getElementById("logger").innerHTML += msg + "<br>";
}
var req = indexedDB.open(dbname + "1");
req.onupgradeneeded = function (e) {
var db = e.target.result;
if (e.oldVersion === 1) {
return;
}
db.createObjectStore('store', {keyPath: 'id', autoIncrement: true}).createIndex('key', 'key', {unique: true});
};
req.onsuccess = function (e) {
var db = e.target.result;
var mergeOnKey = function(data, objectStore){
return new Promise( function (resolve, reject) {
var openIndex = objectStore.index('key');
var request = openIndex.get(data.key);
request.onsuccess = function (e) {
if(e.target.result){
data.id = e.target.result.id;
}
var request = objectStore.put(data);
request.onsuccess = function (e) {
resolve( e.target.result );
};
request.onerror = reject;
};
request.onerror = reject;
});
};
var batchMergeOnKey = function( dataArray ){
var txn = db.transaction('store', 'readwrite');
var objectStore = txn.objectStore('store');
var keys = [];
return new Promise( function(resolve, reject) {
dataArray.forEach(function(data){
mergeOnKey(data, objectStore).then( function(key) {
keys.push(key);
});
});
txn.oncomplete = function (e) {
resolve(keys);
};
});
};
batchMergeOnKey([{ key: 'a' }, { key: 'b' }])
.then( function (keys) {
log('created keys ' + keys);
return batchMergeOnKey([{ key: 'a', state: 'updated' }, { key: 'c', state: 'new' }]);
})
.then( function (keys) {
log('merged/created keys ' + keys);
if(keys.includes(3)){
log('This is expected behaviour');
} else {
log('There is a bug');
}
});
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment