Skip to content

Add settings to handle errors on connection #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
22 changes: 17 additions & 5 deletions lib/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ exports.initialize = function initializeSchema(schema, callback) {
}

function initializeConnection(connection, schema, callback) {
var s = schema.settings;
var silentOnError = typeof s.silentOnError === 'undefined'?false:s.silentOnError;
var retryOnError = typeof s.retryOnError === 'undefined'?true:s.retryOnError;
var createDatabaseOnError = typeof s.createDatabaseOnError === 'undefined'?true:s.createDatabaseOnError;

// Attach listeners first
connection.on('error', function(err) {
console.log('connection error', err);
Expand All @@ -51,8 +56,13 @@ function initializeConnection(connection, schema, callback) {
else {
connection.connect(function(err) {
if(err) {
console.log('connection.connect err', err);
setTimeout(schema.adapter.connect.bind(schema.adapter, callback), 6000);
schema.emit('init error', err);
if (!silentOnError) {
console.log('connection.connect err', err);
}
if (retryOnError) {
setTimeout(schema.adapter.connect.bind(schema.adapter, callback), 6000);
}
return;
}
initDatabase()
Expand All @@ -61,7 +71,8 @@ function initializeConnection(connection, schema, callback) {
function initDatabase() {
connection.query('USE `' + schema.settings.database + '`', function (err) {
if (err) {
if (err.message.match(/(^|: )unknown database/i)) {
schema.emit('init error', err);
if (createDatabaseOnError && err.message.match(/(^|: )unknown database/i)) {
var dbName = schema.settings.database;
var charset = schema.settings.charset;
var collation = schema.settings.collation;
Expand All @@ -73,14 +84,15 @@ function initializeConnection(connection, schema, callback) {
throw err;
}
});
} else throw err;
} else if (!silentOnError) {
throw err;
}
} else {
callback && callback();
}
});
}
};

/**
* Returns a connection or a connection pool based on the settings object
*
Expand Down