denodrivers/mysql

No sanitize method?

thpglobal opened this issue · 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.

The library auto sanitizes all input with this library https://deno.land/x/sql_builder@v1.7.0/util.ts

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

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;`;