如何在PostgreSQL plpgsql函数中将JSON文本字段转换为UUID



我在RPC(远程过程调用)中使用以下函数,其中我尝试访问JSON对象的可选文本字段并将其转换为UUID:

CREATE OR REPLACE FUNCTION update_wcomponent (item wcomponents)
returns wcomponents
language plpgsql
security definer
SET search_path = public
as $$
DECLARE
existing wcomponents%ROWTYPE;
BEGIN
UPDATE wcomponents
SET
modified_at = now(),
title = item.json::json->'title',
type = item.json::json->'type',
-- Following line errors
attribute_id = (item.json::json->'attribute_wcomponent_id')::text::uuid,
json = item.json
WHERE id = item.id AND modified_at = item.modified_at;
-- Get the latest value
SELECT * INTO existing FROM wcomponents WHERE id = item.id;
return existing;
END;
$$;

但是,它在将文本强制转换为uid时出现错误:

invalid input syntax for type uuid: ""310edbfb-0af1-411b-9275-3fc87948c3a5""

我将它发布为以下结构的JSON对象:

{
"item": {
"base_id": 18,
"id": "27e46ec1-3d9a-412d-9807-8e08e515988d",
"json": {
"id": "27e46ec1-3d9a-412d-9807-8e08e515988d",
"title": "",
"type": "state_value",
"attribute_wcomponent_id": "310edbfb-0af1-411b-9275-3fc87948c3a5"
},
"modified_at": "2022-04-23T22:11:13.533Z"
}
}

attribute_wcomponent_id是可选的,所以当它是undefined时,它会很好地工作,因为它只是不存在。

我如何成功地将它从json文本属性转换为uid?似乎文本字符串被引用为"310edbfb-0af1-411b-9275-3fc87948c3a5"而不仅仅是310edbfb-0af1-411b-9275-3fc87948c3a5

您需要使用->>运算符将attribute_wcomponent_id值返回为text,而不是json。然后,在uuid之前转换为text类型是没有必要的,并且您不再有您所看到的双引号问题。

attribute_id = (item.json::json->>'attribute_wcomponent_id')::uuid

最新更新