加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 将EXPLAIN结果放入表中?

发布时间:2020-12-13 15:53:56 所属栏目:百科 来源:网络整理
导读:我从 Postgres 8.1 docs看到EXPLAIN生成了类似于表格数据: Prior to PostgreSQL 7.3,the plan was emitted in the form of a NOTICE message. Now it appears as a query result (formatted like a table with a single text column). 我正在使用9.0,为此,d
我从 Postgres 8.1 docs看到EXPLAIN生成了类似于表格数据:

Prior to PostgreSQL 7.3,the plan was emitted in the form of a NOTICE
message. Now it appears as a query result (formatted like a table with
a single text column).

我正在使用9.0,为此,docs说,输出可以是各种类型,包括TEXT和XML.我真正想做的是将输出视为标准查询结果,以便为查询或一组查询生成简单的报告,例如,

SELECT maxcost FROM (
    EXPLAIN VERBOSE 
    SELECT COUNT(*) 
      FROM Mytable
     WHERE value>17);

上面的内容不能用于我尝试过的任何形式,并且我编写了属性maxcost来演示抽取特定数据位(在这种情况下,查询的最大估计成本)是多么简洁.我能做些什么会让我成为那里的一部分吗?我宁愿能够在一个简单的SQL控制台中工作.

解决方法

到目前为止还没有其他答案,所以这是我自己的努力.

可以将解释结果读入plpgsql中的变量,并且由于输出可以是XML,因此可以将EXPLAIN包装在存储函数中,以使用xpath产生顶级成本:

CREATE OR REPLACE FUNCTION estimate_cost(IN query text,OUT startup numeric,OUT totalcost numeric,OUT planrows numeric,OUT planwidth numeric)
AS
$BODY$
DECLARE
    query_explain  text;
    explanation       xml;
    nsarray text[][];
BEGIN
nsarray := ARRAY[ARRAY['x','http://www.postgresql.org/2009/explain']];
query_explain :=e'EXPLAIN(FORMAT XML) ' || query;
EXECUTE query_explain INTO explanation;
startup := (xpath('/x:explain/x:Query/x:Plan/x:Startup-Cost/text()',explanation,nsarray))[1];
totalcost := (xpath('/x:explain/x:Query/x:Plan/x:Total-Cost/text()',nsarray))[1];
planrows := (xpath('/x:explain/x:Query/x:Plan/x:Plan-Rows/text()',nsarray))[1];
planwidth := (xpath('/x:explain/x:Query/x:Plan/x:Plan-Width/text()',nsarray))[1];
RETURN;
END;
$BODY$
LANGUAGE plpgsql;

因此,问题的例子变成:

SELECT totalcost
FROM estimate_cost('SELECT COUNT(*) 
      FROM Mytable
     WHERE value>17');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读