query.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. 'use strict';
  2. const process = require('process');
  3. const Timers = require('timers');
  4. const Readable = require('stream').Readable;
  5. const Command = require('./command.js');
  6. const Packets = require('../packets/index.js');
  7. const getTextParser = require('../parsers/text_parser.js');
  8. const staticParser = require('../parsers/static_text_parser.js');
  9. const ServerStatus = require('../constants/server_status.js');
  10. const EmptyPacket = new Packets.Packet(0, Buffer.allocUnsafe(4), 0, 4);
  11. // http://dev.mysql.com/doc/internals/en/com-query.html
  12. class Query extends Command {
  13. constructor(options, callback) {
  14. super();
  15. this.sql = options.sql;
  16. this.values = options.values;
  17. this._queryOptions = options;
  18. this.namedPlaceholders = options.namedPlaceholders || false;
  19. this.onResult = callback;
  20. this.timeout = options.timeout;
  21. this.queryTimeout = null;
  22. this._fieldCount = 0;
  23. this._rowParser = null;
  24. this._fields = [];
  25. this._rows = [];
  26. this._receivedFieldsCount = 0;
  27. this._resultIndex = 0;
  28. this._localStream = null;
  29. this._unpipeStream = function () {};
  30. this._streamFactory = options.infileStreamFactory;
  31. this._connection = null;
  32. }
  33. then() {
  34. const err =
  35. "You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://sidorares.github.io/node-mysql2/docs#using-promise-wrapper, or the mysql2 documentation at https://sidorares.github.io/node-mysql2/docs/documentation/promise-wrapper";
  36. console.log(err);
  37. throw new Error(err);
  38. }
  39. /* eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }] */
  40. start(_packet, connection) {
  41. if (connection.config.debug) {
  42. console.log(' Sending query command: %s', this.sql);
  43. }
  44. this._connection = connection;
  45. this.options = Object.assign({}, connection.config, this._queryOptions);
  46. this._setTimeout();
  47. const clientFlags =
  48. connection.config.clientFlags & (connection.serverCapabilityFlags || 0);
  49. const cmdPacket = new Packets.Query(
  50. this.sql,
  51. connection.config.charsetNumber,
  52. this._queryOptions.attributes,
  53. clientFlags
  54. );
  55. connection.writePacket(cmdPacket.toPacket(1));
  56. return Query.prototype.resultsetHeader;
  57. }
  58. done() {
  59. this._unpipeStream();
  60. // if all ready timeout, return null directly
  61. if (this.timeout && !this.queryTimeout) {
  62. return null;
  63. }
  64. // else clear timer
  65. if (this.queryTimeout) {
  66. Timers.clearTimeout(this.queryTimeout);
  67. this.queryTimeout = null;
  68. }
  69. if (this.onResult) {
  70. let rows, fields;
  71. if (this._resultIndex === 0) {
  72. rows = this._rows[0];
  73. fields = this._fields[0];
  74. } else {
  75. rows = this._rows;
  76. fields = this._fields;
  77. }
  78. if (fields) {
  79. process.nextTick(() => {
  80. this.onResult(null, rows, fields);
  81. });
  82. } else {
  83. process.nextTick(() => {
  84. this.onResult(null, rows);
  85. });
  86. }
  87. }
  88. return null;
  89. }
  90. doneInsert(rs) {
  91. if (this._localStreamError) {
  92. if (this.onResult) {
  93. this.onResult(this._localStreamError, rs);
  94. } else {
  95. this.emit('error', this._localStreamError);
  96. }
  97. return null;
  98. }
  99. this._rows.push(rs);
  100. this._fields.push(void 0);
  101. this.emit('fields', void 0);
  102. this.emit('result', rs);
  103. if (rs.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) {
  104. this._resultIndex++;
  105. return this.resultsetHeader;
  106. }
  107. return this.done();
  108. }
  109. resultsetHeader(packet, connection) {
  110. const rs = new Packets.ResultSetHeader(packet, connection);
  111. this._fieldCount = rs.fieldCount;
  112. if (connection.config.debug) {
  113. console.log(
  114. ` Resultset header received, expecting ${rs.fieldCount} column definition packets`
  115. );
  116. }
  117. if (this._fieldCount === 0) {
  118. return this.doneInsert(rs);
  119. }
  120. if (this._fieldCount === null) {
  121. return this._streamLocalInfile(connection, rs.infileName);
  122. }
  123. this._receivedFieldsCount = 0;
  124. this._rows.push([]);
  125. this._fields.push([]);
  126. return this.readField;
  127. }
  128. _streamLocalInfile(connection, path) {
  129. if (this._streamFactory) {
  130. this._localStream = this._streamFactory(path);
  131. } else {
  132. this._localStreamError = new Error(
  133. `As a result of LOCAL INFILE command server wants to read ${path} file, but as of v2.0 you must provide streamFactory option returning ReadStream.`
  134. );
  135. connection.writePacket(EmptyPacket);
  136. return this.infileOk;
  137. }
  138. const onConnectionError = () => {
  139. this._unpipeStream();
  140. };
  141. const onDrain = () => {
  142. this._localStream.resume();
  143. };
  144. const onPause = () => {
  145. this._localStream.pause();
  146. };
  147. const onData = function (data) {
  148. const dataWithHeader = Buffer.allocUnsafe(data.length + 4);
  149. data.copy(dataWithHeader, 4);
  150. connection.writePacket(
  151. new Packets.Packet(0, dataWithHeader, 0, dataWithHeader.length)
  152. );
  153. };
  154. const onEnd = () => {
  155. connection.removeListener('error', onConnectionError);
  156. connection.writePacket(EmptyPacket);
  157. };
  158. const onError = (err) => {
  159. this._localStreamError = err;
  160. connection.removeListener('error', onConnectionError);
  161. connection.writePacket(EmptyPacket);
  162. };
  163. this._unpipeStream = () => {
  164. connection.stream.removeListener('pause', onPause);
  165. connection.stream.removeListener('drain', onDrain);
  166. this._localStream.removeListener('data', onData);
  167. this._localStream.removeListener('end', onEnd);
  168. this._localStream.removeListener('error', onError);
  169. };
  170. connection.stream.on('pause', onPause);
  171. connection.stream.on('drain', onDrain);
  172. this._localStream.on('data', onData);
  173. this._localStream.on('end', onEnd);
  174. this._localStream.on('error', onError);
  175. connection.once('error', onConnectionError);
  176. return this.infileOk;
  177. }
  178. readField(packet, connection) {
  179. this._receivedFieldsCount++;
  180. // Often there is much more data in the column definition than in the row itself
  181. // If you set manually _fields[0] to array of ColumnDefinition's (from previous call)
  182. // you can 'cache' result of parsing. Field packets still received, but ignored in that case
  183. // this is the reason _receivedFieldsCount exist (otherwise we could just use current length of fields array)
  184. if (this._fields[this._resultIndex].length !== this._fieldCount) {
  185. const field = new Packets.ColumnDefinition(
  186. packet,
  187. connection.clientEncoding
  188. );
  189. this._fields[this._resultIndex].push(field);
  190. if (connection.config.debug) {
  191. console.log(' Column definition:');
  192. console.log(` name: ${field.name}`);
  193. console.log(` type: ${field.columnType}`);
  194. console.log(` flags: ${field.flags}`);
  195. }
  196. }
  197. // last field received
  198. if (this._receivedFieldsCount === this._fieldCount) {
  199. const fields = this._fields[this._resultIndex];
  200. this.emit('fields', fields);
  201. if (this.options.disableEval) {
  202. this._rowParser = staticParser(fields, this.options, connection.config);
  203. } else {
  204. this._rowParser = new (getTextParser(
  205. fields,
  206. this.options,
  207. connection.config
  208. ))(fields);
  209. }
  210. return Query.prototype.fieldsEOF;
  211. }
  212. return Query.prototype.readField;
  213. }
  214. fieldsEOF(packet, connection) {
  215. // check EOF
  216. if (!packet.isEOF()) {
  217. return connection.protocolError('Expected EOF packet');
  218. }
  219. return this.row;
  220. }
  221. row(packet, _connection) {
  222. if (packet.isEOF()) {
  223. const status = packet.eofStatusFlags();
  224. const moreResults = status & ServerStatus.SERVER_MORE_RESULTS_EXISTS;
  225. if (moreResults) {
  226. this._resultIndex++;
  227. return Query.prototype.resultsetHeader;
  228. }
  229. return this.done();
  230. }
  231. let row;
  232. try {
  233. row = this._rowParser.next(
  234. packet,
  235. this._fields[this._resultIndex],
  236. this.options
  237. );
  238. } catch (err) {
  239. this._localStreamError = err;
  240. return this.doneInsert(null);
  241. }
  242. if (this.onResult) {
  243. this._rows[this._resultIndex].push(row);
  244. } else {
  245. this.emit('result', row, this._resultIndex);
  246. }
  247. return Query.prototype.row;
  248. }
  249. infileOk(packet, connection) {
  250. const rs = new Packets.ResultSetHeader(packet, connection);
  251. return this.doneInsert(rs);
  252. }
  253. stream(options) {
  254. options = options || Object.create(null);
  255. options.objectMode = true;
  256. const stream = new Readable({
  257. ...options,
  258. emitClose: true,
  259. autoDestroy: true,
  260. read: () => {
  261. this._connection && this._connection.resume();
  262. },
  263. });
  264. // Prevent a breaking change for users that rely on `end` event
  265. stream.once('close', () => {
  266. if (!stream.readableEnded) {
  267. stream.emit('end');
  268. }
  269. });
  270. const onResult = (row, index) => {
  271. if (stream.destroyed) return;
  272. if (!stream.push(row)) {
  273. this._connection && this._connection.pause();
  274. }
  275. stream.emit('result', row, index); // replicate old emitter
  276. };
  277. const onFields = (fields) => {
  278. if (stream.destroyed) return;
  279. stream.emit('fields', fields); // replicate old emitter
  280. };
  281. const onEnd = () => {
  282. if (stream.destroyed) return;
  283. stream.push(null); // pushing null, indicating EOF
  284. };
  285. const onError = (err) => {
  286. stream.destroy(err);
  287. };
  288. stream._destroy = (err, cb) => {
  289. this._connection && this._connection.resume();
  290. this.removeListener('result', onResult);
  291. this.removeListener('fields', onFields);
  292. this.removeListener('end', onEnd);
  293. this.removeListener('error', onError);
  294. cb(err); // Pass on any errors
  295. };
  296. this.on('result', onResult);
  297. this.on('fields', onFields);
  298. this.on('end', onEnd);
  299. this.on('error', onError);
  300. return stream;
  301. }
  302. _setTimeout() {
  303. if (this.timeout) {
  304. const timeoutHandler = this._handleTimeoutError.bind(this);
  305. this.queryTimeout = Timers.setTimeout(timeoutHandler, this.timeout);
  306. }
  307. }
  308. _handleTimeoutError() {
  309. if (this.queryTimeout) {
  310. Timers.clearTimeout(this.queryTimeout);
  311. this.queryTimeout = null;
  312. }
  313. const err = new Error('Query inactivity timeout');
  314. err.errorno = 'PROTOCOL_SEQUENCE_TIMEOUT';
  315. err.code = 'PROTOCOL_SEQUENCE_TIMEOUT';
  316. err.syscall = 'query';
  317. if (this.onResult) {
  318. this.onResult(err);
  319. } else {
  320. this.emit('error', err);
  321. }
  322. }
  323. }
  324. Query.prototype.catch = Query.prototype.then;
  325. module.exports = Query;