packet.js 24 KB

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