运行 pg_notify 内的 Postgres SELECT

Running a Postgres SELECT within a pg_notify

我可以在 pg_notify 中 运行(和 return 结果)一个 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))::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' }

要实现这一点,您必须使用 整行引用 以便您获得一个元组并为子查询添加一组额外的括号:

row_to_json((SELECT mt_addresses FROM mt_addresses WHERE mt = NEW.mt))