Skip to main content

SKY-Q508 · Quality, structure and performance

Mismatched PostgreSQL foreign key column counts

Medium

A foreign key lists a different number of columns on each side of REFERENCES. PostgreSQL needs a target column for each referencing column.

Languages
PostgreSQL
Quality gate
listed, not counted by the gate (full and diff scans). This PostgreSQL finding is report-only.
Finding type
review
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

The migration cannot install the intended constraint, leaving later changes in the migration unapplied.

What Skylos flags

migration.sql · SQLReported on line 1
ALTER TABLE orders ADD FOREIGN KEY (tenant_id, owner_id)  REFERENCES owners(id);
pyproject.toml · TOML
[tool.skylos.sql]dialect = "postgresql"

What Skylos leaves alone

migration.sql · SQL
ALTER TABLE orders ADD FOREIGN KEY (tenant_id, owner_id)  REFERENCES owners(tenant_id, id);

pyproject.toml: same as in the flagged example.

Why Skylos leaves it alone

Match each referencing column with its intended referenced column, in order. Confirm the target has an eligible key.

How Skylos decides

  1. Skylos compares explicit column lists in CREATE TABLE and ALTER TABLE.
  2. An inline column REFERENCES has one local column. An omitted target list depends on the referenced primary key.

How to fix it

Match each referencing column with its intended referenced column, in order. Confirm the target has an eligible key.

migration.sql · SQL · the fix, against the flagged file
ALTER TABLE orders ADD FOREIGN KEY (tenant_id, owner_id)Removed:   REFERENCES owners(id);Added:   REFERENCES owners(tenant_id, id);

When it can be wrong

  • Equal counts leave type compatibility and the existence of a matching unique key for PostgreSQL to verify.

Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.

How to silence it

  • Review the statement in the context of its migration.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.