PostgreSQL 原始碼解讀(51)- 查詢語句#36(Optimizer Review#2)
這一小節是Review PG的Optimizer機制的第二篇,同樣的,PG的Optimizer機制在原始碼中的README檔案(src/backend/optimizer/README)有相關說明,這一小節介紹了最佳化函式的全流程和相關的資料結構等。
一、Optimizer Functions
Optimizer Functions-查詢最佳化函式
The primary entry point is planner().
planner() //主入口
set up for recursive handling of subqueries
-subquery_planner()//planner->subquery_planner
pull up sublinks and subqueries from rangetable, if possible
canonicalize qual
Attempt to simplify WHERE clause to the most useful form; this includes
flattening nested AND/ORs and detecting clauses that are duplicated in
different branches of an OR.
simplify constant expressions
process sublinks
convert Vars of outer query levels into Params
--grouping_planner()//planner->subquery_planner->grouping_planner
preprocess target list for non-SELECT queries
handle UNION/INTERSECT/EXCEPT, GROUP BY, HAVING, aggregates,
ORDER BY, DISTINCT, LIMIT
---query_planner()//subquery_planner->grouping_planner->query_planner
make list of base relations used in query
split up the qual into restrictions (a=1) and joins (b=c)
find qual clauses that enable merge and hash joins
----make_one_rel()//...grouping_planner->query_planner->make_one_rel
set_base_rel_pathlists() //為每一個RelOptInfo生成訪問路徑
find seqscan and all index paths for each base relation
find selectivity of columns used in joins
make_rel_from_joinlist() //使用遺傳演算法或動態規劃演算法構造連線路徑
hand off join subproblems to a plugin, GEQO, or standard_join_search()
-----standard_join_search()//這是動態規劃演算法
call join_search_one_level() for each level of join tree needed
join_search_one_level():
For each joinrel of the prior level, do make_rels_by_clause_joins()
if it has join clauses, or make_rels_by_clauseless_joins() if not.
Also generate "bushy plan" joins between joinrels of lower levels.
Back at standard_join_search(), generate gather paths if needed for
each newly constructed joinrel, then apply set_cheapest() to extract
the cheapest path for it.
Loop back if this wasn't the top join level.
Back at grouping_planner:
do grouping (GROUP BY) and aggregation//在最高層處理分組/聚集/唯一過濾/排序/控制輸出元組數目等
do window functions
make unique (DISTINCT)
do sorting (ORDER BY)
do limit (LIMIT/OFFSET)
Back at planner():
convert finished Path tree into a Plan tree
do final cleanup after planning
二、Optimizer Data Structures
Optimizer Data Structures
資料結構
PlannerGlobal - global information for a single planner invocation
PlannerInfo - information for planning a particular Query (we make
a separate PlannerInfo node for each sub-Query)
RelOptInfo - a relation or joined relations
RestrictInfo - WHERE clauses, like "x = 3" or "y = z"
(note the same structure is used for restriction and
join clauses)
Path - every way to generate a RelOptInfo(sequential,index,joins)
SeqScan - represents a sequential scan plan //順序掃描
IndexPath - index scan //索引掃描
BitmapHeapPath - top of a bitmapped index scan //點陣圖索引掃描
TidPath - scan by CTID //CTID掃描
SubqueryScanPath - scan a subquery-in-FROM //FROM子句中的子查詢掃描
ForeignPath - scan a foreign table, foreign join or foreign upper-relation //FDW
CustomPath - for custom scan providers //定製化掃描
AppendPath - append multiple subpaths together //多個子路徑APPEND,常見於集合操作
MergeAppendPath - merge multiple subpaths, preserving their common sort order //保持順序的APPEND
ResultPath - a childless Result plan node (used for FROM-less SELECT)//結果路徑(如SELECT 2+2)
MaterialPath - a Material plan node //物化路徑
UniquePath - remove duplicate rows (either by hashing or sorting) //去除重複行路徑
GatherPath - collect the results of parallel workers //並行
GatherMergePath - collect parallel results, preserving their common sort order //並行,保持順序
ProjectionPath - a Result plan node with child (used for projection) //投影
ProjectSetPath - a ProjectSet plan node applied to some sub-path //投影(應用於子路徑上)
SortPath - a Sort plan node applied to some sub-path //排序
GroupPath - a Group plan node applied to some sub-path //分組
UpperUniquePath - a Unique plan node applied to some sub-path //應用於子路徑的Unique Plan
AggPath - an Agg plan node applied to some sub-path //應用於子路徑的聚集
GroupingSetsPath - an Agg plan node used to implement GROUPING SETS //分組集合
MinMaxAggPath - a Result plan node with subplans performing MIN/MAX //最大最小
WindowAggPath - a WindowAgg plan node applied to some sub-path //應用於子路徑的視窗函式
SetOpPath - a SetOp plan node applied to some sub-path //應用於子路徑的集合操作
RecursiveUnionPath - a RecursiveUnion plan node applied to two sub-paths //遞迴UNION
LockRowsPath - a LockRows plan node applied to some sub-path //應用於子路徑的的LockRows
ModifyTablePath - a ModifyTable plan node applied to some sub-path(s) //應用於子路徑的資料表更新(如INSERT/UPDATE操作等)
LimitPath - a Limit plan node applied to some sub-path//應用於子路徑的LIMIT
NestPath - nested-loop joins//巢狀迴圈連線
MergePath - merge joins//Merge Join
HashPath - hash joins//Hash Join
EquivalenceClass - a data structure representing a set of values known equal
PathKey - a data structure representing the sort ordering of a path
The optimizer spends a good deal of its time worrying about the ordering
of the tuples returned by a path. The reason this is useful is that by
knowing the sort ordering of a path, we may be able to use that path as
the left or right input of a mergejoin and avoid an explicit sort step.
Nestloops and hash joins don't really care what the order of their inputs
is, but mergejoin needs suitably ordered inputs. Therefore, all paths
generated during the optimization process are marked with their sort order
(to the extent that it is known) for possible use by a higher-level merge.
最佳化器在元組的排序上面花費了不少時間,原因是為了在Merge Join時避免專門的排序步驟.
It is also possible to avoid an explicit sort step to implement a user's
ORDER BY clause if the final path has the right ordering already, so the
sort ordering is of interest even at the top level. grouping_planner() will
look for the cheapest path with a sort order matching the desired order,
then compare its cost to the cost of using the cheapest-overall path and
doing an explicit sort on that.
When we are generating paths for a particular RelOptInfo, we discard a path
if it is more expensive than another known path that has the same or better
sort order. We will never discard a path that is the only known way to
achieve a given sort order (without an explicit sort, that is). In this
way, the next level up will have the maximum freedom to build mergejoins
without sorting, since it can pick from any of the paths retained for its
inputs.
以上解釋了最佳化器為什麼要返回一個未排序和排好序的兩個路徑給上層的原因.排好序的路徑可以直接用於Merge Join或者排序.
三、參考資料
README
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/6906/viewspace-2374860/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- PostgreSQL 原始碼解讀(50)- 查詢語句#35(Optimizer Review#1)SQL原始碼View
- PostgreSQL 原始碼解讀(36)- 查詢語句#21(查詢優化-消除外連線)SQL原始碼優化
- PostgreSQL 原始碼解讀(24)- 查詢語句#9(查詢重寫)SQL原始碼
- PostgreSQL 原始碼解讀(66)- 查詢語句#51(make_one_rel函式#16-...SQL原始碼函式
- PostgreSQL 原始碼解讀(20)- 查詢語句#5(查詢樹Query詳解)SQL原始碼
- PostgreSQL 原始碼解讀(18)- 查詢語句#3(SQL Parse)SQL原始碼
- PostgreSQL 原始碼解讀(19)- 查詢語句#4(ParseTree詳解)SQL原始碼
- PostgreSQL 原始碼解讀(17)- 查詢語句#2(查詢優化基礎)SQL原始碼優化
- PostgreSQL 原始碼解讀(25)- 查詢語句#10(查詢優化概覽)SQL原始碼優化
- PostgreSQL 原始碼解讀(83)- 查詢語句#68(PortalStart函式)SQL原始碼函式
- PostgreSQL 原始碼解讀(75)- 查詢語句#60(Review - standard_...SQL原始碼View
- PostgreSQL 原始碼解讀(74)- 查詢語句#59(Review - subquery_...SQL原始碼View
- PostgreSQL 原始碼解讀(42)- 查詢語句#27(等價類)SQL原始碼
- PostgreSQL 原始碼解讀(29)- 查詢語句#14(查詢優化-上拉子查詢)SQL原始碼優化
- PostgreSQL 原始碼解讀(37)- 查詢語句#22(查詢優化-grouping_plan...SQL原始碼優化
- PostgreSQL 原始碼解讀(82)- 查詢語句#67(PortalXXX系列函式)SQL原始碼函式
- PostgreSQL 原始碼解讀(81)- 查詢語句#66(Review - exec_simp...SQL原始碼View
- PostgreSQL 原始碼解讀(89)- 查詢語句#74(SeqNext函式#2)SQL原始碼函式
- PostgreSQL 原始碼解讀(90)- 查詢語句#75(ExecHashJoin函式#1)SQL原始碼函式
- PostgreSQL 原始碼解讀(91)- 查詢語句#76(ExecHashJoin函式#2)SQL原始碼函式
- PostgreSQL 原始碼解讀(88)- 查詢語句#73(SeqNext函式#1)SQL原始碼函式
- PostgreSQL 原始碼解讀(87)- 查詢語句#72(PortalRunSelect->E...SQL原始碼
- PostgreSQL 原始碼解讀(84)- 查詢語句#69(PortalStart->InitP...SQL原始碼
- PostgreSQL 原始碼解讀(85)- 查詢語句#70(PortalRun->InitPla...SQL原始碼
- PostgreSQL 原始碼解讀(86)- 查詢語句#71(PortalRun->PortalR...SQL原始碼
- PostgreSQL 原始碼解讀(93)- 查詢語句#77(ExecHashJoin函式#3)SQL原始碼函式
- PostgreSQL 原始碼解讀(21)- 查詢語句#6(PlannedStmt詳解-跟蹤分析)SQL原始碼
- PostgreSQL 原始碼解讀(73)- 查詢語句#58(grouping_planner函式...SQL原始碼函式
- PostgreSQL 原始碼解讀(23)- 查詢語句#8(PlannedStmt與QUERY P...SQL原始碼
- PostgreSQL 原始碼解讀(95)- 查詢語句#78(ExecHashJoin函式#4-H...SQL原始碼函式
- PostgreSQL 原始碼解讀(97)- 查詢語句#79(ExecHashJoin函式#5-H...SQL原始碼函式
- PostgreSQL 原始碼解讀(16)- 查詢語句#1(基礎:關係代數)SQL原始碼
- PostgreSQL 原始碼解讀(43)- 查詢語句#28(query_planner函式#5)SQL原始碼函式
- PostgreSQL 原始碼解讀(45)- 查詢語句#30(query_planner函式#6)SQL原始碼函式
- PostgreSQL 原始碼解讀(46)- 查詢語句#31(query_planner函式#7)SQL原始碼函式
- PostgreSQL 原始碼解讀(47)- 查詢語句#32(query_planner函式#8)SQL原始碼函式
- PostgreSQL 原始碼解讀(48)- 查詢語句#33(query_planner函式#9)SQL原始碼函式
- PostgreSQL 原始碼解讀(38)- 查詢語句#23(query_planner函式#1)SQL原始碼函式