动态访问 PostgreSQL 函数中的列和转换数据类型

问题描述 投票:0回答:1

在 PostgreSQL 的自定义函数中,我可以访问

NEW
对象来检索特定列的值,例如:

NEW.description 
NEW.city

本质上,这是代码编写阶段的静态引用。但是是否可以动态地实现相同的目的,例如,类似于在 Map 结构中完成的方式:

NEW['description'] 
NEW['name']

换句话说,在代码编写阶段,我不知道要引用

NEW
中的哪一列,因为这是在函数执行过程中动态确定的。

同样的问题也适用于类型转换——我可以动态地将检索到的值转换为在函数执行期间确定的类型吗?例如,

INTEGER
BOOLEAN
等。也就是说,我在函数执行期间动态获取这些类型为
TEXT
,可能是从查询到另一个配置表,并且我想从
转换列值NEW
到这样的类型。

postgresql triggers user-defined-functions plpgsql
1个回答
0
投票

NEW
只是一个
record
,因此您可以使用
jsonb
 自动将其转换为 
to_jsonb(NEW)
并获得您想要的确切语法和行为:
db<>fiddle 的演示

create table test(
   a int generated by default as identity primary key
  ,b boolean
  ,c text);

create table debug_(payload jsonb,comment text,ts timestamp default clock_timestamp());

create function f_test_trigger()returns trigger as $f$
declare new_jsonb jsonb:=to_jsonb(new);
begin
  insert into debug_ select new_jsonb['c'],'just one of the columns';
  insert into debug_ select new_jsonb['x'],'this column does not exist';
  return new;
end $f$ language plpgsql;

create trigger test_trigger after insert on test
for each row execute function f_test_trigger();

insert into test(b,c)values(true,'2024-10-01');

table debug_;
有效负载 评论 ts
“2024-10-01” 仅其中一列 2025-01-15 16:13:26.302934
该栏目不存在 2025-01-15 16:13:26.30309

只要您正在处理的

text
值可以作为给定目标类型的输入,您的转换就会起作用。讨论一个具体的示例会更容易,因为其中任何一个的实用性可能会受到您稍后计划如何处理这些值的限制。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.