Skip to content

A foreign key to a UNIQUE column rejects values that exist #2661

Open

Description

@mathiasrw

A foreign key that references a UNIQUE column of the parent table (not its primary key) rejects values that exist.

Reproduced on develop, compared with SQLite 3.43 (PRAGMA foreign_keys=ON):

CREATE TABLE p (a INT, b INT, u INT, PRIMARY KEY (a, b), UNIQUE (u));
INSERT INTO p VALUES (1, 1, 7);
CREATE TABLE d (v INT, FOREIGN KEY (v) REFERENCES p (u));
INSERT INTO d VALUES (7);
-- AlaSQL: Foreign key "7" not found in table "p"
-- SQLite: inserted

Cause

The check in src/60createtable.js always looks the referenced values up in the parent's primary key index (fktable.pk), whatever columns the foreign key names.

Direction

When the table is created, find the parent's key (primary key or UNIQUE) whose columns match the referenced columns, keep it on the foreign key, and look values up in that index. Without a matching key, refuse the foreign key at CREATE TABLE, as SQL requires a referenced key.

This turns a wrong error into the right result, so it can go into 4.x.

Tests: the example above; a composite foreign key to a composite UNIQUE; a foreign key to columns without a key refused at CREATE TABLE.

Related: #1179, #2656.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions