Prevent foreign key references to unlogged partitions

From: Zsolt Parragi <zsolt(dot)parragi(at)percona(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Prevent foreign key references to unlogged partitions
Date: 2026-08-31 13:44:40
Message-ID: CAN4CZFMsEnA0TbYLHjicUn4MTjsJthCOmNvpWoTJb4_sm4F-aA@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello!

This is another find with my claude feature-crosscheck analysis[1],
with the combination of unlogged tables, partitioned tables and
foreign keys.

Currently foreign key persistence checks only target the specific
relation referenced in the constraint. Partitioned tables are always
permanent, but the partitions can be unlogged, allowing a persistent
table's foreign key to reference an unlogged table.

Simple repro:

CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY RANGE (a);
CREATE UNLOGGED TABLE pk1 PARTITION OF pk FOR VALUES FROM (0) TO (100);
CREATE TABLE fk (x int REFERENCES pk);

(ALTER TABLE SET UNLOGGED on an already attached partition fails, all
other variations I tried currently succeed on master)

0002 aims to fix this with an additional check, and adds some test cases.

And there's actually a "user" of this bug in the code: pgbench with
both --partitions and --unlogged-tables silently ignores the unlogged
flag for top level tables, but creates the partitions of
pgbench_accounts unlogged, which are referenced by other permanent
tables. initCreateTables handles the combination differently,
createPartitions only checks the unlogged flag.

We could possibly make pgbench error out for this combination, ignore
unlogged-tables properly even for the partitions, or fix it to make as
many relations unlogged as possible.

0001 does the latter, only leaving pgbench_accounts (the parent, not
the partitions) and pgbench_branches permanent, everything else is
properly unlogged. We have to keep pgbench_branches permanent, because
pgbench_accounts is a partitioned table, and it can't be unlogged,
even if all of its partitions are unlogged.

[1]: https://postgr.es/m/CAN4CZFPBcRObk2sHJKidnuN7hJ_fG7QCdim%3DYnrN1sjSLFN68A%40mail.gmail.com

Attachment Content-Type Size
0001-pgbench-don-t-disable-unlogged-tables-when-partition.patch application/octet-stream 3.1 KB
0002-Disallow-foreign-keys-referencing-unlogged-partition.patch application/octet-stream 8.4 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Amit Langote 2026-08-31 13:53:34 Re: Re-read conindid under the referenced table's lock in the RI fast path
Previous Message Pierre Forstmann 2026-08-31 13:41:45 Re: [Patch] Don't stop a `vacuumdb --all` on a connection failure