暂无图片
Postgresql、Opengauss查看绑定变量的执行计划、plan_cache_mode参数
最近更新:2023-02-23 12:29:55

适用范围

Postgresql、Opengauss

背景概述

Postgresql、Opengauss查看执行计划需要使用explain方式查看,类似explain SQL1语句方式,但是如果SQL1语句有绑定变量则该explain方式展示执行计划需要修改绑定变量为具体值,才可以使用explain SQL1的方式查看执行计划。

postgres=# explain select * from t_pg_class where relname=$1;
ERROR:  there is no parameter $1
LINE 1: explain select * from t_pg_class where relname=$1;

Postgresql、Opengauss推出plan_cache_mode参数设置:

  • 1、plan_cache_mode参数force_generic_plan,强制设置该值为绑定变量的方式去,配合传入任意值来查看类似绑定变量执行计划.
  • 2、plan_cache_mode参数设置也直接关系优化器解析执行计划的选择,对于plan_cache_mode设置默认为auto模式下,优化器需要对于相同SQL硬解析五次之后就会生成一个类似Oracle绑定变量窥视的执行计划,用于后续类似SQL去重用这个SQL的执行计划。

解决方案

一、Opengauss 2.0.1查看执行计划

先构建一张测试表:
create table test (id int , info text, crt_time timestamp);  
insert into test select generate_series(1,1000000);  
insert into test select 1 from generate_series(1,10000000);  
create index idx_test on test(id);

显然该表查询id=1会走全表扫描(大部分记录id都为1),而id为其他值可以走索引扫描。

1.plan_cache_mode=auto,即默认情况下:

[omm@opengauss-slave ~]$ gsql  -p 26000 -d postgres
gsql ((openGauss 2.0.1 build d97c0e8a) compiled at 2021-06-02 19:37:16 commit 0 last mr  )
Non-SSL connection (SSL connection is recommended when requiring high-security)
Type "help" for help.

postgres=# set plan_cache_mode=auto;
SET
postgres=# prepare plan1 as select * from test where id = ($1);
PREPARE
postgres=# explain execute plan1(1);
                           QUERY PLAN                            
-----------------------------------------------------------------
......