create or replace function get_explain_as_json(text, out json) language plpgsql as $$
begin
execute 'explain (analyse, verbose, format json) ' || $1 into $2;
return;
end $$;
select
j,
j->0->>'Planning Time' as plan_time,
j->0->>'Execution Time' as exec_time,
j->0->'Plan'->>'Actual Rows' as total_rows
-- And so on...
from get_explain_as_json('select 1 where 2 = 3') as j;
┌──────────────────────────────────────┬──────────── ┬────────────┬────────────┐
│ j │ plan_time │ exec_time │ total_rows │
╞═════════════════════════════════════╪═══════════ ╪═══════════╪════════════╡
│ [ ↵│ 0.042 │ 0.026 │ 0 │
│ { ↵│ │ │ │
│ “计划”:{ ↵│ │ │ │
│ “节点类型”:“结果”,↵│ │ │ │
│ “平行感知”:假,↵│ │ │ │
│ “启动成本”:0.00, ↵│ │ │ │
│ “总成本”:0.01, ↵│ │ │ │
│ “计划行”:1,↵│ │ │ │
│ “平面宽度”:4,↵│ │ │ │
│“实际启动时间”:0.002,↵│ │ │ │
│“实际总时间”:0.002,↵│ │ │ │
│ “实际行数”:0, ↵│ │ │ │
│ “实际循环”:1,↵│ │ │ │
│ "输出": ["1"], ↵│ │ │ │
│ "一次性过滤器": "false" ↵│ │ │ │
│ }, ↵│ │ │ │
│ “计划时间”:0.042,↵│ │ │ │
│ “触发器”:[ ↵│ │ │ │
│ ], ↵│ │ │ │
│ “执行时间”:0.026 ↵│ │ │ │
│ } ↵│ │ │ │
│ ] │ │ │ │
└──────────────────────────────────────┴──────────── ┴────────────┴────────────┘
链接:
EXPLAIN
JSON operators
更新
要获得一组查询的计划集,几种可能的解决方案之一:
with queries(q) as (values(array[
$$
select 1 where 2 = 3
$$,
$$
select 2 where 4 = 4
$$
]::text[]))
select ... from queries, unnest(q) as q, get_explain_as_json(q) as j;
或者将其包装到函数中:
create or replace function get_explain_as_json(text[]) returns setof json language plpgsql as $$
declare
q text;
j json;
begin
for q in select unnest($1) loop
execute 'explain (analyse, verbose, format json) ' || q into j;
return next j;
end loop;
return;
end $$;
with queries(q) as (values(array[
$$
select 1 where 2 = 3
$$,
$$
select 2 where 4 = 4
$$
]::text[]))
select ... from queries, get_explain_as_json(q) as j;
或者使用variadic参数(和之前差不多):
create or replace function get_explain_as_json(variadic text[]) returns setof json language plpgsql as $$
declare
q text;
j json;
begin
for q in select unnest($1) loop
execute 'explain (analyse, verbose, format json) ' || q into j;
return next j;
end loop;
return;
end $$;
select ...
from get_explain_as_json($$select 1 where 2 = 3$$, $$select 2 where 4 = 4$$) as j;