Search code examples
rubytransactionssequel

Using after_commit transaction hook in Ruby's Sequel


I'm making a series of updates to my Postgres database. Halfway through these updates I need to run a chunk of code which also modifies the database, but must not be inside a transaction.

I've discovered the DB.after_commit transaction hook, which seems to be perfect, except that it doesn't behave how I would expect:

acc = []
acc << ["before", DB.in_transaction?]
DB.transaction do
    acc << ["inside", DB.in_transaction?]
    SomeModel.create(value: "foo")
    DB.after_commit {
        acc << ["after_commit", DB.in_transaction?]
    }
end
acc << ["after", DB.in_transaction?]

I would expect acc to be [["before",false],["inside",true],["after_commit",false],["after",false]], but I am seeing [["before",false],["inside",true],["after_commit",true],["after",false]]

Is there a way to prevent the callback from being run inside a transaction?


Solution

  • Database#in_transaction? is apparently not accurate inside an after_commit block. But after_commit is definitely being called after the COMMIT happens, not before.