"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Efficient implementation of multi-line insertion techniques using pg-promise

Efficient implementation of multi-line insertion techniques using pg-promise

Posted on 2025-04-16
Browse:400

How to Achieve Multi-Row Inserts with Efficiency Using pg-promise?

Multi-Row Inserts with pg-promise

Problem Statement:

How to efficiently insert multiple rows into a database using a single INSERT query in pg-promise?

Solution:

The preferred approach in pg-promise is to use the helpers namespace for high performance and flexibility.

const {ColumnSet, insert} = pgp.helpers;

const cs = new ColumnSet(['col_a', 'col_b'], {table: 'tmp'});
const values = [{col_a: 'a1', col_b: 'b1'}, {col_a: 'a2', col_b: 'b2'}];

const query = insert(values, cs);
// => INSERT INTO "tmp"("col_a","col_b") VALUES('a1','b1'),('a2','b2')

await db.none(query);

Additional Considerations:

  • The ColumnSet object should be created statically to cache formatting templates for optimal performance.
  • This multi-row insert is transactionless, meaning all or none of the values will be inserted.
  • SQL injection protection is provided by using the helpers namespace in conjunction with SQL Names.

Extras:

  • To obtain the ID of each new record, append RETURNING id to the query and execute it with db.many().
  • For inserting large datasets, consider utilizing the Data Imports feature.
  • You can encapsulate query generation within a function for enhanced error handling.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3