本节介绍Sort模块排序功能的技术实现。
关键数据结构 TupleTableSlot
TupleTableSlot是元组在执行器节点之间传递的通用封装。为了能够统一的表示各种形式的元组,
执行器定义了数据结构TupleTableSlot和相关的处理函数TupleTableSlotOps,以便在执行过程中
按照需要使用相应形式的元组进行处理,并支持各种形式之间的转换。


TupSortStatus 描述当前排序所处的阶段

关键数据结构Tuplesortstate 描述元组排序过程中的每个阶段的状态

以nodeSort计划节点为例,典型的排序流程:

Sort模块支持3种排序算法:快速排序,堆排序,外部排序,3种算法的流程为



外部排序的关键函数有两个
- dumptuples
- mergeruns
下面举个例子说一下这两个函数的流程
测试用例
set work_mem=64;
set max_parallel_workers_per_gather = 0;
create table t1(a int);
insert into t1 select generate_series(1,1000000);
insert into t1 select generate_series(1,1008);
test=# explain analyze select * from t1 order by a;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Sort (cost=168959.65..171462.17 rows=1001008 width=4) (actual time=1612.207..1890.516 rows=1001008 loops=1)
Sort Key: a
Sort Method: external merge Disk: 13744kB
-> Seq Scan on t1 (cost=0.00..14440.08 rows=1001008 width=4) (actual time=0.031..193.254 rows=1001008 loops=1)
Planning Time: 0.069 ms
Execution Time: 1951.633 ms
(6 rows)
dumptuples

mergeruns

最后再说一下Tuplestore模块使用方法,功能是在SQL或函数执行过程中缓存元组,
以函数pg_stat_get_activity为例





