r/SQL • u/Global-Apartment-872 • 8d 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
3
u/Straight_Waltz_9530 8d 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 8d ago
Isn't this more of an underlying model issue?
1
u/mirinai_ai 8d 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/MongooseWonderful198 7d ago
Could you add an older-snapshot case to
race_test.sh? Using its existing fixture:BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM posts;and stays open.'{50}'intoposts.tag_idsand commits.The current cases test overlapping locks. Here B's key-share lock has already been released, while A retains its earlier snapshot. The parent trigger's ordinary
SELECT EXISTSagainst the child table is the part to check. The pass condition is an error rather than both transactions committing a dangling reference. This is a suggested regression case from reading the SQL; I haven't run the extension.1
u/Thlvg 8d ago
Why?