From 32ad074786f905b919999c1ff2fb7b3993cc7fad Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Sat, 20 Jun 2020 19:39:44 +0200 Subject: server: Database schema version --- db.c | 34 +++++++++++++++++++++++++++++----- schema.sql | 4 ++++ 2 files changed, 33 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){ diff --git a/schema.sql b/schema.sql index 6291102..55fe091 100644 --- a/schema.sql +++ b/schema.sql @@ -1,5 +1,9 @@ pragma foreign_keys = on; +create table Meta ( + version integer +); + create table Rooms ( id integer primary key, name text -- cgit v1.2.3-70-g09d2