Domanda

I am trying to read a row from a table with a lock so that others can not do any read operation on that table.

Here is my query that I am running from the psql console with a 30 seconds of sleep.

select * from TABLE_NAME for update; SELECT pg_sleep(30);

I also tried nowait:

select * from TABLE_NAME for update nowait; SELECT pg_sleep(30);

My table has only one row for the test purpose, so where condition is not required here.

Now, from another psql console I am doing a select operation on the same table(within the 30 seconds), but I am still able to read the records.

My question is, why this locking is not working? Or Its not the right way to do it? Can someone guide me a bit?

È stato utile?

Soluzione

The problem is that your SELECT FOR UPDATE should be wrapped in a transaction to be effective.

When typing this in a single line in psql:

select * from TABLE_NAME for update; SELECT pg_sleep(30);

it gets broken down into two sql statements executed separately, so the locking effect of FOR UPDATE is lost before the pg_sleep even starts.

Try:

 BEGIN; select * from TABLE_NAME for update; SELECT pg_sleep(30); END;

and in the other session:

select * from TABLE_NAME for update;

to see the second session being blocked for 30 seconds.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top