vistur
vistur

Reputation: 631

Check mysql connection in sequelize

I have a very simple program in where I create a Sequelize instance and then I perform a raw query on a mysql database. The case is that when MySql is up and running there is no problem, I can perform the query with no problems. But when MySql is not running then the query doesn't emmit any error until the query timeout has reached and then it emmits a ETIMEOUT error. But that's not really what's happening. I expect the query to emit ENOTFOUND error or something like that if mysql is not running so I can manage the error and perform different actions if Mysql has gone down or Mysql is very busy and has a very large response time. What shoul'd I do to check if Mysql is up and running without having to wait the timeout exception.

sequelize = new Sequelize(db_name, db_user, db_pass, opts);

sequelize.query('SELECT * FROM some_table').success(function(result) {
  console.log(result);
}).error(function(err) {
  console.log(err);
});

Upvotes: 36

Views: 54745

Answers (4)

Yan Foto
Yan Foto

Reputation: 11388

As of latest version of Sequelize (i.e. 3.3.2), authenticate can be used to check the connection:

var sequelize = new Sequelize("db", "user", "pass");

sequelize.authenticate().then(function(errors) { console.log(errors) });

authenticate simply runs SELECT 1+1 AS result query to check the db connection.

UPDATE:

Errors by the newest API need to be handled in catch:

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

UPDATE 2:

I haven't tested this, but its only logical that the same thing can be reached with async/await:

try {
  await sequelize.authenticate()
} catch (err) {
  console.error('Unable to connect to the database:', err)
}

Upvotes: 60

Franck Freiburger
Franck Freiburger

Reputation: 28478

I use the following code to wait for the db engine to start:

function sleep(ms) {

    return new Promise(function(resolve) {

        setTimeout(resolve, ms);
    });
}

for (;;) {

    try {

        await db.authenticate();
        break;
    } catch(ex) {

        await sleep(1000);
    }
}

Upvotes: 0

Nate
Nate

Reputation: 6474

You won't see errors, like password authentication errors, in .then.

From the sequelize documentation here:

You can use the .authenticate() function like this to test the connection.

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  })
  .catch(function (err) {
    console.log('Unable to connect to the database:', err);
  });

Upvotes: 9

avisheks
avisheks

Reputation: 1180

Please check "wait_timeout" system variable if its been reset to some trivial value

Upvotes: 0

Related Questions