Global database transactions per request?


#1

Hi,

I’d like to use transactions during every request I handle and hence I’d like to create a global transaction around middleware phase and either commit or rollback it after the controller’s code was executed.

What would be the best way to accomplish such a behaviour?


#2

You’re probably better off handling the transactions in your controller rather than trying to automatically apply a global solution. Reason being, while you could initiate a transaction in some upstream middleware handler, you’d still have to manually trigger commit or rollback within your controller depending on the circumstance, so you’re not really saving yourself any effort, and you’re preventing yourself being able to make use of a transaction callback which will automatically take care of your commit/rollback.

So yeah, you could have some middleware that starts a transaction, but I don’t think you can finish a transaction with middleware. Also, in the event something is called that caused that transaction to be opened, but then it never gets closed for whatever reason, you’d have excess DB connections laying around that will eventually degrade performance and/or cause issues.

I don’t think this is something you really want to pursue, even if you could get it to work – which is likely to be very challenging if not impossible.


#3

I agree with @willvincent and you also lack global execution context for example; How would you use the transaction inside a hook?