postgres_rewrite
The `postgres_rewrite` directive alters the response status code based on the result of a PostgreSQL query.
Description
The postgres_rewrite directive is a powerful feature of the PostgreSQL module for NGINX that allows users to manipulate the HTTP response status code based on the results returned from a PostgreSQL database query. It can be used in various contexts, such as http, server, location, and if within a location. This directive takes a minimum of two parameters: the condition under which the rewrite should be applied (like no_changes, changes, no_rows, or rows) and the resulting HTTP status code to return if the condition is satisfied. If the status code is prefixed with an =, the body of the original response is returned instead of a default error response, providing further flexibility in handling responses to the client.
The conditions specified with postgres_rewrite help define operational logic for different SQL operations. For example, no_changes indicates that an INSERT, UPDATE, or DELETE operation did not affect any rows, whereas changes indicates that at least one row was affected. This behavior is particularly useful in applications that need to respond with specific status codes based on database interactions. Furthermore, these directives can be specified multiple times in the same context, allowing for intricate control over the response logic based on varying query results.
Config Example
location /query {
postgres_pass my_upstream;
postgres_query SELECT * FROM users;
postgres_rewrite changes 201;
postgres_rewrite no_changes 204;
}Ensure that the conditions are specified correctly; a misplaced condition could lead to unexpected behavior.
Remember that only the first matching postgres_rewrite directive will be executed; subsequent matches are ignored.
The conditions no_changes and changes only apply to specific SQL commands (INSERT, UPDATE, DELETE, etc.).