Search code examples
node.jspostgresqlpg

Is it possible to have nested queries in Postgres pg module


Here is my code that tries to update a record in the db. But if the record is not there then I want to insert it. Is it OK to call client.query again? Or what's the best way to do it?

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);
                    }
                }
            }
        }
    });
});

Solution

  • It is perfectly OK as long as you call release after you're done with the client. From the docs:

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

    So, you could do this:

    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);
                        }
                    }
                }
            }
        });