Skip to content

Check a foreign key against the key of the referenced table that it names #2662

Open
0 of 1 issue completed

Description

@mathiasrw

What happens today

Foreign keys are closures in table.checks built by CREATE TABLE in src/statements/createtable.js.

What to change

  1. At CREATE TABLE, resolve the referenced key once and keep it on the foreign key in table.schema.foreignKeys (Keep the definition of a table as data in table.schema and build its rules from it #3169). Take the parent's primary key when its columns are the referenced columns or no columns are named, otherwise the parent's UNIQUE key with exactly those columns. Match column names for both forms of UNIQUE (uk.columns holds names in the column form and objects with an expression in the table form).
  2. The check builds the lookup row with the parent's column names in key order, calls the key's onrightfn, reads that key's index and compares the whole values of the found row, as foreignKeyExists does for prefix keys (A foreign key to a primary key with a prefix length compares only the prefix #2883). Keep a reference to the parent's index and read it through syncKeyIndexes (Move the key and check rules of a table into one module #2716).
  3. When the parent has no key on the referenced columns, keep the row-by-row search.
  4. Keep the error texts (Foreign key "7" not found in table "p", Invalid foreign key on table ..., FOREIGN KEY allowed only to tables with PRIMARY KEYs).

What stays the same

Done when

Fixes

Fixes #2661, #3153.

Depends on

#3169

Sub-issues

Sub-issues

0 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. added this to the v4.x Focus milestone on Nov 26, 2026
  2. changed the title [-]Review #1179 for code improvements: foreign key check bound to the primary key index[/-] [+]Check a foreign key against the key of the referenced table that it names[/+] on Nov 26, 2026
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions