connection.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. // This file was modified by Oracle on June 1, 2021.
  2. // The changes involve new logic to handle an additional ERR Packet sent by
  3. // the MySQL server when the connection is closed unexpectedly.
  4. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  5. // This file was modified by Oracle on June 17, 2021.
  6. // The changes involve logic to ensure the socket connection is closed when
  7. // there is a fatal error.
  8. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  9. // This file was modified by Oracle on September 21, 2021.
  10. // The changes involve passing additional authentication factor passwords
  11. // to the ChangeUser Command instance.
  12. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  13. 'use strict';
  14. const Net = require('net');
  15. const Tls = require('tls');
  16. const Timers = require('timers');
  17. const EventEmitter = require('events').EventEmitter;
  18. const Readable = require('stream').Readable;
  19. const Queue = require('denque');
  20. const SqlString = require('sql-escaper');
  21. const { createLRU } = require('lru.min');
  22. const PacketParser = require('../packet_parser.js');
  23. const Packets = require('../packets/index.js');
  24. const Commands = require('../commands/index.js');
  25. const ConnectionConfig = require('../connection_config.js');
  26. const CharsetToEncoding = require('../constants/charset_encodings.js');
  27. const {
  28. traceCallback,
  29. tracePromise,
  30. getServerContext,
  31. shouldTrace,
  32. queryChannel,
  33. executeChannel,
  34. connectChannel,
  35. } = require('../tracing.js');
  36. let _connectionId = 0;
  37. let convertNamedPlaceholders = null;
  38. class BaseConnection extends EventEmitter {
  39. constructor(opts) {
  40. super();
  41. this.config = opts.config;
  42. // TODO: fill defaults
  43. // if no params, connect to /var/lib/mysql/mysql.sock ( /tmp/mysql.sock on OSX )
  44. // if host is given, connect to host:3306
  45. // TODO: use `/usr/local/mysql/bin/mysql_config --socket` output? as default socketPath
  46. // if there is no host/port and no socketPath parameters?
  47. if (!opts.config.stream) {
  48. if (opts.config.socketPath) {
  49. this.stream = Net.connect(opts.config.socketPath);
  50. } else {
  51. this.stream = Net.connect(opts.config.port, opts.config.host);
  52. // Optionally enable keep-alive on the socket.
  53. if (this.config.enableKeepAlive) {
  54. this.stream.on('connect', () => {
  55. this.stream.setKeepAlive(true, this.config.keepAliveInitialDelay);
  56. });
  57. }
  58. // Enable TCP_NODELAY flag. This is needed so that the network packets
  59. // are sent immediately to the server
  60. this.stream.setNoDelay(true);
  61. }
  62. // if stream is a function, treat it as "stream agent / factory"
  63. } else if (typeof opts.config.stream === 'function') {
  64. this.stream = opts.config.stream(opts);
  65. } else {
  66. this.stream = opts.config.stream;
  67. }
  68. this._internalId = _connectionId++;
  69. this._commands = new Queue();
  70. this._command = null;
  71. this._paused = false;
  72. this._paused_packets = new Queue();
  73. this._statements = createLRU({
  74. max: this.config.maxPreparedStatements,
  75. onEviction: function (_, statement) {
  76. statement.close();
  77. },
  78. });
  79. this.serverCapabilityFlags = 0;
  80. this.authorized = false;
  81. this.sequenceId = 0;
  82. this.compressedSequenceId = 0;
  83. this.threadId = null;
  84. this._handshakePacket = null;
  85. this._fatalError = null;
  86. this._protocolError = null;
  87. this._outOfOrderPackets = [];
  88. this.clientEncoding = CharsetToEncoding[this.config.charsetNumber];
  89. this.stream.on('error', this._handleNetworkError.bind(this));
  90. // see https://gist.github.com/khoomeister/4985691#use-that-instead-of-bind
  91. this.packetParser = new PacketParser((p) => {
  92. this.handlePacket(p);
  93. });
  94. this.stream.on('data', (data) => {
  95. if (this.connectTimeout) {
  96. Timers.clearTimeout(this.connectTimeout);
  97. this.connectTimeout = null;
  98. }
  99. this.packetParser.execute(data);
  100. });
  101. this.stream.on('end', () => {
  102. // emit the end event so that the pooled connection can close the connection
  103. this.emit('end');
  104. });
  105. this.stream.on('close', () => {
  106. // we need to set this flag everywhere where we want connection to close
  107. if (this._closing) {
  108. return;
  109. }
  110. if (!this._protocolError) {
  111. // no particular error message before disconnect
  112. this._protocolError = new Error(
  113. 'Connection lost: The server closed the connection.'
  114. );
  115. this._protocolError.fatal = true;
  116. this._protocolError.code = 'PROTOCOL_CONNECTION_LOST';
  117. }
  118. this._notifyError(this._protocolError);
  119. });
  120. let handshakeCommand;
  121. if (!this.config.isServer) {
  122. handshakeCommand = new Commands.ClientHandshake(this.config.clientFlags);
  123. handshakeCommand.on('end', () => {
  124. // this happens when handshake finishes early either because there was
  125. // some fatal error or the server sent an error packet instead of
  126. // an hello packet (for example, 'Too many connections' error)
  127. if (
  128. !handshakeCommand.handshake ||
  129. this._fatalError ||
  130. this._protocolError
  131. ) {
  132. return;
  133. }
  134. this._handshakePacket = handshakeCommand.handshake;
  135. this.threadId = handshakeCommand.handshake.connectionId;
  136. this.emit('connect', handshakeCommand.handshake);
  137. });
  138. handshakeCommand.on('error', (err) => {
  139. this._closing = true;
  140. this._notifyError(err);
  141. });
  142. this.addCommand(handshakeCommand);
  143. // Trace the connection handshake
  144. if (shouldTrace(connectChannel)) {
  145. const config = this.config;
  146. tracePromise(
  147. connectChannel,
  148. () =>
  149. new Promise((resolve, reject) => {
  150. /* eslint-disable prefer-const */
  151. let onConnect, onError;
  152. onConnect = (param) => {
  153. this.removeListener('error', onError);
  154. resolve(param);
  155. };
  156. onError = (err) => {
  157. this.removeListener('connect', onConnect);
  158. reject(err);
  159. };
  160. /* eslint-enable prefer-const */
  161. this.once('connect', onConnect);
  162. this.once('error', onError);
  163. }),
  164. () => {
  165. const server = getServerContext(config);
  166. return {
  167. database: config.database || '',
  168. serverAddress: server.serverAddress,
  169. serverPort: server.serverPort,
  170. user: config.user || '',
  171. };
  172. }
  173. ).catch(() => {
  174. // errors are already handled by the handshake error listener
  175. });
  176. }
  177. }
  178. // in case there was no initial handshake but we need to read sting, assume it utf-8
  179. // most common example: "Too many connections" error ( packet is sent immediately on connection attempt, we don't know server encoding yet)
  180. // will be overwritten with actual encoding value as soon as server handshake packet is received
  181. this.serverEncoding = 'utf8';
  182. if (this.config.connectTimeout) {
  183. const timeoutHandler = this._handleTimeoutError.bind(this);
  184. this.connectTimeout = Timers.setTimeout(
  185. timeoutHandler,
  186. this.config.connectTimeout
  187. );
  188. }
  189. }
  190. _addCommandClosedState(cmd) {
  191. const err = new Error(
  192. "Can't add new command when connection is in closed state"
  193. );
  194. err.fatal = true;
  195. if (cmd.onResult) {
  196. cmd.onResult(err);
  197. } else {
  198. this.emit('error', err);
  199. }
  200. }
  201. _handleFatalError(err) {
  202. err.fatal = true;
  203. // stop receiving packets
  204. this.stream.removeAllListeners('data');
  205. this.addCommand = this._addCommandClosedState;
  206. this.write = () => {
  207. this.emit('error', new Error("Can't write in closed state"));
  208. };
  209. this._notifyError(err);
  210. this._fatalError = err;
  211. }
  212. _handleNetworkError(err) {
  213. if (this.connectTimeout) {
  214. Timers.clearTimeout(this.connectTimeout);
  215. this.connectTimeout = null;
  216. }
  217. // Do not throw an error when a connection ends with a RST,ACK packet
  218. if (err.code === 'ECONNRESET' && this._closing) {
  219. return;
  220. }
  221. this._handleFatalError(err);
  222. }
  223. _handleTimeoutError() {
  224. if (this.connectTimeout) {
  225. Timers.clearTimeout(this.connectTimeout);
  226. this.connectTimeout = null;
  227. }
  228. this.stream.destroy && this.stream.destroy();
  229. const err = new Error('connect ETIMEDOUT');
  230. err.errorno = 'ETIMEDOUT';
  231. err.code = 'ETIMEDOUT';
  232. err.syscall = 'connect';
  233. this._handleNetworkError(err);
  234. }
  235. // notify all commands in the queue and bubble error as connection "error"
  236. // called on stream error or unexpected termination
  237. _notifyError(err) {
  238. if (this.connectTimeout) {
  239. Timers.clearTimeout(this.connectTimeout);
  240. this.connectTimeout = null;
  241. }
  242. // prevent from emitting 'PROTOCOL_CONNECTION_LOST' after EPIPE or ECONNRESET
  243. if (this._fatalError) {
  244. return;
  245. }
  246. let command;
  247. // if there is no active command, notify connection
  248. // if there are commands and all of them have callbacks, pass error via callback
  249. let bubbleErrorToConnection = !this._command;
  250. if (this._command && this._command.onResult) {
  251. this._command.onResult(err);
  252. this._command = null;
  253. // connection handshake is special because we allow it to be implicit
  254. // if error happened during handshake, but there are others commands in queue
  255. // then bubble error to other commands and not to connection
  256. } else if (
  257. !(
  258. this._command &&
  259. this._command.constructor === Commands.ClientHandshake &&
  260. this._commands.length > 0
  261. )
  262. ) {
  263. bubbleErrorToConnection = true;
  264. }
  265. while ((command = this._commands.shift())) {
  266. if (command.onResult) {
  267. command.onResult(err);
  268. } else {
  269. bubbleErrorToConnection = true;
  270. }
  271. }
  272. // notify connection if some comands in the queue did not have callbacks
  273. // or if this is pool connection ( so it can be removed from pool )
  274. if (bubbleErrorToConnection || this._pool) {
  275. this.emit('error', err);
  276. }
  277. // close connection after emitting the event in case of a fatal error
  278. if (err.fatal) {
  279. this.close();
  280. }
  281. }
  282. write(buffer) {
  283. const result = this.stream.write(buffer, (err) => {
  284. if (err) {
  285. this._handleNetworkError(err);
  286. }
  287. });
  288. if (!result) {
  289. this.stream.emit('pause');
  290. }
  291. }
  292. // http://dev.mysql.com/doc/internals/en/sequence-id.html
  293. //
  294. // The sequence-id is incremented with each packet and may wrap around.
  295. // It starts at 0 and is reset to 0 when a new command
  296. // begins in the Command Phase.
  297. // http://dev.mysql.com/doc/internals/en/example-several-mysql-packets.html
  298. _resetSequenceId() {
  299. this.sequenceId = 0;
  300. this.compressedSequenceId = 0;
  301. }
  302. _bumpCompressedSequenceId(numPackets) {
  303. this.compressedSequenceId += numPackets;
  304. this.compressedSequenceId %= 256;
  305. }
  306. _bumpSequenceId(numPackets) {
  307. this.sequenceId += numPackets;
  308. this.sequenceId %= 256;
  309. }
  310. writePacket(packet) {
  311. const MAX_PACKET_LENGTH = 16777215;
  312. const length = packet.length();
  313. let chunk, offset, header;
  314. if (length < MAX_PACKET_LENGTH) {
  315. packet.writeHeader(this.sequenceId);
  316. if (this.config.debug) {
  317. console.log(
  318. `${this._internalId} ${this.connectionId} <== ${this._command._commandName}#${this._command.stateName()}(${[this.sequenceId, packet._name, packet.length()].join(',')})`
  319. );
  320. console.log(
  321. `${this._internalId} ${this.connectionId} <== ${packet.buffer.toString('hex')}`
  322. );
  323. }
  324. this._bumpSequenceId(1);
  325. this.write(packet.buffer);
  326. } else {
  327. if (this.config.debug) {
  328. console.log(
  329. `${this._internalId} ${this.connectionId} <== Writing large packet, raw content not written:`
  330. );
  331. console.log(
  332. `${this._internalId} ${this.connectionId} <== ${this._command._commandName}#${this._command.stateName()}(${[this.sequenceId, packet._name, packet.length()].join(',')})`
  333. );
  334. }
  335. for (offset = 4; offset < 4 + length; offset += MAX_PACKET_LENGTH) {
  336. chunk = packet.buffer.slice(offset, offset + MAX_PACKET_LENGTH);
  337. if (chunk.length === MAX_PACKET_LENGTH) {
  338. header = Buffer.from([0xff, 0xff, 0xff, this.sequenceId]);
  339. } else {
  340. header = Buffer.from([
  341. chunk.length & 0xff,
  342. (chunk.length >> 8) & 0xff,
  343. (chunk.length >> 16) & 0xff,
  344. this.sequenceId,
  345. ]);
  346. }
  347. this._bumpSequenceId(1);
  348. this.write(header);
  349. this.write(chunk);
  350. }
  351. }
  352. }
  353. // 0.11+ environment
  354. startTLS(onSecure) {
  355. if (this.config.debug) {
  356. console.log('Upgrading connection to TLS');
  357. }
  358. const secureContext = Tls.createSecureContext({
  359. ca: this.config.ssl.ca,
  360. cert: this.config.ssl.cert,
  361. ciphers: this.config.ssl.ciphers,
  362. key: this.config.ssl.key,
  363. passphrase: this.config.ssl.passphrase,
  364. minVersion: this.config.ssl.minVersion,
  365. maxVersion: this.config.ssl.maxVersion,
  366. });
  367. const rejectUnauthorized = this.config.ssl.rejectUnauthorized;
  368. const verifyIdentity = this.config.ssl.verifyIdentity;
  369. const servername = Net.isIP(this.config.host)
  370. ? undefined
  371. : this.config.host;
  372. let secureEstablished = false;
  373. this.stream.removeAllListeners('data');
  374. const secureSocket = Tls.connect(
  375. {
  376. rejectUnauthorized,
  377. requestCert: rejectUnauthorized,
  378. checkServerIdentity: verifyIdentity
  379. ? Tls.checkServerIdentity
  380. : function () {
  381. return undefined;
  382. },
  383. secureContext,
  384. isServer: false,
  385. socket: this.stream,
  386. servername,
  387. },
  388. () => {
  389. secureEstablished = true;
  390. if (rejectUnauthorized) {
  391. if (typeof servername === 'string' && verifyIdentity) {
  392. const cert = secureSocket.getPeerCertificate(true);
  393. const serverIdentityCheckError = Tls.checkServerIdentity(
  394. servername,
  395. cert
  396. );
  397. if (serverIdentityCheckError) {
  398. onSecure(serverIdentityCheckError);
  399. return;
  400. }
  401. }
  402. }
  403. onSecure();
  404. }
  405. );
  406. // error handler for secure socket
  407. secureSocket.on('error', (err) => {
  408. if (secureEstablished) {
  409. this._handleNetworkError(err);
  410. } else {
  411. onSecure(err);
  412. }
  413. });
  414. secureSocket.on('data', (data) => {
  415. this.packetParser.execute(data);
  416. });
  417. this.stream = secureSocket;
  418. }
  419. protocolError(message, code) {
  420. // Starting with MySQL 8.0.24, if the client closes the connection
  421. // unexpectedly, the server will send a last ERR Packet, which we can
  422. // safely ignore.
  423. // https://dev.mysql.com/worklog/task/?id=12999
  424. if (this._closing) {
  425. return;
  426. }
  427. const err = new Error(message);
  428. err.fatal = true;
  429. err.code = code || 'PROTOCOL_ERROR';
  430. this.emit('error', err);
  431. }
  432. get state() {
  433. // Error state has highest priority
  434. if (this._fatalError || this._protocolError) {
  435. return 'error';
  436. }
  437. // Closing state has second priority
  438. if (this._closing || (this.stream && this.stream.destroyed)) {
  439. return 'disconnected';
  440. }
  441. // Authenticated state has third priority
  442. if (this.authorized) {
  443. return 'authenticated';
  444. }
  445. // Connected state: handshake completed but not yet authorized
  446. // This matches the original mysql driver's 'connected' state
  447. if (this._handshakePacket) {
  448. return 'connected';
  449. }
  450. // Protocol handshake state: connection established, handshake in progress
  451. if (this.stream && !this.stream.destroyed) {
  452. return 'protocol_handshake';
  453. }
  454. // Default: not connected
  455. return 'disconnected';
  456. }
  457. get fatalError() {
  458. return this._fatalError;
  459. }
  460. handlePacket(packet) {
  461. if (this._paused) {
  462. this._paused_packets.push(packet);
  463. return;
  464. }
  465. if (this.config.debug) {
  466. if (packet) {
  467. console.log(
  468. ` raw: ${packet.buffer
  469. .slice(packet.offset, packet.offset + packet.length())
  470. .toString('hex')}`
  471. );
  472. console.trace();
  473. const commandName = this._command
  474. ? this._command._commandName
  475. : '(no command)';
  476. const stateName = this._command
  477. ? this._command.stateName()
  478. : '(no command)';
  479. console.log(
  480. `${this._internalId} ${this.connectionId} ==> ${commandName}#${stateName}(${[packet.sequenceId, packet.type(), packet.length()].join(',')})`
  481. );
  482. }
  483. }
  484. if (!this._command) {
  485. const marker = packet.peekByte();
  486. // If it's an Err Packet, we should use it.
  487. if (marker === 0xff) {
  488. const error = Packets.Error.fromPacket(packet);
  489. this.protocolError(error.message, error.code);
  490. } else {
  491. // Otherwise, it means it's some other unexpected packet.
  492. this.protocolError(
  493. 'Unexpected packet while no commands in the queue',
  494. 'PROTOCOL_UNEXPECTED_PACKET'
  495. );
  496. }
  497. this.close();
  498. return;
  499. }
  500. if (packet) {
  501. // Note: when server closes connection due to inactivity, Err packet ER_CLIENT_INTERACTION_TIMEOUT from MySQL 8.0.24, sequenceId will be 0
  502. if (this.sequenceId !== packet.sequenceId) {
  503. const err = new Error(
  504. `Warning: got packets out of order. Expected ${this.sequenceId} but received ${packet.sequenceId}`
  505. );
  506. err.expected = this.sequenceId;
  507. err.received = packet.sequenceId;
  508. this.emit('warn', err); // REVIEW
  509. console.error(err.message);
  510. }
  511. this._bumpSequenceId(packet.numPackets);
  512. }
  513. try {
  514. if (this._fatalError) {
  515. // skip remaining packets after client is in the error state
  516. return;
  517. }
  518. const done = this._command.execute(packet, this);
  519. if (done) {
  520. this._command = this._commands.shift();
  521. if (this._command) {
  522. this.sequenceId = 0;
  523. this.compressedSequenceId = 0;
  524. this.handlePacket();
  525. }
  526. }
  527. } catch (err) {
  528. this._handleFatalError(err);
  529. this.stream.destroy();
  530. }
  531. }
  532. addCommand(cmd) {
  533. // this.compressedSequenceId = 0;
  534. // this.sequenceId = 0;
  535. if (this.config.debug) {
  536. const commandName = cmd.constructor.name;
  537. console.log(`Add command: ${commandName}`);
  538. cmd._commandName = commandName;
  539. }
  540. if (!this._command) {
  541. this._command = cmd;
  542. this.handlePacket();
  543. } else {
  544. this._commands.push(cmd);
  545. }
  546. return cmd;
  547. }
  548. format(sql, values) {
  549. if (typeof this.config.queryFormat === 'function') {
  550. return this.config.queryFormat.call(
  551. this,
  552. sql,
  553. values,
  554. this.config.timezone
  555. );
  556. }
  557. const opts = {
  558. sql: sql,
  559. values: values,
  560. };
  561. this._resolveNamedPlaceholders(opts);
  562. return SqlString.format(
  563. opts.sql,
  564. opts.values,
  565. this.config.stringifyObjects,
  566. this.config.timezone
  567. );
  568. }
  569. escape(value) {
  570. return SqlString.escape(value, false, this.config.timezone);
  571. }
  572. escapeId(value) {
  573. return SqlString.escapeId(value, false);
  574. }
  575. raw(sql) {
  576. return SqlString.raw(sql);
  577. }
  578. _resolveNamedPlaceholders(options) {
  579. let unnamed;
  580. if (this.config.namedPlaceholders || options.namedPlaceholders) {
  581. if (Array.isArray(options.values)) {
  582. // if an array is provided as the values, assume the conversion is not necessary.
  583. // this allows the usage of unnamed placeholders even if the namedPlaceholders flag is enabled.
  584. return;
  585. }
  586. if (convertNamedPlaceholders === null) {
  587. convertNamedPlaceholders = require('named-placeholders')();
  588. }
  589. unnamed = convertNamedPlaceholders(options.sql, options.values);
  590. options.sql = unnamed[0];
  591. options.values = unnamed[1];
  592. }
  593. }
  594. query(sql, values, cb) {
  595. let cmdQuery;
  596. if (sql.constructor === Commands.Query) {
  597. cmdQuery = sql;
  598. } else {
  599. cmdQuery = BaseConnection.createQuery(sql, values, cb, this.config);
  600. }
  601. this._resolveNamedPlaceholders(cmdQuery);
  602. const rawSql = this.format(
  603. cmdQuery.sql,
  604. cmdQuery.values !== undefined ? cmdQuery.values : []
  605. );
  606. cmdQuery.sql = rawSql;
  607. if (cmdQuery.onResult) {
  608. // Callback mode: traceCallback wraps the callback with tracing lifecycle, or calls through directly when no subscribers are registered
  609. traceCallback(
  610. queryChannel,
  611. (wrappedCb) => {
  612. cmdQuery.onResult = wrappedCb;
  613. this.addCommand(cmdQuery);
  614. },
  615. 0,
  616. () => {
  617. const server = getServerContext(this.config);
  618. return {
  619. query: cmdQuery.sql,
  620. values: cmdQuery.values,
  621. database: this.config.database || '',
  622. serverAddress: server.serverAddress,
  623. serverPort: server.serverPort,
  624. };
  625. },
  626. null,
  627. cmdQuery.onResult
  628. );
  629. } else if (shouldTrace(queryChannel)) {
  630. // Event-emitter mode: tracePromise wraps the async lifecycle
  631. tracePromise(
  632. queryChannel,
  633. () =>
  634. new Promise((resolve, reject) => {
  635. cmdQuery.once('error', reject);
  636. cmdQuery.once('end', () => resolve());
  637. this.addCommand(cmdQuery);
  638. }),
  639. () => {
  640. const server = getServerContext(this.config);
  641. return {
  642. query: cmdQuery.sql,
  643. values: cmdQuery.values,
  644. database: this.config.database || '',
  645. serverAddress: server.serverAddress,
  646. serverPort: server.serverPort,
  647. };
  648. }
  649. ).catch(() => {
  650. // errors are already emitted on the command
  651. });
  652. } else {
  653. this.addCommand(cmdQuery);
  654. }
  655. return cmdQuery;
  656. }
  657. pause() {
  658. this._paused = true;
  659. this.stream.pause();
  660. }
  661. resume() {
  662. let packet;
  663. this._paused = false;
  664. while ((packet = this._paused_packets.shift())) {
  665. this.handlePacket(packet);
  666. // don't resume if packet handler paused connection
  667. if (this._paused) {
  668. return;
  669. }
  670. }
  671. this.stream.resume();
  672. }
  673. // TODO: named placeholders support
  674. prepare(options, cb) {
  675. if (typeof options === 'string') {
  676. options = { sql: options };
  677. }
  678. return this.addCommand(new Commands.Prepare(options, cb));
  679. }
  680. unprepare(sql) {
  681. let options = {};
  682. if (typeof sql === 'object') {
  683. options = sql;
  684. } else {
  685. options.sql = sql;
  686. }
  687. const key = BaseConnection.statementKey(options);
  688. const stmt = this._statements.get(key);
  689. if (stmt) {
  690. this._statements.delete(key);
  691. stmt.close();
  692. }
  693. return stmt;
  694. }
  695. execute(sql, values, cb) {
  696. let options = {
  697. infileStreamFactory: this.config.infileStreamFactory,
  698. };
  699. if (typeof sql === 'object') {
  700. // execute(options, cb)
  701. options = {
  702. ...options,
  703. ...sql,
  704. sql: sql.sql,
  705. values: sql.values,
  706. };
  707. if (typeof values === 'function') {
  708. cb = values;
  709. } else {
  710. options.values = options.values || values;
  711. }
  712. } else if (typeof values === 'function') {
  713. // execute(sql, cb)
  714. cb = values;
  715. options.sql = sql;
  716. options.values = undefined;
  717. } else {
  718. // execute(sql, values, cb)
  719. options.sql = sql;
  720. options.values = values;
  721. }
  722. this._resolveNamedPlaceholders(options);
  723. // check for values containing undefined
  724. if (options.values) {
  725. //If namedPlaceholder is not enabled and object is passed as bind parameters
  726. if (!Array.isArray(options.values)) {
  727. throw new TypeError(
  728. 'Bind parameters must be array if namedPlaceholders parameter is not enabled'
  729. );
  730. }
  731. options.values.forEach((val) => {
  732. //If namedPlaceholder is not enabled and object is passed as bind parameters
  733. if (!Array.isArray(options.values)) {
  734. throw new TypeError(
  735. 'Bind parameters must be array if namedPlaceholders parameter is not enabled'
  736. );
  737. }
  738. if (val === undefined) {
  739. throw new TypeError(
  740. 'Bind parameters must not contain undefined. To pass SQL NULL specify JS null'
  741. );
  742. }
  743. if (typeof val === 'function') {
  744. throw new TypeError(
  745. 'Bind parameters must not contain function(s). To pass the body of a function as a string call .toString() first'
  746. );
  747. }
  748. });
  749. }
  750. const executeCommand = new Commands.Execute(options, cb);
  751. const prepareAndExecute = (errorCb) => {
  752. const prepareCommand = new Commands.Prepare(options, (err, stmt) => {
  753. if (err) {
  754. // skip execute command if prepare failed
  755. executeCommand.start = function () {
  756. return null;
  757. };
  758. errorCb(err);
  759. executeCommand.emit('end');
  760. return;
  761. }
  762. executeCommand.statement = stmt;
  763. });
  764. this.addCommand(prepareCommand);
  765. this.addCommand(executeCommand);
  766. };
  767. if (executeCommand.onResult) {
  768. // Callback mode: traceCallback wraps the callback with tracing lifecycle, or calls through directly when no subscribers are registered
  769. const origExecCb = executeCommand.onResult;
  770. traceCallback(
  771. executeChannel,
  772. (wrappedCb) => {
  773. executeCommand.onResult = wrappedCb;
  774. prepareAndExecute(wrappedCb);
  775. },
  776. 0,
  777. () => {
  778. const server = getServerContext(this.config);
  779. return {
  780. query: options.sql,
  781. values: options.values,
  782. database: this.config.database || '',
  783. serverAddress: server.serverAddress,
  784. serverPort: server.serverPort,
  785. };
  786. },
  787. null,
  788. origExecCb
  789. );
  790. } else if (shouldTrace(executeChannel)) {
  791. // Event-emitter mode: tracePromise wraps the async lifecycle
  792. tracePromise(
  793. executeChannel,
  794. () =>
  795. new Promise((resolve, reject) => {
  796. prepareAndExecute((err) => {
  797. executeCommand.emit('error', err);
  798. });
  799. executeCommand.once('error', reject);
  800. executeCommand.once('end', () => resolve());
  801. }),
  802. () => {
  803. const server = getServerContext(this.config);
  804. return {
  805. query: options.sql,
  806. values: options.values,
  807. database: this.config.database || '',
  808. serverAddress: server.serverAddress,
  809. serverPort: server.serverPort,
  810. };
  811. }
  812. ).catch(() => {
  813. // errors are already emitted on the command
  814. });
  815. } else {
  816. prepareAndExecute((err) => {
  817. executeCommand.emit('error', err);
  818. });
  819. }
  820. return executeCommand;
  821. }
  822. changeUser(options, callback) {
  823. if (!callback && typeof options === 'function') {
  824. callback = options;
  825. options = {};
  826. }
  827. const charsetNumber = options.charset
  828. ? ConnectionConfig.getCharsetNumber(options.charset)
  829. : this.config.charsetNumber;
  830. return this.addCommand(
  831. new Commands.ChangeUser(
  832. {
  833. user: options.user || this.config.user,
  834. // for the purpose of multi-factor authentication, or not, the main
  835. // password (used for the 1st authentication factor) can also be
  836. // provided via the "password1" option
  837. password:
  838. options.password ||
  839. options.password1 ||
  840. this.config.password ||
  841. this.config.password1,
  842. password2: options.password2 || this.config.password2,
  843. password3: options.password3 || this.config.password3,
  844. passwordSha1: options.passwordSha1 || this.config.passwordSha1,
  845. database: options.database || this.config.database,
  846. timeout: options.timeout,
  847. charsetNumber: charsetNumber,
  848. currentConfig: this.config,
  849. },
  850. (err) => {
  851. if (err) {
  852. err.fatal = true;
  853. }
  854. if (callback) {
  855. callback(err);
  856. }
  857. }
  858. )
  859. );
  860. }
  861. // transaction helpers
  862. beginTransaction(cb) {
  863. return this.query('START TRANSACTION', cb);
  864. }
  865. commit(cb) {
  866. return this.query('COMMIT', cb);
  867. }
  868. rollback(cb) {
  869. return this.query('ROLLBACK', cb);
  870. }
  871. ping(cb) {
  872. return this.addCommand(new Commands.Ping(cb));
  873. }
  874. reset(cb) {
  875. return this.addCommand(new Commands.ResetConnection(cb));
  876. }
  877. _registerSlave(opts, cb) {
  878. return this.addCommand(new Commands.RegisterSlave(opts, cb));
  879. }
  880. _binlogDump(opts, cb) {
  881. return this.addCommand(new Commands.BinlogDump(opts, cb));
  882. }
  883. // currently just alias to close
  884. destroy() {
  885. this.close();
  886. }
  887. close() {
  888. if (this.connectTimeout) {
  889. Timers.clearTimeout(this.connectTimeout);
  890. this.connectTimeout = null;
  891. }
  892. this._closing = true;
  893. this.stream.end();
  894. this.addCommand = this._addCommandClosedState;
  895. }
  896. createBinlogStream(opts) {
  897. // TODO: create proper stream class
  898. // TODO: use through2
  899. let test = 1;
  900. const stream = new Readable({ objectMode: true });
  901. stream._read = function () {
  902. return {
  903. data: test++,
  904. };
  905. };
  906. this._registerSlave(opts, () => {
  907. const dumpCmd = this._binlogDump(opts);
  908. dumpCmd.on('event', (ev) => {
  909. stream.push(ev);
  910. });
  911. dumpCmd.on('eof', () => {
  912. stream.push(null);
  913. // if non-blocking, then close stream to prevent errors
  914. if (opts.flags && opts.flags & 0x01) {
  915. this.close();
  916. }
  917. });
  918. // TODO: pipe errors as well
  919. });
  920. return stream;
  921. }
  922. connect(cb) {
  923. if (!cb) {
  924. return;
  925. }
  926. if (this._fatalError || this._protocolError) {
  927. return cb(this._fatalError || this._protocolError);
  928. }
  929. if (this._handshakePacket) {
  930. return cb(null, this);
  931. }
  932. /* eslint-disable prefer-const */
  933. let onError, onConnect;
  934. onError = (param) => {
  935. this.removeListener('connect', onConnect);
  936. cb(param);
  937. };
  938. onConnect = (param) => {
  939. this.removeListener('error', onError);
  940. cb(null, param);
  941. };
  942. /* eslint-enable prefer-const */
  943. this.once('error', onError);
  944. this.once('connect', onConnect);
  945. }
  946. // ===================================
  947. // outgoing server connection methods
  948. // ===================================
  949. writeColumns(columns) {
  950. this.writePacket(Packets.ResultSetHeader.toPacket(columns.length));
  951. columns.forEach((column) => {
  952. this.writePacket(
  953. Packets.ColumnDefinition.toPacket(column, this.serverConfig.encoding)
  954. );
  955. });
  956. this.writeEof();
  957. }
  958. // row is array of columns, not hash
  959. writeTextRow(column) {
  960. this.writePacket(
  961. Packets.TextRow.toPacket(column, this.serverConfig.encoding)
  962. );
  963. }
  964. writeBinaryRow(column) {
  965. this.writePacket(
  966. Packets.BinaryRow.toPacket(column, this.serverConfig.encoding)
  967. );
  968. }
  969. writeTextResult(rows, columns, binary = false) {
  970. this.writeColumns(columns);
  971. rows.forEach((row) => {
  972. const arrayRow = new Array(columns.length);
  973. columns.forEach((column) => {
  974. arrayRow.push(row[column.name]);
  975. });
  976. if (binary) {
  977. this.writeBinaryRow(arrayRow);
  978. } else this.writeTextRow(arrayRow);
  979. });
  980. this.writeEof();
  981. }
  982. writeEof(warnings, statusFlags) {
  983. this.writePacket(Packets.EOF.toPacket(warnings, statusFlags));
  984. }
  985. writeOk(args) {
  986. if (!args) {
  987. args = { affectedRows: 0 };
  988. }
  989. this.writePacket(Packets.OK.toPacket(args, this.serverConfig.encoding));
  990. }
  991. writeError(args) {
  992. // if we want to send error before initial hello was sent, use default encoding
  993. const encoding = this.serverConfig ? this.serverConfig.encoding : 'cesu8';
  994. this.writePacket(Packets.Error.toPacket(args, encoding));
  995. }
  996. serverHandshake(args) {
  997. this.serverConfig = args;
  998. this.serverConfig.encoding =
  999. CharsetToEncoding[this.serverConfig.characterSet];
  1000. return this.addCommand(new Commands.ServerHandshake(args));
  1001. }
  1002. [Symbol.dispose]() {
  1003. if (!this._closing) {
  1004. this.end();
  1005. }
  1006. }
  1007. // ===============================================================
  1008. end(callback) {
  1009. if (this.config.isServer) {
  1010. this._closing = true;
  1011. const quitCmd = new EventEmitter();
  1012. setImmediate(() => {
  1013. this.stream.end();
  1014. quitCmd.emit('end');
  1015. });
  1016. return quitCmd;
  1017. }
  1018. // trigger error if more commands enqueued after end command
  1019. const quitCmd = this.addCommand(new Commands.Quit(callback));
  1020. this.addCommand = this._addCommandClosedState;
  1021. return quitCmd;
  1022. }
  1023. static createQuery(sql, values, cb, config) {
  1024. let options = {
  1025. rowsAsArray: config.rowsAsArray,
  1026. infileStreamFactory: config.infileStreamFactory,
  1027. };
  1028. if (typeof sql === 'object') {
  1029. // query(options, cb)
  1030. options = {
  1031. ...options,
  1032. ...sql,
  1033. sql: sql.sql,
  1034. values: sql.values,
  1035. };
  1036. if (typeof values === 'function') {
  1037. cb = values;
  1038. } else if (values !== undefined) {
  1039. options.values = values;
  1040. }
  1041. } else if (typeof values === 'function') {
  1042. // query(sql, cb)
  1043. cb = values;
  1044. options.sql = sql;
  1045. options.values = undefined;
  1046. } else {
  1047. // query(sql, values, cb)
  1048. options.sql = sql;
  1049. options.values = values;
  1050. }
  1051. return new Commands.Query(options, cb);
  1052. }
  1053. static statementKey(options) {
  1054. return `${typeof options.nestTables}/${options.nestTables}/${options.rowsAsArray}${options.sql}`;
  1055. }
  1056. }
  1057. module.exports = BaseConnection;