Sequelize Transactions

Sequelize Transactions

①Unmanaged transactions

// First, we start a transaction and save it into a variable
const t = await sequelize.transaction();

try {

  // Then, we do some calls passing this transaction as an option:

  const user = await User.create({
    firstName: 'Bart',
    lastName: 'Simpson'
  }, { transaction: t });

  await user.addSibling({
    firstName: 'Lisa',
    lastName: 'Simpson'
  }, { transaction: t });

  // If the execution reaches this line, no errors were thrown.
  // We commit the transaction.
  await t.commit();

} catch (error) {

  // If the execution reaches this line, an error was thrown.
  // We rollback the transaction.
  await t.rollback();

}

②Managed transactions
try {

  const result = await sequelize.transaction(async (t) => {

    const user = await User.create({
      firstName: 'Abraham',
      lastName: 'Lincoln'
    }, { transaction: t });

    await user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, { transaction: t });

    return user;

  });

  // If the execution reaches this line, the transaction has been committed successfully
  // `result` is whatever was returned from the transaction callback (the `user`, in this case)

} catch (error) {

  // If the execution reaches this line, an error occurred.
  // The transaction has already been rolled back automatically by Sequelize!

}

from:https://sequelize.org/master/manual/transactions.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Transactions(事务)是指将一组数据库操作作为单个逻辑工作单元执行的过程,它要么完全执行,要么完全不执行。如果执行过程中出现故障,那么所有的更改都会回滚,以确保数据库保持一致性。 在关系型数据库中,事务通常遵循ACID(原子性、一致性、隔离性和持久性)原则,以确保数据的正确性和完整性。以下是ACID的详细解释: - 原子性(Atomicity):一个事务是原子的,即它是一个不可分割的最小工作单元。如果事务成功执行,则所有更改将提交到数据库中;如果事务失败,则所有更改将回滚到状态的起点。 - 一致性(Consistency):在事务开始之前和事务结束时,数据库必须处于一致状态。这意味着事务中的所有更改都必须满足数据库中的约束条件。 - 隔离性(Isolation):隔离性指的是并发事务之间的互相隔离性。这意味着一个事务的执行不应该影响另一个事务的执行。 - 持久性(Durability):一旦事务完成,其结果就应该是永久的。这意味着事务中的所有更改都应该保存在数据库中,并且在系统故障时也应该能够恢复。 在实际应用中,事务通常由BEGIN、COMMIT和ROLLBACK语句控制。BEGIN语句用于标识事务的开始,COMMIT语句用于标识事务的结束,并将更改保存到数据库中,而ROLLBACK语句用于回滚事务中的所有更改。 事务可以确保数据的正确性和完整性,特别是在具有高并发读写操作的应用场景下非常有用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值