Skip to content
This repository has been archived by the owner on Feb 12, 2023. It is now read-only.

Commit

Permalink
feat(db): Support schema version upgrades
Browse files Browse the repository at this point in the history
  • Loading branch information
sphaerophoria committed Dec 2, 2018
1 parent 157be30 commit fb805b9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/persistence/history.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
*/

static constexpr int NUM_MESSAGES_DEFAULT = 100; // arbitrary number of messages loaded when not loading by date
static constexpr int SCHEMA_VERSION = 0;

/**
* @brief Prepares the database to work with the history.
Expand All @@ -48,6 +49,13 @@ History::History(std::shared_ptr<RawDatabase> db)
return;
}

dbSchemaUpgrade();

// dbSchemaUpgrade may have put us in an invalid state
if (!isValid()) {
return;
}

db->execLater(
"CREATE TABLE IF NOT EXISTS peers (id INTEGER PRIMARY KEY, public_key TEXT NOT NULL "
"UNIQUE);"
Expand Down Expand Up @@ -493,3 +501,41 @@ QList<History::HistMessage> History::getChatHistory(const QString& friendPk, con

return messages;
}

/**
* @brief Upgrade the db schema
* @note On future alterations of the database all you have to do is bump the SCHEMA_VERSION
* variable and add another case to the switch statement below. Make sure to fall through on each case.
*/
void History::dbSchemaUpgrade()
{
int64_t databaseSchemaVersion;
db->execNow(RawDatabase::Query("PRAGMA user_version", [&] (const QVector<QVariant>& row){
databaseSchemaVersion = row[0].toLongLong();
}));

if (databaseSchemaVersion > SCHEMA_VERSION) {
qWarning() << "Database version is newer than we currently support. Please upgrade qTox";
// We don't know what future versions have done, we have to disable db access until we re-upgrade
db.reset();
}
else if (databaseSchemaVersion == SCHEMA_VERSION) {
// No work to do
return;
}

switch (databaseSchemaVersion)
{
//case 0:
// do 0 -> 1 upgrade
// //fallthrough
//case 1:
// do 1 -> 2 upgrade
// //fallthrough
// etc.
default:
db->execLater(RawDatabase::Query(QStringLiteral("PRAGMA user_version = %1;").arg(SCHEMA_VERSION)));
qDebug() << "Database upgrade finished (databaseSchemaVersion "
<< databaseSchemaVersion << " -> " << SCHEMA_VERSION << ")";
}
}
1 change: 1 addition & 0 deletions src/persistence/history.h
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ class History
private:
QList<HistMessage> getChatHistory(const QString& friendPk, const QDateTime& from,
const QDateTime& to, int numMessages);
void dbSchemaUpgrade();
std::shared_ptr<RawDatabase> db;
QHash<QString, int64_t> peers;
};
Expand Down

0 comments on commit fb805b9

Please sign in to comment.