postgresql - 是否允许使用基本类型的 json(或 jsonb)“创建域”?
问题描述
我有一个自定义类型,其代码类似于以下(为简洁起见缩短):
create domain massFraction as jsonb (
value->'h' > 0 and value->'h' is not null
);
运行它会引发以下错误:
ERROR: type modifier is not allowed for type "jsonb"
该文档没有提到 json 是域的不允许的基本类型。
https://www.postgresql.org/docs/12/sql-createdomain.html
我还认为这可能是约束的“非空”部分,文档提到它是“棘手的”。此外,我尝试过没有任何 json 运算符的类似语句。所有这些似乎都是不允许的。
我很讨厌不阅读文档,更糟糕的是当我费心阅读文档时理解文档......所以它不存在,还是我在错误的地方寻找是否允许这样做?为什么不允许?
解决方案
你错过了一个CHECK
after jsonb
:
create domain massFraction as jsonb check (
value->'h' > 0 and value->'h' is not null
);
这导致另一个错误:
ERROR: 42883: operator does not exist: jsonb > integer
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
我相信你想要的是
CREATE DOMAIN massFraction AS jsonb CHECK (
CASE jsonb_typeof(value->'h')
-- only cast when it is safe to do so
-- note: this will reject numeric values stored as text in the json object (eg '{"h": "1"}')
WHEN 'number' THEN (value->>'h')::integer > 0
ELSE false
END
)
您收到的错误来自您输入的内容被解析为
CREATE DOMAIN massFraction AS jsonb(<modifier>) -- like in varchar(10)
顺便说一句,我建议不要在 postgresql 中使用 camelCase,massFraction
这与(除非引用)相同,massfraction
并且 postgresql 在报告错误、提示等时将使用小写形式。
推荐阅读
- jquery-mobile - 包含 JQuery Mobile 文件时,click() 不会触发
- spring-boot - LoadBalanced WebClient 与 Eureka WebClient 一起启用
- flutter - “无法找到 Android SDK。”在 Windows 10 上运行颤振医生时
- scrapy - 处理多个链接时,scrapy-splash 并不总是成功
- php - 运行 composer 时出错需要 pusher/pusher-php-server
- python - 将文本文件中的键和值添加到字典
- reactjs - 部署后反应不显示图像
- groovy - 在 Jmeter Groovy 中读取请求 Cokkie
- python - 如何使用外键/多键编写测试 - Django
- reactjs - 使用 FormData 从 React 应用程序上传 Sailsjs 文件不起作用