forked from rodrigogs/zongji
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
323 lines (281 loc) · 8.62 KB
/
index.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
var mysql = require('mysql');
var Connection = require('mysql/lib/Connection');
var Pool = require('mysql/lib/Pool');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var generateBinlog = require('./lib/sequence/binlog');
var alternateDsn = [
{ type: Connection, config: function(obj) { return obj.config; } },
{ type: Pool, config: function(obj) { return obj.config.connectionConfig; } }
];
function ZongJi(dsn, options) {
this.set(options);
EventEmitter.call(this);
var binlogDsn;
// one connection to send table info query
// Check first argument against possible connection objects
for (var i = 0; i < alternateDsn.length; i++) {
if (dsn.constructor.name === alternateDsn[i].type.name) {
this.ctrlConnection = dsn;
this.ctrlConnectionOwner = false;
binlogDsn = cloneObjectSimple(alternateDsn[i].config(dsn));
}
}
if (!binlogDsn) {
// assuming that the object passed is the connection settings
var ctrlDsn = cloneObjectSimple(dsn);
this.ctrlConnection = mysql.createConnection(ctrlDsn);
this.ctrlConnection.on('error', this._emitError.bind(this));
this.ctrlConnection.on('unhandledError', this._emitError.bind(this));
this.ctrlConnection.connect();
this.ctrlConnectionOwner = true;
binlogDsn = dsn;
}
this.ctrlCallbacks = [];
this.connection = mysql.createConnection(binlogDsn);
this.connection.on('error', this._emitError.bind(this));
this.connection.on('unhandledError', this._emitError.bind(this));
this.tableMap = {};
this.ready = false;
this.useChecksum = false;
// Include 'rotate' events to keep these properties updated
this.binlogName = null;
this.binlogNextPos = null;
this._init();
}
var cloneObjectSimple = function(obj) {
var out = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
out[i] = obj[i];
}
}
return out;
};
util.inherits(ZongJi, EventEmitter);
ZongJi.prototype._init = function() {
var self = this;
var binlogOptions = {
tableMap: self.tableMap,
};
var asyncMethods = [
{
name: '_isChecksumEnabled',
callback: function(checksumEnabled) {
self.useChecksum = checksumEnabled;
binlogOptions.useChecksum = checksumEnabled;
}
},
{
name: '_findBinlogEnd',
callback: function(result) {
if (result && self.options.startAtEnd) {
binlogOptions.filename = result.Log_name;
binlogOptions.position = result.File_size;
}
}
}
];
var methodIndex = 0;
var nextMethod = function() {
var method = asyncMethods[methodIndex];
self[method.name](function(/* args */) {
method.callback.apply(this, arguments);
methodIndex++;
if (methodIndex < asyncMethods.length) {
nextMethod();
}
else {
ready();
}
});
};
nextMethod();
var ready = function() {
// Run asynchronously from _init(), as serverId option set in start()
if (self.options.serverId !== undefined) {
binlogOptions.serverId = self.options.serverId;
}
if (('binlogName' in self.options) && ('binlogNextPos' in self.options)) {
binlogOptions.filename = self.options.binlogName;
binlogOptions.position = self.options.binlogNextPos;
}
self.binlog = generateBinlog.call(self, binlogOptions);
self.ready = true;
self._executeCtrlCallbacks();
};
};
ZongJi.prototype._isChecksumEnabled = function(next) {
var self = this;
var sql = 'select @@GLOBAL.binlog_checksum as checksum';
var ctrlConnection = self.ctrlConnection;
var connection = self.connection;
ctrlConnection.query(sql, function(err, rows) {
if (err) {
if (err.toString().match(/ER_UNKNOWN_SYSTEM_VARIABLE/)) {
// MySQL < 5.6.2 does not support @@GLOBAL.binlog_checksum
return next(false);
} else {
// Any other errors should be emitted
self.emit('error', err);
return;
}
}
var checksumEnabled = true;
if (rows[0].checksum === 'NONE') {
checksumEnabled = false;
}
var setChecksumSql = 'set @master_binlog_checksum=@@global.binlog_checksum';
if (checksumEnabled) {
connection.query(setChecksumSql, function(err) {
if (err) {
// Errors should be emitted
self.emit('error', err);
return;
}
next(checksumEnabled);
});
} else {
next(checksumEnabled);
}
});
};
ZongJi.prototype._findBinlogEnd = function(next) {
var self = this;
self.ctrlConnection.query('SHOW BINARY LOGS', function(err, rows) {
if (err) {
// Errors should be emitted
self.emit('error', err);
return;
}
next(rows.length > 0 ? rows[rows.length - 1] : null);
});
};
ZongJi.prototype._executeCtrlCallbacks = function() {
if (this.ctrlCallbacks.length > 0) {
this.ctrlCallbacks.forEach(function(cb) {
setImmediate(cb);
});
}
};
var tableInfoQueryTemplate = `
SELECT
COLUMN_NAME, COLLATION_NAME, CHARACTER_SET_NAME,
COLUMN_COMMENT, COLUMN_TYPE
FROM
information_schema.columns
WHERE
table_schema='%s' AND table_name='%s'
ORDER BY ORDINAL_POSITION;
`;
ZongJi.prototype._fetchTableInfo = function(tableMapEvent, next) {
var self = this;
var sql = util.format(tableInfoQueryTemplate,
tableMapEvent.schemaName, tableMapEvent.tableName);
this.ctrlConnection.query(sql, function(err, rows) {
if (err) {
// Errors should be emitted
self.emit('error', err);
// This is a fatal error, no additional binlog events will be
// processed since next() will never be called
return;
}
if (rows.length === 0) {
self.emit('error', new Error(
'Insufficient permissions to access: ' +
tableMapEvent.schemaName + '.' + tableMapEvent.tableName) +
', or this table have been dropped.');
return next();
}
self.tableMap[tableMapEvent.tableId] = {
columnSchemas: rows,
parentSchema: tableMapEvent.schemaName,
tableName: tableMapEvent.tableName
};
next();
});
};
ZongJi.prototype.set = function(options) {
this.options = options || {};
};
ZongJi.prototype.start = function(options) {
var self = this;
self.set(options);
var _start = function() {
self.connection._implyConnect();
self.connection._protocol._enqueue(new self.binlog(function(error, event) {
if (error) return self.emit('error', error);
// Do not emit events that have been filtered out
if (event === undefined || event._filtered === true) return;
switch (event.getTypeName()) {
case 'TableMap':
var tableMap = self.tableMap[event.tableId];
if (!tableMap) {
self.connection.pause();
self._fetchTableInfo(event, function() {
// merge the column info with metadata
event.updateColumnInfo();
self.emit('binlog', event);
self.connection.resume();
});
return;
}
break;
case 'Rotate':
if (self.binlogName !== event.binlogName) {
self.binlogName = event.binlogName;
}
break;
}
self.binlogNextPos = event.nextPosition;
self.emit('binlog', event);
}));
};
if (this.ready) {
_start();
}
else {
this.ctrlCallbacks.push(_start);
}
};
ZongJi.prototype.stop = function() {
var self = this;
// Binary log connection does not end with destroy()
self.connection.destroy();
self.ctrlConnection.query(
'KILL ' + self.connection.threadId,
function() {
if (self.ctrlConnectionOwner)
self.ctrlConnection.destroy();
}
);
};
ZongJi.prototype._skipEvent = function(eventName) {
var include = this.options.includeEvents;
var exclude = this.options.excludeEvents;
return !(
(include === undefined ||
(include instanceof Array && include.indexOf(eventName) !== -1)) &&
(exclude === undefined ||
(exclude instanceof Array && exclude.indexOf(eventName) === -1)));
};
ZongJi.prototype._skipSchema = function(database, table) {
var include = this.options.includeSchema;
var exclude = this.options.excludeSchema;
return !(
(include === undefined ||
(database !== undefined && (database in include) &&
(include[database] === true ||
(include[database] instanceof Array &&
include[database].indexOf(table) !== -1)))) &&
(exclude === undefined ||
(database !== undefined &&
(!(database in exclude) ||
(exclude[database] !== true &&
(exclude[database] instanceof Array &&
exclude[database].indexOf(table) === -1))))));
};
ZongJi.prototype._emitError = function(error) {
this.emit('error', error);
};
module.exports = ZongJi;