mysql: Client.prototype.format shouldn't treat "?" as placeholder inside string literals
Description
Client.prototype.format
attempts to replace every occurrence of ?
for a variable. Even if it’s inside a string literal.
E.g.:
mysql.query("SELECT * FROM ponies WHERE emotion = 'wtf?' AND id = ?", [1])
results in error because function expects two parameters instead of one.
Solutions
Option 1
Pretend it’s a feature 😃 And do adhoc stuff like this:
mysql.query("SELECT * FROM ponies WHERE emotion = 'wtf?' AND id = ?", ['?', 1])
Option 2
Placeholders should be left intact if in string literals. Such behavior can be observed in PHP PDO
mysql.query("SELECT * FROM ponies WHERE emotion = 'wtf?' AND id = ?", [1])
// SELECT * FROM ponies WHERE emotion = 'wtf?' AND id = 1
Option 3
Add escaping convention for ?
.
For example, use #
or \
and do something like:
? => value
#? => ?
## => #
###? => #?
IMHO, we should stay away from \
as it can easily turn into escaping hell like in these non-real-world examples:
// SELECT * FROM ponies WHERE emotion = 'wtf?' AND id = ?
mysql.query('SELECT * FROM ponies WHERE emotion = \'wtf\\?\' AND id = ?', [1])
// SELECT * FROM ninjas WHERE slash_and_question = '\\?' AND id = ?'
// has to be: SELECT * FROM ninjas WHERE slash_and_question = '\\\\\?' AND id = ?'
mysql.query('SELECT * FROM ninjas WHERE slash_and_question = \'\\\\\\\\\\?\' AND id = ?', [1])
I have patch for options 1 and 2. Option 3 is a piece of cake. Which one should I attach? 😃
About this issue
- Original URL
- State: closed
- Created 13 years ago
- Comments: 21
Commits related to this issue
- Fixes #118 https://github.com/felixge/node-mysql/issues/118 Modified Client.prototype.format to not replace "?" in query string literals — committed to TEHEK/node-mysql by TEHEK 13 years ago
- Fixes #118 https://github.com/felixge/node-mysql/issues/118 Modified Client.prototype.format to not replace "?" in query string literals denoted by single or double quotes or backticks. Fixed escap... — committed to TEHEK/node-mysql by TEHEK 13 years ago
- Fixes #118 Simplified #format() parser a bit and corrected comment block with descriptions — committed to TEHEK/node-mysql by TEHEK 13 years ago
- Fixes #118 Added one crazy escaping test — committed to TEHEK/node-mysql by TEHEK 13 years ago
- Add CHANGELOG Fixes issue #118 — committed to dveeden/mysql by julienschmidt 11 years ago
@qwy https://github.com/mysqljs/mysql/blob/master/License#L13-L19
is it still remain open bug? kinda incredible if it is after 5 year. i’m using “mysql”: “^2.12.0”, it’s still making trouble there. and yet i cannot find an elegant way out. either option 2 or 3 makes sense to me.
please do fix it. or let me know if my info is incorrect. thanks.