aboutsummaryrefslogtreecommitdiff
path: root/db.c
diff options
context:
space:
mode:
authorTom Smeding <tom.smeding@gmail.com>2020-06-20 19:39:44 +0200
committerTom Smeding <tom.smeding@gmail.com>2020-06-20 19:39:44 +0200
commit32ad074786f905b919999c1ff2fb7b3993cc7fad (patch)
tree522d8bd3855c7c96d7e756729df8e77b8b66b748 /db.c
parent7a8d4d0934cb51c8ad7f7af84669bb0197c7b89e (diff)
server: Database schema version
Diffstat (limited to 'db.c')
-rw-r--r--db.c34
1 files changed, 29 insertions, 5 deletions
diff --git a/db.c b/db.c
index 32a8df4..4572ea2 100644
--- a/db.c
+++ b/db.c
@@ -9,6 +9,8 @@
#define SQLITE(func,...) do{if(sqlite3_##func(__VA_ARGS__)!=SQLITE_OK){die_sqlite("sqlite3_" #func);}}while(0)
+#define DATABASE_VERSION 1
+
sqlite3 *database=NULL;
@@ -21,13 +23,35 @@ static void die_sqlite(const char *func){
void db_init(void){
SQLITE(config,SQLITE_CONFIG_SERIALIZED);
SQLITE(initialize);
+
SQLITE(open_v2,"db.db",&database,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,NULL);
SQLITE(busy_timeout,database,500);
- char *str=malloc(schema_sql_len+1,char);
- memcpy(str,schema_sql,schema_sql_len);
- str[schema_sql_len]='\0';
- sqlite3_exec(database,str,NULL,NULL,NULL);
- free(str);
+
+ sqlite3_stmt *stmt;
+ int res = sqlite3_prepare_v2(database, "select version from Meta", -1, &stmt, NULL);
+ if (res == SQLITE_OK && sqlite3_step(stmt) == SQLITE_ROW) {
+ i64 version = sqlite3_column_int64(stmt, 0);
+ SQLITE(finalize, stmt);
+
+ if (version != DATABASE_VERSION) {
+ die("Database version incompatible: database %" PRIi64 ", application %d",
+ version, DATABASE_VERSION);
+ }
+ } else {
+ if (res == SQLITE_OK) SQLITE(finalize, stmt);
+
+ char *str=malloc(schema_sql_len+1,char);
+ memcpy(str,schema_sql,schema_sql_len);
+ str[schema_sql_len]='\0';
+ SQLITE(exec,database,str,NULL,NULL,NULL);
+ free(str);
+
+ SQLITE(prepare_v2, database, "insert into Meta (version) values (?)", -1, &stmt, NULL);
+ SQLITE(bind_int64, stmt, 1, DATABASE_VERSION);
+ if (sqlite3_step(stmt) != SQLITE_DONE) {
+ die("Could not set database version: %s", sqlite3_errmsg(database));
+ }
+ }
}
void db_reinit(void){