You shouldn't need to escape literals; that's what parameterised statements are for. psycopg2
supports them for both plannable statements (insert/update/delete/select) and non-plannable statements (create table, create index, ...).
You should always be using parameterised statements in preference to directly substituting literals into query strings.
It looks like psycopg2 exposes some quoting functions too - particularly psycopg2.extensions.adapt
.
That said, for modern PostgreSQL it's pretty trivial; you can follow the same rules as for identifiers, just with '
instead of "
:
- If there's a zero byte (
\x00
) in the string, truncate the string before the zero byte;
- For every
'
in the string, replace it with ''
; and
- Prepend and append
'
.
That's it. Backslashes have no special meaning, so there's nothing else to escape.
You just need to make sure that standard_conforming_strings
is enabled (SELECT current_setting('standard_conforming_strings')
and throw an exception if it isn't, because these rules are completely wrong for old-style strings and E''
strings.
It'd be very nice to have escape_literal
and escape_identifier
functions in psycopg2
. Consider submitting a patch.
See also: