/*
 * Seagull: A SQLite helper library
 * Copyright (C) Seagull Developers
 *
 * Seagull is the legal property of its developers, whose names are too
 * numerous to list here. Please refer to the AUTHORS file distributed with
 * this source distribution
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include <sqlite3.h>

#include "seagulltransaction.h"

G_DEFINE_QUARK(seagull-transaction-error, seagull_transaction_error)

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
seagull_transaction_begin(SeagullSqlite3 *db, GError **error) {
	int result = 0;
	char *error_message = NULL;
	gboolean ret = TRUE;

	g_return_val_if_fail(db != NULL, FALSE);

	result = sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &error_message);
	if(result != SQLITE_OK) {
		ret = FALSE;

		g_set_error(error,
		            SEAGULL_TRANSACTION_ERROR,
		            SEAGULL_TRANSACTION_ERROR_BEGIN_FAILED,
		            "failed to begin transaction: %s",
		            error_message);
	}

	g_clear_pointer(&error_message, sqlite3_free);

	return ret;
}

gboolean
seagull_transaction_commit(SeagullSqlite3 *db, GError **error) {
	int result = 0;
	char *error_message = NULL;
	gboolean ret = TRUE;

	g_return_val_if_fail(db != NULL, FALSE);

	result = sqlite3_exec(db, "COMMIT", NULL, NULL, &error_message);
	if(result != SQLITE_OK) {
		ret = FALSE;

		g_set_error(error,
		            SEAGULL_TRANSACTION_ERROR,
		            SEAGULL_TRANSACTION_ERROR_COMMIT_FAILED,
		            "failed to commit transaction: %s",
		            error_message);
	}

	g_clear_pointer(&error_message, sqlite3_free);

	return ret;
}

gboolean
seagull_transaction_rollback(SeagullSqlite3 *db, GError **error) {
	int result = 0;
	char *error_message = NULL;
	gboolean ret = TRUE;

	g_return_val_if_fail(db != NULL, FALSE);

	result = sqlite3_exec(db, "ROLLBACK", NULL, NULL, &error_message);
	if(result != SQLITE_OK) {
		ret = FALSE;

		g_set_error(error,
		            SEAGULL_TRANSACTION_ERROR,
		            SEAGULL_TRANSACTION_ERROR_ROLLBACK_FAILED,
		            "failed to rollback transaction: %s",
		            error_message);
	}

	g_clear_pointer(&error_message, sqlite3_free);

	return ret;
}
