From f8a5cc728d91432108de7fec180e112cdbb8a84b Mon Sep 17 00:00:00 2001 From: Joakim Carlstein Date: Mon, 5 Feb 2024 14:41:03 +0100 Subject: [PATCH] fix(storage): make sure the storage initialization crashes when db connection can't be established --- .changeset/tasty-bulldogs-guess.md | 6 ++++++ packages/mysql/src/index.ts | 2 ++ packages/postgres/src/index.ts | 14 +++++++------- 3 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 .changeset/tasty-bulldogs-guess.md diff --git a/.changeset/tasty-bulldogs-guess.md b/.changeset/tasty-bulldogs-guess.md new file mode 100644 index 0000000..eb34947 --- /dev/null +++ b/.changeset/tasty-bulldogs-guess.md @@ -0,0 +1,6 @@ +--- +'@emigrate/postgres': patch +'@emigrate/mysql': patch +--- + +Make sure the storage initialization crashes when a database connection can't be established diff --git a/packages/mysql/src/index.ts b/packages/mysql/src/index.ts index 46a1f55..de253c9 100644 --- a/packages/mysql/src/index.ts +++ b/packages/mysql/src/index.ts @@ -171,6 +171,8 @@ export const createMysqlStorage = ({ table = defaultTable, connection }: MysqlSt async initializeStorage() { const pool = getPool(connection); + await pool.query('SELECT 1'); + try { await initializeTable(pool, table); } catch (error) { diff --git a/packages/postgres/src/index.ts b/packages/postgres/src/index.ts index bcbe9e1..b6e3e4c 100644 --- a/packages/postgres/src/index.ts +++ b/packages/postgres/src/index.ts @@ -32,12 +32,12 @@ export type PostgresLoaderOptions = { connection: ConnectionOptions | string; }; -const getPool = (connection: ConnectionOptions | string) => { - if (typeof connection === 'string') { - return postgres(connection); - } +const getPool = async (connection: ConnectionOptions | string): Promise => { + const sql = typeof connection === 'string' ? postgres(connection) : postgres(connection); - return postgres(connection); + await sql`SELECT 1`; + + return sql; }; const lockMigration = async (sql: Sql, table: string, migration: MigrationMetadata) => { @@ -122,7 +122,7 @@ export const createPostgresStorage = ({ }: PostgresStorageOptions): EmigrateStorage => { return { async initializeStorage() { - const sql = getPool(connection); + const sql = await getPool(connection); try { await initializeTable(sql, table); @@ -211,7 +211,7 @@ export const createPostgresLoader = ({ connection }: PostgresLoaderOptions): Loa loadableExtensions: ['.sql'], async loadMigration(migration) { return async () => { - const sql = getPool(connection); + const sql = await getPool(connection); try { // @ts-expect-error The "simple" option is not documented, but it exists