Error while 2 sequential writes in 1 transaction
Closed this issue · 3 comments
I have following function
(defn create-user! [ email password db]
(c/with-write-transaction [db tx]
(let [encrypted-password (p/encrypt password)
next-user-id (inc (c/get-at tx [:counters :user-id]))
user {:email email
:password-hash encrypted-password}]
(c/merge-at tx [:users] {next-user-id user})
(c/assoc-at tx [:counters :user-id] next-user-id))))
As you see I have one read and two writes within one transaction. But only the last write occurs. I expect that both writes should occur.
Transactions are like (and implemented by) standard maps which contain uncommitted database modifications. When you change something a new transaction is returned, but the old transaction is unmodified. To make multiple changes to a transaction, you need to thread the transaction through multiple transformations, like so:
(-> tx
(c/merge-at [:users] {next-user-id user})
(c/assoc-at [:counters :user-id] next-user-id)))))
This is beautful solution which is totally not obvious :-) Please document that somehow
Thank you for the feedback. I added an FAQ section to the README with examples based on our discussion here and in #9. Let me know if you think I should include anything else.