我希望澄清我对PostgreSQL中幕后设置返回函数的理解。
设置我有一套名为' a_at_date'返回:
SELECT * FROM a WHERE date = a_date
其中a_date是函数参数。
如果我这样使用它:
SELECT *
FROM a_at_date(a_date)
WHERE other_field = 123
然后,例如,这可以利用[date,other_field]上的索引以与此相同的方式:
SELECT *
FROM a
WHERE a = a_date AND other_field = 123
换句话说,set return函数是否独立于任何外部查询运行,因此限制了索引选项?
答案 0 :(得分:2)
原则上,优化器不知道函数的作用 - 函数体是由函数的过程语言的调用处理程序处理的字符串。
一个例外是用LANGUAGE sql
编写的函数。如果它们足够简单,并且内联它们可以证明不会改变SQL语句的语义,那么查询重写器将内联它们。
请参阅backend/optimizer/prep/prepjointree.c
中的以下评论:
/*
* inline_set_returning_functions
* Attempt to "inline" set-returning functions in the FROM clause.
*
* If an RTE_FUNCTION rtable entry invokes a set-returning function that
* contains just a simple SELECT, we can convert the rtable entry to an
* RTE_SUBQUERY entry exposing the SELECT directly. This is especially
* useful if the subquery can then be "pulled up" for further optimization,
* but we do it even if not, to reduce executor overhead.
*
* This has to be done before we have started to do any optimization of
* subqueries, else any such steps wouldn't get applied to subqueries
* obtained via inlining. However, we do it after pull_up_sublinks
* so that we can inline any functions used in SubLink subselects.
*
* Like most of the planner, this feels free to scribble on its input data
* structure.
*/
inline_set_returning_function
中的backend/optimizer/util/clauses.c
还有两条有用的评论:
/*
* Forget it if the function is not SQL-language or has other showstopper
* properties. In particular it mustn't be declared STRICT, since we
* couldn't enforce that. It also mustn't be VOLATILE, because that is
* supposed to cause it to be executed with its own snapshot, rather than
* sharing the snapshot of the calling query. (Rechecking proretset is
* just paranoia.)
*/
和
/*
* Make sure the function (still) returns what it's declared to. This
* will raise an error if wrong, but that's okay since the function would
* fail at runtime anyway. Note that check_sql_fn_retval will also insert
* RelabelType(s) and/or NULL columns if needed to make the tlist
* expression(s) match the declared type of the function.
*
* If the function returns a composite type, don't inline unless the check
* shows it's returning a whole tuple result; otherwise what it's
* returning is a single composite column which is not what we need. (Like
* check_sql_fn_retval, we deliberately exclude domains over composite
* here.)
*/
使用EXPLAIN
查看您的功能是否内联。
它起作用的一个例子:
CREATE TABLE a (
"date" date NOT NULL,
other_field text NOT NULL
);
CREATE OR REPLACE FUNCTION a_at_date(date)
RETURNS TABLE ("date" date, other_field text)
LANGUAGE sql STABLE CALLED ON NULL INPUT
AS 'SELECT "date", other_field FROM a WHERE "date" = $1';
EXPLAIN (VERBOSE, COSTS off)
SELECT *
FROM a_at_date(current_date)
WHERE other_field = 'value';
QUERY PLAN
-------------------------------------------------------------------------
Seq Scan on laurenz.a
Output: a.date, a.other_field
Filter: ((a.other_field = 'value'::text) AND (a.date = CURRENT_DATE))
(3 rows)