text_parser.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. 'use strict';
  2. const Types = require('../constants/types.js');
  3. const Charsets = require('../constants/charsets.js');
  4. const helpers = require('../helpers');
  5. const genFunc = require('generate-function');
  6. const parserCache = require('./parser_cache.js');
  7. const typeNames = [];
  8. for (const t in Types) {
  9. typeNames[Types[t]] = t;
  10. }
  11. function readCodeFor(type, charset, encodingExpr, config, options) {
  12. const supportBigNumbers =
  13. options.supportBigNumbers || config.supportBigNumbers;
  14. const bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings;
  15. const timezone = options.timezone || config.timezone;
  16. const dateStrings = options.dateStrings || config.dateStrings;
  17. switch (type) {
  18. case Types.TINY:
  19. case Types.SHORT:
  20. case Types.LONG:
  21. case Types.INT24:
  22. case Types.YEAR:
  23. return 'packet.parseLengthCodedIntNoBigCheck()';
  24. case Types.LONGLONG:
  25. if (supportBigNumbers && bigNumberStrings) {
  26. return 'packet.parseLengthCodedIntString()';
  27. }
  28. return `packet.parseLengthCodedInt(${supportBigNumbers})`;
  29. case Types.FLOAT:
  30. case Types.DOUBLE:
  31. return 'packet.parseLengthCodedFloat()';
  32. case Types.NULL:
  33. return 'packet.readLengthCodedNumber()';
  34. case Types.DECIMAL:
  35. case Types.NEWDECIMAL:
  36. if (config.decimalNumbers) {
  37. return 'packet.parseLengthCodedFloat()';
  38. }
  39. return 'packet.readLengthCodedString("ascii")';
  40. case Types.DATE:
  41. if (helpers.typeMatch(type, dateStrings, Types)) {
  42. return 'packet.readLengthCodedString("ascii")';
  43. }
  44. return `packet.parseDate('${timezone}')`;
  45. case Types.DATETIME:
  46. case Types.TIMESTAMP:
  47. if (helpers.typeMatch(type, dateStrings, Types)) {
  48. return 'packet.readLengthCodedString("ascii")';
  49. }
  50. return `packet.parseDateTime('${timezone}')`;
  51. case Types.TIME:
  52. return 'packet.readLengthCodedString("ascii")';
  53. case Types.GEOMETRY:
  54. return 'packet.parseGeometryValue()';
  55. case Types.JSON:
  56. // Since for JSON columns mysql always returns charset 63 (BINARY),
  57. // we have to handle it according to JSON specs and use "utf8",
  58. // see https://github.com/sidorares/node-mysql2/issues/409
  59. return 'JSON.parse(packet.readLengthCodedString("utf8"))';
  60. default:
  61. if (charset === Charsets.BINARY) {
  62. return 'packet.readLengthCodedBuffer()';
  63. }
  64. return `packet.readLengthCodedString(${encodingExpr})`;
  65. }
  66. }
  67. function compile(fields, options, config) {
  68. // use global typeCast if current query doesn't specify one
  69. if (
  70. typeof config.typeCast === 'function' &&
  71. typeof options.typeCast !== 'function'
  72. ) {
  73. options.typeCast = config.typeCast;
  74. }
  75. function wrap(field, _this) {
  76. return {
  77. type: typeNames[field.columnType],
  78. length: field.columnLength,
  79. db: field.schema,
  80. table: field.table,
  81. name: field.name,
  82. string: function() {
  83. return _this.packet.readLengthCodedString(field.encoding);
  84. },
  85. buffer: function() {
  86. return _this.packet.readLengthCodedBuffer();
  87. },
  88. geometry: function() {
  89. return _this.packet.parseGeometryValue();
  90. }
  91. };
  92. }
  93. const parserFn = genFunc();
  94. /* eslint-disable no-trailing-spaces */
  95. /* eslint-disable no-spaced-func */
  96. /* eslint-disable no-unexpected-multiline */
  97. parserFn('(function () {')(
  98. 'return class TextRow {'
  99. );
  100. // constructor method
  101. parserFn('constructor(fields) {');
  102. // node-mysql typeCast compatibility wrapper
  103. // see https://github.com/mysqljs/mysql/blob/96fdd0566b654436624e2375c7b6604b1f50f825/lib/protocol/packets/Field.js
  104. if (typeof options.typeCast === 'function') {
  105. parserFn('const _this = this;');
  106. parserFn('for(let i=0; i<fields.length; ++i) {');
  107. parserFn('this[`wrap${i}`] = wrap(fields[i], _this);');
  108. parserFn('}');
  109. }
  110. parserFn('}');
  111. // next method
  112. parserFn('next(packet, fields, options) {');
  113. parserFn("this.packet = packet;");
  114. if (options.rowsAsArray) {
  115. parserFn(`const result = new Array(${fields.length});`);
  116. } else {
  117. parserFn("const result = {};");
  118. }
  119. const resultTables = {};
  120. let resultTablesArray = [];
  121. if (options.nestTables === true) {
  122. for (let i=0; i < fields.length; i++) {
  123. resultTables[fields[i].table] = 1;
  124. }
  125. resultTablesArray = Object.keys(resultTables);
  126. for (let i=0; i < resultTablesArray.length; i++) {
  127. parserFn(`result[${helpers.srcEscape(resultTablesArray[i])}] = {};`);
  128. }
  129. }
  130. let lvalue = '';
  131. let fieldName = '';
  132. for (let i = 0; i < fields.length; i++) {
  133. fieldName = helpers.srcEscape(fields[i].name);
  134. parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);
  135. if (typeof options.nestTables === 'string') {
  136. lvalue = `result[${helpers.srcEscape(
  137. fields[i].table + options.nestTables + fields[i].name
  138. )}]`;
  139. } else if (options.nestTables === true) {
  140. lvalue = `result[${helpers.srcEscape(fields[i].table)}][${fieldName}]`;
  141. } else if (options.rowsAsArray) {
  142. lvalue = `result[${i.toString(10)}]`;
  143. } else {
  144. lvalue = `result[${fieldName}]`;
  145. }
  146. if (options.typeCast === false) {
  147. parserFn(`${lvalue} = packet.readLengthCodedBuffer();`);
  148. } else {
  149. const encodingExpr = `fields[${i}].encoding`;
  150. const readCode = readCodeFor(
  151. fields[i].columnType,
  152. fields[i].characterSet,
  153. encodingExpr,
  154. config,
  155. options
  156. );
  157. if (typeof options.typeCast === 'function') {
  158. parserFn(`${lvalue} = options.typeCast(this.wrap${i}, function() { return ${readCode} });`);
  159. } else {
  160. parserFn(`${lvalue} = ${readCode};`);
  161. }
  162. }
  163. }
  164. parserFn('return result;');
  165. parserFn('}');
  166. parserFn('};')('})()');
  167. /* eslint-enable no-trailing-spaces */
  168. /* eslint-enable no-spaced-func */
  169. /* eslint-enable no-unexpected-multiline */
  170. if (config.debug) {
  171. helpers.printDebugWithCode(
  172. 'Compiled text protocol row parser',
  173. parserFn.toString()
  174. );
  175. }
  176. if (typeof options.typeCast === 'function') {
  177. return parserFn.toFunction({wrap});
  178. }
  179. return parserFn.toFunction();
  180. }
  181. function getTextParser(fields, options, config) {
  182. return parserCache.getParser('text', fields, options, config, compile);
  183. }
  184. module.exports = getTextParser;