I have a table (table1
) and I'm performing a REPLACE
statement on it.
I have triggers on this table on BEFORE INSERT
, AFTER INSERT
and BEFORE DELETE
, and in these triggers I modify another table (table2
). I don't want any other session to edit table2
while the REPLACE
statement and the operations inside the triggers are running.
I know I can use LOCK TABLES
on table1
and tables inside the triggers will also lock. But I'm doing the modification inside a stored procedure so, therefore, I cant use LOCK TABLES
. (Based on this)
How can I make sure that table1
and table2
stay locked and no other sessions could access them until the REPLACE
statement has finished without using LOCK TABLES
?
I have also read this. But it is impossible to return a ResultSet
from a trigger and also I'm already returning another ResultSet
from my stored procedure and I don't want to return such a large ResultSet
just because I want to lock the table.
UPDATE:
Here is an example of what's happening in a trigger:
- selects
row1
fromtable2
- selects
row2
fromtable2
- inserts a row in
table2
, based on the selected values - updates
row1
and inserts or updates some other rows fromtable2
based on the selected values - Inserts another row to
table2
Let's say I use START TRANSACTION
and assume that both transactions are working with the same rows. Now transaction1
and transaction2
have finished the second step, meaning that they have read their needed values, then transaction1
goes into the next steps and locks transaction2
until transaction1
is completely finished, then transaction2
goes into step 3, but now the selected value from step 1 is not right because transaction1
has updated row1
. Therefore, it's going to insert and update with wrong values.
How can I avoid this scenario?
(Also if this scenario is impossible to happen, what other scenarios could happen based on the steps that are happening in the trigger? Because I AM SURE that something wrong is happening when using this code with more than 1000 inserts at the same time from different transactions)