Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Created March 4, 2015 13:10
Show Gist options
  • Save dmitry-vsl/a0a535f238463f59fee9 to your computer and use it in GitHub Desktop.
Save dmitry-vsl/a0a535f238463f59fee9 to your computer and use it in GitHub Desktop.
Две параллельные транзакции, одна слева, другая справа.
Каждая проверяет количество активных пользователей,
убеждается что оно не превышает лимит, и вставляет нового пользователя. В некоторых БД реализация такой функциональности потребовала бы явной блокировки таблицы перед запросом select count(*), но только не в постгресе
test=# test=# begin transaction;
test=# begin transaction; BEGIN
BEGIN test=# select count(*) from u where status='active';
test=# select count(*) from u where status = 'active'; count
count -------
------- 6
6 (1 row)
(1 row)
test=# insert into u(status) values('active');
test=# insert into u(status) values('active'); INSERT 0 1
INSERT 0 1 test=# commit;
test=# ERROR: could not serialize access due to read/write dependencies among transactions
test=# commit; DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt.
COMMIT HINT: The transaction might succeed if retried.
test=# test=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment