set_quote_pgsql_str

The set_quote_pgsql_str directive is used to escape special characters in strings for safe use in PostgreSQL queries.

Syntaxset_quote_pgsql_str variable [$variable];
Defaultnone
Contexthttp, server, location, if in server, if in location
Arguments1-2

Description

The set_quote_pgsql_str directive processes a given string variable and escapes characters that have special meaning in PostgreSQL. This includes transforming strings to ensure that they are wrapped in an E'...' format, which allows for the inclusion of escape sequences such as newlines `
and quotes \`. When specified, it can enhance security by preventing SQL injection attacks via careful handling of user input that will be included in a SQL query.

The directive accepts one or two arguments. The first is the variable containing the string to be processed, and the second (optional) can be the same variable to modify it in-place. If the second argument is omitted, the value from the first argument will be modified directly. This flexibility allows users to either output a new variable with the escaped content or alter the original variable directly without needing to create another.

Usage scenarios include validating or sanitizing inputs in a web application that interfaces with the PostgreSQL database, ensuring safe execution of dynamic SQL commands without unintended behavior. It should be noted that while this directive is effective for escaping strings for PostgreSQL, developers should always consider additional measures for handling SQL queries securely, such as using prepared statements whenever possible.

Config Example

 location /bar {
     set $foo "hello\n\n'\"\\";
     set_quote_pgsql_str $foo;  # for PostgreSQL
     # now $foo is: E'hello\n\n\'\"\\'
 }

Ensure the input variable is defined and contains the intended value; otherwise, the output may not be as expected.

Be cautious about using the directive without the second argument if you don't want to overwrite your original variable unintentionally.

← Back to all directives