add: basic macro functions
add: better migration handling (transactions)
This commit is contained in:
parent
7275d66c86
commit
f67b7e9e0f
7 changed files with 122 additions and 36 deletions
src
|
@ -5,6 +5,7 @@
|
|||
#include <database.h>
|
||||
|
||||
#include <sql/migration_0.h>
|
||||
#include <sql/migration_1.h>
|
||||
|
||||
sqlite3 *global_database;
|
||||
static int in_transaction;
|
||||
|
@ -32,11 +33,35 @@ database_free()
|
|||
sqlite3_close(global_database);
|
||||
}
|
||||
|
||||
static void
|
||||
database_migrate_step_simple(int level, const char* sql_migration)
|
||||
{
|
||||
LOGGER_INFO("migrating LEVEL %d\n", level);
|
||||
char* err_msg;
|
||||
|
||||
sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL);
|
||||
|
||||
int rc = sqlite3_exec(global_database, sql_migration, NULL, NULL, &err_msg);
|
||||
if(rc)
|
||||
{
|
||||
LOGGER_CRIT("couldn't migrate LEVEL %d (%s)\n", level, err_msg);
|
||||
sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
LOGGER_DEBUG("storing new user_version %d\n", level + 1);
|
||||
char pragma_query[32];
|
||||
sprintf(pragma_query, "PRAGMA user_version=%d;", level + 1);
|
||||
sqlite3_exec(global_database, pragma_query, 0, 0, 0);
|
||||
|
||||
sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
void
|
||||
database_migrate()
|
||||
{
|
||||
uint16_t version_num = 0;
|
||||
int s, rc;
|
||||
int s;
|
||||
sqlite3_stmt *stmt;
|
||||
sqlite3_prepare_v2(global_database, "PRAGMA user_version;", -1, &stmt, NULL);
|
||||
s = sqlite3_step(stmt);
|
||||
|
@ -49,31 +74,20 @@ database_migrate()
|
|||
version_num = 0;
|
||||
}
|
||||
|
||||
uint16_t new_version_num = version_num;
|
||||
char* err_msg;
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
switch(version_num)
|
||||
{
|
||||
case 0:
|
||||
LOGGER_INFO("migrating LEVEL 0\n");
|
||||
rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg);
|
||||
if(rc)
|
||||
{
|
||||
LOGGER_CRIT("couldn't migrate LEVEL 0 (%s)\n", err_msg);
|
||||
exit(1);
|
||||
}
|
||||
new_version_num = 1;
|
||||
database_migrate_step_simple(0, (const char*)sql_migration_0_sql);
|
||||
__attribute__ ((fallthrough));
|
||||
case 1:
|
||||
database_migrate_step_simple(1, (const char*)sql_migration_1_sql);
|
||||
__attribute__ ((fallthrough));
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
char pragma_query[32];
|
||||
sprintf(pragma_query, "PRAGMA user_version=%d;", new_version_num);
|
||||
sqlite3_exec(global_database, pragma_query, 0, 0, 0);
|
||||
LOGGER_DEBUG("storing new user_version %d\n", new_version_num);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue