pica/database/mysql/transaction.cpp

38 lines
1.1 KiB
C++
Raw Normal View History

2023-12-22 23:25:20 +00:00
// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
2023-12-20 22:42:13 +00:00
#include "transaction.h"
2023-12-29 17:40:00 +00:00
DB::MySQL::Transaction::Transaction(MYSQL* connection):
2023-12-20 22:42:13 +00:00
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;
}
2023-12-29 17:40:00 +00:00
DB::MySQL::Transaction::~Transaction() {
2023-12-20 22:42:13 +00:00
if (opened)
abort();
}
2023-12-29 17:40:00 +00:00
void DB::MySQL::Transaction::commit() {
2023-12-20 22:42:13 +00:00
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));
}
2023-12-29 17:40:00 +00:00
void DB::MySQL::Transaction::abort() {
2023-12-20 22:42:13 +00:00
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));
}