Re: Long living and expiring locks?

Поиск
Список
Период
Сортировка
От Laurenz Albe
Тема Re: Long living and expiring locks?
Дата
Msg-id 6b66751bfdf9954404348a60b93959188b620dc9.camel@cybertec.at
обсуждение исходный текст
Ответ на Long living and expiring locks?  (Tim Uckun <timuckun@gmail.com>)
Список pgsql-general
On Fri, 2022-05-20 at 15:43 +1200, Tim Uckun wrote:
> I have multiple processes connecting to the same database. In order to
> prevent race conditions the I would like the process to  issue a
> SELECT FOR UPDATE  to lock the records that need to be processed.
> 
> The problem is that the locks are not inside of a single translation.
> The process is multi step. Records are selected and presented to the
> user, the user does some stuff and submits a form, the submitted form
> updates those records and frees the lock.
> 
> Ideally I would do a select for update when the form is shown to the
> user but with an expiry time so that if the user decides to move on
> and not submit any changes the locks will expire.
> 
> I could do this with a locked_at field that I can update on select but
> I would prefer to let postgres handle the locks if possible.

The customary solution to this is to use optimistic locking:

During the UPDATE, you check if a concurrent transaction modified
the row since you read it, and if yes, you redo the whole operation.

That could look like:

SELECT id, col_to_change, othercol1, othercol2
FROM tab
WHERE id = 42;

[user interaction]

UPDATE tab
SET col_to_change = 'newvalue'
WHERE id = 42
  AND othercol1 = 'original value'
  AND othercol2 = 'original value';

If the UPDATE modifies no row, something must have changed, and you
redo the whole operation.

The advantage is that you don't have to keep a transaction open.
(Regular) long transactions are a big problem in relational databases.

In PostgreSQL you could use the system columns "ctid" and "xmin"
to check if the row changed, so you don't have to fetch and check
all columns.

Yours,
Laurenz Albe
-- 
Cybertec | https://www.cybertec-postgresql.com



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

Предыдущее
От: Dominique Devienne
Дата:
Сообщение: Re: No default for (user-specific) service file location on Windows?
Следующее
От: Koen De Groote
Дата:
Сообщение: Re: In case of network issues, how long before archive_command does retries