Re: BUG #14149: when use LATERAL functions with IMMUTABLE called multiple times

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: turon(dot)david(at)seznam(dot)cz
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: BUG #14149: when use LATERAL functions with IMMUTABLE called multiple times
Date: 2016-05-19 13:43:08
Message-ID: 15800.1463665388@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

turon(dot)david(at)seznam(dot)cz writes:
> we found strange behavior LATERAL when we upgrade from 9.3.12 to 9.5.3,
> simple example:

> CREATE OR REPLACE FUNCTION f_imutable(OUT a int, out b int) AS $$
> BEGIN
> a := 1;
> b := 2;
> RAISE NOTICE 'call function f_imutable';
> END;
> $$ LANGUAGE plpgsql IMMUTABLE;

> --execution on 9.3.12, for one row one call

> SELECT (x.y).a, (x.y).b FROM generate_series(1,1), LATERAL (SELECT
> f_imutable()) AS x(y);

> --execution on 9.5.3 called 2x

I think you are confusing an implementation artifact of older versions
with a guaranteed behavior. Declaring a function IMMUTABLE (or STABLE)
says that it's okay if the generated plan calls the function more or fewer
times than naive analysis might suggest. 9.3 happened not to do so, for
this specific query, but 9.5 does.

Really the best fix for this is to mark a function VOLATILE if you can't
afford for the planner to rearrange the calls. In this particular case,
you might also consider rearranging the query so that the function is
called as a FROM item rather than a select-list item:

# SELECT x.a, x.b FROM generate_series(1,1), LATERAL f_imutable() as x;
NOTICE: call function f_imutable
a | b
---+---
1 | 2
(1 row)

but I wouldn't really want to promise that that won't ever change behavior
either. The argument for it is as much that it's a less messy notation
as anything else.

regards, tom lane

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message onic 2016-05-19 15:00:37 BUG #14151: Xml special symbols are not unescaped when gettting value of Xml via xpath
Previous Message David G. Johnston 2016-05-19 13:42:36 Re: ALTER TABLE can NOT use set (OIDS=true)