Skip site navigation (1) Skip section navigation (2)

Re: Avoiding execution of some functions by query rewriting

From: Florian Pflug <fgp(at)phlo(dot)org>
To: Thomas Girault <toma(dot)girault(at)gmail(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Avoiding execution of some functions by query rewriting
Date: 2012-05-16 13:01:00
Message-ID: 22BEEF9E-C25D-4E5C-8B0C-C652D6502429@phlo.org (view raw or flat)
Thread:
Lists: pgsql-hackers
On May16, 2012, at 14:30 , Thomas Girault wrote:
> I would like to allow the execution of a function (my_function) only if its argument (my_table.x) belongs to a predefined interval (e.g. [100,1000]).
> 
> Let's take the following query example :
> (q)  SELECT * FROM my_table WHERE my_function(mytable.x);
> 
> I would like this query automatically rewrites itself to check whether "mytable.x" belong to the interval [100,1000] :
> (q')  SELECT * FROM my_table WHERE (my_table.x BETWEEN 100 AND 1000) AND my_function(my_table.x);


Rename my_function to my_function_impl or the like, and create a SQL-language
wrapper function which does

  SELECT (my_table.x BETWEEN 100 AND 1000) AND my_function_impl(my_table.x)

i.e. do

CREATE FUNCTION my_function(sometype) RETURNS BOOL AS $$
  SELECT ($1 BETWEEN 100 AND 1000) AND my_function_impl($1)
$$ LANGUAGE SQL IMMUTABLE;  

This works because sufficiently simply SQL-language functions are inlined early during
query planning, which allows later stages to see through the function call and e.g.
use an index range scan to pull only those rows which satisfy a BETWEEN clause.

I don't remember the precise conditions under which SQL-language functions are inlined,
but I'm pretty sure that not referencing any tables and not having a FROM clause is
sufficient. Note that inlining *only* happens for SQL-language functions, *not* for
PLPGSQL functions, even if the latter consist of a simple RETURN statement.

best regards,
Florian Pflug


In response to

pgsql-hackers by date

Next:From: Tom LaneDate: 2012-05-16 13:08:26
Subject: Re: 9.2beta1 regression: pg_restore --data-only does not set sequence values any more
Previous:From: Sandro SantilliDate: 2012-05-16 12:42:45
Subject: Re: Interrupting long external library calls

Privacy Policy | About PostgreSQL
Copyright © 1996-2013 The PostgreSQL Global Development Group