4

I'm trying to sync two databases and for each type of operation I want it to be a whole transaction, I've setup something rather basic but I'm unsure if this will actually run and rollback as a single transaction. I've been looking through the documentation but the one for NodeJS is rather scarce.

My example code:

 const tx = session.beginTransaction();

  SyncElements(doc.lists.elements, existingElements, tx);

  tx.commit()
    .then(res => {
      console.log('SYNC ELEMENTS SUCCESSFUL, RESULT:', res);
    })
    .catch(err => {
      console.error('COULD NOT SYNC ELEMENTS TRANSACTION FAILURE: ', err);
    });

Now within that SyncElements() function which gets the tx object, it will call tx.run( dozens of times.

My question is, those dozens of tx.run calls, will they all be considered part of the main transaction that I'm commiting above? and if any of those calls fails, will all the changes made using that tx. object be reversed?

EDIT: my second attempt:

Each of my runs returns the promise as such:

  deleteElements.forEach(el => {
    allOperations.push(deleteElement(el, tx));
  });

and then


const deleteElement = (
  el: Element,
  tx: neo4j.default.Transaction,
): Promise<neo4j.default.StatementResult> => {
  return tx.run(`MATCH... STATEMENT`);
};

I'm storing them in an array and then running:

try {
    await Promise.all(allOperations);
    await tx.commit();
    return;
  } catch (err) {
    await tx.rollback();
    console.error('COULD NOT SYNC ELEMENTS TRANSACTION FAILURE: ', err);
  }

I think this is more on par with the documentation? I guess in my first attempt I didn't really have any way to rollback the transaction so just assumbed it will not commit if there's an error?

SebastianG
  • 8,563
  • 8
  • 47
  • 111
  • I'm not familiar with manual hanlding of transactions via `session.beginTransaction()`, but the documentation on [`session.writeTransaction()`](https://neo4j.com/docs/api/javascript-driver/4.4/class/lib6/session.js~Session.html#instance-method-writeTransaction) is a lot clearer and it auto commits or rollbacks automatically. – zirkelc Jul 13 '22 at 12:16

0 Answers0