首页 > 解决方案 > 是否允许使用基本类型的 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 运算符的类似语句。所有这些似乎都是不允许的。

我很讨厌不阅读文档,更糟糕的是当我费心阅读文档时理解文档......所以它不存在,还是我在错误的地方寻找是否允许这样做?为什么不允许?

标签: postgresql

解决方案


你错过了一个CHECKafter 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 在报告错误、提示等时将使用小写形式。


推荐阅读