core-legacy/database.c
2020-05-05 11:42:02 +02:00

67 lines
1.5 KiB
C

#include <stdint.h>
#include <stddef.h>
#include <logger.h>
#include <database.h>
#include <migrations/0.sql.h>
sqlite3 *global_database;
int
database_migrate()
{
uint16_t version_num = 0;
int s, rc;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(global_database, "SELECT version_num FROM meta LIMIT 1;", -1, &stmt, NULL);
s = sqlite3_step(stmt);
if (s == SQLITE_ROW)
{
version_num = sqlite3_column_int(stmt, 0);
}
else
{
version_num = 0;
}
uint16_t new_version_num = version_num;
char* err_msg;
sqlite3_finalize(stmt);
switch(version_num)
{
case 0:
LOG_INFO("migrating LEVEL 0\n");
rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg);
if(rc != 0)
{
LOG_FATAL("couldn't migrate LEVEL 0 (%s)\n", err_msg);
break;
}
new_version_num = 1;
default:
break;
}
if(version_num == 0)
{
sqlite3_prepare_v2(global_database, "INSERT INTO meta (version_num) VALUES (?1);", -1, &stmt, NULL);
}
else
{
sqlite3_prepare_v2(global_database, "UPDATE meta SET version_num=?1;", -1, &stmt, NULL);
}
sqlite3_bind_int(stmt, 1, new_version_num);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
{
LOG_FATAL("couldn't write new schema version");
}
sqlite3_finalize(stmt);
return rc != SQLITE_DONE;
}