fix(storage): make sure the storage initialization crashes when db connection can't be established

This commit is contained in:
Joakim Carlstein 2024-02-05 14:41:03 +01:00 committed by Joakim Carlstein
parent f6761fe434
commit f8a5cc728d
3 changed files with 15 additions and 7 deletions

View file

@ -0,0 +1,6 @@
---
'@emigrate/postgres': patch
'@emigrate/mysql': patch
---
Make sure the storage initialization crashes when a database connection can't be established

View file

@ -171,6 +171,8 @@ export const createMysqlStorage = ({ table = defaultTable, connection }: MysqlSt
async initializeStorage() { async initializeStorage() {
const pool = getPool(connection); const pool = getPool(connection);
await pool.query('SELECT 1');
try { try {
await initializeTable(pool, table); await initializeTable(pool, table);
} catch (error) { } catch (error) {

View file

@ -32,12 +32,12 @@ export type PostgresLoaderOptions = {
connection: ConnectionOptions | string; connection: ConnectionOptions | string;
}; };
const getPool = (connection: ConnectionOptions | string) => { const getPool = async (connection: ConnectionOptions | string): Promise<Sql> => {
if (typeof connection === 'string') { const sql = typeof connection === 'string' ? postgres(connection) : postgres(connection);
return postgres(connection);
}
return postgres(connection); await sql`SELECT 1`;
return sql;
}; };
const lockMigration = async (sql: Sql, table: string, migration: MigrationMetadata) => { const lockMigration = async (sql: Sql, table: string, migration: MigrationMetadata) => {
@ -122,7 +122,7 @@ export const createPostgresStorage = ({
}: PostgresStorageOptions): EmigrateStorage => { }: PostgresStorageOptions): EmigrateStorage => {
return { return {
async initializeStorage() { async initializeStorage() {
const sql = getPool(connection); const sql = await getPool(connection);
try { try {
await initializeTable(sql, table); await initializeTable(sql, table);
@ -211,7 +211,7 @@ export const createPostgresLoader = ({ connection }: PostgresLoaderOptions): Loa
loadableExtensions: ['.sql'], loadableExtensions: ['.sql'],
async loadMigration(migration) { async loadMigration(migration) {
return async () => { return async () => {
const sql = getPool(connection); const sql = await getPool(connection);
try { try {
// @ts-expect-error The "simple" option is not documented, but it exists // @ts-expect-error The "simple" option is not documented, but it exists