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.
Related
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.
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;
1:
I was trying this and it was working fine:
start transaction;
select * from orders where id = 21548 LOCK IN SHARE MODE;
update orders set amount = 1500 where id = 21548;
commit;
According to the definition of LOCK IN SHARE MODE , it locks the table with IS lock and lock the selected rows with S lock.
When a row is locked with S lock.How can it be modified without releasing lock?
It needs X lock to modify it.Right? Or is it valid only for different connection transaction?
2:
//session1
start transaction;
select * from orders where id = 21548 FOR UPDATE;
Keep this session1 same and try this in the different session:
//session2
select * from orders where id = 21548; //working
update orders set amount = 2000 where id = 21548; //waiting
FOR UPDATE locks the entire table into IX mode and selected row into X mode.
As X mode is incompatible with S mode then how come select query in second session is getting executed?
One answer might be that select query is not asking for S lock that's why it's running successfully.But update query in the second session is also not asking for X lock , but as you execute it , it starts waiting for the lock held by session1.
I have read a lot of stuff regarding this but not able to clear my doubts.Please help.
Bill Karwin answered this question through email.He said:
The same transaction that holds an S lock can promote the lock to an X lock. This is not a conflict.
The SELECT in session 1 with FOR UPDATE acquires an X lock. A simple SELECT query with no locking clause specified does not need to acquire an S lock.
Any UPDATE or DELETE needs to acquire an X lock. That's implicit. Those statements don't have any special locking clause for that.
For more details on IS/IX locks and FOR UPDATE/LOCK IN SHARE MODE please visit
shared-and-exclusive-locks .
I am updating some records in session 1 with open transaction -
begin transaction
update aa
set name = 'harry1'
where name = 'harry'
As you can see that commit/rollback transaction is not issued. Now i try to read the records from another session session 2.
set transaction isolation level repeatable read
select * from aa
Now Isolation level - repeatable read should give me the same old value that was there before update statement in session 1 that should be harry and not harry1.. please correct me if i am wrong.
But when I try to read record in session 2 while transaction is still open in session 1 I get deadlock..can someone tell me why repeatable read is not working and is behaving like read committed .
REPEATABLE READ is same as READ COMMITTED but in addition share locks are retained on rows read for the duration of the transaction. In other words any row that is read cannot be modified by another connection until the transaction commits or rolls back.
So your query on the session 2 is waiting for either commit or rollback on the session 1.
while data is being read in the begin tran block, no other transactions are allow update, preventing a dirty read. Therefore a non-repeatable read does not occur. Once the commit has occurred that an update to the customer table is allow by a concurrent process.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
--first read
SELECT first_name, last_name from customer WHERE customer_id=5
---second read
SELECT first_name, last_name from customer WHERE customer_id=5
COMMIT TRAN
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.