Skip to content

PostgreSQL dialect emits invalid DDL for composite foreign keys (source columns joined inside one pair of quotes) #5735

Closed

Description

@stohal

Bug

In the PostgreSQL dialect the two sides of a foreign-key constraint are quoted differently. Reference columns are quoted per column, but source columns are joined inside a single pair of quotes:

// lib/src/database/dialects/postgres.dart
var refColumnsFmt = referenceColumns.map((e) => '"$e"');

out += 'ALTER TABLE ONLY "$tableName"\n';
out += '    ADD CONSTRAINT "$constraintName"\n';
out += '    FOREIGN KEY("${columns.join(', ')}")\n';
out += '    REFERENCES "$referenceTable"(${refColumnsFmt.join(', ')})';

For a single-column foreign key this is correct. For a ForeignKeyDefinition carrying two or more source columns it produces:

FOREIGN KEY("tenantId, parentId")
REFERENCES "parent"("tenantId", "id")

"tenantId, parentId" is a single quoted identifier, so the statement is invalid.

Why it is reachable

Model relations only ever generate single-column foreign keys (see #5566), so this cannot be triggered from a .spy.yaml today.

It is reachable through definitions read from a live database. ForeignKeyDefinition already carries columns and referenceColumns as lists, and a database may legitimately contain composite foreign keys created by custom SQL. create-repair-migration compares against the live schema, so on such a database it can construct a multi-column ForeignKeyDefinition and emit the invalid DDL above.

Suggested fix

Mirror the reference side:

var columnsFmt = columns.map((e) => '"$e"');
...
out += '    FOREIGN KEY(${columnsFmt.join(', ')})\n';

Verification

Read from the 4.0.0 sources. I have not executed a repair migration against a database containing composite foreign keys — on such a schema it would also propose dropping those constraints, so I would rather not run it. It should reproduce directly in a unit test by passing a hand-built ForeignKeyDefinition with two source columns to the dialect and asserting on the generated DDL.

Version

serverpod / serverpod_cli 4.0.0

Activity

  1. mackings commented on Oct 5, 2026

    @mackings
    Contributor

    I'd like to fix this. The same bug is in the SQLite dialect too, so I'll fix both and add tests. PR coming soon.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions