微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 为什么我的视图列可以为空?

我在 Windows上运行Postgresql 9.2.

我有一个现有的表,其中包含一些不可为空的列:

CREATE TABLE testtable
(
  bkid serial NOT NULL,bklabel character varying(128),lacid integer NOT NULL
}

在这个表上创建了一个视图:

CREATE OR REPLACE VIEW test AS
SELECT testtable.bkid,testtable.lacid
from public.testtable;

我很惊讶视图报告的@R_784_4045@ion_schema.columns对于所选列是否可以为YES?

select * from @R_784_4045@ion_schema.columns where table_name = 'test'

报告:

"MyDatabase";"public";"test";"bkid";1;"";"YES";"integer";;;32;2;0;;"";;"";"";"";"";"";"";"";"";"";"MyDatabase";"pg_catalog";"int4";"";"";"";;"1";"NO";"NO";"";"";"";"";"";"";"NEVER";"";"NO"
"MyDatabase";"public";"test";"lacid";2;"";"YES";"integer";;;32;2;0;;"";;"";"";"";"";"";"";"";"";"";"MyDatabase";"pg_catalog";"int4";"";"";"";;"2";"NO";"NO";"";"";"";"";"";"";"NEVER";"";"NO"

这是预期的行为吗?

我的问题是我正在尝试在实体框架数据模型中导入此类视图,但它失败了,因为所有列都标记为可为空.

编辑1:

以下查询

select attrelid,attname,attnotnull,pg_class.relname
from pg_attribute
inner join pg_class on attrelid = oid
where relname = 'test'

回报:

attrelid;attname;attnotnull;relname
271543;"bkid";f;"test"
271543;"lacid";f;"test"

正如所料,attnotnull是’假’.

正如@ Mike-Sherrill-Catcall建议的那样,我可以手动将它们设置为true:

update pg_attribute
set attnotnull = 't'
where attrelid = 271543

并且更改反映在@R_784_4045@ion_schema.columns中:

select * from @R_784_4045@ion_schema.columns where table_name = 'test'

输出是:

"MyDatabase";"public";"test";"bkid";1;"";"NO";"integer";;;32;2;0;;"";;"";"";"";"";"";"";"";"";"";"MyDatabase";"pg_catalog";"int4";"";"";"";;"1";"NO";"NO";"";"";"";"";"";"";"NEVER";"";"NO"
"MyDatabase";"public";"test";"lacid";2;"";"NO";"integer";;;32;2;0;;"";;"";"";"";"";"";"";"";"";"";"MyDatabase";"pg_catalog";"int4";"";"";"";;"2";"NO";"NO";"";"";"";"";"";"";"NEVER";"";"NO"

我将尝试导入Entity Framework数据模型中的视图.

编辑2:

正如猜测的那样,它可以工作,现在可以在实体框架数据模型中正确导入视图.
当然,我不会将所有列设置为不可为空,如上所示,只有那些在底层表中不可为空的列.

解决方法

我相信这是预期的行为,但我不会假装完全理解它.基表中的列似乎具有正确的属性.

这里的@R_784_4045@ion_schema底层的系统表中的列似乎是“attrnotnull”.我在pgsql-hackers listserv:cataloguing NOT NULL constraints中只看到一个引用“attnotnull”的线程.(但是该列可能在早期版本中有不同的名称.这可能值得研究.)

您可以使用此查询查看行为.您需要使用WHERE子句来准确获取您需要查看的内容.

select attrelid,pg_class.relname
from pg_attribute
inner join pg_class on attrelid = oid
where attname like 'something%'

在我的系统上,具有主键约束的列和具有NOT NULL约束的列将“attnotnull”设置为“t”.视图中的相同列将“attnotnull”设置为“f”.

如果你倾斜你的头并且恰到好处地眯着眼睛,那就是有道理的.视图中的列未声明为NOT NULL.只是基表中的列.

列pg_attribute.attnotnull是可更新的.您可以将其设置为TRUE,并且该更改似乎会反映在@R_784_4045@ion_schema视图中.虽然您可以直接将其设置为TRUE,但我认为我更愿意将其设置为与基表中的值匹配. (而且更舒服,我并不是说我在系统表中捣乱我都很舒服.)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐