epgsql / pgapp

Erlang Postgres application that uses Poolboy and deals with the database being unavailable
MIT License
66 stars 43 forks source link

`with_transaction` with explicitly specified pool names #24

Open lukyanov opened 7 years ago

lukyanov commented 7 years ago

pgapp assumes that pgapp:squery and pgapp:equery in the callback function in with_transaction must not contain PoolName if you want those queries to be executed inside the transaction. While this is appropriate in most cases, you may end up with unexpected behaviour when using multiple pool names in your app.

In these changes I aim for two goals:

  1. You should be able to specify pool name inside the callback of with_transaction. The behaviour should be that if the pool name in squery or equery is not specified or equal to the one with_transaction was called with, it is considered as queries within the transaction. If the pool name is different, then those queries are working with another pool and are not within the transaction.

    Example:

    pgapp:with_transaction(pool1, fun() ->
                                 pgapp:squery("update ..."),
                                 pgapp:squery(pool1, "update ..."),
                                 pgapp:squery(pool1, "delete from ..."),
                                 pgapp:squery(pool2, "update ...")
                           end).

    The last query (to pool2) is outside the transaction, but an error in the query still affects the transaction in pool1.

  2. If nested calls of with_transaction with the same pool name take place, they should be ignored as postgres does not support nested transactions anyway.

    Example:

    doing_stuff1() ->
       pgapp:with_transaction(pool1, fun() ->
                                    pgapp:squery("update ..."),
                                    doing_stuff2()
                               end).
    
    doing_stuff2() ->
       pgapp:with_transaction(pool1, fun() ->
                                    pgapp:squery("update ..."),
                                    pgapp:squery("update ..."),
                              end).

    While doing_stuff2 is a standalone function making queries in its own transaction, when being called in doing_stuff1 all the queries of both functions become a single transaction.

lukyanov commented 7 years ago

An alternative for https://github.com/epgsql/pgapp/pull/23