r/SQL • u/Global-Apartment-872 • 1d ago
PostgreSQL Foreign keys for array column elements
Postgres foreign keys can't check the elements of an array column, so a
product_ids bigint[] can hold ids that don't exist, and deleting the referenced
row leaves them dangling.
I wrote an extension that enforces it with triggers:
SELECT anyfk.add('orders(product_ids)', 'products(id)');
Feedback welcome.
7
Upvotes
2
u/Straight_Waltz_9530 1d ago
Sounds very heavyweight compared to typical foreign key constraints. An unnest and query on every mutation? Oof. What do benchmarks say?
2
u/TheMagarity 21h ago
Isn't this more of an underlying model issue?
1
u/mirinai_ai 13h ago
On squadette23's question about why the junction table comes out slower: in that design the 5000 orders become 25,000 child rows, each with its own tuple, its own index entries (the primary key plus the B-tree on product_id) and its own foreign key check. The array version writes 5000 rows and runs one check per row. So the benchmark is mostly measuring per-row overhead, and it would help to say how the junction rows were inserted, since one multi-row INSERT or COPY usually narrows the gap compared with 25,000 single-row statements.
Since the README's case for arrays is the read path, a read benchmark might be more convincing than inserts: loading one order with its products, and finding every order that contains a given product (GIN with @> against the B-tree on the junction table).
I'd also test pg_dump and restore. The triggers on the user tables should come across, but if the registered constraints live in an extension table, they're only included in a dump when the extension marks that table with pg_extension_config_dump. A quick check that anyfk.constraints and drop_constraint still work after restoring into a fresh database would settle it.
1
u/Thlvg 22h ago
Why?