-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Description
Problem
Self-referencing foreign keys cannot be embedded using PostgREST's standard resource embedding. While regular FKs between different tables are auto-detected and embeddable via the !hint disambiguation syntax, self-referencing FKs require manually defining computed relationship functions.
For example, given a table with a self-referencing FK:
create table patients (
patient_id int primary key generated always as identity,
first_name text not null,
last_name text not null,
referring_patient_id int references patients(patient_id)
);There is no way to query the referring patient via standard embedding. You must define a boilerplate function:
create or replace function referred_by(patients)
returns setof patients rows 1 as $$
select * from patients where patient_id = $1.referring_patient_id
$$ stable language sql;This is the only documented approach for recursive relationships. It creates downstream issues — for example, Supabase's type generator now embeds these functions into the table's Row type, forcing workarounds in application code.
Solution
Support self-referencing FK embedding natively using the existing !hint disambiguation syntax:
GET /patients?select=*,referred_by:patients!referring_patient_id(patient_id,first_name,last_name)PostgREST already detects the FK (referring_patient_id -> patient_id). The !fk_name hint provides enough information to resolve the self-join unambiguously, the same way it resolves ambiguity when multiple FKs point to different tables.