我正在尝试编写 Postgres 触发器以在插入或更新新行之前取消嵌套数组字段。例如
SELECT
unnest(something)
FROM NEW
Run Code Online (Sandbox Code Playgroud)
但是,这似乎会导致错误:
关系“新”不存在
如何使用触发器函数内的 NEW 行,以允许我取消嵌套数组字段以进行进一步处理?
创建表语句
以下是表结构的示例:
CREATE TABLE parent_table (
id uuid NOT NULL,
jsonb_array_field jsonb[] NOT NULL DEFAULT '{}'::jsonb[],
CONSTRAINT "parent_table_pkey" PRIMARY KEY (id),
);
Run Code Online (Sandbox Code Playgroud)
CREATE TABLE many_to_one_table (
id serial primary key,
parent_table_id uuid references parent_table(id),
subfield_a text,
subfield_a text
);
Run Code Online (Sandbox Code Playgroud)
触发功能
下面是 TRIGGER 函数的本质:
CREATE OR REPLACE FUNCTION unnest_and_normalize_json() RETURNS TRIGGER AS
$body$
begin
if NEW.jsonb_array_field is null then
raise exception 'jsonb_array_field is null';
else
insert into
many_to_one_table(subfield_a, subfield_b) …Run Code Online (Sandbox Code Playgroud)