Postgresql JSON Dynamic Expand&增量

时间:2018-04-11 09:24:00

标签: json postgresql plpgsql

大家好,我一直在尝试使用postgresql和python构建一个软件。

基本上我想要增量和/或动态扩展json

示例:首先该字段将为空:

#insert (toyota,honda,nissan)

{"toyota":1,
"honda":1,
"nissan":1}

#insert (toyota)

{"toyota":2,
"honda":1,
"nissan":1}

#insert (honda,mitsubitshi)

{"toyota":2,
"honda":2,
"nissan":1,
"mitsubitshi":1}

是的我知道可以通过首先通过python检索json来完成它,但我不这样做: 我对postgresql程序或触发器功能没有多少经验。

任何帮助都会被证实: - )

2 个答案:

答案 0 :(得分:0)

请检查以下功能。希望它符合您的要求!

CREATE FUNCTION sp_test(json)
RETURNS VOID AS
$BODY$
DECLARE
    var_sql varchar;
BEGIN 

    IF (EXISTS (
            SELECT json_object_keys($1)
            EXCEPT
            SELECT column_name FROM information_schema.columns WHERE table_schema = 'your schema' AND table_name = 'test_table'
            )) THEn
        RAISE EXCEPTION 'There is column(s) does not exists on table'; -- Checking structure.
    END IF;

    var_sql := 'Update test_table t SET ' || (SELECT string_agg(CONCAT(t.key, ' = (t.', t.key, ' + ', t.value,')'),', ')  FROM json_each($1) t);

    EXECUTE (var_sql);

END;
$BODY$
LANGUAGE plpgsql;

答案 1 :(得分:0)

Normalized tables would be more performant, however json solution may be quite comfortable using this function:

create or replace function add_cars(cars jsonb, variadic car text[])
returns jsonb language plpgsql as $$
declare
    new_car text;
begin
    foreach new_car in array car loop
        cars = cars || jsonb_build_object(new_car, coalesce(cars->>new_car, '0')::int+ 1);
    end loop;
    return cars;
end $$;

Find the full example in DbFiddle.

中提取链接