简体   繁体   English

文本数组中的Postgres检查约束以确保值的有效性

[英]Postgres check constraint in text array for the validity of the values

I want to create something similar to this 我想创建类似的东西

CHECK (ALL(scopes) IN ('read', 'write', 'delete', 'update'))

scopes here is a field in the table which is text[] and I want to be sure that all the values in this array are one of the values above. 这里的scopes是表中的一个字段,它是text[] ,我想确保此数组中的所有值都是上述值之一。 Any opinions on this? 有什么意见吗? And also is it possible the get these values via SELECT from another table? 还有可能通过另一个表的SELECT获取这些值吗?

I have seen the below solution but I was curious if there is a simpler one. 我已经看到了以下解决方案,但我很好奇是否有一个更简单的解决方案。

Postgresql check constraint on all individual elements in array using function 使用函数对数组中所有单个元素的PostgreSQL检查约束

demo:db<>fiddle 演示:分贝<>小提琴

Using the <@ operator : 使用<@运算符

CHECK(scopes <@ ARRAY['read', 'write', 'delete', 'update'])

Not knowing your exact use case, but I would prefer a more normalized solution: Putting the four operations into a separate table which can be updated. 不知道确切的用例,但我希望有一个更规范的解决方案:将这四个操作放入一个单独的表中,该表可以更新。 Then you can work with foreign keys instead of the check contraint. 然后,您可以使用外键而不是检查约束。 If you have to update these four keywords you do not need to change the table DDL but only the values in the foreign table. 如果必须更新这四个关键字,则无需更改表DDL,而只需更改外部表中的值即可。

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

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