/
connection.js
1364 lines (1269 loc) · 41.3 KB
/
connection.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const EventEmitter = require('events');
const Queue = require('denque');
const Net = require('net');
const PacketInputStream = require('./io/packet-input-stream');
const PacketOutputStream = require('./io/packet-output-stream');
const CompressionInputStream = require('./io/compression-input-stream');
const CompressionOutputStream = require('./io/compression-output-stream');
const ServerStatus = require('./const/server-status');
const ConnectionInformation = require('./misc/connection-information');
const tls = require('tls');
const Errors = require('./misc/errors');
const Utils = require('./misc/utils');
const Capabilities = require('./const/capabilities');
/*commands*/
const Authentication = require('./cmd/handshake/authentication');
const Quit = require('./cmd/quit');
const Ping = require('./cmd/ping');
const Reset = require('./cmd/reset');
const Query = require('./cmd/query');
const Prepare = require('./cmd/prepare');
const OkPacket = require('./cmd/class/ok-packet');
const Execute = require('./cmd/execute');
const ClosePrepare = require('./cmd/close-prepare');
const BatchBulk = require('./cmd/batch-bulk');
const ChangeUser = require('./cmd/change-user');
const { Status } = require('./const/connection_status');
const CommandParameter = require('./command-parameter');
const LruPrepareCache = require('./lru-prepare-cache');
const convertFixedTime = function (tz, conn) {
if (tz === 'UTC' || tz === 'Etc/UTC' || tz === 'Z' || tz === 'Etc/GMT') {
return '+00:00';
} else if (tz.startsWith('Etc/GMT') || tz.startsWith('GMT')) {
let tzdiff;
let negate;
// strangely Etc/GMT+8 = GMT-08:00 = offset -8
if (tz.startsWith('Etc/GMT')) {
tzdiff = tz.substring(7);
negate = !tzdiff.startsWith('-');
} else {
tzdiff = tz.substring(3);
negate = tzdiff.startsWith('-');
}
let diff = parseInt(tzdiff.substring(1));
if (isNaN(diff)) {
throw Errors.createFatalError(
`Automatic timezone setting fails. wrong Server timezone '${tz}' conversion to +/-HH:00 conversion.`,
Errors.ER_WRONG_AUTO_TIMEZONE,
conn.info
);
}
return (negate ? '-' : '+') + (diff >= 10 ? diff : '0' + diff) + ':00';
}
return tz;
};
/**
* New Connection instance.
*
* @param options connection options
* @returns Connection instance
* @constructor
* @fires Connection#connect
* @fires Connection#end
* @fires Connection#error
*
*/
class Connection extends EventEmitter {
opts;
sendQueue = new Queue();
receiveQueue = new Queue();
waitingAuthenticationQueue = new Queue();
status = Status.NOT_CONNECTED;
socket = null;
timeout = null;
addCommand;
streamOut;
streamIn;
info;
prepareCache;
constructor(options) {
super();
this.opts = Object.assign(new EventEmitter(), options);
this.info = new ConnectionInformation(this.opts);
this.prepareCache =
this.opts.prepareCacheLength > 0 ? new LruPrepareCache(this.info, this.opts.prepareCacheLength) : null;
this.addCommand = this.addCommandQueue;
this.streamOut = new PacketOutputStream(this.opts, this.info);
this.streamIn = new PacketInputStream(
this.unexpectedPacket.bind(this),
this.receiveQueue,
this.streamOut,
this.opts,
this.info
);
this.on('close_prepare', this._closePrepare.bind(this));
this.escape = Utils.escape.bind(this, this.opts, this.info);
this.escapeId = Utils.escapeId.bind(this, this.opts, this.info);
}
//*****************************************************************
// public methods
//*****************************************************************
/**
* Connect event
*
* @returns {Promise} promise
*/
connect() {
const conn = this;
this.status = Status.CONNECTING;
const authenticationParam = new CommandParameter(null, null, this.opts, null);
return new Promise(function (resolve, reject) {
conn.connectRejectFct = reject;
conn.connectResolveFct = resolve;
// add a handshake to msg queue
const authentication = new Authentication(
authenticationParam,
conn.authSucceedHandler.bind(conn),
conn.authFailHandler.bind(conn),
conn.createSecureContext.bind(conn),
conn.getSocket.bind(conn)
);
Error.captureStackTrace(authentication);
authentication.once('end', () => {
conn.receiveQueue.shift();
// conn.info.collation might not be initialized
// in case of handshake throwing error
if (!conn.opts.collation && conn.info.collation) {
conn.opts.emit('collation', conn.info.collation);
}
process.nextTick(conn.nextSendCmd.bind(conn));
});
conn.receiveQueue.push(authentication);
conn.streamInitSocket.call(conn);
});
}
executePromise(cmdParam, prepare, resolve, reject) {
const cmd = new Execute(resolve, this._logAndReject.bind(this, reject), this.opts, cmdParam, prepare);
this.addCommand(cmd);
}
batch(cmdParam) {
if (!cmdParam.sql) {
const err = Errors.createError(
'sql parameter is mandatory',
Errors.ER_UNDEFINED_SQL,
this.info,
'HY000',
null,
false,
cmdParam.stack
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
}
if (!cmdParam.values) {
const err = Errors.createError(
'Batch must have values set',
Errors.ER_BATCH_WITH_NO_VALUES,
this.info,
'HY000',
cmdParam.sql,
false,
cmdParam.stack
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
}
return new Promise(this.prepare.bind(this, cmdParam)).then((prepare) => {
const usePlaceHolder = (cmdParam.opts && cmdParam.opts.namedPlaceholders) || this.opts.namedPlaceholders;
let vals;
if (Array.isArray(cmdParam.values)) {
if (usePlaceHolder) {
vals = cmdParam.values;
} else if (Array.isArray(cmdParam.values[0])) {
vals = cmdParam.values;
} else if (prepare.parameterCount === 1) {
vals = [];
for (let i = 0; i < cmdParam.values.length; i++) {
vals.push([cmdParam.values[i]]);
}
} else {
vals = [cmdParam.values];
}
} else {
vals = [[cmdParam.values]];
}
cmdParam.values = vals;
let useBulk = this._canUseBulk(vals, cmdParam.opts);
if (useBulk) {
return new Promise(this.executeBulkPromise.bind(this, cmdParam, prepare, this.opts));
} else {
const executes = [];
const cmdOpt = Object.assign({}, this.opts, cmdParam.opts);
for (let i = 0; i < vals.length; i++) {
executes.push(prepare.execute(vals[i], cmdParam.opts, null, cmdParam.stack));
}
return Promise.all(executes)
.then(
function (res) {
if (cmdParam.opts && cmdParam.opts.fullResult) {
return Promise.resolve(res);
} else {
// aggregate results
let firstResult = res[0];
if (cmdOpt.metaAsArray) firstResult = firstResult[0];
if (firstResult instanceof OkPacket) {
let affectedRows = 0;
const insertId = firstResult.insertId;
const warningStatus = firstResult.warningStatus;
if (cmdOpt.metaAsArray) {
for (let i = 0; i < res.length; i++) {
affectedRows += res[i][0].affectedRows;
}
return Promise.resolve([new OkPacket(affectedRows, insertId, warningStatus), []]);
} else {
for (let i = 0; i < res.length; i++) {
affectedRows += res[i].affectedRows;
}
return Promise.resolve(new OkPacket(affectedRows, insertId, warningStatus));
}
} else {
// results have result-set. example :'INSERT ... RETURNING'
// aggregate results
if (cmdOpt.metaAsArray) {
const rs = [];
res.forEach((row) => {
rs.push(...row[0]);
});
return Promise.resolve([rs, res[0][1]]);
} else {
const rs = [];
res.forEach((row) => {
rs.push(...row);
});
Object.defineProperty(rs, 'meta', {
value: res[0].meta,
writable: true,
enumerable: this.opts.metaEnumerable
});
return Promise.resolve(rs);
}
}
}
}.bind(this)
)
.finally(() => prepare.close());
}
});
}
executeBulkPromise(cmdParam, prepare, opts, resolve, reject) {
const cmd = new BatchBulk(
(res) => {
prepare.close();
return resolve(res);
},
function (err) {
prepare.close();
if (opts.logger.error) opts.logger.error(err);
reject(err);
},
opts,
prepare,
cmdParam
);
this.addCommand(cmd);
}
/**
* Send an empty MySQL packet to ensure connection is active, and reset @@wait_timeout
* @param cmdParam command context
* @param resolve success function
* @param reject rejection function
*/
ping(cmdParam, resolve, reject) {
if (cmdParam.opts && cmdParam.opts.timeout) {
if (cmdParam.opts.timeout < 0) {
const err = Errors.createError(
'Ping cannot have negative timeout value',
Errors.ER_BAD_PARAMETER_VALUE,
this.info,
'0A000'
);
if (this.opts.logger.error) this.opts.logger.error(err);
reject(err);
return;
}
let tOut = setTimeout(
function () {
tOut = undefined;
const err = Errors.createFatalError('Ping timeout', Errors.ER_PING_TIMEOUT, this.info, '0A000');
if (this.opts.logger.error) this.opts.logger.error(err);
// close connection
this.addCommand = this.addCommandDisabled;
clearTimeout(this.timeout);
if (this.status !== Status.CLOSING && this.status !== Status.CLOSED) {
this.sendQueue.clear();
this.status = Status.CLOSED;
this.socket.destroy();
}
this.clear();
reject(err);
}.bind(this),
cmdParam.opts.timeout
);
this.addCommand(
new Ping(
cmdParam,
() => {
if (tOut) {
clearTimeout(tOut);
resolve();
}
},
(err) => {
if (this.opts.logger.error) this.opts.logger.error(err);
clearTimeout(tOut);
reject(err);
}
)
);
return;
}
this.addCommand(new Ping(cmdParam, resolve, reject));
}
/**
* Send a reset command that will
* - rollback any open transaction
* - reset transaction isolation level
* - reset session variables
* - delete user variables
* - remove temporary tables
* - remove all PREPARE statement
*/
reset(cmdParam, resolve, reject) {
if (
(this.info.isMariaDB() && this.info.hasMinVersion(10, 2, 4)) ||
(!this.info.isMariaDB() && this.info.hasMinVersion(5, 7, 3))
) {
const conn = this;
const resetCmd = new Reset(
cmdParam,
() => {
conn.prepareCache.reset();
let prom = Promise.resolve();
// re-execute init query / session query timeout
prom
.then(conn.handleTimezone.bind(conn))
.then(conn.executeInitQuery.bind(conn))
.then(conn.executeSessionTimeout.bind(conn))
.then(resolve)
.catch(reject);
},
reject
);
this.addCommand(resetCmd);
return;
}
const err = new Error(
`Reset command not permitted for server ${this.info.serverVersion.raw} (requires server MariaDB version 10.2.4+ or MySQL 5.7.3+)`
);
err.stack = cmdParam.stack;
if (this.opts.logger.error) this.opts.logger.error(err);
reject(err);
}
/**
* Indicates the state of the connection as the driver knows it
* @returns {boolean}
*/
isValid() {
return this.status === Status.CONNECTED;
}
/**
* Terminate connection gracefully.
*/
end(cmdParam, resolve, reject) {
this.addCommand = this.addCommandDisabled;
clearTimeout(this.timeout);
if (this.status < Status.CLOSING && this.status !== Status.NOT_CONNECTED) {
this.status = Status.CLOSING;
const ended = () => {
this.status = Status.CLOSED;
this.socket.destroy();
this.socket.unref();
this.clear();
this.receiveQueue.clear();
resolve();
};
const quitCmd = new Quit(cmdParam, ended, ended);
this.sendQueue.push(quitCmd);
this.receiveQueue.push(quitCmd);
if (this.sendQueue.length === 1) {
process.nextTick(this.nextSendCmd.bind(this));
}
} else resolve();
}
/**
* Force connection termination by closing the underlying socket and killing server process if any.
*/
destroy() {
this.addCommand = this.addCommandDisabled;
clearTimeout(this.timeout);
if (this.status < Status.CLOSING) {
this.status = Status.CLOSING;
this.sendQueue.clear();
if (this.receiveQueue.length > 0) {
//socket is closed, but server may still be processing a huge select
//only possibility is to kill process by another thread
//TODO reuse a pool connection to avoid connection creation
const self = this;
const killCon = new Connection(this.opts);
killCon
.connect()
.then(() => {
//*************************************************
//kill connection
//*************************************************
new Promise(killCon.query.bind(killCon, { sql: `KILL ${self.info.threadId}` })).finally((err) => {
const destroyError = Errors.createFatalError(
'Connection destroyed, command was killed',
Errors.ER_CMD_NOT_EXECUTED_DESTROYED,
self.info
);
if (self.opts.logger.error) self.opts.logger.error(destroyError);
self.socketErrorDispatchToQueries(destroyError);
if (self.socket) {
const sok = self.socket;
process.nextTick(() => {
sok.destroy();
});
}
self.status = Status.CLOSED;
self.clear();
new Promise(killCon.end.bind(killCon)).catch(() => {});
});
})
.catch(() => {
//*************************************************
//failing to create a kill connection, end normally
//*************************************************
const ended = () => {
let sock = self.socket;
self.clear();
self.status = Status.CLOSED;
sock.destroy();
self.receiveQueue.clear();
};
const quitCmd = new Quit(ended, ended);
self.sendQueue.push(quitCmd);
self.receiveQueue.push(quitCmd);
if (self.sendQueue.length === 1) {
process.nextTick(self.nextSendCmd.bind(self));
}
});
} else {
this.status = Status.CLOSED;
this.socket.destroy();
this.clear();
}
}
}
pause() {
this.socket.pause();
}
resume() {
this.socket.resume();
}
format(sql, values) {
const err = Errors.createError(
'"Connection.format intentionally not implemented. please use Connection.query(sql, values), it will be more secure and faster',
Errors.ER_NOT_IMPLEMENTED_FORMAT,
this.info,
'0A000'
);
if (this.opts.logger.error) this.opts.logger.error(err);
throw err;
}
//*****************************************************************
// additional public methods
//*****************************************************************
/**
* return current connected server version information.
*
* @returns {*}
*/
serverVersion() {
if (!this.info.serverVersion) {
const err = new Error('cannot know if server information until connection is established');
if (this.opts.logger.error) this.opts.logger.error(err);
throw err;
}
return this.info.serverVersion.raw;
}
/**
* Change option "debug" during connection.
* @param val debug value
*/
debug(val) {
if (typeof val === 'boolean') {
if (val && !this.opts.logger.network) this.opts.logger.network = console.log;
} else if (typeof val === 'function') {
this.opts.logger.network = val;
}
this.opts.emit('debug', val);
}
debugCompress(val) {
if (val) {
if (typeof val === 'boolean') {
this.opts.debugCompress = val;
if (val && !this.opts.logger.network) this.opts.logger.network = console.log;
} else if (typeof val === 'function') {
this.opts.debugCompress = true;
this.opts.logger.network = val;
}
} else this.opts.debugCompress = false;
}
//*****************************************************************
// internal public testing methods
//*****************************************************************
get __tests() {
return new TestMethods(this.info.collation, this.socket);
}
//*****************************************************************
// internal methods
//*****************************************************************
/**
* Use multiple COM_STMT_EXECUTE or COM_STMT_BULK_EXECUTE
*
* @param values current batch values
* @param _options batch option
* @return {boolean} indicating if can use bulk command
*/
_canUseBulk(values, _options) {
if (_options && _options.fullResult) return false;
// not using info.isMariaDB() directly in case of callback use,
// without connection being completely finished.
if (
this.info.serverVersion &&
this.info.serverVersion.mariaDb &&
this.info.hasMinVersion(10, 2, 7) &&
this.opts.bulk &&
(this.info.serverCapabilities & Capabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) > 0n
) {
//ensure that there is no stream object
if (values !== undefined) {
if (!this.opts.namedPlaceholders) {
//ensure that all parameters have same length
//single array is considered as an array of single element.
const paramLen = Array.isArray(values[0]) ? values[0].length : values[0] ? 1 : 0;
if (paramLen === 0) return false;
for (let r = 0; r < values.length; r++) {
let row = values[r];
if (!Array.isArray(row)) row = [row];
if (paramLen !== row.length) {
return false;
}
// streaming data not permitted
for (let j = 0; j < paramLen; j++) {
const val = row[j];
if (
val != null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val.read === 'function'
) {
return false;
}
}
}
} else {
for (let r = 0; r < values.length; r++) {
let row = values[r];
const keys = Object.keys(row);
for (let j = 0; j < keys.length; j++) {
const val = row[keys[j]];
if (
val != null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val.read === 'function'
) {
return false;
}
}
}
}
}
return true;
}
return false;
}
executeSessionVariableQuery() {
if (this.opts.sessionVariables) {
const values = [];
let sessionQuery = 'set ';
let keys = Object.keys(this.opts.sessionVariables);
if (keys.length > 0) {
for (let k = 0; k < keys.length; ++k) {
sessionQuery += (k !== 0 ? ',' : '') + '@@' + keys[k].replace(/[^a-z0-9_]/gi, '') + '=?';
values.push(this.opts.sessionVariables[keys[k]]);
}
return new Promise(this.query.bind(this, new CommandParameter(sessionQuery, values))).catch((initialErr) => {
const err = Errors.createFatalError(
`Error setting session variable (value ${JSON.stringify(this.opts.sessionVariables)}). Error: ${
initialErr.message
}`,
Errors.ER_SETTING_SESSION_ERROR,
this.info,
'08S01',
sessionQuery
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
});
}
}
return Promise.resolve();
}
/**
* Asking server timezone if not set in case of 'auto'
* @returns {Promise<void>}
* @private
*/
handleTimezone() {
const conn = this;
if (this.opts.timezone === 'local') this.opts.timezone = undefined;
if (this.opts.timezone === 'auto') {
return new Promise(
this.query.bind(this, new CommandParameter('SELECT @@system_time_zone stz, @@time_zone tz'))
).then((res) => {
const serverTimezone = res[0].tz === 'SYSTEM' ? res[0].stz : res[0].tz;
const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (serverTimezone === localTz || convertFixedTime(serverTimezone, conn) === convertFixedTime(localTz, conn)) {
//server timezone is identical to client tz, skipping setting
this.opts.timezone = localTz;
return Promise.resolve();
}
return this._setSessionTimezone(convertFixedTime(localTz, conn));
});
}
if (this.opts.timezone) {
return this._setSessionTimezone(convertFixedTime(this.opts.timezone, conn));
}
return Promise.resolve();
}
_setSessionTimezone(tz) {
return new Promise(this.query.bind(this, new CommandParameter('SET time_zone=?', [tz]))).catch((err) => {
const er = Errors.createFatalError(
`setting timezone '${tz}' fails on server.\n look at https://mariadb.com/kb/en/mysql_tzinfo_to_sql/ to load IANA timezone. `,
Errors.ER_WRONG_IANA_TIMEZONE,
this.info
);
if (this.opts.logger.error) this.opts.logger.error(er);
return Promise.reject(er);
});
}
checkServerVersion() {
if (!this.opts.forceVersionCheck) {
return Promise.resolve();
}
return new Promise(this.query.bind(this, new CommandParameter('SELECT @@VERSION AS v'))).then(
function (res) {
this.info.serverVersion.raw = res[0].v;
this.info.serverVersion.mariaDb = this.info.serverVersion.raw.includes('MariaDB');
ConnectionInformation.parseVersionString(this.info);
return Promise.resolve();
}.bind(this)
);
}
executeInitQuery() {
if (this.opts.initSql) {
const initialArr = Array.isArray(this.opts.initSql) ? this.opts.initSql : [this.opts.initSql];
const initialPromises = [];
initialArr.forEach((sql) => {
initialPromises.push(new Promise(this.query.bind(this, new CommandParameter(sql))));
});
return Promise.all(initialPromises).catch((initialErr) => {
const err = Errors.createFatalError(
`Error executing initial sql command: ${initialErr.message}`,
Errors.ER_INITIAL_SQL_ERROR,
this.info
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
});
}
return Promise.resolve();
}
executeSessionTimeout() {
if (this.opts.queryTimeout) {
if (this.info.isMariaDB() && this.info.hasMinVersion(10, 1, 2)) {
const query = `SET max_statement_time=${this.opts.queryTimeout / 1000}`;
new Promise(this.query.bind(this, new CommandParameter(query))).catch(
function (initialErr) {
const err = Errors.createFatalError(
`Error setting session queryTimeout: ${initialErr.message}`,
Errors.ER_INITIAL_TIMEOUT_ERROR,
this.info,
'08S01',
query
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
}.bind(this)
);
} else {
const err = Errors.createError(
`Can only use queryTimeout for MariaDB server after 10.1.1. queryTimeout value: ${this.opts.queryTimeout}`,
Errors.ER_TIMEOUT_NOT_SUPPORTED,
this.info,
'HY000',
this.opts.queryTimeout
);
if (this.opts.logger.error) this.opts.logger.error(err);
return Promise.reject(err);
}
}
return Promise.resolve();
}
getSocket() {
return this.socket;
}
/**
* Initialize socket and associate events.
* @private
*/
streamInitSocket() {
if (this.opts.connectTimeout) {
this.timeout = setTimeout(this.connectTimeoutReached.bind(this), this.opts.connectTimeout, Date.now());
}
if (this.opts.socketPath) {
this.socket = Net.connect(this.opts.socketPath);
} else if (this.opts.stream) {
if (typeof this.opts.stream === 'function') {
const tmpSocket = this.opts.stream(
function (err, stream) {
if (err) {
this.authFailHandler(err);
return;
}
this.socket = stream ? stream : Net.connect(this.opts.port, this.opts.host);
this.socketInit();
}.bind(this)
);
if (tmpSocket) {
this.socket = tmpSocket;
this.socketInit();
}
} else {
this.authFailHandler(
Errors.createError(
'stream option is not a function. stream must be a function with (error, callback) parameter',
Errors.ER_BAD_PARAMETER_VALUE,
this.info
)
);
}
return;
} else {
this.socket = Net.connect(this.opts.port, this.opts.host);
this.socket.setNoDelay(true);
}
this.socketInit();
}
socketInit() {
this.socket.on('data', this.streamIn.onData.bind(this.streamIn));
this.socket.on('error', this.socketErrorHandler.bind(this));
this.socket.on('end', this.socketErrorHandler.bind(this));
this.socket.on(
'connect',
function () {
if (this.status === Status.CONNECTING) {
this.status = Status.AUTHENTICATING;
this.socket.setTimeout(this.opts.socketTimeout, this.socketTimeoutReached.bind(this));
this.socket.setNoDelay(true);
// keep alive for socket. This won't reset server wait_timeout use pool option idleTimeout for that
if (this.opts.keepAliveDelay) {
this.socket.setKeepAlive(true, this.opts.keepAliveDelay);
}
}
}.bind(this)
);
this.socket.writeBuf = (buf) => this.socket.write(buf);
this.socket.flush = () => {};
this.streamOut.setStream(this.socket);
}
/**
* Authentication success result handler.
*
* @private
*/
authSucceedHandler() {
//enable packet compression according to option
if (this.opts.compress) {
if (this.info.serverCapabilities & Capabilities.COMPRESS) {
this.streamOut.setStream(new CompressionOutputStream(this.socket, this.opts, this.info));
this.streamIn = new CompressionInputStream(this.streamIn, this.receiveQueue, this.opts, this.info);
this.socket.removeAllListeners('data');
this.socket.on('data', this.streamIn.onData.bind(this.streamIn));
} else if (this.opts.logger.error) {
this.opts.logger.error(
Errors.createError(
"connection is configured to use packet compression, but the server doesn't have this capability",
Errors.ER_COMPRESSION_NOT_SUPPORTED,
this.info
)
);
}
}
this.addCommand = this.opts.pipelining ? this.addCommandEnablePipeline : this.addCommandEnable;
const conn = this;
this.status = Status.INIT_CMD;
this.executeSessionVariableQuery()
.then(this.handleTimezone.bind(this))
.then(this.checkServerVersion.bind(this))
.then(this.executeInitQuery.bind(this))
.then(this.executeSessionTimeout.bind(this))
.then(() => {
clearTimeout(this.timeout);
conn.status = Status.CONNECTED;
process.nextTick(conn.connectResolveFct, conn);
const commands = conn.waitingAuthenticationQueue.toArray();
commands.forEach((cmd) => {
conn.addCommand(cmd);
});
conn.waitingAuthenticationQueue = null;
conn.connectRejectFct = null;
conn.connectResolveFct = null;
})
.catch((err) => {
if (!err.fatal) {
const res = () => {
conn.authFailHandler.call(conn, err);
};
conn.end(res, res);
} else {
conn.authFailHandler.call(conn, err);
}
});
}
/**
* Authentication failed result handler.
*
* @private
*/
authFailHandler(err) {
if (this.connectRejectFct) {
if (this.opts.logger.error) this.opts.logger.error(err);
//remove handshake command
this.receiveQueue.shift();
this.fatalError(err, true);
process.nextTick(this.connectRejectFct, err);
this.connectRejectFct = null;
}
}
/**
* Create TLS socket and associate events.
*
* @param callback callback function when done
* @private
*/
createSecureContext(callback) {
const sslOption = Object.assign({}, this.opts.ssl, {
servername: this.opts.host,
socket: this.socket
});
try {
const secureSocket = tls.connect(sslOption, callback);
secureSocket.on('data', this.streamIn.onData.bind(this.streamIn));
secureSocket.on('error', this.socketErrorHandler.bind(this));
secureSocket.on('end', this.socketErrorHandler.bind(this));
secureSocket.writeBuf = (buf) => secureSocket.write(buf);
secureSocket.flush = () => {};
this.socket.removeAllListeners('data');
this.socket = secureSocket;
this.streamOut.setStream(secureSocket);
} catch (err) {
this.socketErrorHandler(err);
}
}
/**
* Handle packet when no packet is expected.
* (there can be an ERROR packet send by server/proxy to inform that connection is ending).
*
* @param packet packet
* @private
*/
unexpectedPacket(packet) {
if (packet && packet.peek() === 0xff) {
//can receive unexpected error packet from server/proxy
//to inform that connection is closed (usually by timeout)
let err = packet.readError(this.info);
if (err.fatal && this.status < Status.CLOSING) {
this.emit('error', err);
if (this.opts.logger.error) this.opts.logger.error(err);
this.end(
() => {},
() => {}
);
}
} else if (this.status < Status.CLOSING) {
const err = Errors.createFatalError(
`receiving packet from server without active commands\nconn:${this.info.threadId ? this.info.threadId : -1}(${
packet.pos
},${packet.end})\n${Utils.log(this.opts, packet.buf, packet.pos, packet.end)}`,
Errors.ER_UNEXPECTED_PACKET,
this.info
);
if (this.opts.logger.error) this.opts.logger.error(err);
this.emit('error', err);
this.destroy();
}
}
/**
* Handle connection timeout.
*
* @private
*/
connectTimeoutReached(initialConnectionTime) {
this.timeout = null;
const handshake = this.receiveQueue.peekFront();
const err = Errors.createFatalError(
`Connection timeout: failed to create socket after ${Date.now() - initialConnectionTime}ms`,
Errors.ER_CONNECTION_TIMEOUT,
this.info,
'08S01',
null,
handshake ? handshake.stack : null
);
if (this.opts.logger.error) this.opts.logger.error(err);
this.authFailHandler(err);
}
/**
* Handle socket timeout.
*
* @private
*/
socketTimeoutReached() {
const err = Errors.createFatalError('socket timeout', Errors.ER_SOCKET_TIMEOUT, this.info);
if (this.opts.logger.error) this.opts.logger.error(err);