by Retr0id · 4mo ago · 0 comments
Why not? Why should I be allowed to db.commit() midway through a transaction?
This ability to compose transactions is their main benefit over other kinds of concurrency control!
BEGIN TRAN
BEGIN TRAN
COMMIT TRAN
ROLLBACK TRANWhich works entirely fine in most cases. You're at greater risk of phantom reads and general "stuff that can occur while you hold open a transaction", but if you're not handling that correctly then you're not handling that correctly. It's only a matter of volume, not existence.
... with a clear exception for cases where you do need to truly end a transaction, like if you're relying on some other thread to do something on a different transaction that needs to see your changes, or when you risk a deadlock somewhere due to not releasing your lock. Those are both a risky patterns for a lot of reasons though, and worth avoiding at design-time if at all possible.
Combining that with spaghetti that does transaction magic at random places guarantees the sort of pain that makes cursing the entire human race seem like a pretty mild response.
Higher-level abstractions may prevent some footguns; e.g., an “atomic” decorator/annotation commits automatically after a successful call. They are somewhat easier to understand but come with their own limitations and caveats.
The problem isn't being able to commit. The problem is being able to commit and then not notice that you're no longer in the transaction. You could easily have `begin_transaction` return a `Transaction` object, having operations in the transaction happen on the object, and calling `commit` on it makes it throw an error if you try to use it again after. Maybe the reason that working with databases is "ridiculously hard" because the API isn't well-designed...
I do not know why that mentality exists in the industry, but I see it all the time... for the past 35 years.
I think the option should be there, but it needs to be used responsibly.