About z_db transactions

8 views
Skip to first unread message

Alvaro Pagliari

unread,
Sep 14, 2021, 2:10:29 PM9/14/21
to Zotonic users
Hello,

I would like to know what is the correct way to use z_db:transaction(F, Context)...
I was creating a function
F = fun(Ctx) ->
       try
           %Here I would use z_db:q to execute queries...
           do_something_with_db(Ctx),
           ok
       catch
           X -> {rollback, X}
       end
     end,
z_db:transaction(F, Ctx).

But I noticed that even returning {rollback, error} instead of ok doesn't rollback the transaction. Is there a different/correct way to use this function?

This is on zotonic 0.62.0.

Cheers,

--
Álvaro Pagliari

Marc Worrell

unread,
Sep 15, 2021, 3:01:40 AM9/15/21
to 'Marc Worrell' via Zotonic users
Hi Alvaro,

The transaction function performs a rollback if:

 - Fun returns {rollback, …}
 - Fun throws an exception
 - The final COMMIT errors

And of course if the whole process is killed during the transaction.

In your case, are you sure you are passing the correct Context?

Normally I use:


F = fun(Ctx) -> …. (do something with Ctx) end,
z_db:transaction(F, Context).

Note that I pass Context to the transaction function, and inside the F only Ctx is used.

Cheers,

Marc



--

---
You received this message because you are subscribed to the Google Groups "Zotonic users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to zotonic-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/zotonic-users/ff39c3e2-b96f-4606-865f-3a03fd368ebfn%40googlegroups.com.

Alvaro Pagliari

unread,
Sep 15, 2021, 2:39:54 PM9/15/21
to Zotonic users
Hello,

I was talking with a friend about Postgres and he told me that postgres doesn't like long-running transactions. So, probably, the database is closing the transaction and starting a new one by itself. 
It seems postgres added an option to enable long-running transactions from version 9.6, but I need to research more to be sure about it.
Thanks!

--
Álvaro Gianni Pagliari
alvaropag [at] gmail [dot] com


Reply all
Reply to author
Forward
0 new messages