[PATCH] Fix infinite recursion when foreign table references itself

John Mikk <jomikk2706@gmail.com>

From: John Mikk <jomikk2706@gmail.com>
To: pgsql-hackers@lists.postgresql.org
Date: 2026-05-12T14:06:08Z
Lists: pgsql-hackers

Attachments

Hi, hackers.

If you create a foreign table referencing itself on a loopback server,
an unpleasant error occurs:

```sql
create extension if not exists postgres_fdw;

drop server if exists loopback cascade ;
create server loopback
    foreign data wrapper postgres_fdw
    options (dbname 'postgres', host 'localhost');

create user mapping for current_user server loopback;

create foreign table test_self (id int)
    server loopback options (table_name 'test_self');
--> Ok

insert into test_self select 1;
--> Err
/*
[08001] ERROR: could not connect to server "loopback"
  Detail: connection to server on socket "/tmp/.s.PGSQL.54321" failed:
FATAL:  sorry, too many clients already
  Where: remote SQL command: INSERT INTO public.test_self(id) VALUES ($1)
    remote SQL command: INSERT INTO public.test_self(id) VALUES ($1)
    remote SQL command: INSERT INTO public.test_self(id) VALUES ( ...
*/
```

The proposed patch fixes this error.

```sql
create foreign table test_self (id int)
    server loopback options (table_name 'test_self');
--> Err
/*
[42P16] ERROR: foreign table "test_self" cannot reference itself
  Hint: Foreign table pointing to the same table on the same database
creates circular reference
*/
```

John.