Re: Locking several tables within one transaction

Поиск
Список
Период
Сортировка
От Ilia Lilov
Тема Re: Locking several tables within one transaction
Дата
Msg-id CAM+V_49crNdBa4uUMYoO3uvdAK7hTnPYaaGrpO5MnS6pM2ZP9Q@mail.gmail.com
обсуждение исходный текст
Ответ на Re: Locking several tables within one transaction  (Scott Marlowe <scott.marlowe@gmail.com>)
Список pgsql-general
Thank you, Scott. I wondered about it, actually.

I've found perfect (I believe) solution. It uses pg_advisory_lock() as
I guessed before, but I thought wrong about it. For some reason I
thought session is some kind of scope for advisory lock, so one
program can't see locking made by another program from another
session, but it isn't true of course. Advisory locks are global, but
when session ends, all the locks made during the session unlocks. So,
it is exactly what I need.

In hope it will be useful for someone, I post my solution here.
We need two advisory locks: first one to "notify" all the programs
which read data not to start reading; and second one to ensure there
is no such programs reading data at the moment.
So, SQL code for the program which needs to have exclusive access for
long enough operations (C++ code in my example):
====
--Connect database
SELECT pg_advisory_lock(1);
SELECT pg_advisory_lock(2);
--All the SQL commands to operate (mostly to write) with data (they
don't need to be within single transaction)
SELECT pg_advisory_unlock(2);
SELECT pg_advisory_unlock(1);
--Disconnect database
====

And SQL code for programs which need not exclusive access and may
access to db at the same time (PHP code in my example):
====
--Connect database
SELECT pg_advisory_lock_shared(1);
SELECT pg_advisory_unlock_shared(1);
SELECT pg_advisory_lock_shared(2);
--All the SQL commands to operate (mostly to read) with data (they
don't need to be within single transaction)
SELECT pg_advisory_unlock_shared(2);
--Disconnect database
====

If anyone needs further explanation, fell free to mail me.
Ilia Lilov.

В списке pgsql-general по дате отправления:

Предыдущее
От: Chris Travers
Дата:
Сообщение: Re: Implementing "thick"/"fat" databases
Следующее
От: Pablo Romero Abiti
Дата:
Сообщение: Re : Update columns in same table from update trigger?