我可以在SELECT
内运行(并返回结果)pg_notify
查询吗?
我的旧代码有效:
CREATE OR REPLACE FUNCTION outbound_notify_fn() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('outbound_notify', json_build_object('table', TG_TABLE_NAME, 'type', TG_OP, 'row', row_to_json(NEW))::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
当我添加SELECT
查询时:
CREATE OR REPLACE FUNCTION outbound_notify_fn() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('outbound_notify', json_build_object('table', TG_TABLE_NAME, 'type', TG_OP, 'row', row_to_json(NEW), 'mt_addresses', row_to_json(SELECT * FROM mt_addresses WHERE mt = NEW.mt))::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
我收到错误:
ERROR: syntax error at or near "SELECT"
LINE 3: ...w', row_to_json(NEW), 'mt_addresses', row_to_json(SELECT * F...
^
更新:我也尝试过:
CREATE OR REPLACE FUNCTION outbound_notify_fn() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('outbound_notify', json_build_object('table', TG_TABLE_NAME, 'type', TG_OP, 'row', row_to_json(NEW), 'mt_addresses', row_to_json(
$func$
BEGIN
RETURN QUERY
SELECT *
FROM mt_addresses
WHERE mt = NEW.mt
END
$func$
))::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
这至少可以在没有错误的情况下添加到数据库中。
当它在运行时触发时,会导致错误:
{ error: input of anonymous composite types is not implemented
at Connection.parseE (/redacted/node_modules/pg/lib/connection.js:572:11)
at Connection.parseMessage (/redacted/node_modules/pg/lib/connection.js:396:17)
at Socket.<anonymous> (/redacted/node_modules/pg/lib/connection.js:132:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:172:18)
at Socket.Readable.push (_stream_readable.js:130:10)
at TCP.onread (net.js:535:20)
name: 'error',
length: 466,
severity: 'ERROR',
code: '0A000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: '152',
internalQuery: 'SELECT pg_notify(\'outbound_notify\', json_build_object(\'table\', TG_TABLE_NAME, \'type\', TG_OP, \'row\', row_to_json(NEW), \'mt_addresses\', row_to_json(\n $func$\n BEGIN\n RETURN QUERY\n SELECT *\n FROM mt_addresses\n WHERE mt = NEW.mt\n END\n $func$\n ))::text)',
where: 'PL/pgSQL function outbound_notify_fn() line 3 at PERFORM',
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'rowtypes.c',
line: '103',
routine: 'record_in' }
答案 0 :(得分:1)
要实现这一目标,您必须使用整行引用,以便获得元组并为子查询添加一组额外的括号:
row_to_json((SELECT mt_addresses FROM mt_addresses WHERE mt = NEW.mt))