Search code examples
node.jspostgresqles6-promisepg-promisepromise.all

How pg-promise handles transactions with Promise.all()


In one of my projects, I want to execute 2 queries in parallel with pg-promise. I have these queries wrapped inside the transaction as added below. I am also using Promise.all() to make database calls in paralllel. I want to understand how this works internally, since transaction uses single db connection for bothe queries, does it mean the second query can only execute after first is completed as the txn is hold by the first query?


const {TransactionMode} = pgp.txMode;

// Create a reusable transaction mode (serializable + read-only + deferrable):
const mode = new TransactionMode({
    readOnly: true,
    deferrable: true
});

db.tx({mode}, t => {
    return Promise.all([t.any('SELECT * FROM table1'),t.any('SELECT * FROM table2')]);
})
.then(data => {
   // success;
})
.catch(error => {
   // error
});

Since the transaction acquires a single db connection to run all queries within the transaction , it would be interesting to know how it is done.


Solution

  • Since transaction uses single db connection for both queries, does it mean the second query can only execute after first is completed?

    Yes, exactly that. Postgres does not support parallel queries[1,2] on the same client connection, and certainly not within the same transaction.

    1: Query parallelization for single connection in Postgres
    2: The Postgres wire protocol does support pipelining, but the queries are still executed sequentially.


    Update from the author of pg-promise:

    If it is the best performance the OP seeks for 2 select queries, then the best way is to use multi:

    const [sel1, sel2] = await db.multi('SELECT * FROM table1; SELECT * FROM table2');
    

    i.e. you do not need a transaction for this at all.