원칙적으로 옵티마이 저는 함수가 수행하는 바가 전혀 없음 – 함수 본문은 함수 처리 순서 언어의에 의해 처리되는 문자열입니다.
한 가지 예외는 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.
*/
backend/optimizer/util/clauses.c
에서 inline_set_returning_function
두 가지 교훈 의견도있다 :
/*
* 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)
당신은 실행 계획을 볼 수 있습니다. Postgres 최적화에 대해 많이 알지 못해서, 나는 set-returning 함수가 최적화면에서 "장벽"이 될 것으로 기대한다. 즉, 최적화를 위해 함수에 외부 술어가 전달되면 나는 놀랄 것입니다. –
PostgreSQL에 놀란 : ^) –