We have a Postgres (9.6) table my_table
with a row email_address jsonb[] NOT NULL
:
DROP TABLE my_table;
CREATE TABLE my_table (email_address jsonb NOT NULL);
We want to store an array of email addresses as JSONB (for the sake of this example, I'll only keep the address
key):
INSERT INTO my_table (email_address)
VALUES (ARRAY[ $${"address": "A"}$$::jsonb,
$${"address": "B"}$$::jsonb,
$${"address": "C"}$$::jsonb ]);
INSERT INTO my_table (email_address)
VALUES (ARRAY[ $${"address": "D"}$$::jsonb ]);
We want to make sure that each of the element we add to the array have a unique set of address
.
-- ["A", "B"] <@ ["A", "B", "C"], SHOULD FAIL
INSERT INTO my_table (email_address)
VALUES (ARRAY[ $${"address": "A"}$$::jsonb, $${"address": "B"}$$::jsonb ]
-- ["A", "D"] IS UNIQUE SET, SHOULD SUCCEED
INSERT INTO my_table (email_address)
VALUES (ARRAY[ $${"address": "A"}$$::jsonb, $${"address": "D"}$$::jsonb ];
We were thinking about a exclusion constraint using a function maybe? We are currently trying to "map" the jsonb[]
into a text[]
([{address: "A"}, {address: "B"}]
into ["A", "B"]
) to perform a simple @>
operation but we struggle to obtain any convincing result.
Our question is: Is such a constraint possible (if yes any help on the code would be greatly appreciated), and if not what would be the best way to implement such a system without having to create another table?