crystal icon indicating copy to clipboard operation
crystal copied to clipboard

v5: Mutations with foreign keys that have default values are not-null in the GraphQL schema

Open RedShift1 opened this issue 1 month ago • 3 comments

Summary

When an SQL table has a foreign key column with a default value, in the GraphQL schema this turns into a not-null input.

Steps to reproduce

Use this database schema to start Postgraphile:

CREATE TABLE IF NOT EXISTS "group"
(
    "group_id"  integer NOT NULL GENERATED ALWAYS AS IDENTITY,
    "name"      text NOT NULL,
    PRIMARY KEY ("group_id")
);

CREATE TABLE IF NOT EXISTS "test"
(
    "test_id"               integer NOT NULL GENERATED ALWAYS AS IDENTITY,
    "group"                 integer NOT NULL DEFAULT 1,
    "group_without_fk"      integer NOT NULL DEFAULT 1,
    "name"                  text    NULL,
    PRIMARY KEY ("test_id"),
    FOREIGN KEY ("group") REFERENCES "group"("group_id")
);

Expected results

The createTest mutation doesn't require the field group as input. The mutation accepts input without group as input and that results in the database using the default value as per the SQL schema definition.

Actual results

The createTest mutation requires the field group:

Image

Additional context

postgraphile 5.0.0-rc.1

Possible Solution

Make foreign key input not required if the SQL schema allows that.

RedShift1 avatar Dec 03 '25 15:12 RedShift1

Interesting find! I'd be open to someone opening a pull request to address this; but it's so rare for foreign key relations to have a default value that I'm not convinced it's worth the effort to fix. These extremely rare cases can be addressed via the changeNullability() plugin on an ad-hoc basis.

benjie avatar Dec 05 '25 16:12 benjie

It's a common pattern for me to do something like

CREATE TABLE "test"
(
    ...
    "user_id"                 integer NOT NULL DEFAULT current_user_id(),
    ...
);

Often these are things that have an owner but that owner can be changed later.

RedShift1 avatar Dec 09 '25 11:12 RedShift1

Is this specifically an issue with the Relay preset? I don’t think what you shared above would be non-nullable normally.

benjie avatar Dec 09 '25 14:12 benjie