Mysql_real_escape_string/addslashes for DB2 CLI

C++ developers are well aware of the popular mysql_real_escape_string function for escaping both traditional text and binary strings. When working on the revisions for my presentation for IDUG Europe, I noticed there was no equivalent to the mysql_real_escape_string in the DB2 CLI. A quick searching through the mysql source code I was able to find the function and a couple of modifications later I was able to make it generic enough to support DB2 SQL escaping.

size_t escape_string_for_db2(char *to, size_t to_length,
                               const char *from, size_t length)
{
  const char *to_start= to;
  const char *end, *to_end= to_start + (to_length ? to_length-1 : 2*length);
  bool overflow= false;

  for (end= from + length; from < end; from++)
  {
    char escape= 0;

    switch (*from) {
    case 0:/* Must be escaped for 'mysql' */
      escape= '0';
      break;
    case '
':/* Must be escaped for logs */
      escape= 'n';
      break;
    case '
':
      escape= 'r';
      break;
    case '':
      escape= '';
      break;
    case ''':
      escape= ''';
      break;
    case '"':/* Better safe than sorry */
      escape= '"';
      break;
    case '�32':/* This gives problems on Win32 */
      escape= 'Z';
      break;
    }
    if (escape)
    {
      if (to + 2 > to_end)
      {
        overflow= true;
        break;
      }
      *to++= '';
      *to++= escape;
    }
    else
    {
      if (to + 1 > to_end)
      {
        overflow= true;
        break;
      }
      *to++= *from;
    }
  }
  *to= 0;
  return overflow ? (size_t) -1 : (size_t) (to - to_start);
}

Recent Stories
Mysql_real_escape_string/addslashes for DB2 CLI

Packet sniffing the DRDA protocol – A very low impact way to view incoming statements going into DB2

Disk Throughput on Amazon EC2, VM Ware, Slicehost, Internal Storage, and SANs