javascript - Node.js - How to use Sequelize transaction - Stack Overflow

I am a beginner with sequelize and cannot get the transactions to work. Documentation is unclear and ma

I am a beginner with sequelize and cannot get the transactions to work. Documentation is unclear and makes the following example not able to adapt to my requirements.

  return sequelize.transaction(t => {
  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user => {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result => {
  // Transaction has been mitted
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

First I have to insert a tuple in 'Conto', then insert another tuple in 'Preferenze' and finally based on the 'tipo' attribute insert a tuple in 'ContoPersonale' or 'ContoAziendale'.

If only one of these queries fails, the transaction must make a total rollback, mit.

The queries are:

Conto.create({
        id: nextId(),
        mail: reg.email,
        password: reg.password,
        tipo: reg.tipo,
        telefono: reg.telefono,
        idTelegram: reg.telegram,
        saldo: saldoIniziale,
        iban: generaIBAN()
    })

Preferenze.create({
        refConto: 68541
    })

if (tipo == 0) {
        ContoPersonale.create({
        nomeint: reg.nome,
        cognomeint: reg.cognome,
        dataN: reg.datan,
        cf: reg.cf,
        refConto: nextId()
        }) 
        }
else if (tipo == 1) { 
        ContoAziendale.create({
        pIva: reg.piva,
        ragioneSociale: reg.ragsoc,
        refConto: nextId()
        })
        }

I am a beginner with sequelize and cannot get the transactions to work. Documentation is unclear and makes the following example not able to adapt to my requirements.

  return sequelize.transaction(t => {
  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user => {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result => {
  // Transaction has been mitted
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

First I have to insert a tuple in 'Conto', then insert another tuple in 'Preferenze' and finally based on the 'tipo' attribute insert a tuple in 'ContoPersonale' or 'ContoAziendale'.

If only one of these queries fails, the transaction must make a total rollback, mit.

The queries are:

Conto.create({
        id: nextId(),
        mail: reg.email,
        password: reg.password,
        tipo: reg.tipo,
        telefono: reg.telefono,
        idTelegram: reg.telegram,
        saldo: saldoIniziale,
        iban: generaIBAN()
    })

Preferenze.create({
        refConto: 68541
    })

if (tipo == 0) {
        ContoPersonale.create({
        nomeint: reg.nome,
        cognomeint: reg.cognome,
        dataN: reg.datan,
        cf: reg.cf,
        refConto: nextId()
        }) 
        }
else if (tipo == 1) { 
        ContoAziendale.create({
        pIva: reg.piva,
        ragioneSociale: reg.ragsoc,
        refConto: nextId()
        })
        }
Share Improve this question edited Nov 9, 2019 at 14:46 Cadmos 2674 silver badges21 bronze badges asked Nov 9, 2019 at 11:38 Cruciano Christian ScacciaCruciano Christian Scaccia 351 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

With a transaction you pass it to each query you want to be part of the transaction, and then call transaction.mit() when you finished, or transaction.rollback() to roll back all the changes. This can be done use thenables however it is clearer when using async/await.

Since none of your queries depend on each other you can also make them concurrently using Promise.all().

thenables (with auto mit)

sequelize.transaction((transaction) => {
  // execute all queries, pass in transaction
  return Promise.all([
    Conto.create({
      id: nextId(),
      mail: reg.email,
      password: reg.password,
      tipo: reg.tipo,
      telefono: reg.telefono,
      idTelegram: reg.telegram,
      saldo: saldoIniziale,
      iban: generaIBAN()
    }, { transaction }),

    Preferenze.create({
      refConto: 68541
    }, { transaction }),

    // this query is determined by "tipo"
    tipo === 0
      ? ContoPersonale.create({
          nomeint: reg.nome,
          cognomeint: reg.cognome,
          dataN: reg.datan,
          cf: reg.cf,
          refConto: nextId()
        }, { transaction })
      : ContoAziendale.create({
          pIva: reg.piva,
          ragioneSociale: reg.ragsoc,
          refConto: nextId()
        }, { transaction })
  ]);

  // if we get here it will auto mit
  // if there is an error it with automatically roll back.

})
.then(() => {
  console.log('queries ran successfully');
})
.catch((err) => {
  console.log('queries failed', err);
});

async/await

let transaction;
try {
  // start a new transaction
  transaction = await sequelize.transaction();

  // run queries, pass in transaction
  await Promise.all([
    Conto.create({
      id: nextId(),
      mail: reg.email,
      password: reg.password,
      tipo: reg.tipo,
      telefono: reg.telefono,
      idTelegram: reg.telegram,
      saldo: saldoIniziale,
      iban: generaIBAN()
    }, { transaction }),

    Preferenze.create({
      refConto: 68541
    }, { transaction }),

    // this query is determined by "tipo"
    tipo === 0
      ? ContoPersonale.create({
          nomeint: reg.nome,
          cognomeint: reg.cognome,
          dataN: reg.datan,
          cf: reg.cf,
          refConto: nextId()
        }, { transaction })
      : ContoAziendale.create({
          pIva: reg.piva,
          ragioneSociale: reg.ragsoc,
          refConto: nextId()
        }, { transaction })
  ]);

  // if we get here they ran successfully, so...
  await transaction.mit();
} catch (err) {
  // if we got an error and we created the transaction, roll it back
  if (transaction) {
    await transaction.rollback();
  }
  console.log('Err', err);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742416428a4439828.html

相关推荐

  • javascript - Node.js - How to use Sequelize transaction - Stack Overflow

    I am a beginner with sequelize and cannot get the transactions to work. Documentation is unclear and ma

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信