packet.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. // This file was modified by Oracle on June 1, 2021.
  2. // A comment describing some changes in the strict default SQL mode regarding
  3. // non-standard dates was introduced.
  4. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  5. 'use strict';
  6. const ErrorCodeToName = require('../constants/errors.js');
  7. const NativeBuffer = require('buffer').Buffer;
  8. const Long = require('long');
  9. const StringParser = require('../parsers/string.js');
  10. const Types = require('../constants/types.js');
  11. const INVALID_DATE = new Date(NaN);
  12. // this is nearly duplicate of previous function so generated code is not slower
  13. // due to "if (dateStrings)" branching
  14. const pad = '000000000000';
  15. function leftPad(num, value) {
  16. const s = value.toString();
  17. // if we don't need to pad
  18. if (s.length >= num) {
  19. return s;
  20. }
  21. return (pad + s).slice(-num);
  22. }
  23. // The whole reason parse* function below exist
  24. // is because String creation is relatively expensive (at least with V8), and if we have
  25. // a buffer with "12345" content ideally we would like to bypass intermediate
  26. // "12345" string creation and directly build 12345 number out of
  27. // <Buffer 31 32 33 34 35> data.
  28. // In my benchmarks the difference is ~25M 8-digit numbers per second vs
  29. // 4.5 M using Number(packet.readLengthCodedString())
  30. // not used when size is close to max precision as series of *10 accumulate error
  31. // and approximate result mihgt be diffreent from (approximate as well) Number(bigNumStringValue))
  32. // In the futire node version if speed difference is smaller parse* functions might be removed
  33. // don't consider them as Packet public API
  34. const minus = '-'.charCodeAt(0);
  35. const plus = '+'.charCodeAt(0);
  36. // TODO: handle E notation
  37. const dot = '.'.charCodeAt(0);
  38. const exponent = 'e'.charCodeAt(0);
  39. const exponentCapital = 'E'.charCodeAt(0);
  40. class Packet {
  41. constructor(id, buffer, start, end) {
  42. // hot path, enable checks when testing only
  43. // if (!Buffer.isBuffer(buffer) || typeof start == 'undefined' || typeof end == 'undefined')
  44. // throw new Error('invalid packet');
  45. this.sequenceId = id;
  46. this.numPackets = 1;
  47. this.buffer = buffer;
  48. this.start = start;
  49. this.offset = start + 4;
  50. this.end = end;
  51. }
  52. // ==============================
  53. // readers
  54. // ==============================
  55. reset() {
  56. this.offset = this.start + 4;
  57. }
  58. length() {
  59. return this.end - this.start;
  60. }
  61. slice() {
  62. return this.buffer.slice(this.start, this.end);
  63. }
  64. dump() {
  65. console.log(
  66. [this.buffer.asciiSlice(this.start, this.end)],
  67. this.buffer.slice(this.start, this.end),
  68. this.length(),
  69. this.sequenceId
  70. );
  71. }
  72. haveMoreData() {
  73. return this.end > this.offset;
  74. }
  75. skip(num) {
  76. this.offset += num;
  77. }
  78. readInt8() {
  79. return this.buffer[this.offset++];
  80. }
  81. readInt16() {
  82. this.offset += 2;
  83. return this.buffer.readUInt16LE(this.offset - 2);
  84. }
  85. readInt24() {
  86. return this.readInt16() + (this.readInt8() << 16);
  87. }
  88. readInt32() {
  89. this.offset += 4;
  90. return this.buffer.readUInt32LE(this.offset - 4);
  91. }
  92. readSInt8() {
  93. return this.buffer.readInt8(this.offset++);
  94. }
  95. readSInt16() {
  96. this.offset += 2;
  97. return this.buffer.readInt16LE(this.offset - 2);
  98. }
  99. readSInt32() {
  100. this.offset += 4;
  101. return this.buffer.readInt32LE(this.offset - 4);
  102. }
  103. readInt64JSNumber() {
  104. const word0 = this.readInt32();
  105. const word1 = this.readInt32();
  106. const l = new Long(word0, word1, true);
  107. return l.toNumber();
  108. }
  109. readSInt64JSNumber() {
  110. const word0 = this.readInt32();
  111. const word1 = this.readInt32();
  112. if (!(word1 & 0x80000000)) {
  113. return word0 + 0x100000000 * word1;
  114. }
  115. const l = new Long(word0, word1, false);
  116. return l.toNumber();
  117. }
  118. readInt64String() {
  119. const word0 = this.readInt32();
  120. const word1 = this.readInt32();
  121. const res = new Long(word0, word1, true);
  122. return res.toString();
  123. }
  124. readSInt64String() {
  125. const word0 = this.readInt32();
  126. const word1 = this.readInt32();
  127. const res = new Long(word0, word1, false);
  128. return res.toString();
  129. }
  130. readInt64() {
  131. const word0 = this.readInt32();
  132. const word1 = this.readInt32();
  133. const res = new Long(word0, word1, true);
  134. const resNumber = res.toNumber();
  135. return Number.isSafeInteger(resNumber) ? resNumber : res.toString();
  136. }
  137. readSInt64() {
  138. const word0 = this.readInt32();
  139. const word1 = this.readInt32();
  140. const res = new Long(word0, word1, false);
  141. const resNumber = res.toNumber();
  142. return Number.isSafeInteger(resNumber) ? resNumber : res.toString();
  143. }
  144. isEOF() {
  145. return this.buffer[this.offset] === 0xfe && this.length() < 13;
  146. }
  147. eofStatusFlags() {
  148. return this.buffer.readInt16LE(this.offset + 3);
  149. }
  150. eofWarningCount() {
  151. return this.buffer.readInt16LE(this.offset + 1);
  152. }
  153. readLengthCodedNumber(bigNumberStrings, signed) {
  154. const byte1 = this.buffer[this.offset++];
  155. if (byte1 < 251) {
  156. return byte1;
  157. }
  158. return this.readLengthCodedNumberExt(byte1, bigNumberStrings, signed);
  159. }
  160. readLengthCodedNumberSigned(bigNumberStrings) {
  161. return this.readLengthCodedNumber(bigNumberStrings, true);
  162. }
  163. readLengthCodedNumberExt(tag, bigNumberStrings, signed) {
  164. let word0, word1;
  165. let res;
  166. if (tag === 0xfb) {
  167. return null;
  168. }
  169. if (tag === 0xfc) {
  170. return this.readInt8() + (this.readInt8() << 8);
  171. }
  172. if (tag === 0xfd) {
  173. return this.readInt8() + (this.readInt8() << 8) + (this.readInt8() << 16);
  174. }
  175. if (tag === 0xfe) {
  176. // TODO: check version
  177. // Up to MySQL 3.22, 0xfe was followed by a 4-byte integer.
  178. word0 = this.readInt32();
  179. word1 = this.readInt32();
  180. if (word1 === 0) {
  181. return word0; // don't convert to float if possible
  182. }
  183. if (word1 < 2097152) {
  184. // max exact float point int, 2^52 / 2^32
  185. return word1 * 0x100000000 + word0;
  186. }
  187. res = new Long(word0, word1, !signed); // Long need unsigned
  188. const resNumber = res.toNumber();
  189. const resString = res.toString();
  190. if (bigNumberStrings || !Number.isSafeInteger(resNumber)) {
  191. return resString;
  192. }
  193. return resNumber;
  194. }
  195. console.trace();
  196. throw new Error(`Should not reach here: ${tag}`);
  197. }
  198. readFloat() {
  199. const res = this.buffer.readFloatLE(this.offset);
  200. this.offset += 4;
  201. return res;
  202. }
  203. readDouble() {
  204. const res = this.buffer.readDoubleLE(this.offset);
  205. this.offset += 8;
  206. return res;
  207. }
  208. readBuffer(len) {
  209. if (typeof len === 'undefined') {
  210. len = this.end - this.offset;
  211. }
  212. this.offset += len;
  213. return this.buffer.slice(this.offset - len, this.offset);
  214. }
  215. // DATE, DATETIME and TIMESTAMP
  216. readDateTime(timezone) {
  217. if (!timezone || timezone === 'Z' || timezone === 'local') {
  218. const length = this.readInt8();
  219. if (length === 0xfb) {
  220. return null;
  221. }
  222. let y = 0;
  223. let m = 0;
  224. let d = 0;
  225. let H = 0;
  226. let M = 0;
  227. let S = 0;
  228. let ms = 0;
  229. if (length > 3) {
  230. y = this.readInt16();
  231. m = this.readInt8();
  232. d = this.readInt8();
  233. }
  234. if (length > 6) {
  235. H = this.readInt8();
  236. M = this.readInt8();
  237. S = this.readInt8();
  238. }
  239. if (length > 10) {
  240. ms = this.readInt32() / 1000;
  241. }
  242. // NO_ZERO_DATE mode and NO_ZERO_IN_DATE mode are part of the strict
  243. // default SQL mode used by MySQL 8.0. This means that non-standard
  244. // dates like '0000-00-00' become NULL. For older versions and other
  245. // possible MySQL flavours we still need to account for the
  246. // non-standard behaviour.
  247. if (y + m + d + H + M + S + ms === 0) {
  248. return INVALID_DATE;
  249. }
  250. if (timezone === 'Z') {
  251. return new Date(Date.UTC(y, m - 1, d, H, M, S, ms));
  252. }
  253. return new Date(y, m - 1, d, H, M, S, ms);
  254. }
  255. let str = this.readDateTimeString(6, 'T', null);
  256. if (!str) {
  257. return INVALID_DATE;
  258. }
  259. if (str.length === 10) {
  260. str += 'T00:00:00';
  261. }
  262. return new Date(str + timezone);
  263. }
  264. readDateTimeString(decimals, timeSep, columnType) {
  265. const length = this.readInt8();
  266. let y = 0;
  267. let m = 0;
  268. let d = 0;
  269. let H = 0;
  270. let M = 0;
  271. let S = 0;
  272. let ms = 0;
  273. let str;
  274. if (length > 3) {
  275. y = this.readInt16();
  276. m = this.readInt8();
  277. d = this.readInt8();
  278. str = [leftPad(4, y), leftPad(2, m), leftPad(2, d)].join('-');
  279. }
  280. if (length > 6) {
  281. H = this.readInt8();
  282. M = this.readInt8();
  283. S = this.readInt8();
  284. str += `${timeSep || ' '}${[
  285. leftPad(2, H),
  286. leftPad(2, M),
  287. leftPad(2, S),
  288. ].join(':')}`;
  289. } else if (
  290. columnType === Types.DATETIME ||
  291. columnType === Types.TIMESTAMP
  292. ) {
  293. str += ' 00:00:00';
  294. }
  295. if (length > 10) {
  296. ms = this.readInt32();
  297. str += '.';
  298. if (decimals) {
  299. ms = leftPad(6, ms);
  300. if (ms.length > decimals) {
  301. ms = ms.substring(0, decimals); // rounding is done at the MySQL side, only 0 are here
  302. }
  303. }
  304. str += ms;
  305. }
  306. return str;
  307. }
  308. // TIME - value as a string, Can be negative
  309. readTimeString(convertTtoMs) {
  310. const length = this.readInt8();
  311. if (length === 0) {
  312. return '00:00:00';
  313. }
  314. const sign = this.readInt8() ? -1 : 1; // 'isNegative' flag byte
  315. let d = 0;
  316. let H = 0;
  317. let M = 0;
  318. let S = 0;
  319. let ms = 0;
  320. if (length > 6) {
  321. d = this.readInt32();
  322. H = this.readInt8();
  323. M = this.readInt8();
  324. S = this.readInt8();
  325. }
  326. if (length > 10) {
  327. ms = this.readInt32();
  328. }
  329. if (convertTtoMs) {
  330. H += d * 24;
  331. M += H * 60;
  332. S += M * 60;
  333. ms += S * 1000;
  334. ms *= sign;
  335. return ms;
  336. }
  337. // Format follows mySQL TIME format ([-][h]hh:mm:ss[.u[u[u[u[u[u]]]]]])
  338. // For positive times below 24 hours, this makes it equal to ISO 8601 times
  339. return (
  340. (sign === -1 ? '-' : '') +
  341. [leftPad(2, d * 24 + H), leftPad(2, M), leftPad(2, S)].join(':') +
  342. (ms ? `.${ms}`.replace(/0+$/, '') : '')
  343. );
  344. }
  345. readLengthCodedString(encoding) {
  346. const len = this.readLengthCodedNumber();
  347. // TODO: check manually first byte here to avoid polymorphic return type?
  348. if (len === null) {
  349. return null;
  350. }
  351. this.offset += len;
  352. // TODO: Use characterSetCode to get proper encoding
  353. // https://github.com/sidorares/node-mysql2/pull/374
  354. return StringParser.decode(
  355. this.buffer,
  356. encoding,
  357. this.offset - len,
  358. this.offset
  359. );
  360. }
  361. readLengthCodedBuffer() {
  362. const len = this.readLengthCodedNumber();
  363. if (len === null) {
  364. return null;
  365. }
  366. return this.readBuffer(len);
  367. }
  368. readNullTerminatedString(encoding) {
  369. const start = this.offset;
  370. let end = this.offset;
  371. while (end < this.end && this.buffer[end] !== 0x00) {
  372. end = end + 1;
  373. }
  374. this.offset = end + 1;
  375. return StringParser.decode(this.buffer, encoding, start, end);
  376. }
  377. // TODO reuse?
  378. readString(len, encoding) {
  379. if (typeof len === 'string' && typeof encoding === 'undefined') {
  380. encoding = len;
  381. len = undefined;
  382. }
  383. if (typeof len === 'undefined') {
  384. len = this.end - this.offset;
  385. }
  386. this.offset += len;
  387. return StringParser.decode(
  388. this.buffer,
  389. encoding,
  390. this.offset - len,
  391. this.offset
  392. );
  393. }
  394. parseInt(len, supportBigNumbers) {
  395. if (len === null) {
  396. return null;
  397. }
  398. if (len >= 14 && !supportBigNumbers) {
  399. const s = this.buffer.toString('ascii', this.offset, this.offset + len);
  400. this.offset += len;
  401. return Number(s);
  402. }
  403. let result = 0;
  404. const start = this.offset;
  405. const end = this.offset + len;
  406. let sign = 1;
  407. if (len === 0) {
  408. return 0; // TODO: assert? exception?
  409. }
  410. if (this.buffer[this.offset] === minus) {
  411. this.offset++;
  412. sign = -1;
  413. }
  414. // max precise int is 9007199254740992
  415. let str;
  416. const numDigits = end - this.offset;
  417. if (supportBigNumbers) {
  418. if (numDigits >= 15) {
  419. str = this.readString(end - this.offset, 'binary');
  420. result = parseInt(str, 10);
  421. if (Number.isSafeInteger(sign * result)) {
  422. return sign * result;
  423. }
  424. return sign === -1 ? `-${str}` : str;
  425. }
  426. if (numDigits > 16) {
  427. str = this.readString(end - this.offset);
  428. return sign === -1 ? `-${str}` : str;
  429. }
  430. }
  431. if (this.buffer[this.offset] === plus) {
  432. this.offset++; // just ignore
  433. }
  434. while (this.offset < end) {
  435. result *= 10;
  436. result += this.buffer[this.offset] - 48;
  437. this.offset++;
  438. }
  439. const num = result * sign;
  440. if (!supportBigNumbers) {
  441. return num;
  442. }
  443. if (Number.isSafeInteger(num)) {
  444. return num;
  445. }
  446. return this.buffer.toString('ascii', start, end);
  447. }
  448. // note that if value of inputNumberAsString is bigger than MAX_SAFE_INTEGER
  449. // ( or smaller than MIN_SAFE_INTEGER ) the parseIntNoBigCheck result might be
  450. // different from what you would get from Number(inputNumberAsString)
  451. // String(parseIntNoBigCheck) <> String(Number(inputNumberAsString)) <> inputNumberAsString
  452. parseIntNoBigCheck(len) {
  453. if (len === null) {
  454. return null;
  455. }
  456. let result = 0;
  457. const end = this.offset + len;
  458. let sign = 1;
  459. if (len === 0) {
  460. return 0; // TODO: assert? exception?
  461. }
  462. if (this.buffer[this.offset] === minus) {
  463. this.offset++;
  464. sign = -1;
  465. }
  466. if (this.buffer[this.offset] === plus) {
  467. this.offset++; // just ignore
  468. }
  469. while (this.offset < end) {
  470. result *= 10;
  471. result += this.buffer[this.offset] - 48;
  472. this.offset++;
  473. }
  474. return result * sign;
  475. }
  476. // adapted from https://github.com/mysqljs/mysql/blob/dc9c152a87ec51a1f647447268917243d2eab1fd/lib/protocol/Parser.js
  477. parseGeometryValue() {
  478. const buffer = this.readLengthCodedBuffer();
  479. let offset = 4;
  480. if (buffer === null || !buffer.length) {
  481. return null;
  482. }
  483. const bufferLength = buffer.length;
  484. function parseGeometry() {
  485. let x, y, i, j, numPoints, numRings, num, line;
  486. let result = null;
  487. if (offset + 5 > bufferLength) {
  488. return null;
  489. }
  490. const byteOrder = buffer.readUInt8(offset);
  491. offset += 1;
  492. const wkbType = byteOrder
  493. ? buffer.readUInt32LE(offset)
  494. : buffer.readUInt32BE(offset);
  495. offset += 4;
  496. switch (wkbType) {
  497. case 1: // WKBPoint
  498. if (offset + 16 > bufferLength) {
  499. return null;
  500. }
  501. x = byteOrder
  502. ? buffer.readDoubleLE(offset)
  503. : buffer.readDoubleBE(offset);
  504. offset += 8;
  505. y = byteOrder
  506. ? buffer.readDoubleLE(offset)
  507. : buffer.readDoubleBE(offset);
  508. offset += 8;
  509. result = { x: x, y: y };
  510. break;
  511. case 2: // WKBLineString
  512. if (offset + 4 > bufferLength) {
  513. return null;
  514. }
  515. numPoints = byteOrder
  516. ? buffer.readUInt32LE(offset)
  517. : buffer.readUInt32BE(offset);
  518. offset += 4;
  519. if (numPoints > (bufferLength - offset) / 16) {
  520. return null;
  521. }
  522. result = [];
  523. for (i = numPoints; i > 0; i--) {
  524. if (offset + 16 > bufferLength) {
  525. break;
  526. }
  527. x = byteOrder
  528. ? buffer.readDoubleLE(offset)
  529. : buffer.readDoubleBE(offset);
  530. offset += 8;
  531. y = byteOrder
  532. ? buffer.readDoubleLE(offset)
  533. : buffer.readDoubleBE(offset);
  534. offset += 8;
  535. result.push({ x: x, y: y });
  536. }
  537. break;
  538. case 3: // WKBPolygon
  539. if (offset + 4 > bufferLength) {
  540. return null;
  541. }
  542. numRings = byteOrder
  543. ? buffer.readUInt32LE(offset)
  544. : buffer.readUInt32BE(offset);
  545. offset += 4;
  546. if (numRings > (bufferLength - offset) / 4) {
  547. return null;
  548. }
  549. result = [];
  550. for (i = numRings; i > 0; i--) {
  551. if (offset + 4 > bufferLength) {
  552. break;
  553. }
  554. numPoints = byteOrder
  555. ? buffer.readUInt32LE(offset)
  556. : buffer.readUInt32BE(offset);
  557. offset += 4;
  558. line = [];
  559. for (j = numPoints; j > 0; j--) {
  560. if (offset + 16 > bufferLength) {
  561. break;
  562. }
  563. x = byteOrder
  564. ? buffer.readDoubleLE(offset)
  565. : buffer.readDoubleBE(offset);
  566. offset += 8;
  567. y = byteOrder
  568. ? buffer.readDoubleLE(offset)
  569. : buffer.readDoubleBE(offset);
  570. offset += 8;
  571. line.push({ x: x, y: y });
  572. }
  573. result.push(line);
  574. }
  575. break;
  576. case 4: // WKBMultiPoint
  577. case 5: // WKBMultiLineString
  578. case 6: // WKBMultiPolygon
  579. case 7: // WKBGeometryCollection
  580. if (offset + 4 > bufferLength) {
  581. return null;
  582. }
  583. num = byteOrder
  584. ? buffer.readUInt32LE(offset)
  585. : buffer.readUInt32BE(offset);
  586. offset += 4;
  587. if (num > (bufferLength - offset) / 9) {
  588. return null;
  589. }
  590. result = [];
  591. for (i = num; i > 0; i--) {
  592. result.push(parseGeometry());
  593. }
  594. break;
  595. }
  596. return result;
  597. }
  598. return parseGeometry();
  599. }
  600. parseVector() {
  601. const bufLen = this.readLengthCodedNumber();
  602. const vectorEnd = this.offset + bufLen;
  603. const result = [];
  604. while (this.offset < vectorEnd && this.offset < this.end) {
  605. result.push(this.readFloat());
  606. }
  607. return result;
  608. }
  609. parseDate(timezone) {
  610. const strLen = this.readLengthCodedNumber();
  611. if (strLen === null) {
  612. return null;
  613. }
  614. if (strLen !== 10) {
  615. // we expect only YYYY-MM-DD here.
  616. // if for some reason it's not the case return invalid date
  617. return new Date(NaN);
  618. }
  619. const y = this.parseInt(4);
  620. this.offset++; // -
  621. const m = this.parseInt(2);
  622. this.offset++; // -
  623. const d = this.parseInt(2);
  624. if (!timezone || timezone === 'local') {
  625. return new Date(y, m - 1, d);
  626. }
  627. if (timezone === 'Z') {
  628. return new Date(Date.UTC(y, m - 1, d));
  629. }
  630. return new Date(
  631. `${leftPad(4, y)}-${leftPad(2, m)}-${leftPad(2, d)}T00:00:00${timezone}`
  632. );
  633. }
  634. parseDateTime(timezone) {
  635. const str = this.readLengthCodedString('binary');
  636. if (str === null) {
  637. return null;
  638. }
  639. if (!timezone || timezone === 'local') {
  640. return new Date(str);
  641. }
  642. return new Date(`${str}${timezone}`);
  643. }
  644. parseFloat(len) {
  645. if (len === null) {
  646. return null;
  647. }
  648. if (len === 0) {
  649. return 0; // TODO: assert? exception?
  650. }
  651. // For numbers with many digits (>17), use built-in parseFloat to avoid
  652. // precision loss from accumulated rounding errors in repeated *10 operations.
  653. // This fixes issues #2928 (MAX_VALUE doubles) and #3690 (DECIMAL(36,18))
  654. // where very large numbers or numbers with many fractional digits lose precision.
  655. // The threshold of 17 is based on IEEE 754 double precision (~15-17 significant digits).
  656. // Testing shows minimal performance impact as most real-world numbers are shorter.
  657. if (len > 17) {
  658. const str = this.buffer.toString('utf8', this.offset, this.offset + len);
  659. this.offset += len;
  660. return Number.parseFloat(str);
  661. }
  662. let result = 0;
  663. const end = this.offset + len;
  664. let factor = 1;
  665. let pastDot = false;
  666. let charCode = 0;
  667. if (this.buffer[this.offset] === minus) {
  668. this.offset++;
  669. factor = -1;
  670. }
  671. if (this.buffer[this.offset] === plus) {
  672. this.offset++; // just ignore
  673. }
  674. while (this.offset < end) {
  675. charCode = this.buffer[this.offset];
  676. if (charCode === dot) {
  677. pastDot = true;
  678. this.offset++;
  679. } else if (charCode === exponent || charCode === exponentCapital) {
  680. // Scientific notation detected - bail out to parseFloat for exact match.
  681. // Manual calculation with Math.pow(10, exp) cannot match parseFloat()
  682. // exactly for most non-zero exponents due to accumulated rounding errors.
  683. const start = end - len;
  684. const str = this.buffer.toString('utf8', start, end);
  685. this.offset = end;
  686. return Number.parseFloat(str);
  687. } else {
  688. result *= 10;
  689. result += this.buffer[this.offset] - 48;
  690. this.offset++;
  691. if (pastDot) {
  692. factor = factor * 10;
  693. }
  694. }
  695. }
  696. return result / factor;
  697. }
  698. parseLengthCodedIntNoBigCheck() {
  699. return this.parseIntNoBigCheck(this.readLengthCodedNumber());
  700. }
  701. parseLengthCodedInt(supportBigNumbers) {
  702. return this.parseInt(this.readLengthCodedNumber(), supportBigNumbers);
  703. }
  704. parseLengthCodedIntString() {
  705. return this.readLengthCodedString('binary');
  706. }
  707. parseLengthCodedFloat() {
  708. return this.parseFloat(this.readLengthCodedNumber());
  709. }
  710. peekByte() {
  711. return this.buffer[this.offset];
  712. }
  713. // OxFE is often used as "Alt" flag - not ok, not error.
  714. // For example, it's first byte of AuthSwitchRequest
  715. isAlt() {
  716. return this.peekByte() === 0xfe;
  717. }
  718. isError() {
  719. return this.peekByte() === 0xff;
  720. }
  721. asError(encoding) {
  722. this.reset();
  723. this.readInt8(); // fieldCount
  724. const errorCode = this.readInt16();
  725. let sqlState = '';
  726. if (this.buffer[this.offset] === 0x23) {
  727. this.skip(1);
  728. sqlState = this.readBuffer(5).toString();
  729. }
  730. const message = this.readString(undefined, encoding);
  731. const err = new Error(message);
  732. err.code = ErrorCodeToName[errorCode];
  733. err.errno = errorCode;
  734. err.sqlState = sqlState;
  735. err.sqlMessage = message;
  736. return err;
  737. }
  738. writeInt32(n) {
  739. this.buffer.writeUInt32LE(n, this.offset);
  740. this.offset += 4;
  741. }
  742. writeInt24(n) {
  743. this.writeInt8(n & 0xff);
  744. this.writeInt16(n >> 8);
  745. }
  746. writeInt16(n) {
  747. this.buffer.writeUInt16LE(n, this.offset);
  748. this.offset += 2;
  749. }
  750. writeInt8(n) {
  751. this.buffer.writeUInt8(n, this.offset);
  752. this.offset++;
  753. }
  754. writeDouble(n) {
  755. this.buffer.writeDoubleLE(n, this.offset);
  756. this.offset += 8;
  757. }
  758. writeBuffer(b) {
  759. b.copy(this.buffer, this.offset);
  760. this.offset += b.length;
  761. }
  762. writeNull() {
  763. this.buffer[this.offset] = 0xfb;
  764. this.offset++;
  765. }
  766. // TODO: refactor following three?
  767. writeNullTerminatedString(s, encoding) {
  768. const buf = StringParser.encode(s, encoding);
  769. this.buffer.length && buf.copy(this.buffer, this.offset);
  770. this.offset += buf.length;
  771. this.writeInt8(0);
  772. }
  773. writeString(s, encoding) {
  774. if (s === null) {
  775. this.writeInt8(0xfb);
  776. return;
  777. }
  778. if (s.length === 0) {
  779. return;
  780. }
  781. // const bytes = Buffer.byteLength(s, 'utf8');
  782. // this.buffer.write(s, this.offset, bytes, 'utf8');
  783. // this.offset += bytes;
  784. const buf = StringParser.encode(s, encoding);
  785. this.buffer.length && buf.copy(this.buffer, this.offset);
  786. this.offset += buf.length;
  787. }
  788. writeLengthCodedString(s, encoding) {
  789. const buf = StringParser.encode(s, encoding);
  790. this.writeLengthCodedNumber(buf.length);
  791. this.buffer.length && buf.copy(this.buffer, this.offset);
  792. this.offset += buf.length;
  793. }
  794. writeLengthCodedBuffer(b) {
  795. this.writeLengthCodedNumber(b.length);
  796. b.copy(this.buffer, this.offset);
  797. this.offset += b.length;
  798. }
  799. writeLengthCodedNumber(n) {
  800. if (n < 0xfb) {
  801. return this.writeInt8(n);
  802. }
  803. if (n < 0xffff) {
  804. this.writeInt8(0xfc);
  805. return this.writeInt16(n);
  806. }
  807. if (n < 0xffffff) {
  808. this.writeInt8(0xfd);
  809. return this.writeInt24(n);
  810. }
  811. if (n === null) {
  812. return this.writeInt8(0xfb);
  813. }
  814. this.writeInt8(0xfe);
  815. this.buffer.writeUInt32LE(n >>> 0, this.offset);
  816. this.offset += 4;
  817. this.buffer.writeUInt32LE(Math.floor(n / 0x100000000), this.offset);
  818. this.offset += 4;
  819. return this.offset;
  820. }
  821. writeDate(d, timezone) {
  822. this.buffer.writeUInt8(11, this.offset);
  823. if (!timezone || timezone === 'local') {
  824. this.buffer.writeUInt16LE(d.getFullYear(), this.offset + 1);
  825. this.buffer.writeUInt8(d.getMonth() + 1, this.offset + 3);
  826. this.buffer.writeUInt8(d.getDate(), this.offset + 4);
  827. this.buffer.writeUInt8(d.getHours(), this.offset + 5);
  828. this.buffer.writeUInt8(d.getMinutes(), this.offset + 6);
  829. this.buffer.writeUInt8(d.getSeconds(), this.offset + 7);
  830. this.buffer.writeUInt32LE(d.getMilliseconds() * 1000, this.offset + 8);
  831. } else {
  832. if (timezone !== 'Z') {
  833. const offset =
  834. (timezone[0] === '-' ? -1 : 1) *
  835. (parseInt(timezone.substring(1, 3), 10) * 60 +
  836. parseInt(timezone.substring(4), 10));
  837. if (offset !== 0) {
  838. d = new Date(d.getTime() + 60000 * offset);
  839. }
  840. }
  841. this.buffer.writeUInt16LE(d.getUTCFullYear(), this.offset + 1);
  842. this.buffer.writeUInt8(d.getUTCMonth() + 1, this.offset + 3);
  843. this.buffer.writeUInt8(d.getUTCDate(), this.offset + 4);
  844. this.buffer.writeUInt8(d.getUTCHours(), this.offset + 5);
  845. this.buffer.writeUInt8(d.getUTCMinutes(), this.offset + 6);
  846. this.buffer.writeUInt8(d.getUTCSeconds(), this.offset + 7);
  847. this.buffer.writeUInt32LE(d.getUTCMilliseconds() * 1000, this.offset + 8);
  848. }
  849. this.offset += 12;
  850. }
  851. writeHeader(sequenceId) {
  852. const offset = this.offset;
  853. this.offset = 0;
  854. this.writeInt24(this.buffer.length - 4);
  855. this.writeInt8(sequenceId);
  856. this.offset = offset;
  857. }
  858. clone() {
  859. return new Packet(this.sequenceId, this.buffer, this.start, this.end);
  860. }
  861. type() {
  862. if (this.isEOF()) {
  863. return 'EOF';
  864. }
  865. if (this.isError()) {
  866. return 'Error';
  867. }
  868. if (this.buffer[this.offset] === 0) {
  869. return 'maybeOK'; // could be other packet types as well
  870. }
  871. return '';
  872. }
  873. static lengthCodedNumberLength(n) {
  874. if (n < 0xfb) {
  875. return 1;
  876. }
  877. if (n < 0xffff) {
  878. return 3;
  879. }
  880. if (n < 0xffffff) {
  881. return 5;
  882. }
  883. return 9;
  884. }
  885. static lengthCodedStringLength(str, encoding) {
  886. const buf = StringParser.encode(str, encoding);
  887. const slen = buf.length;
  888. return Packet.lengthCodedNumberLength(slen) + slen;
  889. }
  890. static MockBuffer() {
  891. const noop = function () {};
  892. const res = Buffer.alloc(0);
  893. for (const op in NativeBuffer.prototype) {
  894. if (typeof res[op] === 'function') {
  895. res[op] = noop;
  896. }
  897. }
  898. return res;
  899. }
  900. }
  901. module.exports = Packet;