在 PostgreSQL 9.4 中推送或附加到 JSON 数组

gen*_*chm 5 postgresql array json postgresql-9.4

我有一个表,其中一个字段是 JSON 数组。我需要将接收到的 JSON 数组附加到该字段中而不覆盖现有值。

类似的东西:

CREATE OR REPLACE FUNCTION add_array(
    array_received json[])
  RETURNS void AS
$BODY$

    update table set _array_field = _array_field | array_received ...;

$BODY$
  LANGUAGE plpgsql VOLATILE;
Run Code Online (Sandbox Code Playgroud)

gen*_*chm 0

我是用plv8语言做的。对于 Windows 用户,从以下位置获取包

PostgreSQL 9.3

http://www.postgresonline.com/journal/archives/305-PostgreSQL-9.3-extension-treats-for-windows-users-plV8.html

PostgreSQL 9.4

http://www.postgresonline.com/journal/archives/341-PLV8-binaries-for-PostgreSQL-9.4-windows-both-32-bit-and-64-bit.html

PostgreSQL 9.5

http://www.postgresonline.com/journal/archives/360-PLV8-binaries-for-PostgreSQL-9.5-windows-both-32-bit-and-64-bit.html

PostgreSQL 9.6 Beta1

http://www.postgresonline.com/journal/archives/367-PLV8-binaries-for-PostgreSQL-9.6beta1-windows-both-32-bit-and-64-bit.html

然后运行这个命令

CREATE EXTENSION plv8
Run Code Online (Sandbox Code Playgroud)

这是函数

CREATE OR REPLACE FUNCTION jsonarray_append(row_id bigint, append json[]) RETURNS void AS $$

    var json_array = [];

    var json_result = plv8.execute('select json_array_field from sometable where _id=$1',[row_id]);

    if(json_result[0].json_array_field != null){
        for(var i=0; i < append.length; i++){
            json_result[0].json_array_field .push(append[i]);
        }
        json_array = json_result[0].json_array_field;
    }
    else{
        json_array = append;
    }


    plv8.execute('update sometable set json_array_field = $1 where _id=$2', [json_array, row_id]);

$$ LANGUAGE plv8 IMMUTABLE STRICT;
Run Code Online (Sandbox Code Playgroud)