Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize transaction error

Trying to implement oauth2. Stuck with sequelize transactions.

Getting error:

Executing (9edf48f7-5823-4b4f-b444-faa4c1896831): START TRANSACTION;

Executing (9edf48f7-5823-4b4f-b444-faa4c1896831): COMMIT;

Unhandled rejection Error: commit has been called on this transaction(9edf48f7-5823-4b4f-b444-faa4c1896831), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)

`

at.save({transaction: t}).then(() => {
                rt.save({transaction: t}).then(() => {
                    t.commit();
                    return done(false, accessToken, refreshToken, {
                        expires_at: expires,
                        scope: scope});
                }).error(function(
                    err) {
                    t.rollback();
                    return done(err);
                });
            }).error(function(err) {
                t.rollback();
                return done(err);
            });

Sequelize 4.x.x with Postgres

like image 236
Андрей Гузюк Avatar asked Aug 15 '17 09:08

Андрей Гузюк


1 Answers

When you are working with Sequelize transactions using the auto-commit feature, you need to make sure that you return the promises from each of the queries. It looks like you didn't return the promise from the nested queries, which means that your original promise resolves after the first query, which commits the transaction. In order to wait for the entire chain of commits to finish, you must return the nested promises.

return sequelize.transaction(t => {
  return at.save({ transaction: t })
    .then(() => {
      return rt.save({ transaction: t })
        .then(() => {
          return t.commit() // Commit also returns a promise, you will want that to finish too
            .then(() => {
              return done();
            });
        });
    });
});

In my example above you can completely omit the t.commit() call because Sequelize automatically commits a transaction if the promise chain resolves. If you are not using the callback style for transaction then you should keep that there. In my example I used the callback style.

Good luck! :)

like image 151
Dylan Aspden Avatar answered Oct 21 '22 19:10

Dylan Aspden