sqlite: convert migrations to async

This removes quite a bunch of indention and callbacks
This commit is contained in:
Reto Brunner 2022-10-10 21:43:30 +02:00
parent bbe81bb2fa
commit f068fd4290

View file

@ -63,52 +63,47 @@ class SqliteMessageStorage implements ISqliteMessageStorage {
this.database = new sqlite3.Database(sqlitePath); this.database = new sqlite3.Database(sqlitePath);
this.run_migrations() this.run_migrations().catch((err) => {
log.error("Migration failed", String(err));
this.isEnabled = false;
});
} }
private run_migrations() { async run_migrations() {
this.database.serialize(() => { for (const stmt of schema) {
schema.forEach((line) => this.run(line)); await this.serialize_run(stmt, []);
this.database.get(
"SELECT value FROM options WHERE name = 'schema_version'",
(err, row) => {
if (err) {
return log.error(`Failed to retrieve schema version: ${err.toString()}`);
} }
// New table const version = await this.serialize_get(
if (row === undefined) { "SELECT value FROM options WHERE name = 'schema_version'"
this.run( );
if (version === undefined) {
// new table
await this.serialize_run(
"INSERT INTO options (name, value) VALUES ('schema_version', ?)", "INSERT INTO options (name, value) VALUES ('schema_version', ?)",
currentSchemaVersion [currentSchemaVersion]
); );
return; return;
} }
const storedSchemaVersion = parseInt(row.value, 10); const storedSchemaVersion = parseInt(version.value, 10);
if (storedSchemaVersion === currentSchemaVersion) { if (storedSchemaVersion === currentSchemaVersion) {
return; return;
} }
if (storedSchemaVersion > currentSchemaVersion) { if (storedSchemaVersion > currentSchemaVersion) {
return log.error( throw `sqlite messages schema version is higher than expected (${storedSchemaVersion} > ${currentSchemaVersion}). Is The Lounge out of date?`;
`sqlite messages schema version is higher than expected (${storedSchemaVersion} > ${currentSchemaVersion}). Is The Lounge out of date?`
);
} }
log.info( log.info(
`sqlite messages schema version is out of date (${storedSchemaVersion} < ${currentSchemaVersion}). Running migrations if any.` `sqlite messages schema version is out of date (${storedSchemaVersion} < ${currentSchemaVersion}). Running migrations if any.`
); );
this.run( await this.serialize_run("UPDATE options SET value = ? WHERE name = 'schema_version'", [
"UPDATE options SET value = ? WHERE name = 'schema_version'", currentSchemaVersion,
currentSchemaVersion ]);
);
}
);
});
} }
close(callback?: (error?: Error | null) => void) { close(callback?: (error?: Error | null) => void) {