mysqljs / sqlstring

Simple SQL escape and format for MySQL
MIT License
403 stars 78 forks source link

Question about the Regex literals in Google App Script #28

Closed garymcm closed 6 years ago

garymcm commented 6 years ago

This is a great utility. I copied it into a Google App Scripts project and defined it as an immediate execute function. It required a little tweaking, like removing Buffer, but works fine.

When I called String.format with an Array, as for an IN clause, subsequent calls no longer work, even simple substitutions, i.e.

console.log(SqlString.format('employees in (?)', [[5, 6, 7, 8, 9]])); // OK
console.log(SqlString.format('employee_id = ?', 97)); // No substitution happens

FYI, Quokka doesn't exhibit this issue locally, interestingly.

I finally found it to be related to the literal regex and by making it a new object every time the issue was resolved. I am scratching my head why, though. Perhaps it's a bug in Google App Script Environment?

// var placeholdersRegex = /\?\??/g; 
var placeholdersRegex = new RegExp(/\?\??/g);

I am not asking for support, since clearly it's no longer the same code base, but I am just curious why the state of the match seems to be preserved after these two calls?

Thanks for making this utility. Really makes life easier.

dougwilson commented 6 years ago

Hi @garymcm that's OK. I'm not familiar with Google App Scripts, so don't know what is happening or if it is specific to them off-hand, unfortunately. Does the same thing happen when you run your same exact code in Node.js? If not, then it does sound like maybe Google App Scripts, but I don't know anything about them, unfortunately.

garymcm commented 6 years ago

Thanks for the reply. I am pretty certain it's an issue with GAS. I can see the regex's lastIndex property is still set from the prior call, which causes current exec() to return no matches. At that point it's set back to 0, so the next call works. If I explicitly set the lastIndex to 0, that also fixes the problem. Under Node.js, every call shows lastIndex at zero at the beginning, so definitely nothing wrong with your code.