Dexie.js
Dexie.js copied to clipboard
Should I use transaction around modify?
Hello, there is my db schema
db.version(1).stores({
planner_documents: `id&, room_id, idempotency_key&`,
});
I want to modify one of documents, maybe in multiple browser tabs, how to make it safe?
Do I need explicit transaction like
async function save_serialized_doc(doc_id, content, position) {
return await db.transaction("rw", db.planner_documents, async () => {
await db.planner_documents
.where({ id: doc_id })
.and((e) => !e.last_saved_id || e.last_saved_id < position)
.modify({ saved_document: content, last_saved_id: position });
});
}
If you only do a single expression, like your sample shows, explicit transaction is not needed - the modify operation will perform an implicit transaction around the whole querying and modification parts anyway.
Note: This regards to the atomicity of it (which I suppose was the doubt in your case). If isolation is considered it's another story and there would be a difference, at least in Dexie 4 with the default optimistic cache enabled.
If you would have an ongoing liveQuery, it may react to the change before the implicit transaction commits, which could theoretically manifest in a temporary successful change that later on disappears if the implicit transaction finally fails. Should this be a consideration and you absolutely need full isolation also against liveQueries observing the data, an explicit transaction will make a difference and provide full isolation and only wake up live queries after the transaction commits.
Hm, would the livequery be restarted after transaction fail?
Hm, would the livequery be restarted after transaction fail?
Yes, if the livequery was optimistically notified about the operation but and then finally the implicit transaction fails for some reason, the livequery will be retriggered with data according to reverted operation.