From 5d324aac9e4de8e9fc012971123d9d974ea702ee Mon Sep 17 00:00:00 2001 From: Bruno Bernardino Date: Fri, 11 Jul 2025 09:14:17 +0100 Subject: [PATCH] Fail loudly on connection error while running migrations Closes #77 --- deno.json | 1 + docker-compose.yml | 2 +- lib/interfaces/database.ts | 14 ++++++++++++-- migrate-db.ts | 2 +- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/deno.json b/deno.json index ae28e36..5b98d2b 100644 --- a/deno.json +++ b/deno.json @@ -36,6 +36,7 @@ "$fresh/": "https://deno.land/x/fresh@1.7.3/", "std/": "https://deno.land/std@0.224.0/", "$std/": "https://deno.land/std@0.224.0/", + "postgres": "https://deno.land/x/postgres@v0.19.3/mod.ts", "preact": "https://esm.sh/preact@10.23.2", "preact/": "https://esm.sh/preact@10.23.2/", "@preact/signals": "https://esm.sh/*@preact/signals@1.3.0", diff --git a/docker-compose.yml b/docker-compose.yml index 1ff0c32..79ca95c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ services: website: - image: ghcr.io/bewcloud/bewcloud:v2.2.2 + image: ghcr.io/bewcloud/bewcloud:v2.2.3 restart: always ports: - 127.0.0.1:8000:8000 diff --git a/lib/interfaces/database.ts b/lib/interfaces/database.ts index 393ff96..a950746 100644 --- a/lib/interfaces/database.ts +++ b/lib/interfaces/database.ts @@ -1,4 +1,4 @@ -import { Client } from 'https://deno.land/x/postgres@v0.19.3/mod.ts'; +import { Client } from 'postgres'; import 'std/dotenv/load.ts'; const POSTGRESQL_HOST = Deno.env.get('POSTGRESQL_HOST') || ''; @@ -21,8 +21,14 @@ const tls = POSTGRESQL_CAFILE export default class Database { protected db?: Client; + protected throwOnConnectionError?: boolean; + + constructor( + { connectNow = false, throwOnConnectionError = false }: { connectNow?: boolean; throwOnConnectionError?: boolean } = + {}, + ) { + this.throwOnConnectionError = throwOnConnectionError; - constructor(connectNow = false) { if (connectNow) { this.connectToPostgres(); } @@ -64,6 +70,10 @@ export default class Database { console.log('Failed to connect to Postgres!'); console.error(error); + if (this.throwOnConnectionError) { + throw error; + } + // This allows tests (and the app) to work even if Postgres is not available const mockPostgresClient = { queryObject: () => { diff --git a/migrate-db.ts b/migrate-db.ts index 4a2372c..d6970eb 100644 --- a/migrate-db.ts +++ b/migrate-db.ts @@ -6,7 +6,7 @@ const migrationsDirectoryPath = `${Deno.cwd()}/db-migrations`; const migrationsDirectory = Deno.readDir(migrationsDirectoryPath); -const db = new Database(); +const db = new Database({ throwOnConnectionError: true }); interface Migration { id: string;