sidorares / node-mysql2

:zap: fast mysqljs/mysql compatible mysql driver for node.js
https://sidorares.github.io/node-mysql2/
MIT License
3.94k stars 593 forks source link

Transaction issue in my code. Please Help! #2598

Open GeorgeThm07 opened 4 weeks ago

GeorgeThm07 commented 4 weeks ago

I have issues in above code If an error returns from 'saveSpecialOrderV2' procedure, then we have to roll-back all changes, means 'saveAOrder' function inserted row must be roll-back and 'updateInventoryForNewOrder' update query also should be reverted. But when I run this code snippet it is not roll-backing. Is there any issue?

Also I am passing 'connection' to all functions, is it the right way. Will the functions uses same connection that we have begin transaction?

I have following code in Node.js with typescript

async startAnOrderByVendorV2(orderInfo: any): Promise<Result> {
  let connection = await pool().getConnection();
  try {
    await connection.beginTransaction();
    const updateInventoryResult = await this.updateInventoryForNewOrder(
      connection,
      orderInfo.orderGuid,
      orderInfo.loggedInUserId,
      UpdateInventoryType.CANCEL_ORDER
    );
    if (updateInventoryResult.status !== ErrorCodes.SUCCESS) {
      resultData.status = ErrorCodes.ERROR;
      await connection.rollback();
      return resultData;
    }
    const orderResult = await this.saveAOrder(connection, orderInfo);

    const customCutResult = await this.saveCustomCutItemsV2(
      connection,
      customCutInput
    );
    if (customCutResult.status !== ErrorCodes.SUCCESS) {
      resultData.status = ErrorCodes.ERROR;
      await connection.rollback();
      return resultData;
    }

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    resultData.status = ErrorCodes.ERROR;
  } finally {
    connection.release(); // Close the connection in the finally block
  }
  return resultData;
}

async updateInventoryForNewOrder(
  connection: any,
  orderGuid: string,
  loggedInUserId: number,
  type: number
): Promise<Result> {
  const orderResult = await connection.query(
    `CALL GetPickTicketItemsForInventoryCalc_sp(?,@p_ErrID);`,
    [orderGuid]
  ); // Call Get Stored procedure
  // Call Update Stored Procedure
}

async saveAOrder(connection: any, orderInfo: any): Promise<Result> {
  // Call Insert Stored procedure
}

async saveCustomCutItemsV2(
  connection: any,
  customCutInput: any
): Promise<Result> {
  // Call Insert Stored procedure
}