我要使postgresql主动发送通知,将指定数据表的指定一行的数据转换为json字符串,作为通知内容,将通知发给其他的进程,
通过查看官网,我发现有pg_notify和row_to_json这两个函数,pg_notify可以使postgresql主动发送通知给其他进程,row_to_json可以使一行转换为json。
我将这两个写在一起,有以下两个写法,但都抛出了错误
SELECT pg_notify('hello', (
select (select row_to_json(t) as json_obj from (select '1' as a) t) b
))
SELECT pg_notify('hello', (
select row_to_json(t.*) as json_obj from (select '1' as a) t
));
错误信息为
SQL 错误 [42883]: ERROR: function pg_notify(unknown, json) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
如果不用row_to_json,这样写没有问题:
SELECT pg_notify('hello', (select '1' as a) );
怎么解决该问题,怎么将pg_notify和row_to_json这两个函数写在一起不报错?
你需要将 json 类型转换为 text 类型:
SELECT pg_notify('hello', (
select row_to_json(t.*)::text as json_obj from (select '1' as a) t
));
参考:
pg_notify
类型转换