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

时间:2018-08-30 19:57:50

标签: postgresql postgresql-9.5

给出下表:

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

1 个答案:

答案 0 :(得分: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