Reading and writing to the same tuple at the same time may cause read logic exceptions because of the non-atomic action of writing to the override of the tuple.
For MVCC in MySql,
Conceptually, because of ReadView, access to the tuple being written can be avoided by visibility rules, and then the race between reads and writes occurring in the same region can be avoided
But in terms of implementation details, I still have a question: Overwriting a field of a tuple will replace the data in the heap. If a read operation comes in, the same area will be read and written, which may result in read and write conflicts (byte copying is not atomic).
How can I avoid this read-write conflict? Is it a lock?
I did not express what I mean very well, I actually want to express the problem of lock competition:
Insert into tableA(age,num) values(1,1) Assume that there is a piece of data in the database.
At this time, under the read commit, two of the following transactions run concurrently at the same time: Transaction 1: select * from tableA Transaction 2: update tableA set age=2
The steps they run in the database are as follows:
- Transaction 1 accesses the only piece of data in the page: the transaction id that accesses the row of data, and judges that the data is visible through the visibility rule
- Transaction 2 locates the row of data and finds that the written age field is the same as the size occupied by the current data, so it starts to execute the replacement logic
- Transaction 2 copies the value of the age field in the current data to undo, then points the undo pointer to the past, and the transaction id is updated
- Transaction 2 writes the value 2 back to the age field of the current data
- Transaction 1 starts to access the age field, reads that the current data value is 2, and accesses the value of the num field to 1, and returns (2, 1)
- Transaction 2 commit
Through the operation of the above steps, you can see that the result returned by transaction 1 is not expected, and the root cause of this is that the action of reading the transaction id and the action of writing data (undo, transaction id, new data) are not mutually exclusive
mvcc is an access design, but the database engine will still compete for the same area when accessing and writing tuples. How does Innodb cleverly avoid read-write conflicts when implementing mvcc?