Bug #121897 Composite self-referencing foreign key skips ON DELETE CASCADE

Submitted: 24 Nov 4:55
Reporter: QiFan Liu Email Updates:
Status: Open Impact on me:
None 
Category:MySQL Server: Foreign Keys Severity:S2 (Serious)
Version:26.10.0 OS:Linux
Assigned to: CPU Architecture:x86
Tags: composite key, foreign key, on delete cascade, self-reference

[24 Nov 4:55] QiFan Liu
Description:
With SQL-layer foreign-key handling active (innodb_native_foreign_keys=0), ON DELETE CASCADE fails for a composite self-referencing foreign key when the child and referenced parent keys share their first component but differ in the second.

The table contains parent (1,1) and child (1,2), with the child referencing (1,1). Deleting (1,1) should also delete (1,2). Instead, the child remains and becomes an orphan.

Observed output:

native_fk_mode
0
remaining_rows
1
orphan_rows
1

The expected values for remaining_rows and orphan_rows are both 0.

How to repeat:
Run as root on a server where innodb_native_foreign_keys=0:

DROP DATABASE IF EXISTS db1;
CREATE DATABASE db1;
USE db1;

SELECT @@GLOBAL.innodb_native_foreign_keys AS native_fk_mode;

CREATE TABLE t1 (
  id1 INT NOT NULL,
  id2 INT NOT NULL,
  parent1 INT NULL,
  parent2 INT NULL,
  PRIMARY KEY (id1, id2),
  KEY parent_key (parent1, parent2),
  CONSTRAINT fk1
    FOREIGN KEY (parent1, parent2)
    REFERENCES t1 (id1, id2)
    ON DELETE CASCADE
) ENGINE=InnoDB;

INSERT INTO t1
VALUES (1, 1, NULL, NULL), (1, 2, 1, 1);

DELETE FROM t1
WHERE id1 = 1 AND id2 = 1;

SELECT COUNT(*) AS remaining_rows
FROM t1;
-- returns 1, expected 0

SELECT COUNT(*) AS orphan_rows
FROM t1 AS child
LEFT JOIN t1 AS parent
  ON parent.id1 = child.parent1 AND parent.id2 = child.parent2
WHERE child.parent1 IS NOT NULL AND parent.id1 IS NULL;
-- returns 1, expected 0

Suggested fix:
When deciding whether a cascade targets the same row in a composite self-referencing foreign key, compare every key part rather than only the first referenced key part.

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.038 sec. using MySQL 8.4.7-u6-cloud

Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.