Issue with inserting values that fetched from locked rows - mysql

I have two scripts bounded by transactions:
The first:
START TRANSACTION;
update product set price = 70;
SELECT SLEEP(20);
rollback;
The second:
START TRANSACTION;
insert into product_order(product_id, amount, price) select id, amount, price from product;
commit;
The second transaction has started execute when the first one is in 'sleep' state.
So, I expected that second one will have executed during sleeping of the first transaction.
Unexpectedly the second transaction is waiting until the first one goes out from sleep state.
I know that it is something connected to row locking. But I hadn't updated the rows that included into the first transaction.
My question: What is the reason of such behaviour and how I can get rid of it?

It look like the lock will be released after the end of the transaction (You can't read the data because if the transaction fails the database will have to rollback to the previous state)
Before your insert you should set the sessions transaction isolation level so it can read data that are not commited:
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
START TRANSACTION;
insert into product_order(product_id, amount, price) select id, amount, price from product;
COMMIT;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

Related

Deadlock in transaction with isolation level serializable

I was trying to understand how locking works with isolation levels. I have gone through this question but can not understand flow given blow
Here i am starting two transactions in different terminals and reading same row in them. As i try to update them both the terminal keeps waiting for the update. No other query is running apart from this
Here are the series of steps i did
conn1: START TRANSACTION;
conn1: SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
conn2: START TRANSACTION;
conn2: SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
conn1: SELECT * from users WHERE id = 1;
conn2: SELECT * from users WHERE id = 1;
conn1: UPDATE users set name = 'name' WHERE id = 1; waiting...
conn2: UPDATE users set name = 'name' WHERE id = 1; waiting...
Here is my first question
Here i want to understand why both the connections are waiting and if they are who has the lock to update the row ?
If i change above steps to
conn1: START TRANSACTION;
conn1: SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
conn2: START TRANSACTION;
conn2: SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
conn1: UPDATE users set name = 'name' WHERE id = 1;
conn2: SELECT * from users WHERE id = 1; waiting...
conn1: commit
conn2: updated results
In this case the difference is i can see conn1 has the lock and until it either commits or rollback the changes all other request will be waiting and will get updated results if conn1 committed
Here is my second question
Is this the correct way if i want to lock a row and if locked i want other connections to wait(even for read) till this lock releases(commit or rollback) or i should use for update clause
DB - Mysql 5.7
As mysql documentation on SERIALIZABLE isolation level says:
This level is like REPEATABLE READ, but InnoDB implicitly converts all plain SELECT statements to SELECT ... LOCK IN SHARE MODE
The clause on autocommit does not apply here, since you explicitly start a transaction.
This means that in the first scenario both transactions obtain a shared lock on the same record. Then the first transaction (T1) tries to execute an update, which needs an exclusive lock. That cannot be granted, since T2 holds a shared lock. Then T2 tries to update, but cannot due to T1 holding a shared lock.
Whether you use an atomic update or a select ... for update statement to lock records, depends on the application logic you need to apply. If you need to fetch the record's data an do some complex calculations with those before updating the record, the use the select ... for update approach. Otherwise, go for the atomic update.

When multiple transactions insert the same value at the same time, why except one get a duplicate exception?

I don't understand INSERT sets an exclusive lock on the inserted row. part of this document.
https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html
In below part,
Session 1:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 2:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
Session 3:
START TRANSACTION;
INSERT INTO t1 VALUES(1);
I thought they would go in the order below
First transaction got exclusive lock for number 1 row.(didn't committed yet)
Second transaction also try to get exclusive lock.
Second transaction is going to wait, because First transaction already has exclusive lock.
But they didn't like above, the document said
The operations by sessions 2 and 3 both result in a duplicate-key error and they both request a shared lock for the row.
I don't understand why they got duplicate exception.
For a duplicate error to occur, the row must already be committed.
But they didn't. First transaction didn't commit yet.

How do I know which transactions run first

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
INSERT INTO Students VALUES(’Jason’,50);
UPDATE Students SET mark = mark + 10;
COMMIT
SET TRANSACTION ISOLATION READ COMMITED
INSERT INTO Students VALUES (’Kylie’,70);
SELECT SUM(mark) FROM Students;
COMMIT
If I have two transactions that run simultaneously, how do I know what runs first and what values would be returned by the query? I understand that Serializable isolates T1. But more than that I don't know how to proceed.
if you run both at same time, READ COMMITTED will wait for SERIALIZABLE to finish. btw, seems BEGIN TRANSACTION is missing on your TSQL.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
INSERT INTO Students VALUES(’Jason’,50);
UPDATE Students SET mark = mark + 10;
COMMIT TRANSACTION
SET TRANSACTION ISOLATION READ COMMITTED
BEGIN TRANSACTION
INSERT INTO Students VALUES (’Kylie’,70);
SELECT SUM(mark) FROM Students;
COMMIT TRANSACTION

How do I unlock a tuple after updating in MySQL/Innodb?

I am trying to model a transaction database for my databases course. I can't find how to unlock a tuple after using it for update.
I have used commits and assumed that this would release the exclusive lock but it doesn't.
START TRANSACTION;
BEGIN;
SELECT * FROM account WHERE account_num = 3 FOR UPDATE;
UPDATE account SET balance= balance + 100 WHERE account_num = 3;
COMMIT;
What am I supposed to do to make sure this exclusive lock is let go?
START TRANSACTION and BEGIN are synonyms; don't use both.
Unless you are doing something else in the transaction, there is no need for the SELECT, nor for the transaction. UPDATE will lock the row for the duration of the UPDATE.

NHibernate query deadlock in case multiple connection

I have next transaction:
Desc d = new Desc();
d.Descr = "new";
_sess.Transaction.Begin();
_sess.SaveOrUpdate(d);
var desc = _sess.CreateCriteria(typeof(Desc)).List<Desc>();
_sess.Transaction.Commit();
This transaction performs next query:
BEGIN TRANSACTION
INSERT
SELECT
COMMIT TRANSACTION
When I perform this code in two processes I have deadlock, because
1 Process
Perform INSERT and lock Key
2 Process
Perform INSERT and lock key
1 Process wants to perform SELECT and passes in TIMEOUT STATE
2 Process wants to perform SELECT and passes in TIMEOUT STATE
result: deadlock
BD: MS SQL Server 2008 R2
2 questions:
How do me set UPDATE LOCK on All tables what included in transaction
If I use this code:
Desc d = new Desc();
d.Descr = "new";
_sess.Transaction.Begin(IsolationLevel.Serializable);
_sess.SaveOrUpdate(d);
var desc = _sess.CreateCriteria(typeof(Desc)).List();
_sess.Transaction.Commit();
Nothing changes.
What does IsolationLevel.Serializable do ?
UPDATE:
I need to get following:
USE Test
BEGIN TRANSACTION
SELECT TOP 1 Id FROM [Desc] (UPDLOCK)
INSERT INTO [Desc] (Descr) VALUES ('33333')
SELECT * FROM [Desc]
COMMIT TRANSACTION
How do me perform with help NHibernate following:
SELECT TOP 1 Id FROM [Desc] (UPDLOCK)
?
I would change the transaction isolation level to snapshot. This avoids locks when reading data, allows much more concurrency and particularly no deadlocks in read-only transactions.
The reason for the deadlock is following: insert do not conflict with each other. They lock the newly inserted row. The query however is locked out, because it tries to read the newly inserted row from the other transaction. So you get two queries both waiting for the other transaction to complete, which is a deadlock. With isolation level snapshot, the query doesn't care about non committed row at all. Instead of waiting for locks to be released, it only "sees" rows that had been committed. This avoids deadlocks in queries.