我正在创建以下架构:
create domain text_notnull as text not null;
create type foo as (
t1 text_notnull
);
create table test (
data foo
);
insert into test(data) values (ROW('aaa'));
/* Inserted! */
alter type foo add attribute t2 text_not_null;
/* Ok! I expected this to fail because now
there is a row in 'test' that is violating this constrain */
insert into test(data) values (ROW('bbb'));
/* Fails, as expected */
insert into test(data) values (ROW('bbb', '2'));
/* Works, as expected */
如果我在哪里做
alter table test add column x text_notnull
就会失败。那么为什么向列中的类型添加无效属性是确定的,而将其添加为列是不确定的呢?有没有办法强迫这种检查发生?
最佳答案
我想用alter type
-你只需要更新目录。未验证现有值。我认为你不能强迫它本身。但可以使用逻辑检查不正确的候选项,即如果行为空,则其整个值为空。smth类:
select * from test where not (data) is not null
https://www.db-fiddle.com/f/23WnBQWWsyReXkboTqyG48/1
也来自https://www.postgresql.org/docs/current/static/sql-createdomain.html
在转换时检查域约束,特别是不为空的域约束
域类型的值。对于
名义上的域类型读为空,尽管存在这样的
约束。