为什么在 PostgreSQL 枚举类型数组中允许空值? [英] Why in PostgreSQL enum type array null values allowed?

查看:32
本文介绍了为什么在 PostgreSQL 枚举类型数组中允许空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PostgreSQL 数据库,并使用枚举类型的数组作为列之一.

I am working with a PostgreSQL DB, and use an array of an enum type as one of the columns.

CREATE TYPE my_type_enum AS ENUM ('value1', 'value2', 'value3');
ALTER TABLE "my_table" ADD COLUMN IF NOT EXISTS "my_column" my_type_enum ARRAY;

enum 允许我只添加它包含的有效值,但我也可以向它添加 null 元素.

The enum gives me to add only valid values that it contains, but I also can add a null elements to it.

所以,为了防止将 null 元素保存到 DB,我在应用程序中添加了一个过滤器,但我想知道 PostgreSQL 中是否有定义不允许添加 nullarray 的元素?

So, to prevent saving null elements to DB, I added a filter in the app, but I wonder if there is a definition in PostgreSQL not to allow adding null elements to array?

附言我看到这里建议添加函数作为列定义的一部分,但这不是我问的.

P.S. I saw here suggestion to add function as part of the column definition, but this is not what I asked.

推荐答案

您可以添加检查约束以防止元素为 NULL 值.

You can add a check constraint to prevent elements with NULL values.

alter table my_table
  add constraint no_null_element 
  check (cardinality(my_column) = cardinality(array_remove(my_column, null)));


更简洁的解决方案是将外键列定义为 not null

这篇关于为什么在 PostgreSQL 枚举类型数组中允许空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆