Skip to content

Instantly share code, notes, and snippets.

@pyq
Created May 17, 2020 09:30
Show Gist options
  • Save pyq/e73234d3bbefbc36a49f924310cff953 to your computer and use it in GitHub Desktop.
Save pyq/e73234d3bbefbc36a49f924310cff953 to your computer and use it in GitHub Desktop.
MySQL innodb gap lock
-- create table
CREATE TABLE `idempotence_keys` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`)
) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC
-- insert
insert into idempotence_keys (created_at)
value
("2020-05-14 21:33:44"),
("2020-05-14 21:47:55"),
("2020-05-14 21:48:34"),
("2020-05-14 21:52:37"),
("2020-05-14 22:01:56"),
("2020-05-14 22:08:54"),
("2020-05-14 22:11:04"),
("2020-05-14 22:17:27"),
("2020-05-14 22:24:10"),
("2020-05-14 22:28:15"),
("2020-05-14 22:29:44"),
("2020-05-14 22:31:40"),
("2020-05-14 22:34:05"),
("2020-05-15 05:28:47"),
("2020-05-15 07:19:37"),
("2020-05-15 07:26:49"),
("2020-05-15 07:33:28");
-- mysql> SELECT @@TX_ISOLATION;
-- +-----------------+
-- | @@TX_ISOLATION |
-- +-----------------+
-- | REPEATABLE-READ |
-- +-----------------+
-- CASE 1
-- T1
begin;
delete from idempotence_keys
where created_at <= '2020-05-14 22:11:04';
-- T2 (blocked)
begin;
update idempotence_keys set created_at = '2020-05-15 07:33:29' where created_at = '2020-05-15 07:33:28';
-- CASE 2
-- T1
begin;
delete from idempotence_keys where created_at < '2020-05-14 21:52:37';
-- T2 (not - block)
begin;
update idempotence_keys set created_at = '2020-05-15 07:33:29' where created_at = '2020-05-15 07:33:28';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment