r/SQL • • 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.

https://github.com/Vinnu124/pg_anyFK

7 Upvotes

14 comments sorted by

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?

4

u/Global-Apartment-872 8d ago

On postgres 18 (MAC m1), testing on 10k rows and 5000 inserts of an 5 element array

  1. normal array column + no constraint takes about 15 ms(nothing inside the array is checked)
  2. array + pg_anyfk takes about 1300 ms
  3. normal junction table + native FK take about 1990 ms.

The real alternative to this is the 3rd one. Also the trigger wont go on every mutation,only the ones that touch the array column.Updating a different column is still almost the same.

Obviously it is heavier per check than native FK, and if youre writing hard to a wide array , it will show up.

3

u/Discordbothost 8d ago

I'd also time deleting a product with no orders, with a GIN index on the array and a B-tree on the junction table's product_id. That compares the two reference checks without timing any cleanup.

3

u/Global-Apartment-872 8d ago

Good call ,
10k products, 5000 orders of 5 products each, so 25k relationships either way. GIN on the array column, B-tree on the junction table's product_id. Both designs reference the same 5000 products.
array + pg_anyfk: ~1200 ms
junction + native FKs: ~1900 ms
Deleting 1000 unreferenced products, so no cleanup, just the check:
array + pg_anyfk (GIN): 112 ms
junction + native FK (B-tree): 81 ms

1

u/squadette23 8d ago

normal junction table taking longer than array + extension is extremely counterintuitive.

Basically, a cell in a normal junction table can be considered a single-element array, and it would become faster? Do you understand why?

2

u/TheMagarity 8d ago

Isn't this more of an underlying model issue?

1

u/Global-Apartment-872 8d ago

yea, postgres core tried patching this in too but it hasnt landed yet.

3

u/TheMagarity 8d ago

No I mean your model. If you use a 1:many table instead of an array then you can enforce the fk no problem.

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/Global-Apartment-872 7d ago

Ran the reads:
load one order, product ids only: array 0.086 ms junction 0.090 ms
load one order with the product rows: array 0.196 ms junction 0.353 ms
find all orders containing a product: array 0.109 ms junction 0.091 ms

So it splits. Loading an order with its products is faster with the array, since it's one row lookup instead of walking five.

Also the constraints and triggers do come back after a restore (needed a patch for including the id counter in the dump)

2

u/mirinai_ai 7d ago

Nice, that split is a useful result in itself. It might be worth putting those three numbers straight into the README as a trade-off table, since "faster for loading an order, slightly slower for finding orders by product" is exactly what someone choosing between the two designs wants to know.

One thing I'd add to the containment test: try it with a popular product that appears in, say, a third of the orders, not only a rare one. GIN and a B-tree on the junction table can behave quite differently once the result gets large. At sub-millisecond timings, EXPLAIN (ANALYZE, BUFFERS) is also a steadier comparison than wall time, because the buffer counts show how many pages each design actually touched.

1

u/MongooseWonderful198 7d ago

Could you add an older-snapshot case to race_test.sh? Using its existing fixture:

  1. Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM posts; and stays open.
  2. Session B inserts '{50}' into posts.tag_ids and commits.
  3. A deletes tag 50, then attempts to commit.

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 EXISTS against 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/Global-Apartment-872 6d ago

You are right
Under REPEATABLE READ the parent trigger's SELECT uses the transaction snapshot, so it never sees the row B committed. The delete goes through, both commit, no error, one dangling reference

1

u/Thlvg 8d ago

Why?