From 27398fe54ae9434f7ec5ca4517d5ce853ae29cc7 Mon Sep 17 00:00:00 2001 From: Doug Hoyte Date: Fri, 13 Jan 2023 18:54:04 -0500 Subject: [PATCH] detect old DB versions that need to upgrade --- golpe.yaml | 11 +++++++++- src/onAppStartup.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/onAppStartup.cpp diff --git a/golpe.yaml b/golpe.yaml index bba1300..d551cb0 100644 --- a/golpe.yaml +++ b/golpe.yaml @@ -1,6 +1,6 @@ appName: strfry - quadrable: true +onAppStartup: true flatBuffers: | include "../fbs/nostr-index.fbs"; @@ -11,6 +11,15 @@ includes: | } tables: + ## DB meta-data. Single entry, with id = 1 + Meta: + tableId: 2 + + fields: + - name: dbVersion + - name: endianness + + ## Stored nostr events Event: tableId: 1 diff --git a/src/onAppStartup.cpp b/src/onAppStartup.cpp new file mode 100644 index 0000000..60c0cd6 --- /dev/null +++ b/src/onAppStartup.cpp @@ -0,0 +1,49 @@ +#include "golpe.h" + +const size_t CURR_DB_VERSION = 1; + +void onAppStartup(lmdb::txn &txn, const std::string &cmd) { + auto dbTooOld = [&](uint64_t ver) { + LE << "Database version too old: " << ver << ". Expected version " << CURR_DB_VERSION; + LE << "You should 'strfry export' your events, delete (or move) the DB files, and 'strfry import' them"; + throw herr("aborting: DB too old"); + }; + + auto dbTooNew = [&](uint64_t ver) { + LE << "Database version too new: " << ver << ". Expected version " << CURR_DB_VERSION; + LE << "You should upgrade your version of 'strfry'"; + throw herr("aborting: DB too new"); + }; + + auto s = env.lookup_Meta(txn, 1); + + if (!s) { + { + // The first version of the DB didn't use a Meta entry -- we consider this version 0 + + bool eventFound = false; + + env.foreach_Event(txn, [&](auto &ev){ + eventFound = true; + return false; + }); + + if (cmd == "export") return; + if (eventFound) dbTooOld(0); + } + + env.insert_Meta(txn, CURR_DB_VERSION, 1); + return; + } + + if (s->endianness() != 1) throw herr("DB was created on a machine with different endianness"); + + if (s->dbVersion() < CURR_DB_VERSION) { + if (cmd == "export") return; + dbTooOld(s->dbVersion()); + } + + if (s->dbVersion() > CURR_DB_VERSION) { + dbTooNew(s->dbVersion()); + } +}