是否可以在 Postgres pg 模块中进行嵌套查询

Is it possible to have nested queries in Postgres pg module

这是我尝试更新数据库中记录的代码。 但如果记录不存在,那么我想插入它。 可以再次调用 client.query 吗?或者最好的方法是什么?

const {Pool} = require('pg');
const pool   = new Pool(POSTGRES_CONFIG);

pool.connect((err, client, release) => {
    if (err) {
        return console.error('Error acquiring client', err.stack)
    }

    ………

    client.query(query, queryValues, (err, result) => {
        release();

        if(result.rowCount<=0){
            //**** CAN I CALL IT AGAIN WITH OTHER PARAMETERS TO INSERT? ****
            client.query(....... => {
                release();

                if (err) {
                    if(err.code === POSTGRES_ERRORS.UNIQUE_VIOLATION){
                        return console.error('KEY ALREADY EXISTS');
                    } else {
                        return console.error('query error', err);
                    }
                }
            }
        }
    });
});

客户端处理完之后再调用release就完全可以了。来自文档:

You must call the releaseCallback or client.release (which points to the releaseCallback) when you are finished with a client.

所以,你可以这样做:

client.query(query, queryValues, (err, result) => {
        // don't release just yet 

        if(result.rowCount<=0){
            //**** CAN I CALL IT AGAIN WITH OTHER PARAMETERS TO INSERT? ****
            client.query(....... => {
                release(); // now you're done with the client so you can release it

                if (err) {
                    if(err.code === POSTGRES_ERRORS.UNIQUE_VIOLATION){
                        return console.error('KEY ALREADY EXISTS');
                    } else {
                        return console.error('query error', err);
                    }
                }
            }
        }
    });