diff --git a/src/postgres/__tests__/base-pg-store.test.ts b/src/postgres/__tests__/base-pg-store.test.ts index aa92041..694440a 100644 --- a/src/postgres/__tests__/base-pg-store.test.ts +++ b/src/postgres/__tests__/base-pg-store.test.ts @@ -118,4 +118,15 @@ describe('BasePgStore', () => { expect(sqlTransactionContext.getStore()).toBeUndefined(); expect(db.sql).toEqual(obj); }); + + test('isConnected returns true when the connection is alive', async () => { + const connected = await db.isConnected(); + expect(connected).toBe(true); + }); + + test('isConnected returns false when the connection is not alive', async () => { + jest.spyOn(db, 'sql').mockRejectedValueOnce(new Error('Connection lost')); + const connected = await db.isConnected(); + expect(connected).toBe(false); + }); }); diff --git a/src/postgres/base-pg-store.ts b/src/postgres/base-pg-store.ts index 05d4585..aafed13 100644 --- a/src/postgres/base-pg-store.ts +++ b/src/postgres/base-pg-store.ts @@ -84,6 +84,19 @@ export abstract class BasePgStore { isProdEnv ? this.sql`CONCURRENTLY` : this.sql`` } ${this.sql(viewName)}`; } + + /** + * Checks if the database connection is alive. + * @returns True if connected, false otherwise. + */ + async isConnected(): Promise { + try { + await this.sql`SELECT NOW()`; + return true; + } catch (error) { + return false; + } + } } /** @@ -114,4 +127,7 @@ export abstract class BasePgStoreModule { async refreshMaterializedView(viewName: string): Promise { return this.parent.refreshMaterializedView(viewName); } + async isConnected(): Promise { + return this.parent.isConnected(); + } }