3

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

1 Answer 1

3

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);
                    }
                }
            }
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect.. Thank you Daniel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.