进行交易时,为什么/为什么不创建新请求?

时间:2019-04-05 15:07:05

标签: node.js node-mssql

我有一个函数,该函数接受一个对象,该对象的某些属性是数组,并作为事务进行一系列sql查询:

createOrder_transaction: async (order, orderItems, orderPayments) => {           

        const transaction = await scSqlPool.transaction();
        await transaction.begin();

        try {
            const request = transaction.request();

            await request.query`INSERT INTO [TillOrders] 
                                    (orderId, teamName, tillId, orderNo, total, paymentType, date) 
                                    VALUES (${order.orderId}, ${order.teamName}, ${order.tillId}, ${order.orderNo}, ${order.total}, ${order.paymentType}, ${new Date(order.date)})`;

            for (let item of orderItems) {
                await request.query`INSERT INTO [TillOrderItems]
                                        (orderId, itemNo, vCode, qty, totalPrice, price, oldPrice, appliedDiscountNo)
                                        VALUES (${order.orderId}, ${item.itemNo}, ${item.vCode || ""}, ${item.qty}, ${item.totalPrice}, ${item.price}, ${item.oldPrice}, ${item.appliedDiscountNo})`;
            }

            for (let payment of orderPayments) {
                await request.query`INSERT INTO [TillOrderPayments]
                                        (orderId, type, value, notes)
                                        VALUES (${order.orderId}, ${payment.type}, ${payment.value}, ${payment.notes})`;

                if (payment.type === "credit") {
                    await request.query`UPDATE [StoreCredits] SET value = value - ${payment.value} WHERE id = ${payment.notes}`;
                }
            }

            await transaction.commit();
            return true;
        } catch(e) {
            // transaction.rollback().catch(e => {}); // ignore the error // don't need to rollback, it rolls back on error automatically, abortTransactionOnError = true in options
            throw e;
        }
    }

我只使用一个request并在同一查询上进行所有查询,据我所知,它似乎正常工作。

如果我为每个新查询都做一个新的transaction.request()有什么区别?有缺点吗?在同一笔交易中执行不同的请求是否会失败?如果其中一个失败,每个人都会正确请求回滚吗? (这就是我想要发生的事情)

[编辑] 完成测试后,按照正确插入行,在失败时适当回滚的方式,它似乎可以按预期工作。不知道还有什么缺点,每个优点和缺点是什么。

0 个答案:

没有答案