Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/postgres/__tests__/base-pg-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
16 changes: 16 additions & 0 deletions src/postgres/base-pg-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
try {
await this.sql`SELECT NOW()`;
return true;
} catch (error) {
return false;
}
}
}

/**
Expand Down Expand Up @@ -114,4 +127,7 @@ export abstract class BasePgStoreModule {
async refreshMaterializedView(viewName: string): Promise<void> {
return this.parent.refreshMaterializedView(viewName);
}
async isConnected(): Promise<boolean> {
return this.parent.isConnected();
}
}