1
0
forked from blue/pica
pica/database/mysql/transaction.cpp

35 lines
1005 B
C++

#include "transaction.h"
MySQL::Transaction::Transaction(MYSQL* connection):
con(connection),
opened(false)
{
if (mysql_autocommit(con, 0) != 0)
throw std::runtime_error(std::string("Failed to start transaction") + mysql_error(con));
opened = true;
}
MySQL::Transaction::~Transaction() {
if (opened)
abort();
}
void MySQL::Transaction::commit() {
if (mysql_commit(con) != 0)
throw std::runtime_error(std::string("Failed to commit transaction") + mysql_error(con));
opened = false;
if (mysql_autocommit(con, 1) != 0)
throw std::runtime_error(std::string("Failed to return autocommit") + mysql_error(con));
}
void MySQL::Transaction::abort() {
opened = false;
if (mysql_rollback(con) != 0)
throw std::runtime_error(std::string("Failed to rollback transaction") + mysql_error(con));
if (mysql_autocommit(con, 1) != 0)
throw std::runtime_error(std::string("Failed to return autocommit") + mysql_error(con));
}