binary_parser.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. 'use strict';
  2. const FieldFlags = require('../constants/field_flags.js');
  3. const Charsets = require('../constants/charsets.js');
  4. const Types = require('../constants/types.js');
  5. const helpers = require('../helpers');
  6. const genFunc = require('generate-function');
  7. const parserCache = require('./parser_cache.js');
  8. const typeNames = [];
  9. for (const t in Types) {
  10. typeNames[Types[t]] = t;
  11. }
  12. function readCodeFor(field, config, options, fieldNum) {
  13. const supportBigNumbers =
  14. options.supportBigNumbers || config.supportBigNumbers;
  15. const bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings;
  16. const timezone = options.timezone || config.timezone;
  17. const unsigned = field.flags & FieldFlags.UNSIGNED;
  18. switch (field.columnType) {
  19. case Types.TINY:
  20. return unsigned ? 'packet.readInt8();' : 'packet.readSInt8();';
  21. case Types.SHORT:
  22. return unsigned ? 'packet.readInt16();' : 'packet.readSInt16();';
  23. case Types.LONG:
  24. case Types.INT24: // in binary protocol int24 is encoded in 4 bytes int32
  25. return unsigned ? 'packet.readInt32();' : 'packet.readSInt32();';
  26. case Types.YEAR:
  27. return 'packet.readInt16()';
  28. case Types.FLOAT:
  29. return 'packet.readFloat();';
  30. case Types.DOUBLE:
  31. return 'packet.readDouble();';
  32. case Types.NULL:
  33. return 'null;';
  34. case Types.DATE:
  35. case Types.DATETIME:
  36. case Types.TIMESTAMP:
  37. case Types.NEWDATE:
  38. if (config.dateStrings) {
  39. return `packet.readDateTimeString(${field.decimals});`;
  40. }
  41. return `packet.readDateTime('${timezone}');`;
  42. case Types.TIME:
  43. return 'packet.readTimeString()';
  44. case Types.DECIMAL:
  45. case Types.NEWDECIMAL:
  46. if (config.decimalNumbers) {
  47. return 'packet.parseLengthCodedFloat();';
  48. }
  49. return 'packet.readLengthCodedString("ascii");';
  50. case Types.GEOMETRY:
  51. return 'packet.parseGeometryValue();';
  52. case Types.JSON:
  53. // Since for JSON columns mysql always returns charset 63 (BINARY),
  54. // we have to handle it according to JSON specs and use "utf8",
  55. // see https://github.com/sidorares/node-mysql2/issues/409
  56. return 'JSON.parse(packet.readLengthCodedString("utf8"));';
  57. case Types.LONGLONG:
  58. if (!supportBigNumbers) {
  59. return unsigned
  60. ? 'packet.readInt64JSNumber();'
  61. : 'packet.readSInt64JSNumber();';
  62. }
  63. if (bigNumberStrings) {
  64. return unsigned
  65. ? 'packet.readInt64String();'
  66. : 'packet.readSInt64String();';
  67. }
  68. return unsigned ? 'packet.readInt64();' : 'packet.readSInt64();';
  69. default:
  70. if (field.characterSet === Charsets.BINARY) {
  71. return 'packet.readLengthCodedBuffer();';
  72. }
  73. return `packet.readLengthCodedString(CharsetToEncoding[fields[${fieldNum}].characterSet])`;
  74. }
  75. }
  76. function compile(fields, options, config) {
  77. const parserFn = genFunc();
  78. let i = 0;
  79. const nullBitmapLength = Math.floor((fields.length + 7 + 2) / 8);
  80. /* eslint-disable no-trailing-spaces */
  81. /* eslint-disable no-spaced-func */
  82. /* eslint-disable no-unexpected-multiline */
  83. parserFn('(function(){')(
  84. 'return function BinaryRow(packet, fields, options, CharsetToEncoding) {'
  85. );
  86. if (options.rowsAsArray) {
  87. parserFn(`const result = new Array(${fields.length});`);
  88. }
  89. const resultTables = {};
  90. let resultTablesArray = [];
  91. if (options.nestTables === true) {
  92. for (i = 0; i < fields.length; i++) {
  93. resultTables[fields[i].table] = 1;
  94. }
  95. resultTablesArray = Object.keys(resultTables);
  96. for (i = 0; i < resultTablesArray.length; i++) {
  97. parserFn(`this[${helpers.srcEscape(resultTablesArray[i])}] = {};`);
  98. }
  99. }
  100. parserFn('packet.readInt8();'); // status byte
  101. for (i = 0; i < nullBitmapLength; ++i) {
  102. parserFn(`const nullBitmaskByte${i} = packet.readInt8();`);
  103. }
  104. let lvalue = '';
  105. let currentFieldNullBit = 4;
  106. let nullByteIndex = 0;
  107. let fieldName = '';
  108. let tableName = '';
  109. for (i = 0; i < fields.length; i++) {
  110. fieldName = helpers.srcEscape(fields[i].name);
  111. parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);
  112. if (typeof options.nestTables === 'string') {
  113. tableName = helpers.srcEscape(fields[i].table);
  114. lvalue = `this[${helpers.srcEscape(
  115. fields[i].table + options.nestTables + fields[i].name
  116. )}]`;
  117. } else if (options.nestTables === true) {
  118. tableName = helpers.srcEscape(fields[i].table);
  119. lvalue = `this[${tableName}][${fieldName}]`;
  120. } else if (options.rowsAsArray) {
  121. lvalue = `result[${i.toString(10)}]`;
  122. } else {
  123. lvalue = `this[${helpers.srcEscape(fields[i].name)}]`;
  124. }
  125. // TODO: this used to be an optimisation ( if column marked as NOT_NULL don't include code to check null
  126. // bitmap at all, but it seems that we can't rely on this flag, see #178
  127. // TODO: benchmark performance difference
  128. //
  129. // if (fields[i].flags & FieldFlags.NOT_NULL) { // don't need to check null bitmap if field can't be null.
  130. // result.push(lvalue + ' = ' + readCodeFor(fields[i], config));
  131. // } else if (fields[i].columnType == Types.NULL) {
  132. // result.push(lvalue + ' = null;');
  133. // } else {
  134. parserFn(`if (nullBitmaskByte${nullByteIndex} & ${currentFieldNullBit})`);
  135. parserFn(`${lvalue} = null;`);
  136. parserFn('else');
  137. parserFn(`${lvalue} = ${readCodeFor(fields[i], config, options, i)}`);
  138. // }
  139. currentFieldNullBit *= 2;
  140. if (currentFieldNullBit === 0x100) {
  141. currentFieldNullBit = 1;
  142. nullByteIndex++;
  143. }
  144. }
  145. if (options.rowsAsArray) {
  146. parserFn('return result;');
  147. }
  148. parserFn('};')('})()');
  149. /* eslint-enable no-trailing-spaces */
  150. /* eslint-enable no-spaced-func */
  151. /* eslint-enable no-unexpected-multiline */
  152. if (config.debug) {
  153. helpers.printDebugWithCode(
  154. 'Compiled binary protocol row parser',
  155. parserFn.toString()
  156. );
  157. }
  158. return parserFn.toFunction();
  159. }
  160. function getBinaryParser(fields, options, config) {
  161. return parserCache.getParser('binary', fields, options, config, compile);
  162. }
  163. module.exports = getBinaryParser;