简体   繁体   English

Postgres唯一的枚举SET?

[英]Postgres unique SET of enums?

Is there a way to create an unique set of enums in PostgreSQL? 有没有办法在PostgreSQL中创建一组唯一的枚举?

在此处输入图片说明

notifications is a Set of Notification enum. notifications是一组Notification枚举。 I want this Set to be unique, let's say you cannot have {Notification.PUSH, Notification.PUSH} twice in your set. 我希望此集合具有唯一性,假设您的集合中不能两次包含{Notification.PUSH, Notification.PUSH}

Is there a way to set this data type? 有没有办法设置此数据类型?

Yes, that is possible with a check constraint that uses a function: 是的,这可以通过使用函数的检查约束来实现:

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}).

You can use the function in a check constraint: 您可以在检查约束中使用该函数:

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 
$$;

Example usage: 用法示例:

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

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

Is there a way to set this data type? 有没有办法设置此数据类型?

You can create a domain , example: 您可以创建一个域 ,例如:

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"  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM