I am trying to write an object-oriented layer for creating SQL queries for NodeJS, like Zend's DB component. So I want to be able to escape values. Yes, I know parameterized queries are ideal. But reasons I want escaping:
- I want to allow the created queries to be executed driver-agnostically (in terms of creating a platform-specific SQL string, instead of relying on one library's interface for parameterized queries), although I will add support for prepared queries for popular drivers
- Zend's Db component does escaping, so it seems like it should be possible (safe)
- There is nothing like it for NodeJS I am aware of, so I can't find any examples or use another library's escape function
Since Zend uses it, I started with this approach. I found examples for escaping strings for MySQL and PostgresSQL, but didn't find anything for Sqlite3.
I tried tracing PHP's Sqlite3::escapeString function, and ended up at sqlite3VXPrintf
in sqlite3.c, line 19016, which is a massive printf function. I'm not even sure that's where I was supposed to end up. Anyways, I had no luck trying to understand it :P
So I'm hoping someone can give me more pointers as to how to do this. And what do I have to be aware of to make my escaping functions safe? Why isn't replacing all '
with \\'
safe? I'm aware of flaws like second order SQL injection, but that's still because someone forgot to escape something. An interface for creating SQL queries could automatically quote values, unless the developer explicitly says "this is safe"
While I'm at it, regarding the solution in the earlier MySQL question, it looks pretty simple (no special cases?). Is that really all there is to it? Assuming unsafeinput is always escaped. mysqli_real_escape_string escapes NUL (ASCII 0), \n, \r, \, ', ", and Control-Z. Sqlite3's documentation only mentions single quotes, but certain characters like NUL look fishy. Anywhere I can find out more about this?
PostgresSQL's escape function in libpq also looks like it's just replacing quotes with escaped quotes. I guess I'm just making sure this is okay because I always hear "use parameterized queries!" as if escape functions are useless.
TLDR: I have two main questions
- Is escaping special characters for queries safe if it is done properly and everywhere?
- Where can I find examples of Sqlite3 escaping code? The official docs only mention the single quote for literals (want to make sure), and I had no luck tracing PHP source.