Postgres JSONb更新(在Json数组中),当找不到匹配项或null参数时删除数组中的所有元素?

问题描述 投票:1回答:1

鉴于下表:

create table documents(docu_id text, attachments jsonb);
insert into documents values
('001', 
    '[
      {"name": "uno","id":"1"},
      { "name": "dos","id":"2"},   
      { "name": "tres","id":"3"}
    ]'
),
('002', 
    '[
      { "name": "eins","id":"1"  },
      { "name": "zwei", "id":"2" }
    ]'
);
select * from documents;

enter image description here

我有这个postgres查询,当我想用​​现有ID删除时工作正常。但是,当我使用一个不存在的id时,jsonarray附件中的所有项都被删除,如何避免这种行为?

UPDATE documents
   SET attachments = attachments #- /* #- Delete field/element with specified path */
   (
       '{' || /* Concat */ 
            (
            SELECT i
              FROM generate_series(0, jsonb_array_length(attachments) - 1) AS i
             WHERE (attachments->i->'id' = '"x"') /* <=====BUG origin */
           ) 
       || '}'
   )::text[] /* cast as text */
  where docu_id = '002';

与工作数据的示例链接:http://rextester.com/VZYSG74184

postgresql postgresql-9.5
1个回答
1
投票

这是两个可以解释问题来源的简单查询:

select '{' || (select 1 where false) || '}';
┌──────────┐
│ ?column? │
├──────────┤
│ NULL     │
└──────────┘

with t(x) as (values('[1,2,3]'::jsonb))
select *, x #- '{1}', x #- '{}', x #- null from t;
┌───────────┬──────────┬───────────┬──────────┐
│     x     │ ?column? │ ?column?  │ ?column? │
├───────────┼──────────┼───────────┼──────────┤
│ [1, 2, 3] │ [1, 3]   │ [1, 2, 3] │ NULL     │
└───────────┴──────────┴───────────┴──────────┘

如上所示,当使用#-运算符给出的参数为null时,它会从json数组中删除所有内容。

通过以更方便的方式构造数组来修复很简单:

UPDATE documents
   SET attachments = attachments #- /* #- Delete field/element with specified path */
   array(
            SELECT i
              FROM generate_series(0, jsonb_array_length(attachments) - 1) AS i
             WHERE (attachments->i->'id' = '"x"')
   )::text[] /* cast as text */
  where docu_id = '002';

测试链接:http://rextester.com/IIAS33106

© www.soinside.com 2019 - 2024. All rights reserved.