node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

typeCast does not work for the `execute` method

Open joakimbeng opened this issue 10 months ago • 4 comments

I am unable to get the typeCast option to work at all for the execute method. I have tried configuring it both on the connection level and per query, but with no success.

I have set up a minimal reproduction example here: https://github.com/joakimbeng/mysql2-bug

The reproduction repo uses mysql2 v3.12.0 and node v22.

Am I missing something or shouldn't the typeCast option work with both the query and execute methods since v3.9.0?

joakimbeng avatar Feb 03 '25 10:02 joakimbeng

Hi @joakimbeng - please read https://github.com/sidorares/node-mysql2/issues/1446 and linked issues, hope that will give you a context to explain current behavior and future plans

sidorares avatar Feb 03 '25 22:02 sidorares

This is occurring because the null value is not being passed through typeCast:

https://github.com/sidorares/node-mysql2/blob/568a6cfb96be587504f9345c64e0b28c237d056f/lib/parsers/binary_parser.js#L184-L185

An approach would be to check if the typeCast is a function and, if so, return the null through typeCast, for example:

parserFn(`if (nullBitmaskByte${nullByteIndex} & ${currentFieldNullBit}) {`);
if (typeof options.typeCast === 'function') {
  parserFn(`${lvalue} = options.typeCast(wrap(fields[${i}], packet), () => null);`);
} else {
  parserFn(`${lvalue} = null;`);
}
parserFn('} else {');
  • Not a real fix, but it would fix this bug:

[!NOTE] typeCast is not an actively maintained feature because of its planned deprecation, but I'm open to fix it 🙋🏻‍♂️

wellwelwel avatar Feb 04 '25 02:02 wellwelwel

@wellwelwel I see! So it's only for NULL values that it behaves differently than typeCast for the query method then?

If it's such an easy fix I'm all for it! 😃 It would be greatly appreciated if you would release that fix!

joakimbeng avatar Feb 04 '25 07:02 joakimbeng

@joakimbeng, there is a check to ensure if typeCast is a function, but it occurs after the null has already been returned:

https://github.com/sidorares/node-mysql2/blob/568a6cfb96be587504f9345c64e0b28c237d056f/lib/parsers/binary_parser.js#L195-L199

The idea for a fix follows the same idea I mentioned, but would require a small refactoring in the order of the logic.

If it's such an easy fix I'm all for it!

Feel free to do so 🚀

  • I'll merge #3365 tomorrow (already merged), which will allow to use both the query and execute methods without eval. We can apply this fix to both sides afterwards 🙋🏻‍♂️

wellwelwel avatar Feb 04 '25 07:02 wellwelwel