On Sunday, March 6, 2016 at 7:14:59 PM UTC-8, Janko Marohnić wrote:
>
> Hello,
>
> I'm trying to figure out concurrent database transactions, because I
> realized that I don't fully understand transactions. I wanted to find out
> if there are any negative implications of a transaction being open for a
> long time (do you maybe know if there are?). So I created the following
> snippet:
>
> require "sequel"
> require "logger"
>
> DB = Sequel.postgres("transactions")
> DB.create_table!(:users) do
> primary_key :id
> String :age
> end
>
> id = DB[:users].insert({age: 24})
> DB.logger = Logger.new(STDOUT)
>
> pid1 = fork {
> DB.transaction do
> sleep 2
> end
> }
>
> sleep 1
>
> pid2 = fork {
> DB.transaction do
> DB[:users].update(age: 25)
> end
> }
>
> Process.waitpid pid2
> puts DB[:users].first
> Process.waitpid pid1
>
> What I wanted to do is that the transaction from the second subprocess is
> "nested" inside the first (that it happens between BEGIN...COMMIT of the
> first one), because I wanted to produce some abnormal behaviour (not
> important). What I would expect, since Postgres should support concurrent
> transactions, that everything goes fine. But it goes boom (gist
> <https://gist.github.com/janko-m/94ab65e246aa483021b0>). Why do I get the
> warning that there is already a transaction in progress, if Postgres
> supports concurrent transactions?
>
> Sorry if this is not Sequel-related, but I really want to figure out
> what's going on :)
>
This isn't a transaction issue, you aren't disconnecting before fork, so
you are sharing connection sockets in child processes. Call DB.disconnect
before forking.
To answer your earlier question, you should try to keep transactions open
for as short a time as possible. Transactions that do things take out
locks, so leaving them open for periods of time can can other queries to
stop executing. In your particular example, this doesn't happen, because
the transaction that sleeps does nothing, but in real world situations it
can cause problems.
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.