connection-manager.js
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"use strict";
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
, Promise = require('../../promise');
ConnectionManager = function(dialect, sequelize) {
AbstractConnectionManager.call(this, dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 3306;
try {
this.lib = require(sequelize.config.dialectModulePath || 'mysql');
} catch (err) {
throw new Error('Please install mysql package manually');
}
};
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
ConnectionManager.prototype.connect = function(config) {
var self = this;
return new Promise(function (resolve, reject) {
var connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: 'Z'
};
if (config.dialectOptions) {
Object.keys(config.dialectOptions).forEach(function(key) {
connectionConfig[key] = config.dialectOptions[key];
});
}
var connection = self.lib.createConnection(connectionConfig);
connection.connect(function(err) {
if (err) {
switch (err.code) {
case 'ECONNREFUSED':
case 'ER_ACCESS_D2ENIED_ERROR':
reject('Failed to authenticate for MySQL. Please double check your settings.');
break;
case 'ENOTFOUND':
case 'EHOSTUNREACH':
case 'EINVAL':
reject('Failed to find MySQL server. Please double check your settings.');
break;
default:
reject(err);
break;
}
return;
}
resolve(connection);
});
}).tap(function (connection) {
connection.query("SET time_zone = '+0:00'");
});
};
ConnectionManager.prototype.disconnect = function(connection) {
return new Promise(function (resolve, reject) {
connection.end(function(err) {
if (err) return reject(err);
resolve();
});
});
};
ConnectionManager.prototype.validate = function(connection) {
return connection && connection.state !== 'disconnected';
};
module.exports = ConnectionManager;