From: Joel Jacobson <joel@compiler.org>
To: pgsql-general@postgresql.org
Subject: CASE WHEN idiomatic for functions with side-effect?
Date: Tue, 12 Jan 2021 12:13:47 +0400
Message-ID: <6aab85ba-a97c-4394-ab80-6077bb14be2b@www.fastmail.com> (raw)
Is it idiomatic and safe to use
SELECT
CASE boolean_expression WHEN TRUE THEN function_with_side_effects() END
...
in a query to ensure the function_with_side_effects() is only
execute if boolean_expression is true?
function_with_side_effects() is known to be a normal function,
and not an aggregate function.
The documentation at
https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-EXPRESS-EVAL
says the following:
"But this is safe:
SELECT ... WHERE CASE WHEN x > 0 THEN y/x > 1.5 ELSE false END;"
On the other hand, it also says:
"related cases that don't obviously involve constants can occur in queries executed within functions, since the values of function arguments and local variables can be inserted into queries as constants for planning purposes. Within PL/pgSQL functions, for example, using an IF-THEN-ELSE statement to protect a risky computation is much safer than just nesting it in a CASE expression."
Can I trust PostgreSQL not to execute function_with_side_effects() unless boolean_expression IS TRUE?
Or should I rewrite my code to use a PL/pgSQL function with IF-THEN-ELSE here instead?
The affected real code: https://github.com/truthly/uniphant/blob/rls/FUNCTIONS/api/verify_assertion.sql
Many thanks for clarifying.
/Joel
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: joel@compiler.org
Subject: Re: CASE WHEN idiomatic for functions with side-effect?
In-Reply-To: <6aab85ba-a97c-4394-ab80-6077bb14be2b@www.fastmail.com>
References: <6aab85ba-a97c-4394-ab80-6077bb14be2b@www.fastmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox