在我的Postgres服务器上,我使用带有auto_explain
的log_nested_statements
模块来记录PL / pgSQL函数中的其他函数调用。
594 session_preload_libraries = 'auto_explain'
595
596 auto_explain.log_min_duration = 0
597 auto_explain.log_nested_statements = true
598 auto_explain.sample_rate = 1.0
我有一个玩具PL / pgSQL函数baz(count int)
:
Schema | public
Name | baz
Result data type | text
Argument data types | count integer
Type | normal
Volatility | volatile
Parallel | unsafe
Owner | aerust
Security | invoker
Access privileges |
Language | plpgsql
Source code | +
| DECLARE +
| i int := 0; +
| result text := ''; +
| BEGIN +
| +
| IF (count < 1) THEN +
| RETURN result; +
| END IF; +
| +
| LOOP +
| EXIT WHEN i = count; +
| i := i + 1; +
| result := result || ' ' || foo();+
| END LOOP; +
| +
| RETURN result; +
| END; +
|
Description |
哪个调用SQL函数foo()
:
Schema | public
Name | foo
Result data type | text
Argument data types |
Type | normal
Volatility | immutable
Parallel | unsafe
Owner | aerust
Security | invoker
Access privileges |
Language | sql
Source code | SELECT 'foo ' || bar()
Description |
在数据库连接中第一次调用函数baz(1)
时,我看到作为计划的一部分记录的每个嵌套语句:
2019-03-19 15:25:05.765 PDT [37616] LOG: statement: select baz(1);
2019-03-19 15:25:05.768 PDT [37616] LOG: duration: 0.002 ms plan:
Query Text: SELECT 'bar'
Result (cost=0.00..0.01 rows=1 width=32)
2019-03-19 15:25:05.768 PDT [37616] CONTEXT: SQL function "bar" statement 1
SQL function "foo" during startup
SQL statement "SELECT result || ' ' || foo()"
PL/pgSQL function foo(integer) line 14 at assignment
2019-03-19 15:25:05.768 PDT [37616] LOG: duration: 0.001 ms plan:
Query Text: SELECT 'foo ' || bar()
Result (cost=0.00..0.01 rows=1 width=32)
2019-03-19 15:25:05.768 PDT [37616] CONTEXT: SQL function "foo" statement 1
SQL statement "SELECT result || ' ' || foo()"
PL/pgSQL function foo(integer) line 14 at assignment
2019-03-19 15:25:05.768 PDT [37616] LOG: duration: 0.952 ms plan:
Query Text: select baz(1);
Result (cost=0.00..0.26 rows=1 width=32)
但是,当我在同一个连接上再次调用该函数时,我没有在日志中看到嵌套语句:
2019-03-19 15:29:06.608 PDT [37616] LOG: statement: select baz(1);
2019-03-19 15:29:06.608 PDT [37616] LOG: duration: 0.046 ms plan:
Query Text: select baz(1);
Result (cost=0.00..0.26 rows=1 width=32)
为什么是这样?如何在同一数据库连接期间在函数的后续调用中记录嵌套语句?
您可以这样做以便每次都记录语句:
ALTER FUNCTION foo() STABLE;
但那时你的表现会受到一点影响。
解开这个谜团:
IMMUTABLE
表达式。仅在第一次记录的语句是仅在解析baz
中的SQL语句时评估的语句。