From 26e2eae9cc253ebd60519d7274ad57c6bdefbf67 Mon Sep 17 00:00:00 2001 From: Trumeet Date: Sun, 19 Mar 2023 17:16:42 -0700 Subject: Improve upgrade robustness --- db.c | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/db.c b/db.c index a72cbc9..735f510 100644 --- a/db.c +++ b/db.c @@ -16,10 +16,10 @@ struct upgrade { int (*pre_func)(void); - int (*post_func)(void); + int (*post_func)(int); }; -static int upgrade_migrate_msg_index(void); +static int upgrade_migrate_msg_index(int res); static const struct upgrade sql_upgrades[] = { {"CREATE TABLE 'says' (" @@ -52,14 +52,11 @@ sqlite3_stmt *stmt_search = NULL; sqlite3_stmt *stmt_random = NULL; -static int upgrade_migrate_msg_index(void) { +static int upgrade_migrate_msg_index(int res) { int r; sqlite3_stmt *stmt = NULL; sqlite3_stmt *stmt_set = NULL; - /* This is currently not atomic. - * To retry, delete the column msg_index and set user_version to 3 manually. */ - if ((r = sqlite3_prepare_v2(db, "SELECT id,url FROM says;", -1, &stmt, NULL))) { LOGFEV("Cannot upgrade DB: %s", r, sqlite3_errstr(r)); } @@ -70,7 +67,11 @@ static int upgrade_migrate_msg_index(void) { while ((r = sqlite3_step(stmt)) == SQLITE_ROW) { int id = sqlite3_column_int(stmt, 0); char *url = (char *) sqlite3_column_text(stmt, 1); + if (!url || !url[0]) { + continue; + } uint32_t index = tg_url_get_index(url); + LOGIV("Migrating record %d (%s).", id, url); if (!index) { LOGFEV("Unknown URL: %s", 1, url); @@ -138,11 +139,16 @@ void db_init(void) { if (upg->pre_func) { upg->pre_func(); } - if ((r = sqlite3_exec(db, upg->sql, NULL, NULL, &errmsg))) { - goto sql_err; - } + /* TRY to do that anyway, if we have a post-fun. */ + r = sqlite3_exec(db, upg->sql, NULL, NULL, &errmsg); if (upg->post_func) { - upg->post_func(); + if (r) { + LOGEV("Error while executing upgrade: %s, continuing anyway", errmsg); + free(errmsg); + } + upg->post_func(r); + } else if (r) { + goto sql_err; } char sql[60]; sprintf(sql, "PRAGMA user_version = %d;", to); -- cgit v1.2.3