gpt4 book ai didi

postgresql - 为什么我的 View 的列可以为空?

转载 作者:行者123 更新时间:2023-11-29 11:25:24 25 4
gpt4 key购买 nike

我在 Windows 上运行 PostgreSQL 9.2。

我有一个包含一些不可空列的现有表:

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

我在此表上创建一个 View :

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

令我惊讶的是, View 报告的 information_schema.columns is_nullable 对于所选列为 YES?

select * from information_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"

这是预期的行为吗?

我的问题是,我试图在 Entity Framework 数据模型中导入此类 View ,但失败了,因为所有列都标记为可为空。

编辑 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

并且更改反射(reflect)在 information_schema.columns 中:

select * from information_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 数据模型中导入 View 。

编辑 2:

正如猜测的那样,它起作用了, View 现在已正确导入到 Entity Framework 数据模型中。当然,我不会像上面演示的那样将所有列都设置为不可为 null,只有基础表中的那些不可为 null。

最佳答案

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

此处信息模式下的系统表中的列似乎是“attrnotnull”。我在 pgsql-hackers listserv 上只看到一个线程引用“attnotnull”:cataloguing NOT NULL constraints . (但该列在早期版本中可能有不同的名称。这可能值得研究。)

您可以看到此查询的行为。您需要使用 WHERE 子句才能准确获得您需要查看的内容。

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

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

如果您倾斜头部并恰到好处地斜视,那有点是有道理的。 View 中的列 未声明为 NOT NULL。只是基表中的列。

列 pg_attribute.attnotnull 是可更新的。您可以将其设置为 TRUE,该更改似乎反射(reflect)在 information_schema View 中。虽然您可以直接将其设置为 TRUE,但我认为将其设置为匹配基表中的值会更舒服. (而且说更舒服,我并不是说我对在系统表中乱搞感到很舒服。)

关于postgresql - 为什么我的 View 的列可以为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17301323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com