packet.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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. parseDate(timezone) {
  565. const strLen = this.readLengthCodedNumber();
  566. if (strLen === null) {
  567. return null;
  568. }
  569. if (strLen !== 10) {
  570. // we expect only YYYY-MM-DD here.
  571. // if for some reason it's not the case return invalid date
  572. return new Date(NaN);
  573. }
  574. const y = this.parseInt(4);
  575. this.offset++; // -
  576. const m = this.parseInt(2);
  577. this.offset++; // -
  578. const d = this.parseInt(2);
  579. if (!timezone || timezone === 'local') {
  580. return new Date(y, m - 1, d);
  581. }
  582. if (timezone === 'Z') {
  583. return new Date(Date.UTC(y, m - 1, d));
  584. }
  585. return new Date(
  586. `${leftPad(4, y)}-${leftPad(2, m)}-${leftPad(2, d)}T00:00:00${timezone}`
  587. );
  588. }
  589. parseDateTime(timezone) {
  590. const str = this.readLengthCodedString('binary');
  591. if (str === null) {
  592. return null;
  593. }
  594. if (!timezone || timezone === 'local') {
  595. return new Date(str);
  596. }
  597. return new Date(`${str}${timezone}`);
  598. }
  599. parseFloat(len) {
  600. if (len === null) {
  601. return null;
  602. }
  603. let result = 0;
  604. const end = this.offset + len;
  605. let factor = 1;
  606. let pastDot = false;
  607. let charCode = 0;
  608. if (len === 0) {
  609. return 0; // TODO: assert? exception?
  610. }
  611. if (this.buffer[this.offset] === minus) {
  612. this.offset++;
  613. factor = -1;
  614. }
  615. if (this.buffer[this.offset] === plus) {
  616. this.offset++; // just ignore
  617. }
  618. while (this.offset < end) {
  619. charCode = this.buffer[this.offset];
  620. if (charCode === dot) {
  621. pastDot = true;
  622. this.offset++;
  623. } else if (charCode === exponent || charCode === exponentCapital) {
  624. this.offset++;
  625. const exponentValue = this.parseInt(end - this.offset);
  626. return (result / factor) * Math.pow(10, exponentValue);
  627. } else {
  628. result *= 10;
  629. result += this.buffer[this.offset] - 48;
  630. this.offset++;
  631. if (pastDot) {
  632. factor = factor * 10;
  633. }
  634. }
  635. }
  636. return result / factor;
  637. }
  638. parseLengthCodedIntNoBigCheck() {
  639. return this.parseIntNoBigCheck(this.readLengthCodedNumber());
  640. }
  641. parseLengthCodedInt(supportBigNumbers) {
  642. return this.parseInt(this.readLengthCodedNumber(), supportBigNumbers);
  643. }
  644. parseLengthCodedIntString() {
  645. return this.readLengthCodedString('binary');
  646. }
  647. parseLengthCodedFloat() {
  648. return this.parseFloat(this.readLengthCodedNumber());
  649. }
  650. peekByte() {
  651. return this.buffer[this.offset];
  652. }
  653. // OxFE is often used as "Alt" flag - not ok, not error.
  654. // For example, it's first byte of AuthSwitchRequest
  655. isAlt() {
  656. return this.peekByte() === 0xfe;
  657. }
  658. isError() {
  659. return this.peekByte() === 0xff;
  660. }
  661. asError(encoding) {
  662. this.reset();
  663. this.readInt8(); // fieldCount
  664. const errorCode = this.readInt16();
  665. let sqlState = '';
  666. if (this.buffer[this.offset] === 0x23) {
  667. this.skip(1);
  668. sqlState = this.readBuffer(5).toString();
  669. }
  670. const message = this.readString(undefined, encoding);
  671. const err = new Error(message);
  672. err.code = ErrorCodeToName[errorCode];
  673. err.errno = errorCode;
  674. err.sqlState = sqlState;
  675. err.sqlMessage = message;
  676. return err;
  677. }
  678. writeInt32(n) {
  679. this.buffer.writeUInt32LE(n, this.offset);
  680. this.offset += 4;
  681. }
  682. writeInt24(n) {
  683. this.writeInt8(n & 0xff);
  684. this.writeInt16(n >> 8);
  685. }
  686. writeInt16(n) {
  687. this.buffer.writeUInt16LE(n, this.offset);
  688. this.offset += 2;
  689. }
  690. writeInt8(n) {
  691. this.buffer.writeUInt8(n, this.offset);
  692. this.offset++;
  693. }
  694. writeDouble(n) {
  695. this.buffer.writeDoubleLE(n, this.offset);
  696. this.offset += 8;
  697. }
  698. writeBuffer(b) {
  699. b.copy(this.buffer, this.offset);
  700. this.offset += b.length;
  701. }
  702. writeNull() {
  703. this.buffer[this.offset] = 0xfb;
  704. this.offset++;
  705. }
  706. // TODO: refactor following three?
  707. writeNullTerminatedString(s, encoding) {
  708. const buf = StringParser.encode(s, encoding);
  709. this.buffer.length && buf.copy(this.buffer, this.offset);
  710. this.offset += buf.length;
  711. this.writeInt8(0);
  712. }
  713. writeString(s, encoding) {
  714. if (s === null) {
  715. this.writeInt8(0xfb);
  716. return;
  717. }
  718. if (s.length === 0) {
  719. return;
  720. }
  721. // const bytes = Buffer.byteLength(s, 'utf8');
  722. // this.buffer.write(s, this.offset, bytes, 'utf8');
  723. // this.offset += bytes;
  724. const buf = StringParser.encode(s, encoding);
  725. this.buffer.length && buf.copy(this.buffer, this.offset);
  726. this.offset += buf.length;
  727. }
  728. writeLengthCodedString(s, encoding) {
  729. const buf = StringParser.encode(s, encoding);
  730. this.writeLengthCodedNumber(buf.length);
  731. this.buffer.length && buf.copy(this.buffer, this.offset);
  732. this.offset += buf.length;
  733. }
  734. writeLengthCodedBuffer(b) {
  735. this.writeLengthCodedNumber(b.length);
  736. b.copy(this.buffer, this.offset);
  737. this.offset += b.length;
  738. }
  739. writeLengthCodedNumber(n) {
  740. if (n < 0xfb) {
  741. return this.writeInt8(n);
  742. }
  743. if (n < 0xffff) {
  744. this.writeInt8(0xfc);
  745. return this.writeInt16(n);
  746. }
  747. if (n < 0xffffff) {
  748. this.writeInt8(0xfd);
  749. return this.writeInt24(n);
  750. }
  751. if (n === null) {
  752. return this.writeInt8(0xfb);
  753. }
  754. // TODO: check that n is out of int precision
  755. this.writeInt8(0xfe);
  756. this.buffer.writeUInt32LE(n, this.offset);
  757. this.offset += 4;
  758. this.buffer.writeUInt32LE(n >> 32, this.offset);
  759. this.offset += 4;
  760. return this.offset;
  761. }
  762. writeDate(d, timezone) {
  763. this.buffer.writeUInt8(11, this.offset);
  764. if (!timezone || timezone === 'local') {
  765. this.buffer.writeUInt16LE(d.getFullYear(), this.offset + 1);
  766. this.buffer.writeUInt8(d.getMonth() + 1, this.offset + 3);
  767. this.buffer.writeUInt8(d.getDate(), this.offset + 4);
  768. this.buffer.writeUInt8(d.getHours(), this.offset + 5);
  769. this.buffer.writeUInt8(d.getMinutes(), this.offset + 6);
  770. this.buffer.writeUInt8(d.getSeconds(), this.offset + 7);
  771. this.buffer.writeUInt32LE(d.getMilliseconds() * 1000, this.offset + 8);
  772. } else {
  773. if (timezone !== 'Z') {
  774. const offset =
  775. (timezone[0] === '-' ? -1 : 1) *
  776. (parseInt(timezone.substring(1, 3), 10) * 60 +
  777. parseInt(timezone.substring(4), 10));
  778. if (offset !== 0) {
  779. d = new Date(d.getTime() + 60000 * offset);
  780. }
  781. }
  782. this.buffer.writeUInt16LE(d.getUTCFullYear(), this.offset + 1);
  783. this.buffer.writeUInt8(d.getUTCMonth() + 1, this.offset + 3);
  784. this.buffer.writeUInt8(d.getUTCDate(), this.offset + 4);
  785. this.buffer.writeUInt8(d.getUTCHours(), this.offset + 5);
  786. this.buffer.writeUInt8(d.getUTCMinutes(), this.offset + 6);
  787. this.buffer.writeUInt8(d.getUTCSeconds(), this.offset + 7);
  788. this.buffer.writeUInt32LE(d.getUTCMilliseconds() * 1000, this.offset + 8);
  789. }
  790. this.offset += 12;
  791. }
  792. writeHeader(sequenceId) {
  793. const offset = this.offset;
  794. this.offset = 0;
  795. this.writeInt24(this.buffer.length - 4);
  796. this.writeInt8(sequenceId);
  797. this.offset = offset;
  798. }
  799. clone() {
  800. return new Packet(this.sequenceId, this.buffer, this.start, this.end);
  801. }
  802. type() {
  803. if (this.isEOF()) {
  804. return 'EOF';
  805. }
  806. if (this.isError()) {
  807. return 'Error';
  808. }
  809. if (this.buffer[this.offset] === 0) {
  810. return 'maybeOK'; // could be other packet types as well
  811. }
  812. return '';
  813. }
  814. static lengthCodedNumberLength(n) {
  815. if (n < 0xfb) {
  816. return 1;
  817. }
  818. if (n < 0xffff) {
  819. return 3;
  820. }
  821. if (n < 0xffffff) {
  822. return 5;
  823. }
  824. return 9;
  825. }
  826. static lengthCodedStringLength(str, encoding) {
  827. const buf = StringParser.encode(str, encoding);
  828. const slen = buf.length;
  829. return Packet.lengthCodedNumberLength(slen) + slen;
  830. }
  831. static MockBuffer() {
  832. const noop = function () {};
  833. const res = Buffer.alloc(0);
  834. for (const op in NativeBuffer.prototype) {
  835. if (typeof res[op] === 'function') {
  836. res[op] = noop;
  837. }
  838. }
  839. return res;
  840. }
  841. }
  842. module.exports = Packet;