4

Let me start my question with an SQL example.

Here is the table setup:

  1. Create table x and y. With y.x refers to x.id.
  2. Insert a row into x (id=1).

START TRANSACTION;
CREATE TABLE `x` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `value` INT(11) NOT NULL,
    PRIMARY KEY (`id`)
)  ENGINE=INNODB;
CREATE TABLE `y` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `x_id` INT(11) NOT NULL,
    `value` INT(11) NOT NULL,
    PRIMARY KEY (`id`),
    CONSTRAINT `fk_x` FOREIGN KEY (`x_id`)
        REFERENCES `x` (`id`)
)  ENGINE=INNODB;

INSERT INTO x values (1,123456);
COMMIT;

Now start a transaction (Trx A) to update the row in x.

START TRANSACTION;
UPDATE x SET value=value+1 WHERE id = 1;

Before it is committed, I am starting another transaction (Trx B) to insert a row to y.

START TRANSACTION;
INSERT INTO y VALUES (null,1,123456);
---- HANGED ----
-- Until Trx A is committed or rolled-back, the Trx B is hanged here.

The question is - is it expected that Trx B to be hanged at that point? Why and any way to workaround that?

This has been tested on MySQL 5.7.21, Percona 5.7.21, MariaDB 10.2.14

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
HelloSam
  • 2,225
  • 1
  • 20
  • 21

1 Answers1

5

Yes it is expected.

Trx A has an exclusive lock (X) on the record because it is updating it.

Trx B has to acquire a shared mode (S) lock on all foreign key references, to ensure that the constraints are met. It waits for Trx A to release its X lock.

There is no way to avoid this and keep the referential integrity. If you manage to disable the locking, MySQL won't be able to guarantee that the referenced row exists.

The usual workaround is to remove the foreign keys.

Vatev
  • 7,493
  • 1
  • 32
  • 39
  • sigh-that's sad to know but thanks. I thought not updating the key would not cause such from happening. – HelloSam Apr 16 '18 at 10:08
  • What do you mean "not updading the key" – Vatev Apr 16 '18 at 10:55
  • 1
    I mean I wish there is a way that I could promise MySQL that I am not modifying x.id after it is inserted (only other "values" column are updated), hence would not break referential integrity. I guess there just isn't such thing. – HelloSam Apr 17 '18 at 02:25
  • There is :) You can disable the foreign key checks or remove the foreign keys. – Vatev Apr 17 '18 at 06:58
  • FKs are a burden on `INSERTs` -- to check things; FKs are a burden on transactions as this points out. If performance is a big problem, consider debugging your app, then dropping FKs. – Rick James May 04 '18 at 17:30