Skip to content

Instantly share code, notes, and snippets.

@chandelabhishek
Last active January 19, 2025 14:31
Show Gist options
  • Save chandelabhishek/0e422661aa050eb16ce12e4750d22977 to your computer and use it in GitHub Desktop.
Save chandelabhishek/0e422661aa050eb16ce12e4750d22977 to your computer and use it in GitHub Desktop.
batch queries and run it in a single transaction - postgres, nodejs, knex
const pgp = require('pg-promise')();
pgp.pg.types.setTypeParser(20, parseInt);
function AggregateQuery(queryBuilders) {
// pass in a knex transaction
async function run(transaction) {
const queries = queryBuilders.map(qb => {
const { sql: query, bindings: values } = qb.toSQL().toNative();
return { query, values };
});
const pgpQuery = pgp.helpers.concat(queries);
const results = await transaction.raw(pgpQuery);
if (!results) return [];
if (results.constructor.name === 'Result' && !results.command) return [];
return results.constructor.name === 'Result' ? [results] : results;
}
return {
run
};
}
// usage
const queries = [
'Select * from TableA',
'update tableB set cola = 0 where colb = 1',
'delete from tableC where colC = 1'
Knex("TableA").where({id: 1}).delete()
];
AggregateQuery(queries).run().then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment