pg_escape_string

pg_escape_string — Escape a string for use in an SQL string constant

Synopsis

pg_escape_string ?conn? string

Description

pg_escape_string returns its argument with added characters which makes it safe for use in single-quoted SQL string constants. It returns the string with all single quote marks doubled, and in some cases doubles backslash characters too.

For example, pg_escape_string {can't} returns the string can''t.

Arguments

conn

Optional handle of the connection that the string should be escaped for sending to.

string

The string to escape.

Return Value

The string argument, with added characters.

Notes

See also pg_quote.

The optional conn argument was added to this command in pgtclng-1.7.0 and in pgintcl-3.1.0.

The conn argument is used to get character set encoding information, and the state of the PostgreSQL server configuration parameter standard_conforming_strings. The character set encoding is used to make sure that multi-byte characters do not confuse the escaping process. The state of the standard conforming strings setting is used to determine if backslashes need to be doubled. If the conn parameter is supplied, these settings can be accurately determined for the specific database connection being used. (Note that this information is maintained on the client side and does not necessitate any additional database server traffic.)

If the conn parameter is not supplied, a best guess will be made based on the most recent information from any database connection by the client. Therefore, if the client makes a single database connection, or multiple connections with the same encoding and setting for standard_conforming_strings, there is no need to provide the conn parameter.

Caution

Pgintcl uses the conn parameter only to determine if standard_conforming_strings is on. Unlike libpq-based interface implementations, it does not have the ability to use character set encoding information.

This command uses or emulates the PostgreSQL libpq function PQescapeString, if no connection handle is supplied, or PQescapeStringConn if a connection handle is supplied.

Caution

The Pgtcl implementation at Pgfoundry has a command with the same name, but incompatible behavior. That one was originally compatible, but was changed to behave the same as pg_quote. Pgtcl-ng and pgintcl retain the original behavior for pg_escape_string that matches the libpq PQescapeString function (returns the escaped value, without single quotes).