Postgres 检查空的 JSONB 字段

Postgres Check for Empty JSONB Fields

如果 Postgres function.Here 中有一个带有键但没有值的 JSON 对象,我希望能够 ignore 或防止 INSERT 发生是一个人为的小例子:

DROP TABLE IF EXISTS mytable;
create table mytable(
a text,
b text
);

CREATE OR REPLACE FUNCTION insert_to_table(
somedata JSONB
)
RETURNS VOID AS $$
BEGIN 
insert into mytable (a, b) select a,b from jsonb_populate_recordset(null::mytable, ::jsonb);
END;
$$ LANGUAGE plpgsql;

select insert_to_table('[{"a":1,"b":2},{"a":3,"b":4}, {"a":null, "b": null}, {"a": null, "b": "some data"}]');

这将插入 4 条记录,第一行是 1,2,下一行是 3,4。第三行是"", "",第四行是"", some data

在这种情况下,第 1、2 和 4 行有效。我想忽略 3 并阻止它被插入。

我不想要空白行,我的 data/table 将比列出的内容大得多(table 中大约有 20 个字段,而 key/value 中有 20 个 key/value 对JSON).

很可能我需要遍历数组并挑选出 JSON 对象,其中所有键都为空,而不仅仅是 1 或 2。

我该怎么做?

在 Postgres 中,您可以在查询中使用 table(别名)的名称来引用完整的行,并将其与 NULL 进行比较。如果 all 列为空,则记录被视为空。所以你可以这样做:

create or replace function insert_to_table(somedata jsonb)
returns void as $$
begin 
    insert into mytable (a, b) 
    select a, b 
    from jsonb_populate_recordset(null::mytable, somedata) as t
    where not (t is null);
end;
$$ language plpgsql;

请注意 where t is not nullwhere not (t is null) 不同。无论列数或其数据类型如何,这都有效。

可视化逻辑。以下:

select a,b,
       not (t is null) as "not (t is null)", 
       t is null as "t is null", 
       t is not null as "t is not null"
from jsonb_populate_recordset(null::mytable, 
       '[{"a":1,"b":2},
         {"a":3,"b":4}, 
         {"a":null, "b": null}, 
         {"a": null, "b": "some data"}]'::jsonb) as t(a,b)

returns:

a | b         | not (t is null) | t is null | t is not null
--+-----------+-----------------+-----------+--------------
1 | 2         | true            | false     | true         
3 | 4         | true            | false     | true         
  |           | false           | true      | false        
  | some data | true            | false     | false        

不相关:

强制转换 ::jsonb 没有用,因为您已经声明了该类型的参数。