mysql icon indicating copy to clipboard operation
mysql copied to clipboard

No sanitize method?

Open thpglobal opened this issue 4 years ago • 3 comments

It appears that there is no method for sanitizing strings to be safe for mysql. Generally, mysql drivers include this. I found a simple one on stack overflow here (much shorter than the super-long one on nodejs.

thpglobal avatar Jul 29 '21 12:07 thpglobal

The library auto sanitizes all input with this library https://deno.land/x/[email protected]/util.ts

AnInternetTroll avatar Jul 29 '21 16:07 AnInternetTroll

Wouldn't it have been better if instead of sanitizing by escaping as string and formatting the values into the SQL string itself we used the binary protocol to send placeholder values separately?

https://dev.mysql.com/doc/internals/en/com-stmt-execute.html

zumoshi avatar Nov 24 '21 12:11 zumoshi

Here is what I currently use so far:

// Deno function to escape MySQL select, insert, update, delete query values
function _escape(value: string | number): string {

  if (typeof value !== 'string') {
    // Handle non-string values appropriately
    // For example, convert to string or return a default string
    value = String(value);
  }

  return value.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, (char: string) => {
    switch (char) {
      case "\0":
        return "\\0";
      case "\x08":
        return "\\b";
      case "\x09":
        return "\\t";
      case "\x1a":
        return "\\z";
      case "\n":
        return "\\n";
      case "\r":
        return "\\r";
      case "\"":
      case "'":
      case "\\":
      case "%":
        return "\\" + char;
      default:
        return char;
    }
  });
}

/* DELETE record from table */
const sqlDeleteProject: string = 
`DELETE FROM tblProjects 
  WHERE 
    id = '${_escape(reqBody.params.id)}'
  LIMIT 1;`;

suchislife801 avatar Dec 13 '23 00:12 suchislife801