解释 - 只插入一行
Explain - inserts only one row
我正在尝试手动保存优化器计划以供进一步分析,如下所示:
do $$
declare
tmp text;
begin
explain
select * from public.some_table where 1=2 into tmp;
insert into public.plans(plan) values (tmp);
end; $$
但是当我稍后 select 它时,我看到它只保存了解释语句的第一行:
Result (cost=0.00..82.97 rows=1 width=114)
如何保存整个计划?
因为 explain
不能像SELECT
这有点棘手,为此你需要动态 SQL。
以下对我有用:
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;
$$
在字符串中解释语句会使事情变得有点复杂。
如果我经常需要它,我可能会创建一个函数来执行此操作:
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;
然后你可以这样做:
insert into plans
select *
from explain('select ...');
我正在尝试手动保存优化器计划以供进一步分析,如下所示:
do $$
declare
tmp text;
begin
explain
select * from public.some_table where 1=2 into tmp;
insert into public.plans(plan) values (tmp);
end; $$
但是当我稍后 select 它时,我看到它只保存了解释语句的第一行:
Result (cost=0.00..82.97 rows=1 width=114)
如何保存整个计划?
因为 explain
不能像SELECT
这有点棘手,为此你需要动态 SQL。
以下对我有用:
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;
$$
在字符串中解释语句会使事情变得有点复杂。
如果我经常需要它,我可能会创建一个函数来执行此操作:
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;
然后你可以这样做:
insert into plans
select *
from explain('select ...');