Bug #121865 SQL-layer foreign keys between DATETIME and DATETIME(6) (also TIME, TIMESTAMP) are not enforced: orphans, no CASCADE

Submitted: 22 Nov 22:48
Reporter: Ke Han Email Updates:
Status: Open Impact on me:
None 
Category:MySQL Server: Foreign Keys Severity:S2 (Serious)
Version:26.10.0 (trunk 06bcb0eb0ad) OS:Any
Assigned to: CPU Architecture:Any

[22 Nov 22:48] Ke Han
Description:
CREATE TABLE accepts a foreign key between temporal columns with different
fractional-second precision, for example a DATETIME(6) event timestamp
referencing a DATETIME period start (also TIME(3) -> TIME, TIMESTAMP(6) ->
TIMESTAMP), without a warning. With the SQL-layer foreign keys that are the
default since 9.6 (innodb_native_foreign_keys=OFF), such a foreign key is not
enforced in either direction, silently:

- deleting a parent that has children succeeds although the foreign key is
  RESTRICT (expected ERROR 1451);
- ON DELETE CASCADE and ON UPDATE CASCADE leave the children unchanged, and
  ON DELETE SET NULL leaves the old value;
- a child value that matches no parent ('2024-04-01 00:00:00.250000' when the
  parent is '2024-04-01 00:00:00') is accepted (expected ERROR 1452).

In the example all six child rows end up referencing periods that no longer
exist (or never existed); no statement returns an error or a warning. The
same statements with DATETIME(6) on both sides are checked correctly. With
innodb_native_foreign_keys=ON, and on 8.4.13, the same child inserts are
rejected with ERROR 1452, so no orphan can be created there.

CREATE TABLE refuses a foreign key between INT and BIGINT ("ERROR 3780:
Referencing column 'p' and referenced column 'id' in foreign key constraint
... are incompatible"), but not one between DATETIME and DATETIME(6). The
manual asks for "similar data types" and says nothing about fractional
seconds; its list of differences between the SQL-layer and the InnoDB
implementation says that both "correctly reject" an operation that violates a
constraint.

How to repeat:
-- run with: mysql -uroot --table --force < file
CREATE DATABASE m212;
USE m212;
SELECT @@innodb_native_foreign_keys;
-- billing periods with second precision, usage events with microsecond precision
CREATE TABLE periods (id INT PRIMARY KEY, starts_at DATETIME NOT NULL, UNIQUE KEY (starts_at));
CREATE TABLE ev_restrict (id INT PRIMARY KEY, period_start DATETIME(6), KEY (period_start),
  FOREIGN KEY (period_start) REFERENCES periods (starts_at));
CREATE TABLE ev_cascade (id INT PRIMARY KEY, period_start DATETIME(6), KEY (period_start),
  FOREIGN KEY (period_start) REFERENCES periods (starts_at) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE TABLE ev_setnull (id INT PRIMARY KEY, period_start DATETIME(6), KEY (period_start),
  FOREIGN KEY (period_start) REFERENCES periods (starts_at) ON DELETE SET NULL);
INSERT INTO periods VALUES (1, '2024-01-01 00:00:00'), (2, '2024-02-01 00:00:00'),
  (3, '2024-03-01 00:00:00'), (4, '2024-04-01 00:00:00');
INSERT INTO ev_restrict VALUES (10, '2024-01-01 00:00:00'), (11, '2024-01-01 00:00:00');
INSERT INTO ev_cascade VALUES (20, '2024-02-01 00:00:00'), (21, '2024-03-01 00:00:00');
INSERT INTO ev_setnull VALUES (30, '2024-04-01 00:00:00');

-- no period starts at 00:00:00.25 (expected: ERROR 1452)
INSERT INTO ev_restrict VALUES (12, '2024-04-01 00:00:00.250000');
-- period 1 is referenced by ev_restrict rows 10 and 11 (expected: ERROR 1451)
DELETE FROM periods WHERE id = 1;
DELETE FROM periods WHERE id = 2;                                    -- ON DELETE CASCADE
UPDATE periods SET starts_at = '2024-03-02 00:00:00' WHERE id = 3;   -- ON UPDATE CASCADE
DELETE FROM periods WHERE id = 4;                                    -- ON DELETE SET NULL

SELECT * FROM periods ORDER BY id;
SELECT 'ev_restrict' AS t, id, period_start FROM ev_restrict
UNION ALL SELECT 'ev_cascade', id, period_start FROM ev_cascade
UNION ALL SELECT 'ev_setnull', id, period_start FROM ev_setnull ORDER BY 1, 2;
-- child rows whose period does not exist
SELECT c.id, c.period_start FROM
  (SELECT id, period_start FROM ev_restrict UNION ALL SELECT id, period_start FROM ev_cascade
   UNION ALL SELECT id, period_start FROM ev_setnull) c
  LEFT JOIN periods p ON p.starts_at = c.period_start
  WHERE c.period_start IS NOT NULL AND p.id IS NULL ORDER BY c.id;

-- control: with DATETIME(6) in the parent the same statements are checked
CREATE TABLE periods6 (id INT PRIMARY KEY, starts_at DATETIME(6) NOT NULL, UNIQUE KEY (starts_at));
CREATE TABLE ev6 (id INT PRIMARY KEY, period_start DATETIME(6), KEY (period_start),
  FOREIGN KEY (period_start) REFERENCES periods6 (starts_at));
INSERT INTO periods6 VALUES (1, '2024-01-01 00:00:00');
INSERT INTO ev6 VALUES (10, '2024-01-01 00:00:00');
INSERT INTO ev6 VALUES (12, '2024-01-01 00:00:00.250000');
DELETE FROM periods6 WHERE id = 1;

Result on 26.10.0 (innodb_native_foreign_keys = 0):
  every statement of the first part succeeds, no error, no warning
  periods:  (3, 2024-03-02 00:00:00)        <- periods 1, 2 and 4 deleted
  ev_cascade   20  2024-02-01 00:00:00.000000   <- should have been deleted
  ev_cascade   21  2024-03-01 00:00:00.000000   <- should be 2024-03-02 00:00:00
  ev_restrict  10  2024-01-01 00:00:00.000000   <- the DELETE of period 1 should have failed
  ev_restrict  11  2024-01-01 00:00:00.000000
  ev_restrict  12  2024-04-01 00:00:00.250000   <- the INSERT should have failed
  ev_setnull   30  2024-04-01 00:00:00.000000   <- should be NULL
  child rows whose period does not exist: 10, 11, 12, 20, 21, 30
  control (DATETIME(6) parent):
    ERROR 1452 (23000) at line 44: Cannot add or update a child row: a foreign key constraint fails (`m212`.`ev6`, CONSTRAINT `ev6_ibfk_1` FOREIGN KEY (`period_start`) REFERENCES `periods6` (`starts_at`))
    ERROR 1451 (23000) at line 45: Cannot delete or update a parent row: a foreign key constraint fails (`m212`.`ev6`, CONSTRAINT `ev6_ibfk_1` FOREIGN KEY (`period_start`) REFERENCES `periods6` (`starts_at`))

With innodb_native_foreign_keys=ON (and on 8.4.13) every child INSERT of
the first part fails with ERROR 1452, so there are no child rows; the
control gives the same two errors.

Expected: referential integrity holds. Either CREATE TABLE rejects the
foreign key (as for INT vs BIGINT), or the checks compare the values: the
INSERT of row 12 fails with ERROR 1452, the DELETE of period 1 fails with
ERROR 1451, row 20 is deleted, row 21 becomes 2024-03-02 00:00:00, row 30
becomes NULL, and no child row is left without a parent.

Suggested fix:
check_child_fk_ref() (used for RESTRICT/NO ACTION and to find the rows for
CASCADE and SET NULL) builds the search key for the child index with
key_copy_fk() from the parent row; if no child row is found with that key,
none of the actions is taken:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/sq...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/sq...
check_parent_fk_ref() (child INSERT/UPDATE) does the same in the other
direction:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/sq...
key_copy_fk() copies each fixed-length key part with copy_fixed_to_fixed(),
which treats it as a character string: if both fields report the same
charset it memcpy()s the source bytes and pads the rest of the target key
part with the pad character, or trims trailing spaces when the source is
longer:
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/ke...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/ke...
Temporal fields report my_charset_numeric, which is my_charset_latin1, so this
branch is taken for DATETIME vs DATETIME(6):
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/fi...
https://github.com/mysql/mysql-server/blob/06bcb0eb0ad281e08dd2b4d81b99ad25491433e7/sql/fi...
The parent's 5-byte packed DATETIME becomes the child's 8-byte DATETIME(6)
key part followed by three 0x20 bytes, a fraction that no child row has, so
no child is ever found; in the other direction only the first 5 of the
child's 8 bytes are used, so the fraction is ignored and any child value
matches the parent of the same second. Temporal values of different
precision have different binary formats, so the key part needs a value
conversion (or such foreign keys must be refused at CREATE TABLE, as INT vs
BIGINT is).

Workaround: declare both columns with the same fractional-second precision,
or use innodb_native_foreign_keys=ON.

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

Page generated in 0.040 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.