sqlite String data needs escaping.

By checking the rules, it's easy to cobble together a string with a switch statement. The basic rule is: single and double quotes are doubled, and other special characters are prefixed with /.

The C implementation is as follows:

C
char *str_escape(const char *str) {
  static char dest[1024];
  int i;
  int j = 0;
  int len = strlen(str);
  for (i = 0; i < len; i++) {
    switch (str[i]) {
      case '\'':
      case '\"':
        dest[j] = dest[j + 1] = str[i];
        j += 2;
        break;
      case '/':
      case '[':
      case ']':
      case '%':
      case '&':
      case '_':
      case '(':
      case ')':
        dest[j] = '/';
        j++;
      default:
        dest[j] = str[i];
        j++;
    }
  }
  dest[j] = '\0';
  return dest;
}

Looks pretty neat and powerful.

Then I couldn't help but Google for more info, and found that the previous function can be replaced with this:

C
inline char *str_escape(const char *str) {  //
  return sqlite3_mprintf("%q", str);
}

That's right — the system already provides a function for this.

References: