Add/Delete PostgreSQL 中 JSONB 列中每个对象的 属性

Add/Delete a property of every object inside JSONB column in PostgreSQL

TL;DR:我需要两个 UPDATE 脚本来将 (1) 变成 (2),反之亦然(add/delete color 属性 从每个JSONB 列中的对象)

(1)

id | name | squares

 1 |   s1 | [{"x": 5, "y": 5, "width": 10, "height": 10}, {"x": 0, "y": 0, "width": 20, "height": 20}]
 2 |   s2 | [{"x": 0, "y": 3, "width": 13, "height": 11}, {"x": 2, "y": 3, "width": 20, "height": 20}]

(2)

id | name | squares

 1 |   s1 | [{"x": 5, "y": 5, "width": 10, "height": 10, "color": "#FFFFFF"}, {"x": 0, "y": 0, "width": 20, "height": 20, "color": "#FFFFFF"}]
 2 |   s2 | [{"x": 0, "y": 3, "width": 13, "height": 11, "color": "#FFFFFF"}, {"x": 2, "y": 3, "width": 20, "height": 20, "color": "#FFFFFF"}]


我的架构

我有一个名为 scene 的 table 和 squares 列,其类型为 JSONB。在此列中,我存储如下值:[{"x": 5, "y": 5, "width": 10, "height": 10}, {"x": 0, "y": 0, "width": 20, "height": 20}].

我想做什么

我现在想将 color 添加到我的方块,这意味着还要向现有生产数据库中每个 scene 记录的每个方块添加一些默认颜色(如 "#FFFFFF") ,所以我需要迁移。

问题

我需要编写一个迁移,将 "color": "#FFFFFF" 添加到生产数据库中的每个方块。使用关系模式就像为前向迁移编写 ALTER TABLE square ADD color... 和为回滚迁移编写 ALTER TABLE square DROP COLUMN color... 一样简单,但由于 square 不是单独的 table,它是一个类似数组的 JSONB,我需要两个 UPDATE 查询 scene table.

(1) 添加 color:

update scene set squares = (select array_to_json(array_agg(jsonb_insert(v.value, '{color}', '"#FFFFFF"'))) 
        from jsonb_array_elements(squares) v);
select * from scene;

参见 demo

(2) 删除 color:

update scene set squares = (select array_to_json(array_agg(v.value - 'color')) 
    from jsonb_array_elements(squares) v);
select * from scene;

参见 demo