Re: CASE WHEN idiomatic for functions with side-effect?

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Joel Jacobson <joel(at)compiler(dot)org>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: CASE WHEN idiomatic for functions with side-effect?
Date: 2021-01-12 14:45:12
Message-ID: CAKFQuwYFMetu-nb2gzSAco07+xcv8ZKA8ZTziS7ZU=aLRywwYw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, Jan 12, 2021 at 1:14 AM Joel Jacobson <joel(at)compiler(dot)org> wrote:

> Is it idiomatic and safe to use
>
> SELECT
> CASE boolean_expression WHEN TRUE THEN function_with_side_effects() END
>

As long as function_with_side_effects() is defined volatile it is forced to
be executed at runtime, once per row. That situation is always protected
by the case expression.

> "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."
>
> The affected real code:
> https://github.com/truthly/uniphant/blob/rls/FUNCTIONS/api/verify_assertion.sql
>

The relevant function takes in a column argument - it is thus impossible
for the planner to evaluate the expression. And, as above, the planner
respects the "volatile" attribute of functions.

David J.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2021-01-12 14:48:27 Re: CASE WHEN idiomatic for functions with side-effect?
Previous Message Голубева Яна 2021-01-12 08:20:59 Re: Define hash partition for certain column values