【问题标题】:not null constraint inside a jsonb array in postgrespostgres中jsonb数组内的非空约束
【发布时间】:2020-11-16 18:03:21
【问题描述】:

如何在 Postgres 中的 jsonb 列内没有空约束。

我创建了一个 Postgres 表,其中只有一个名为 id 的列,如下所示

create table tablea (
  id jsonb, 
  check 
  ((id->>'test1', id->>'test2') != (null, null))
);

调用者会将数据插入到表中,格式如下:-

[
    {
        "test1":"",
        "test2":"",
        "test3":""
    },
    {
        "test1":"",
        "test2":"",
        "test3":""
    }
]

我的目标是当调用者在 id 列中插入数据时,我希望键 test1 和 test2 不为空。怎么能做到这一点。上面解释了我的表创建逻辑。我正在尝试插入数据,例如

insert into tablea(id) values 
 ('[{"test1":null,"test2":"a","test3":""}]');

理想情况下,这个插入语句应该会引发错误,但它是在表中插入数据。谁能帮帮我

【问题讨论】:

    标签: arrays postgresql jsonb check-constraints


    【解决方案1】:

    您需要创建一个函数来遍历您的数组并验证每个数组元素。

    类似这样的:

    create or replace function validate_json(p_input jsonb)
      returns boolean
    as
    $$
      select not exists (select *
                          from jsonb_array_elements(p_input) as t(element)
                          where nullif(element ->> 'test1', '') is null
                             or nullif(element ->> 'test2', '') is null);
    $$
    language sql 
    stable;
    

    然后你可以用它来定义一个检查约束:

    您无法将null=<> 进行比较。为此,您需要使用 IS NOT NULL

    您似乎也想以与 null 相同的方式处理空字符串。

    create table tablea 
    (
      id jsonb,
      constraint check_json check ( validate_json(id) ) 
    );
    

    【讨论】:

    • 试过了,但查询插入到 tablea(id) 值 ('[{"test1":"abc","test2":"a","test3":""}]' );似乎失败了。它向我显示关系“tablea”的新行违反了检查约束“tablea_id_check
    • @Abhishek:啊,我没有看到你在那里插入数组。这使检查变得更加复杂。您使用的是哪个 Postgres 版本?
    • PostgreSQL 10.11 on x86_64-pc-linux-gnu,由 gcc (GCC) 4.9.3 编译,64 位
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2021-08-21
    • 1970-01-01
    • 2017-05-02
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多