w3c / IndexedDB

Indexed Database API
https://w3c.github.io/IndexedDB/
Other
240 stars 62 forks source link

Add a new event `onbeforecommit` on the interface IDBTransaction #314

Open Jack-Works opened 4 years ago

Jack-Works commented 4 years ago

By adding a onbeforecommit event, developers can suppress the bad transaction that make the db in an inconsistent state to be committed.

e.g.

transaction.onbeforecommit = (event) => {
   // when the transaction enter the `onbeforecommit` event, it becomes readonly.
   // it should be enough for consistency check
   if (dbIsConsistent(transaction)) { event.commit() }
   else { event.abort() } // db is inconsistent if we commit this transaction
}
inexorabletash commented 4 years ago

Can you give examples of the problems you are trying to address with this idea?

Where have you seen the lack of this functionality be a problem?

inexorabletash commented 4 years ago

Also, would the discussion in #34 which allow for explicit control over transaction lifetime handle this?

Jack-Works commented 4 years ago

Here is my usage:

(I'm using the library idb to wrap raw indexeddb as Promise version)

const t = getTransaction('objectStore', 'readwrite')
await doDangerousAction1(t)
await doDangerousAction2(t)

I need a way to do a data consistency check before the transaction end. If the check failed, I want to drop the transaction to prevent my db goes into a inconsistent state.

Currently I use this way to do the job:

async function consistentDBWriteAccess(action: (t: TransactionType) => Promise<void>) {
    const t = (await db()).transaction(['objectStore'], 'readwrite')
    await action(t)
    await assertDBConsistency(t)
}
Jack-Works commented 4 years ago

It will be nicer to append the check like this:

function doDangerousAction1(t) {
   // ....
   t.addEventListener('beforecommit', e => assertDBConsistency(e, t))
}

Therefore I can enforce a consistency check before the transaction commit then abort the transaction if it goes into a invalid state.

Jack-Works commented 4 years ago

It will also be nice to have a diff for what does this transaction changed to complete the check