Skip to content

Instantly share code, notes, and snippets.

@tomsaleeba
Created July 9, 2020 07:02
Show Gist options
  • Save tomsaleeba/266ff6e4a9a9706376f9b8514f0c3b23 to your computer and use it in GitHub Desktop.
Save tomsaleeba/266ff6e4a9a9706376f9b8514f0c3b23 to your computer and use it in GitHub Desktop.
Test if we can modify IndexedDB records (not upgrade the DB version) in one connection while another connection is open. Spoiler, we can!

To run this test, copy and paste the script into the JS console of your browser (or use Snippets in Chrome devtools).

The output is:

starting
upgrading
opened1
req1 success
req2 success
req3 success
req4 success
opened2
cursor continue
cursor continue
delete success for 2
cursor continue
cursor continue
delete success for 4
closing2
closing1
done
runTest(
'test' + Date.now(),
1,
'requests',
).then(console.log)
function runTest(dbName, dbVersion, objectStoreName) {
return new Promise((resolve, reject) => {
console.log('starting')
const connection = indexedDB.open(dbName, dbVersion)
connection.onupgradeneeded = function(event) {
console.log('upgrading')
const db = event.target.result
db.onerror = console.error
const objectStore = db.createObjectStore(objectStoreName)
}
connection.onsuccess = e => {
console.log('opened1')
const db = e.target.result
const transaction = db.transaction([objectStoreName], 'readwrite')
const objectStore = transaction.objectStore([objectStoreName])
objectStore.add({ blah: 1 }, 1).onsuccess = function() {
console.log('req1 success')
}
objectStore.add({ blah: 2 }, 2).onsuccess = function() {
console.log('req2 success')
}
objectStore.add({ blah: 3 }, 3).onsuccess = function() {
console.log('req3 success')
}
objectStore.add({ blah: 4 }, 4).onsuccess = function() {
console.log('req4 success')
modifyWhileOpen(dbName, dbVersion, objectStoreName).then(() => {
console.log('closing1')
db.close()
resolve('done')
})
}
}
})
}
function modifyWhileOpen(dbName, dbVersion, objectStoreName) {
return new Promise((resolve, reject) => {
const conn = indexedDB.open(dbName, dbVersion)
conn.onsuccess = e => {
console.log('opened2')
const db = e.target.result
const transaction = db.transaction([objectStoreName], 'readwrite')
const objectStore = transaction.objectStore([objectStoreName])
const request = objectStore.openCursor()
request.addEventListener('success', e => {
const cursor = e.target.result
if (cursor) {
const val = cursor.key
if (val % 2 === 0) {
const delReq = cursor.delete()
delReq.onsuccess = () => {
console.log('delete success for ' + val)
}
}
console.log('cursor continue')
cursor.continue()
return
}
console.log('closing2')
db.close()
return resolve()
})
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment