PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Array-Eindeutigkeit mit einem eindeutigen PostgreSQL-Index erzwingen

Du kannst eine Funktion nicht direkt in einen Unique-Constraint setzen, aber in einen eindeutigen Index. Mit einer Sortierfunktion wie dieser:

create function sort_array(anyarray) returns anyarray as $$ select array_agg(distinct n order by n) from unnest($1) as t(n); $$ language sql immutable; 

Kannst du dann den Index bauen:

create table mytable ( interface integer[2] ); create unique index mytable_uniq on mytable (sort_array(interface)); 

Beobachte nun, was passiert:

=> insert into mytable (interface) values (array[11,23]); INSERT 0 1 => insert into mytable (interface) values (array[11,23]); ERROR: duplicate key value violates unique constraint "mytable_uniq" DETAIL: Key (sort_array(interface))=({11,23}) already exists. => insert into mytable (interface) values (array[23,11]); ERROR: duplicate key value violates unique constraint "mytable_uniq" DETAIL: Key (sort_array(interface))=({11,23}) already exists. => insert into mytable (interface) values (array[42,11]); INSERT 0 1 

Da der Index die Array-Reihenfolge zuerst normalisiert, werden [11,23] und [23,11] als Duplikate behandelt.