diff options
author | Tom Smeding <tom.smeding@gmail.com> | 2020-06-20 19:39:44 +0200 |
---|---|---|
committer | Tom Smeding <tom.smeding@gmail.com> | 2020-06-20 19:39:44 +0200 |
commit | 32ad074786f905b919999c1ff2fb7b3993cc7fad (patch) | |
tree | 522d8bd3855c7c96d7e756729df8e77b8b66b748 | |
parent | 7a8d4d0934cb51c8ad7f7af84669bb0197c7b89e (diff) |
server: Database schema version
-rw-r--r-- | db.c | 34 | ||||
-rw-r--r-- | schema.sql | 4 |
2 files changed, 33 insertions, 5 deletions
@@ -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){ @@ -1,5 +1,9 @@ pragma foreign_keys = on; +create table Meta ( + version integer +); + create table Rooms ( id integer primary key, name text |