如何使用 pg-promise 一次从多个查询中获取结果?

How to get results from multiple queries at once with pg-promise?

目前我有以下代码获取两次查询的结果

dbro.many("SELECT geoname_id, country_name FROM paises WHERE locale_code= LIMIT 10",data.lang)
   .then(function(countriesData){
      data.countries=countriesData;
      dbro.many("SELECT * FROM categorias")
       .then(function(categoriesData){
         data.categories=(categoriesData)
         console.log(data);
         res.render('layout', data);
         res.end();
      })
       .catch(function(err){
        console.log("error while fetching categories data");
      })
    })
    .catch(function(err){
      console.log("error while fetching countries data",err);
    });

不知怎的,我觉得这是不对的。如果我需要在返回回调之前获取许多查询的结果怎么办?几个 then/catch 的嵌套变得可怕。 objective 是在呈现页面之前准备好所有数据(在 Express 中)

pg-promise documentation has plenty of examples 如何执行多个查询。

初始化

const pgp = require('pg-promise')(/* initialization options */);
const db = pgp('postgres://username:password@host:port/database');

当查询相互依赖时,我们应该使用任务:

db.task('get-user-events', async t => {
        const user = await t.one('select * from users where id = ', 123);
        return t.any('select * from events where login = ', user.name);
})
    .then(data => {
        // data = result from the last query;
    })
    .catch(error => {
        // error
    });

当查询之间没有依赖关系时:

db.task('get-everything', async t => {
    const users = await t.any('select * from users');
    const count = await t.one('select count(*) from events', [], a => +a.count);
    return {users, count};
})
    .then({users, count} => {

    })
    .catch(error => {
        // error
    });

并且当查询更改数据时,我们应该替换task with tx进行交易。

请注意,我用 “应该” 强调了每个语句,因为您可以执行任务或事务之外的所有内容,但由于数据库连接的方式,不建议这样做管理。

当您需要对每个 HTTP 请求执行单个查询时,您应该 只对根协议(db 对象)执行查询。一次多个查询 应该 总是在 tasks/transactions.

内执行

另见Chaining Queries,其要点在底部:

If you do not follow the advised approach, your application will perform better under a small load, due to more connections allocated in parallel, but under a heavy load it will quickly deplete the connection pool, crippling performance and scalability of your application.

更新

pg-promise v7.0.0 开始,我们可以在一条命令中从多个独立查询中提取结果,这比以前的所有解决方案都高效得多:

const {users, count} = await db.multi('SELECT * FROM users;SELECT count(*) FROM events');

库实现 helpers.concat 来格式化和连接多个查询。

另请参阅方法:multi and multiResult