Knex: How to figure out that a disconnect has happened?

Created on 31 Jul 2016  Â·  1Comment  Â·  Source: knex/knex

I'm using knex to access a PostgreSQL database. Now supposed I run my application, and at some point in time the database crashes.

How do I figure this out?
Is there an event that I can subscribe to to get informed?

Something such as:

knex.on('disconnect', () => {
  // ...
});

Or similar?

PS: I have seen that there were issues on this in the past as well (e.g., #407, #522, …), but none of them really comes up with a suitable and working solution.

Most helpful comment

We had another look at it, and what we did _not_ want to do is to periodically run queries against the database such as SELECT 1.

Hence, we decided to check the underlying TCP/IP connection, which emits an end event on the client. This client you need to build by yourself, either using knex.client.driver.Client or by using pg.Client directly.

Anyway, sample code looks like this:

'use strict';

const parse = require('pg-connection-string').parse;
const pg = require('pg');

const connectionString = 'postgres://user:[email protected]:5432/mydb';

const client = new pg.Client(parse(connectionString));

client.connect(err => {
  client.on('end', () => {
    console.log('end');
  });
});

>All comments

We had another look at it, and what we did _not_ want to do is to periodically run queries against the database such as SELECT 1.

Hence, we decided to check the underlying TCP/IP connection, which emits an end event on the client. This client you need to build by yourself, either using knex.client.driver.Client or by using pg.Client directly.

Anyway, sample code looks like this:

'use strict';

const parse = require('pg-connection-string').parse;
const pg = require('pg');

const connectionString = 'postgres://user:[email protected]:5432/mydb';

const client = new pg.Client(parse(connectionString));

client.connect(err => {
  client.on('end', () => {
    console.log('end');
  });
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

koskimas picture koskimas  Â·  3Comments

zettam picture zettam  Â·  3Comments

mishitpatel picture mishitpatel  Â·  3Comments

sandrocsimas picture sandrocsimas  Â·  3Comments

hyperh picture hyperh  Â·  3Comments