From 701105fb647a2ff01d6de072131aa575a7c613d4 Mon Sep 17 00:00:00 2001 From: antao Date: Thu, 15 Nov 2018 16:22:24 +0800 Subject: [PATCH] Fix a rollback bug in transactions --- .../src/postgresql_impl/PgTransactionImpl.cc | 9 +++++--- orm_lib/src/postgresql_impl/test/test2.cc | 22 ++++++++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/orm_lib/src/postgresql_impl/PgTransactionImpl.cc b/orm_lib/src/postgresql_impl/PgTransactionImpl.cc index 646d4dea..a0a57c3e 100644 --- a/orm_lib/src/postgresql_impl/PgTransactionImpl.cc +++ b/orm_lib/src/postgresql_impl/PgTransactionImpl.cc @@ -24,6 +24,7 @@ PgTransactionImpl::PgTransactionImpl(const PgConnectionPtr &connPtr, } PgTransactionImpl::~PgTransactionImpl() { + assert(!_isWorking); if (!_isCommitedOrRolledback) { auto cb = _usedUpCallback; @@ -72,8 +73,9 @@ void PgTransactionImpl::execSql(const std::string &sql, format, rcb, [exceptCallback, thisPtr](const std::exception_ptr &ePtr) { - exceptCallback(ePtr); thisPtr->rollback(); + if(exceptCallback) + exceptCallback(ePtr); }, [thisPtr]() { thisPtr->execNewTask(); @@ -115,7 +117,7 @@ void PgTransactionImpl::rollback() { auto thisPtr = shared_from_this(); - _loop->queueInLoop([thisPtr]() { + _loop->runInLoop([thisPtr]() { if (thisPtr->_isCommitedOrRolledback) return; auto clearupCb = [thisPtr]() { @@ -139,7 +141,8 @@ void PgTransactionImpl::rollback() cmd._exceptCb = [clearupCb](const std::exception_ptr &ePtr) { clearupCb(); }; - thisPtr->_sqlCmdBuffer.push_back(std::move(cmd)); + //Rollback cmd should be executed firstly, so we push it in front of the list + thisPtr->_sqlCmdBuffer.push_front(std::move(cmd)); return; } thisPtr->_isWorking = true; diff --git a/orm_lib/src/postgresql_impl/test/test2.cc b/orm_lib/src/postgresql_impl/test/test2.cc index a0e1a0c9..230300b1 100644 --- a/orm_lib/src/postgresql_impl/test/test2.cc +++ b/orm_lib/src/postgresql_impl/test/test2.cc @@ -35,7 +35,27 @@ int main() LOG_DEBUG << "start!"; { auto trans = client->newTransaction(); - //trans->rollback(); + *trans << "delete from users where user_uuid=201" >> + [](const Result &r) { + std::cout << "delete " << r.affectedRows() << "user!!!!!" << std::endl; + } >> + [](const DrogonDbException &e) { + std::cout << e.base().what() << std::endl; + }; + *trans << "dlelf from users" >> + [](const Result &r) { + std::cout << "delete " << r.affectedRows() << "user!!!!!" << std::endl; + } >> + [](const DrogonDbException &e) { + std::cout << e.base().what() << std::endl; + }; + *trans << "dlelf111 from users" >> + [](const Result &r) { + std::cout << "delete " << r.affectedRows() << "user!!!!!" << std::endl; + } >> + [](const DrogonDbException &e) { + std::cout << e.base().what() << std::endl; + }; } Mapper mapper(client); auto U = mapper.findByPrimaryKey(2);