Fix #12, wait for DB migrations to finish before attempting to use the database

This commit is contained in:
Max Nuding 2023-04-12 20:08:55 +02:00
parent 052c93d461
commit ef4c517ff2
Signed by: phlaym
GPG Key ID: A06651BAB6777237
2 changed files with 39 additions and 2 deletions

View File

@ -5,11 +5,12 @@ import { isTruthy } from '$lib/truthyString';
import sqlite3 from 'sqlite3';
const { DEV } = import.meta.env;
const db: sqlite3.Database = new sqlite3.Database('moshingmammut.db');
const db: sqlite3.Database = new sqlite3.Database('moshingmammut3.db');
const ignoredUsers: string[] =
IGNORE_USERS === undefined
? []
: IGNORE_USERS.split(',').map((u) => (u.startsWith('@') ? u.substring(1) : u));
let databaseReady = false;
if (DEV && isTruthy(env.VERBOSE)) {
sqlite3.verbose();
@ -39,13 +40,25 @@ db.on('open', () => {
db.all('SELECT id FROM migrations', (err, rows) => {
if (err !== null) {
console.error('Could not fetch existing migrations', err);
databaseReady = true;
return;
}
console.debug('Already applied migrations', rows);
const appliedMigrations: Set<number> = new Set(rows.map((row: any) => row['id']));
const toApply = getMigrations().filter((m) => !appliedMigrations.has(m.id));
let remaining = toApply.length;
if (remaining === 0) {
databaseReady = true;
return;
}
for (const migration of toApply) {
db.exec(migration.statement, (err) => {
remaining--;
// This will set databaseReady to true before the migration has been inserted as applies,
// but that doesn't matter. It's only important that is has been applied
if (remaining === 0) {
databaseReady = true;
}
if (err !== null) {
console.error(`Failed to apply migration ${migration.name}`, err);
return;
@ -104,7 +117,28 @@ function getMigrations(): Migration[] {
];
}
async function waitReady(): Promise<undefined> {
// Simpler than a semaphore and is really only needed on startup
return new Promise((resolve) => {
const interval = setInterval(() => {
if (DEV) {
console.debug('Waiting for database to be ready');
}
if (databaseReady) {
if (DEV) {
console.debug('DB is ready');
}
clearInterval(interval);
resolve(undefined);
}
}, 100);
});
}
export async function savePost(post: Post): Promise<undefined> {
if (!databaseReady) {
await waitReady();
}
return new Promise((resolve, reject) => {
console.debug(`Saving post ${post.url}`);
const account = post.account;
@ -198,6 +232,9 @@ export async function savePost(post: Post): Promise<undefined> {
}
export async function getPosts(since: string | null, before: string | null, limit: number) {
if (!databaseReady) {
await waitReady();
}
const promise = await new Promise<Post[]>((resolve, reject) => {
let filter_query = '';
const params: any = { $limit: limit };

View File

@ -155,7 +155,7 @@
<div />
<div class="posts">
{#if data.posts.length === 0}
Sorry, no posts recommending music aave been found yet
Sorry, no posts recommending music have been found yet
{/if}
{#each data.posts as post (post.url)}
<div