does node-postgres support multiple resultsets

吃可爱长大的小学妹 提交于 2019-12-05 10:30:32

UPDATE: See this excellent tutorial for an explanation of how to fetch and manage refcursors.


Since node-postgres isn't recognising the refcursors you're returning as result set handles, it seems likely that it doesn't support multiple result sets from PostgreSQL. That's fair enough as PostgreSQL doesn't really support multiple result sets either, they're just emulated with refcursors.

You can FETCH from a refcursor via SQL-level cursor commands SQL-level cursor commands, though the documentation for it is miserable. You don't need to use PL/PgSQL cursor handling to do it. Just:

FETCH ALL FROM "<unnamed portal 1>";

Note the double quotes, which are important. Subtitute the refcursor name returned from your function for <unnamed portal 1>.

Note also that the transaction that created the refcursor must still be open unless the cursor was created WITH HOLD. Non-HOLD cursors are closed when the transaction commits or rolls back.

For example, given the dummy refcursor-returning function:

CREATE OR REPLACE FUNCTION dummy_cursor_returning_fn() RETURNS SETOF refcursor AS $$
DECLARE
    curs1 refcursor;
    curs2 refcursor;
BEGIN
    OPEN curs1 FOR SELECT generate_series(1,4);
    OPEN curs2 FOR SELECT generate_series(5,8);
    RETURN NEXT curs1;
    RETURN NEXT curs2;
    RETURN;
END;
$$ LANGUAGE 'plpgsql';

... which returns a set of cursors, you can get the results by passing the portal names to FETCH, eg:

regress=# BEGIN;
BEGIN
regress=# SELECT dummy_cursor_returning_fn();
 dummy_cursor_returning_fn 
---------------------------
 <unnamed portal 7>
 <unnamed portal 8>
(2 rows)

regress=# FETCH ALL FROM "<unnamed portal 7>";
 generate_series 
-----------------
               1
               2
               3
               4
(4 rows)

regress=# FETCH ALL FROM "<unnamed portal 8>";
 generate_series 
-----------------
               5
               6
               7
               8
(4 rows)

regress=# 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!