Dexie.js icon indicating copy to clipboard operation
Dexie.js copied to clipboard

Should I use transaction around modify?

Open bokolob opened this issue 1 year ago • 4 comments

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 });
  });
}

bokolob avatar Feb 05 '24 09:02 bokolob

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.

dfahlander avatar Feb 05 '24 09:02 dfahlander

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.

dfahlander avatar Feb 08 '24 22:02 dfahlander

Hm, would the livequery be restarted after transaction fail?

bokolob avatar Feb 09 '24 08:02 bokolob

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.

dfahlander avatar Feb 09 '24 12:02 dfahlander