Search code examples
postgresqlpg-promise

Pgpromise Queries are exectuting without waiting on batch


I'm working with pgpromise to batch my insert queries however they are executed without waiting on the batch transaction batch.

    db.tx((t) => {
      const insertQueries = [];

      queryInfo.forEach((info) => {
        insertQueries.push(
          t.none(
            `INSERT INTO test 
            (name) 
            VALUES  
            ('test')`,
            []
          )
        );
      });
      // return t.batch(insertQueries);
    });

Note that t.batch is commented out. I would therefore (possibly erronously) expect for the queries to not get executed. However the database is showing the inserted rows. If this is not the case, how can I ensure that all the transaction are actually executed how I expect them to?

screenshot of test table results


Solution

  • batch is a legacy API, created before await/async syntax became widely supported.

    await db.tx(async t => {
        for (let a in info) {
            await t.none('INSERT INTO test(name) VALUES($1)', ['test']);
        }
    });
    

    I would therefore (possibly erronously) expect for the queries to not get executed

    You do execute queries by calling t.one. Method batch simply settles all the promises returned from it. If you want to stop producing queries when one of them errors, the above async/await approach is better.