繁体   English   中英

从postgres db中获取节点js中的多个Refcursor(使用pg-promise)

[英]Fetch multiple Refcursor in node js from postgres db (using pg-promise)

我需要从Nodejs中的pg函数获取多个游标。

我已经尝试了以下链接中所述的PG中的两种函数编写方法: http : //www.sqlines.com/postgresql/how-to/return_result_set_from_stored_procedure

在PG管理员|||中 查询工具我可以通过给出名称来查看多个游标的输出。 我想从节点js应用程序中获取相同的内容,我正在使用“ pg-promise”。

选项1

 db.func('get_data',
    [
        name,
        key
    ])
    .then(dbResult => {
        console.log(" RES 1" + dbResult);               
    }).catch(error => {
        console.log(error);
        throw error;
    });

选项2

var retCursor1 = {};
var retCursor2 = {};
db.func('get_data',
    [
        name,
        key,
        retCursor1,
        retCursor2,
    ])
    .then(dbResult => {
        console.log(" RES 1" + dbResult);               
        console.log(" RES 2" + retCursor1);               
        console.log(" RES 3" + retCursor2);               
    }).catch(error => {
        console.log(error);
        throw error;
    });

get_data PG Fucntion将返回2个refCursors。

但是不走运,有人可以建议在Node js中获取多个游标的最佳方法是什么。

来自pg-promise的作者。


不幸的是,底层驱动程序node-postgres不支持FETCH查询。

他们建议为此使用一个单独的模块-node-pg-cursor ,我尝试了它,但是无法使其适合您的情况,请参阅我打开的问题: https : //github.com/brianc/node-pg -光标/问题/ 34

我的建议是通过不返回任何函数游标或至少不希望直接从Node.js调用的游标来尝试完全避免这种游标。

如果您考虑性能和效率,那么最好的方法是通过pg-promise v7.0.0中添加的方法multi ,在单个命令中执行多个SELECT查询:

db.multi('SELECT * FROM users WHERE name LIKE ${user.name};' +
    'SELECT * FROM products WHERE price BETWEEN ${price.min} AND ${price.max}', {
    user: {name: 'John'},
    price: {min: 1, max: 5}
})
    .then(data => {
        // data[0] = users
        // data[1] = products
    })
    .catch(error => {

    });

它与使用两个游标的功能一样快,并且更简单。

db
.tx(t => {
  return t.batch([
            t.func('get_data', [name, key, retCursor1, retCursor2]),
            t.any('FETCH ALL IN $1', retCursor1),
            t.any('FETCH ALL IN $1', retCursor2)
        ]);
    })
.then(data => {
  console.log('DATA:', data); 
})
.catch(error => {
  console.log('ERROR:', error); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM