Postgres唯一的枚举SET?

时间:2019-08-29 11:34:23

标签: postgresql typeorm

是否可以在PostgreSQL中创建一组唯一的枚举?

enter image description here

notifications是一组Notification枚举。我希望此集合是唯一的,假设您的集合中不能有两次{Notification.PUSH, Notification.PUSH}

是否可以设置此数据类型?

2 个答案:

答案 0 :(得分:1)

是的,这可以通过使用函数的检查约束来实现:

CREATE TABLE arr(ia int[]);

CREATE FUNCTION check_array_unique(anyarray) RETURNS boolean
   LANGUAGE sql IMMUTABLE AS
'SELECT (SELECT count(DISTINCT x) FROM unnest($1) AS x(x)) = cardinality($1)';

ALTER TABLE arr ADD CHECK (check_array_unique(ia));

INSERT INTO arr VALUES (ARRAY[1,2,3,4]);
INSERT 0 1

INSERT INTO arr VALUES (ARRAY[1,2,3,4,1]);
ERROR:  new row for relation "arr" violates check constraint "arr_ia_check"
DETAIL:  Failing row contains ({1,2,3,4,1}).

答案 1 :(得分:1)

您可以在检查约束中使用该功能:

create or replace function array_is_unique(arr anyarray)
returns boolean language sql immutable as
$$
    select count(distinct a) = array_length(arr, 1)
    from unnest(arr) a 
$$;

用法示例:

create type notification as enum ('a', 'b', 'c');

create table my_table(
    id serial primary key,
    notifications notification[] check(array_is_unique(notifications))
    );
  

是否可以设置此数据类型?

您可以创建a domain,例如:

create domain notifications as notification[] check(array_is_unique(value));

drop table if exists my_table;
create table my_table(
    id serial primary key,
    notifications notifications
    );

insert into my_table (notifications) 
values ('{a, a}');

ERROR:  value for domain notifications violates check constraint "notifications_check"