Ale*_*Gad 5 postgresql node.js node-postgres
我有一个PostgresQL函数返回多个结果集.我可以在.net中提取这些结果集而没有问题(所以我知道我的函数正常工作),但我在使用node-postgres时遇到了麻烦.
结果对象返回一个包含7个项目的数组,这些项目与返回的数据集数量相匹配.
在Node中,7行中的每一行都只包含一个字符串<unnamed portal 1>.
connection.query("BEGIN");
connection.query({text: "SELECT getoperationaldatasetmodel($1)", values : [clientid]}, function(err, results) {
if (err) {
connection.query("COMMIT");
self.pool.release(connection);
callback(err);
}
else {
var opsDataset = null;
var rows = results.rows;
// this returns 7 rows but the rows do not contain data but rather the name of the dataset.
}
Run Code Online (Sandbox Code Playgroud)
那么:node-postgres是否支持多个结果集,如果是,那么有关如何提取的任何建议?
编辑:这是我用node-postgres的代码,如果其他人需要将来使用它.
// must wrap in a transaction otherwise won't be able to see the multiple sets.
connection.query("BEGIN");
connection.query({text: "SELECT myfunction($1)", values : [clientid]}, function(err, results) {
if (err) {
// handle error here
connection.query("COMMIT;");
}
else {
connection.query('FETCH ALL FROM "<unnamed portal 1>"', function(err, r1) {
// r1.rows will contain the data for the first refcursor
});
connection.query('FETCH ALL FROM "<unnamed portal 2>"', function(err, r2) {
// r2.rows will contain the data for the second refcursor
});
// remember to handle the closure of the transaction
});
Run Code Online (Sandbox Code Playgroud)
更新:有关如何获取和管理refcursors的说明,请参阅此优秀教程.
由于node-postgres无法识别您作为结果集句柄返回的refcursors,因此它似乎不支持PostgreSQL的多个结果集.这很公平,因为PostgreSQL也不支持多个结果集,它们只是用refcursors模拟.
您可以FETCH从refcursor通过SQL级的游标命令SQL级光标指令,但它的文档是苦不堪言.您不需要使用PL/PgSQL游标处理来执行此操作.只是:
FETCH ALL FROM "<unnamed portal 1>";
Run Code Online (Sandbox Code Playgroud)
请注意双引号,这很重要.从您的函数中返回的refcursor名称<unnamed portal 1>.
另请注意,除非创建了游标,否则创建refcursor的事务仍必须处于打开状态WITH HOLD.HOLD当事务提交或回滚时,非游标将关闭.
例如,给定虚拟refcursor-returns函数:
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';
Run Code Online (Sandbox Code Playgroud)
...返回一组游标,您可以通过传递门户名称来获得结果FETCH,例如:
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=#
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2215 次 |
| 最近记录: |