[英]Explain - inserts only one row
I'm trying to manually save optimizer plan for further analysis, like this: 我正在尝试手动保存优化程序计划以进行进一步分析,如下所示:
do $$
declare
tmp text;
begin
explain
select * from public.some_table where 1=2 into tmp;
insert into public.plans(plan) values (tmp);
end; $$
But when I select it later, I see it only saved first row from the explain statement: 但是当我稍后选择它时,我看到它只从explain语句中保存了第一行:
Result (cost=0.00..82.97 rows=1 width=114)
How can I make it to save the whole plan? 如何保存整个计划呢?
Because explain
cannot be used like eg a SELECT
this is a bit tricky and you need dynamic SQL for this. 因为
explain
不能像SELECT
一样使用,这有点棘手,你需要动态SQL。
The following worked for me: 以下对我有用:
do
$$
declare
plan_line record;
begin
for plan_line in execute 'explain select * from public.some_table where 1=2' loop
insert into plans values (plan_line."QUERY PLAN");
end loop;
end;
$$
Having the statement to be explained in a string makes things a bit more complicated. 将语句解释为字符串会使事情变得复杂一些。
If I needed that on a regular basis, I would probably create a function that does this: 如果我经常需要它,我可能会创建一个执行此操作的函数:
create or replace function explain(to_explain text)
returns setof text
as
$$
declare
plan_line record;
begin
for plan_line in execute 'explain '||to_explain loop
return next plan_line."QUERY PLAN";
end loop;
end;
$$
language plpgsql;
Then you can do something like: 然后你可以这样做:
insert into plans
select *
from explain('select ...');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.