Bug #1641 mysql_real_escape_string
Submitted: 23 Oct 2003 23:39 Modified: 21 Apr 2008 13:42
Reporter: Robert Colbert
Status: Won't fix
Category:Server Severity:S4 (Feature request)
Version: OS:Any
Assigned to: Target Version:
Triage: D5 (Feature request)

[23 Oct 2003 23:39] Robert Colbert
Description:
This function requires me to allocate TOO MUCH data! I've written my own to compensate
for this, but it would be nice to share the optimization with the rest of the MySQL
developers.

How to repeat:
This isn't a bug. It's a feature request. To repeat, just allocate srcLen * 2 + 1 for
mysql_real_escape_string(). It's an inefficiency.

Suggested fix:
I'd like a version that simply allocates a string of the proper length and returns that
string and its length to me, leaving it as my responsibility to free the string:

unsigned long mysql_real_escape_string(MYSQL *mysql, char **to, const char *from,
unsigned long length);

char* query = "SELECT * FROM TABLE";
char* result = NULL;
unsigned long resLen = mysql_real_escape_string(mysql, &result, query, strlen(query));

// resLen now holds the length (or zero or error code);
// result is now allocated and holds my escaped string;

free(result);

This way, the escape function can figure out the real length, allocate a buffer, do the
work and return a buffer to me. If I forget to free it and leak, that's my bug, not
yours!

There is no need to assume that passing a non-null "result" should mean that you should
either (1) use my buffer; or (2) free my buffer before allocating a new one. Just stomp
the pointer. Again, that would be MY bug to fix in the application and shouldn't
necessarily be the responsibility of the library.

Thanks in advance,
-Rob Colbert
[22 Jul 2006 20:39] Kent Boortz
Giving NULL as 'to' argument to this function, could be set
to mean "return number of characters only, don't write anything".

Giving NULL in the current implementation is "undefined", and
would in most cases crash the application using the function.
So not sure that altering the behaviour of an existing function
is the right thing to do, a new function

  mysql_real_buffer_size_needed()

might be a better aproach. Note that setting the destination buffer
lenght to zero is already a undocumented special case, for backward
compatibility. It means "I know I have enough buffer".
[22 Jul 2006 20:55] Bugs System
A patch for this bug has been committed. After review, it may
be pushed to the relevant source trees for release in the next
version. You can access the patch from:

  http://lists.mysql.com/commits/9452
[21 Apr 2008 13:42] Kent Boortz
There will most likely eventually be some solution to this.
The MySQL ODBC driver is hit by this problem.