bitcrowd/carbonite

Transaction "reentrancy"

Closed this issue · 3 comments

Is the following use case supported? I can not tell for sure from the documentation. Consider the case where multiple functions call Carbonite.Transaction.changeset(). They are called during a single Ecto transaction in different orders depending on the workflow. All changes should be associated with the same carbonite transaction row. I'm guessing that a carbonite transaction id added to the changeset, so the question is whether Carbonite.Transaction.changeset() looks for it, thus creating only a single transaction row no matter how many times it is called. Is that what happens? That would be fantastic but then I suppose another problem arises where one Ecto transaction involves multiple changesets. Perhaps Carbonite puts the transaction id in, say, the process dictionary?

Hey @terrisgit,

when you use insert_transaction to insert your carbonite transctions multiple times inside the same database transaction, then subsequent calls will be ignored (see this section in the docs for details).

If you build your changeset manually like you suggested, you have to specify on_conflict yourself (at least on the subsequent calls), since otherwise you will run into a uniqueness constraint with the database.

You can check the code for insert_transaction on how to do this, in case you can't use insert_transaction instead for some reason.

I hope that answers your question.
Cheers Andi

It's my understanding that insert_transaction only works with Ecto.Multi. Is that not the case?

There is two versions:

One for multis:
https://hexdocs.pm/carbonite/Carbonite.Multi.html#insert_transaction/3

One without multis:
https://hexdocs.pm/carbonite/Carbonite.html#insert_transaction/3

Also for completeness there is insert_migration_transaction which comes in handy if you have to touch data within a database migration:
https://hexdocs.pm/carbonite/Carbonite.Migrations.html#insert_migration_transaction/2