add: database transactions

This commit is contained in:
Tobias Reisinger 2020-08-15 12:13:03 +02:00
parent 7fa462ef1d
commit 7c6eed8dc2
8 changed files with 119 additions and 30 deletions

View file

@ -7,6 +7,33 @@
#include <sql/migration_0.h>
sqlite3 *global_database;
static int in_transaction;
void
database_init()
{
int rc = sqlite3_open(global_config.database, &global_database);
if(rc)
{
LOGGER_CRIT("can't open database: %s\n", sqlite3_errmsg(global_database));
exit(1);
}
if(database_migrate())
{
exit(1);
}
sqlite3_exec(global_database, "PRAGMA foreign_keys = ON", 0, 0, 0);
in_transaction = 0;
}
void
database_free()
{
sqlite3_close(global_database);
}
int
database_migrate()
@ -65,3 +92,32 @@ database_migrate()
return rc != SQLITE_DONE;
}
int
database_transaction_begin()
{
if(!in_transaction)
{
LOGGER_DEBUG("beginning transaction\n");
sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL);
in_transaction = 1;
return 1;
}
return 0;
}
void
database_transaction_commit()
{
LOGGER_DEBUG("commiting transaction\n");
sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL);
in_transaction = 0;
}
void
database_transaction_rollback()
{
LOGGER_DEBUG("rolling back transaction\n");
sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL);
in_transaction = 0;
}