Red > Green > Refactor > Red

cycle is based on desire

update or delete on table "foreigns" violates foreign key constraint "to_foreigns_to_foreigns_id_fkey" on table "to_foreigns"

CREATE TABLE foreigns (
  foreigns_id INTEGER
    NOT NULL,
  PRIMARY KEY(foreigns_id)
);

CREATE TABLE to_foreigns (
  to_foreigns_id INTEGER
    NOT NULL
    REFERENCES foreigns(foreigns_id),
  PRIMARY KEY(to_foreigns_id)
);

INSERT INTO foreigns    (foreigns_id)    VALUES (1);
INSERT INTO to_foreigns (to_foreigns_id) VALUES (1);

DELETE
FROM foreigns
WHERE foreigns_id = 1;
-- error

error

 update or delete on table "foreigns"
 violates foreign key constraint "to_foreigns_to_foreigns_id_fkey"
 on table "to_foreigns"

CREATE TABLE foreigns (
  foreigns_id INTEGER
    NOT NULL,
  PRIMARY KEY(foreigns_id)
);

CREATE TABLE to_foreigns (
  to_foreigns_id INTEGER
    NOT NULL
    REFERENCES foreigns(foreigns_id),
    ON DELETE CASCADE, -- <<<<<<<<<<<<<<<<<<<<<
  PRIMARY KEY(to_foreigns_id)
);

INSERT INTO foreigns    (foreigns_id)    VALUES (1);
INSERT INTO to_foreigns (to_foreigns_id) VALUES (1);

DELETE
FROM foreigns
WHERE foreigns_id = 1;
-- NO error

stackoverflow.com