How can I use savepoints with Ecto?

I’m looking to use savepoints to rollback within a larger transaction in case of an error, but didn’t see a way to start a “transaction” in Ecto in savepoint mode, as supported by the underlying postgrex (https://github.com/elixir-ecto/postgrex/blob/7ed8c3207a56a1f1ba886f2b1a935719999d4dd9/lib/postgrex.ex#L424).

Is there any way to do so using Ecto or would I need to work with Postgrex directly and manage connections separately?

Digging through the source, it appears that opts is threaded all the way from Ecto.Repo.transaction down to the underlying DB adapter, so passing savepoint: true to the public interface should do the right thing.

HOWEVER

The documentation for DBConnection.rollback specifically mention bubbling up to nested transactions; I suspect the code may be making assumptions that will make rolling back to a previous savepoint (without rolling back the enclosing transaction) tricky.

4 Likes