Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP script need to wait for MySql trigger to complete?

Database is MySQL. I am looking to implement a trigger that updates an aggregate rating table whenever a new rating is placed. Then there are some other similar use cases where I'm looking to implement triggers.

These triggers may be updating federated tables. So my question is: whether a php script that inserts a new rating will need to wait for the trigger to complete before the php script completes?

PS: I understand triggers is not a good idea to put logic, and may be I would be better off with some messaging such as RabbitMQ.

like image 990
jeff musk Avatar asked Dec 17 '22 04:12

jeff musk


1 Answers

Triggers are synchronous; the INSERT/UPDATE/DELETE that spawned them blocks until the trigger completes executing, including any actions the trigger executes (and even any subsequent triggers spawned by those actions).

Triggers are atomic. That is, if any change executed by the trigger fails, then the trigger fails, and it also cancels the change that spawned the trigger.

Triggers also make changes in the scope of the same transaction that spawned the trigger. So changes made by the trigger can be committed/rolled back along with the changes that spawned the trigger. If triggers kept running while your PHP app finishes its transaction and exits, then there would be no way to ensure they happen in that transaction.

This applies both to BEFORE triggers and AFTER triggers. Your app blocks until all triggers are finished.

like image 167
Bill Karwin Avatar answered Mar 30 '23 00:03

Bill Karwin