PostgreSQL 原始碼解讀(84)- 查詢語句#69(PortalStart->InitP...

husthxd發表於2018-11-13

本節介紹了PortalStart->ExecutorStart(standard_ExecutorStart)->InitPlan函式的實現邏輯,該函式用於初始化查詢執行計劃。

一、資料結構

EState
執行器在呼叫時的主要工作狀態


/* ----------------
 *    EState information
 *    EState資訊
 * Master working state for an Executor invocation
 * 執行器在呼叫時的主要工作狀態
 * ----------------
 */
typedef struct EState
{
    NodeTag     type;//標記

    /* Basic state for all query types: */
    //所有查詢型別的基礎狀態
    ScanDirection es_direction; /* 掃描方向,如向前/後等;current scan direction */
    Snapshot    es_snapshot;    /* 時間條件(透過快照實現);time qual to use */
    Snapshot    es_crosscheck_snapshot; /* RI的交叉檢查時間條件;crosscheck time qual for RI */
    List       *es_range_table; /* RTE連結串列;List of RangeTblEntry */
    struct RangeTblEntry **es_range_table_array;    /* 與連結串列等價的陣列;equivalent array */
    Index       es_range_table_size;    /* 陣列大小;size of the range table arrays */
    Relation   *es_relations;   /* RTE中的Relation指標,如未Open則為NULL;
                                 * Array of per-range-table-entry Relation
                                 * pointers, or NULL if not yet opened */
    struct ExecRowMark **es_rowmarks;   /* ExecRowMarks指標陣列;
                                         * Array of per-range-table-entry
                                         * ExecRowMarks, or NULL if none */
    PlannedStmt *es_plannedstmt;    /* 計劃樹的最頂層PlannedStmt;link to top of plan tree */
    const char *es_sourceText;  /* QueryDesc中的源文字;Source text from QueryDesc */

    JunkFilter *es_junkFilter;  /* 最頂層的JunkFilter;top-level junk filter, if any */

    /* If query can insert/delete tuples, the command ID to mark them with */
    //如查詢可以插入/刪除元組,這裡記錄了命令ID
    CommandId   es_output_cid;

    /* Info about target table(s) for insert/update/delete queries: */
    //insert/update/delete 目標表資訊
    ResultRelInfo *es_result_relations; /* ResultRelInfos陣列;array of ResultRelInfos */
    int         es_num_result_relations;    /* 陣列大小;length of array */
    ResultRelInfo *es_result_relation_info; /* 當前活動的陣列;currently active array elt */

    /*
     * Info about the partition root table(s) for insert/update/delete queries
     * targeting partitioned tables.  Only leaf partitions are mentioned in
     * es_result_relations, but we need access to the roots for firing
     * triggers and for runtime tuple routing.
     * 關於針對分割槽表的插入/更新/刪除查詢的分割槽根表的資訊。
     * 在es_result_relations中只提到了葉子分割槽,但是需要訪問根表來觸發觸發器和執行時元組路由。
     */
    ResultRelInfo *es_root_result_relations;    /* ResultRelInfos陣列;array of ResultRelInfos */
    int         es_num_root_result_relations;   /* 陣列大小;length of the array */

    /*
     * The following list contains ResultRelInfos created by the tuple routing
     * code for partitions that don't already have one.
     * 下面的連結串列包含元組路由程式碼為沒有分割槽的分割槽建立的ResultRelInfos。
     */
    List       *es_tuple_routing_result_relations;

    /* Stuff used for firing triggers: */
    //用於觸發觸發器的資訊
    List       *es_trig_target_relations;   /* 與觸發器相關的ResultRelInfos陣列;trigger-only ResultRelInfos */
    TupleTableSlot *es_trig_tuple_slot; /* 用於觸發器輸出的元組; for trigger output tuples */
    TupleTableSlot *es_trig_oldtup_slot;    /* 用於TriggerEnabled;for TriggerEnabled */
    TupleTableSlot *es_trig_newtup_slot;    /* 用於TriggerEnabled;for TriggerEnabled */

    /* Parameter info: */
    //引數資訊
    ParamListInfo es_param_list_info;   /* 外部引數值; values of external params */
    ParamExecData *es_param_exec_vals;  /* 內部引數值; values of internal params */

    QueryEnvironment *es_queryEnv;  /* 查詢環境; query environment */

    /* Other working state: */
    //其他工作狀態
    MemoryContext es_query_cxt; /* EState所在的記憶體上下文;per-query context in which EState lives */

    List       *es_tupleTable;  /* TupleTableSlots連結串列;List of TupleTableSlots */

    uint64      es_processed;   /* 處理的元組數;# of tuples processed */
    Oid         es_lastoid;     /* 最後處理的oid(用於INSERT命令);last oid processed (by INSERT) */

    int         es_top_eflags;  /* 傳遞給ExecutorStart函式的eflags引數;eflags passed to ExecutorStart */
    int         es_instrument;  /* InstrumentOption標記;OR of InstrumentOption flags */
    bool        es_finished;    /* ExecutorFinish函式已完成則為T;true when ExecutorFinish is done */

    List       *es_exprcontexts;    /* EState中的ExprContexts連結串列;List of ExprContexts within EState */

    List       *es_subplanstates;   /* SubPlans的PlanState連結串列;List of PlanState for SubPlans */

    List       *es_auxmodifytables; /* 第二個ModifyTableStates連結串列;List of secondary ModifyTableStates */

    /*
     * this ExprContext is for per-output-tuple operations, such as constraint
     * checks and index-value computations.  It will be reset for each output
     * tuple.  Note that it will be created only if needed.
     * 這個ExprContext用於元組輸出操作,例如約束檢查和索引值計算。它在每個輸出元組時重置。
     * 注意,只有在需要時才會建立它。
     */
    ExprContext *es_per_tuple_exprcontext;

    /*
     * These fields are for re-evaluating plan quals when an updated tuple is
     * substituted in READ COMMITTED mode.  es_epqTuple[] contains tuples that
     * scan plan nodes should return instead of whatever they'd normally
     * return, or NULL if nothing to return; es_epqTupleSet[] is true if a
     * particular array entry is valid; and es_epqScanDone[] is state to
     * remember if the tuple has been returned already.  Arrays are of size
     * es_range_table_size and are indexed by scan node scanrelid - 1.
     * 這些欄位用於在讀取提交模式中替換更新後的元組時重新評估計劃的條件quals。
     * es_epqTuple[]陣列包含掃描計劃節點應該返回的元組,而不是它們通常返回的任何值,如果沒有返回值,則為NULL;
     * 如果特定陣列條目有效,則es_epqTupleSet[]為真;es_epqScanDone[]是狀態,用來記住元組是否已經返回。
     * 陣列大小為es_range_table_size,透過掃描節點scanrelid - 1進行索引。
     */
    HeapTuple  *es_epqTuple;    /* EPQ替換元組的陣列;array of EPQ substitute tuples */
    bool       *es_epqTupleSet; /* 如EPQ元組已提供,則為T;true if EPQ tuple is provided */
    bool       *es_epqScanDone; /* 如EPQ元組已獲取,則為T;true if EPQ tuple has been fetched */

    bool        es_use_parallel_mode;   /* 能否使用並行worker?can we use parallel workers? */

    /* The per-query shared memory area to use for parallel execution. */
    //用於並行執行的每個查詢共享記憶體區域。
    struct dsa_area *es_query_dsa;

    /*
     * JIT information. es_jit_flags indicates whether JIT should be performed
     * and with which options.  es_jit is created on-demand when JITing is
     * performed.
     * JIT的資訊。es_jit_flags指示是否應該執行JIT以及使用哪些選項。在執行JITing時,按需建立es_jit。
     *
     * es_jit_combined_instr is the the combined, on demand allocated,
     * instrumentation from all workers. The leader's instrumentation is kept
     * separate, and is combined on demand by ExplainPrintJITSummary().
     * es_jit_combined_instr是所有workers根據需要分配的組合工具。
     * leader的插裝是獨立的,根據需要由ExplainPrintJITSummary()組合。
     */
    int         es_jit_flags;
    struct JitContext *es_jit;
    struct JitInstrumentation *es_jit_worker_instr;
} EState;

PlanState
PlanState是所有PlanState-type節點的虛父類(請參照物件導向的虛類)

/* ----------------
 *      PlanState node
 *      PlanState節點
 * We never actually instantiate any PlanState nodes; this is just the common
 * abstract superclass for all PlanState-type nodes.
 * 實際上並沒有例項化PlanState節點;
 * 這是所有PlanState-type節點的虛父類(請參照物件導向的虛類).
 * ----------------
 */
typedef struct PlanState
{
    NodeTag     type;//節點型別

    Plan       *plan;           /* 繫結的計劃節點;associated Plan node */

    EState     *state;          /* 在執行期,指向top-level計劃的EState指標
                                 * at execution time, states of individual
                                 * nodes point to one EState for the whole
                                 * top-level plan */

    ExecProcNodeMtd ExecProcNode;   /* 執行返回下一個元組的函式;function to return next tuple */
    ExecProcNodeMtd ExecProcNodeReal;   /* 如果ExecProcNode是封裝器,則這個變數是實際的函式;
                                         * actual function, if above is a
                                         * wrapper */

    Instrumentation *instrument;    /* 該節點可選的執行期統計資訊;Optional runtime stats for this node */
    WorkerInstrumentation *worker_instrument;   /* 每個worker的instrumentation;per-worker instrumentation */

    /* Per-worker JIT instrumentation */
    //worker相應的JIT instrumentation
    struct SharedJitInstrumentation *worker_jit_instrument;

    /*
     * Common structural data for all Plan types.  These links to subsidiary
     * state trees parallel links in the associated plan tree (except for the
     * subPlan list, which does not exist in the plan tree).
     * 所有Plan型別均有的資料結構;
     * 這些連結到附屬狀態透過並行的方式連結到關聯的計劃樹中(除了計劃樹中不存在的子計劃連結串列)。
     */
    ExprState  *qual;           /* 布林條件;boolean qual condition */
    struct PlanState *lefttree; /* 輸入的計劃樹,包括左樹&右樹;input plan tree(s) */
    struct PlanState *righttree;

    List       *initPlan;       /* 初始的SubPlanState節點連結串列;
                                 * Init SubPlanState nodes (un-correlated expr
                                 * subselects) */
    List       *subPlan;        /* 在表示式中的subPlan連結串列;SubPlanState nodes in my expressions */

    /*
     * State for management of parameter-change-driven rescanning
     * 引數改變驅動的重新掃描管理狀態
     */
    Bitmapset  *chgParam;       /* changed Params的IDs集合(用於NestLoop連線);set of IDs of changed Params */

    /*
     * Other run-time state needed by most if not all node types.
     * 大多數(如果不是所有)節點型別都需要的其他執行時狀態。
     */
    TupleDesc ps_ResultTupleDesc;   /* 節點的返回型別;node's return type */
    TupleTableSlot *ps_ResultTupleSlot; /* 結果元組的slot;slot for my result tuples */
    ExprContext *ps_ExprContext;    /* 節點的表示式解析上下文;node's expression-evaluation context */
    ProjectionInfo *ps_ProjInfo;    /* 元組投影資訊;info for doing tuple projection */

    /*
     * Scanslot's descriptor if known. This is a bit of a hack, but otherwise
     * it's hard for expression compilation to optimize based on the
     * descriptor, without encoding knowledge about all executor nodes.
     * Scanslot描述符。
     * 這有點笨拙,但是如果不編碼關於所有執行器節點的知識,那麼表示式編譯就很難基於描述符進行最佳化。
     */
    TupleDesc   scandesc;
} PlanState;

二、原始碼解讀

InitPlan函式初始化查詢執行計劃:開啟檔案/分配儲存空間並啟動規則管理器.

/* ----------------------------------------------------------------
 *      InitPlan
 *
 *      Initializes the query plan: open files, allocate storage
 *      and start up the rule manager
 *      初始化查詢執行計劃:開啟檔案/分配儲存空間並啟動規則管理器
 * ----------------------------------------------------------------
 */
static void
InitPlan(QueryDesc *queryDesc, int eflags)
{
    CmdType     operation = queryDesc->operation;//命令型別
    PlannedStmt *plannedstmt = queryDesc->plannedstmt;//已規劃的語句指標
    Plan       *plan = plannedstmt->planTree;//計劃樹
    List       *rangeTable = plannedstmt->rtable;//RTE連結串列
    EState     *estate = queryDesc->estate;//參見資料結構
    PlanState  *planstate;//參見資料結構
    TupleDesc   tupType;//參見資料結構
    ListCell   *l;
    int         i;

    /*
     * Do permissions checks
     * 許可權檢查
     */
    ExecCheckRTPerms(rangeTable, true);

    /*
     * initialize the node's execution state
     * 初始化節點執行狀態
     */
    ExecInitRangeTable(estate, rangeTable);

    estate->es_plannedstmt = plannedstmt;

    /*
     * Initialize ResultRelInfo data structures, and open the result rels.
     * 初始化ResultRelInfo資料結構,開啟結果rels
     */
    if (plannedstmt->resultRelations)//存在resultRelations
    {
        List       *resultRelations = plannedstmt->resultRelations;//結果Relation連結串列
        int         numResultRelations = list_length(resultRelations);//連結串列大小
        ResultRelInfo *resultRelInfos;//ResultRelInfo陣列
        ResultRelInfo *resultRelInfo;//ResultRelInfo指標

        resultRelInfos = (ResultRelInfo *)
            palloc(numResultRelations * sizeof(ResultRelInfo));//分配空間
        resultRelInfo = resultRelInfos;//指標賦值
        foreach(l, resultRelations)//遍歷連結串列
        {
            Index       resultRelationIndex = lfirst_int(l);
            Relation    resultRelation;

            resultRelation = ExecGetRangeTableRelation(estate,
                                                       resultRelationIndex);//獲取結果Relation
            InitResultRelInfo(resultRelInfo,
                              resultRelation,
                              resultRelationIndex,
                              NULL,
                              estate->es_instrument);//初始化ResultRelInfo
            resultRelInfo++;//處理下一個ResultRelInfo
        }
        estate->es_result_relations = resultRelInfos;//賦值
        estate->es_num_result_relations = numResultRelations;

        /* es_result_relation_info is NULL except when within ModifyTable */
        //設定es_result_relation_info為NULL,除了ModifyTable
        estate->es_result_relation_info = NULL;

        /*
         * In the partitioned result relation case, also build ResultRelInfos
         * for all the partitioned table roots, because we will need them to
         * fire statement-level triggers, if any.
         * 在分割槽結果關係這種情況中,還為所有分割槽表根構建ResultRelInfos,
         * 因為我們需要它們觸發語句級別的觸發器(如果有的話)。
         */
        if (plannedstmt->rootResultRelations)//存在rootResultRelations(並行處理)
        {
            int         num_roots = list_length(plannedstmt->rootResultRelations);

            resultRelInfos = (ResultRelInfo *)
                palloc(num_roots * sizeof(ResultRelInfo));
            resultRelInfo = resultRelInfos;
            foreach(l, plannedstmt->rootResultRelations)
            {
                Index       resultRelIndex = lfirst_int(l);
                Relation    resultRelDesc;

                resultRelDesc = ExecGetRangeTableRelation(estate,
                                                          resultRelIndex);
                InitResultRelInfo(resultRelInfo,
                                  resultRelDesc,
                                  resultRelIndex,
                                  NULL,
                                  estate->es_instrument);
                resultRelInfo++;
            }

            estate->es_root_result_relations = resultRelInfos;
            estate->es_num_root_result_relations = num_roots;
        }
        else
        {
            estate->es_root_result_relations = NULL;
            estate->es_num_root_result_relations = 0;
        }
    }
    else//不存在resultRelations
    {
        /*
         * if no result relation, then set state appropriately
         * 無resultRelations,設定相應的資訊為NULL或為0
         */
        estate->es_result_relations = NULL;
        estate->es_num_result_relations = 0;
        estate->es_result_relation_info = NULL;
        estate->es_root_result_relations = NULL;
        estate->es_num_root_result_relations = 0;
    }

    /*
     * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
     * 下一步,利用PlanRowMark(s)建立ExecRowMark陣列
     */
    if (plannedstmt->rowMarks)//如存在rowMarks
    {
        estate->es_rowmarks = (ExecRowMark **)
            palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
        foreach(l, plannedstmt->rowMarks)
        {
            PlanRowMark *rc = (PlanRowMark *) lfirst(l);
            Oid         relid;
            Relation    relation;
            ExecRowMark *erm;

            /* ignore "parent" rowmarks; they are irrelevant at runtime */
            if (rc->isParent)
                continue;

            /* get relation's OID (will produce InvalidOid if subquery) */
            relid = exec_rt_fetch(rc->rti, estate)->relid;

            /* open relation, if we need to access it for this mark type */
            switch (rc->markType)
            {
                case ROW_MARK_EXCLUSIVE:
                case ROW_MARK_NOKEYEXCLUSIVE:
                case ROW_MARK_SHARE:
                case ROW_MARK_KEYSHARE:
                case ROW_MARK_REFERENCE:
                    relation = ExecGetRangeTableRelation(estate, rc->rti);
                    break;
                case ROW_MARK_COPY:
                    /* no physical table access is required */
                    relation = NULL;
                    break;
                default:
                    elog(ERROR, "unrecognized markType: %d", rc->markType);
                    relation = NULL;    /* keep compiler quiet */
                    break;
            }

            /* Check that relation is a legal target for marking */
            if (relation)
                CheckValidRowMarkRel(relation, rc->markType);

            erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
            erm->relation = relation;
            erm->relid = relid;
            erm->rti = rc->rti;
            erm->prti = rc->prti;
            erm->rowmarkId = rc->rowmarkId;
            erm->markType = rc->markType;
            erm->strength = rc->strength;
            erm->waitPolicy = rc->waitPolicy;
            erm->ermActive = false;
            ItemPointerSetInvalid(&(erm->curCtid));
            erm->ermExtra = NULL;

            Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
                   estate->es_rowmarks[erm->rti - 1] == NULL);

            estate->es_rowmarks[erm->rti - 1] = erm;
        }
    }

    /*
     * Initialize the executor's tuple table to empty.
     * 初始化執行器的元組表為NULL
     */
    estate->es_tupleTable = NIL;
    estate->es_trig_tuple_slot = NULL;
    estate->es_trig_oldtup_slot = NULL;
    estate->es_trig_newtup_slot = NULL;

    /* mark EvalPlanQual not active */
    //標記EvalPlanQual為非活動模式
    estate->es_epqTuple = NULL;
    estate->es_epqTupleSet = NULL;
    estate->es_epqScanDone = NULL;

    /*
     * Initialize private state information for each SubPlan.  We must do this
     * before running ExecInitNode on the main query tree, since
     * ExecInitSubPlan expects to be able to find these entries.
     * 為每個子計劃初始化私有狀態資訊。
     * 在主查詢樹上執行ExecInitNode之前,必須這樣做,因為ExecInitSubPlan希望能夠找到這些條目。
     */
    Assert(estate->es_subplanstates == NIL);
    i = 1;                      /* subplan索引計數從1開始;subplan indices count from 1 */
    foreach(l, plannedstmt->subplans)//遍歷subplans
    {
        Plan       *subplan = (Plan *) lfirst(l);
        PlanState  *subplanstate;
        int         sp_eflags;

        /*
         * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
         * it is a parameterless subplan (not initplan), we suggest that it be
         * prepared to handle REWIND efficiently; otherwise there is no need.
         * 子計劃永遠不需要執行向後掃描或標記/恢復。
         * 如果它是一個無引數的子計劃(不是initplan),建議它準備好有效地處理向後掃描;否則就沒有必要了。
         */
        sp_eflags = eflags
            & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA);//設定sp_eflags
        if (bms_is_member(i, plannedstmt->rewindPlanIDs))
            sp_eflags |= EXEC_FLAG_REWIND;

        subplanstate = ExecInitNode(subplan, estate, sp_eflags);//執行Plan節點初始化過程

        estate->es_subplanstates = lappend(estate->es_subplanstates,
                                           subplanstate);

        i++;
    }

    /*
     * Initialize the private state information for all the nodes in the query
     * tree.  This opens files, allocates storage and leaves us ready to start
     * processing tuples.
     * 為查詢樹中的所有節點初始化私有狀態資訊。
     * 這將開啟檔案、分配儲存並讓我們準備好開始處理元組。
     */
    planstate = ExecInitNode(plan, estate, eflags);//執行Plan節點初始化過程

    /*
     * Get the tuple descriptor describing the type of tuples to return.
     * 獲取元組描述(返回的元組型別等)
     */
    tupType = ExecGetResultType(planstate);

    /*
     * Initialize the junk filter if needed.  SELECT queries need a filter if
     * there are any junk attrs in the top-level tlist.
     * 如需要,初始化垃圾過濾器。如果頂層的tlist中有任何垃圾標識,SELECT查詢需要一個過濾器。
     */
    if (operation == CMD_SELECT)//SELECT命令
    {
        bool        junk_filter_needed = false;
        ListCell   *tlist;

        foreach(tlist, plan->targetlist)//遍歷tlist
        {
            TargetEntry *tle = (TargetEntry *) lfirst(tlist);

            if (tle->resjunk)//如需要垃圾過濾器
            {
                junk_filter_needed = true;//設定為T
                break;
            }
        }

        if (junk_filter_needed)
        {
            JunkFilter *j;

            j = ExecInitJunkFilter(planstate->plan->targetlist,
                                   tupType->tdhasoid,
                                   ExecInitExtraTupleSlot(estate, NULL));//初始化
            estate->es_junkFilter = j;

            /* Want to return the cleaned tuple type */
            //期望返回已清理的元組型別
            tupType = j->jf_cleanTupType;
        }
    }
    //賦值
    queryDesc->tupDesc = tupType;
    queryDesc->planstate = planstate;
}

三、跟蹤分析

測試指令碼如下

testdb=# explain select dw.*,grjf.grbh,grjf.xm,grjf.ny,grjf.je 
testdb-# from t_dwxx dw,lateral (select gr.grbh,gr.xm,jf.ny,jf.je 
testdb(#                         from t_grxx gr inner join t_jfxx jf 
testdb(#                                        on gr.dwbh = dw.dwbh 
testdb(#                                           and gr.grbh = jf.grbh) grjf
testdb-# order by dw.dwbh;
                                        QUERY PLAN                                        
------------------------------------------------------------------------------------------
 Sort  (cost=20070.93..20320.93 rows=100000 width=47)
   Sort Key: dw.dwbh
   ->  Hash Join  (cost=3754.00..8689.61 rows=100000 width=47)
         Hash Cond: ((gr.dwbh)::text = (dw.dwbh)::text)
         ->  Hash Join  (cost=3465.00..8138.00 rows=100000 width=31)
               Hash Cond: ((jf.grbh)::text = (gr.grbh)::text)
               ->  Seq Scan on t_jfxx jf  (cost=0.00..1637.00 rows=100000 width=20)
               ->  Hash  (cost=1726.00..1726.00 rows=100000 width=16)
                     ->  Seq Scan on t_grxx gr  (cost=0.00..1726.00 rows=100000 width=16)
         ->  Hash  (cost=164.00..164.00 rows=10000 width=20)
               ->  Seq Scan on t_dwxx dw  (cost=0.00..164.00 rows=10000 width=20)
(11 rows)

啟動gdb,設定斷點,進入InitPlan

(gdb) b InitPlan
Breakpoint 1 at 0x6d9df2: file execMain.c, line 808.
(gdb) c
Continuing.

Breakpoint 1, InitPlan (queryDesc=0x20838b8, eflags=16) at execMain.c:808
warning: Source file is more recent than executable.
808     CmdType     operation = queryDesc->operation;

輸入引數

(gdb) p *queryDesc
$1 = {operation = CMD_SELECT, plannedstmt = 0x207e6c0, 
  sourceText = 0x1f96eb8 "select dw.*,grjf.grbh,grjf.xm,grjf.ny,grjf.je \nfrom t_dwxx dw,lateral (select gr.grbh,gr.xm,jf.ny,jf.je \n", ' ' <repeats 24 times>, "from t_grxx gr inner join t_jfxx jf \n", ' ' <repeats 34 times>..., 
  snapshot = 0x1fba8e0, crosscheck_snapshot = 0x0, dest = 0xf8f280 <donothingDR>, params = 0x0, queryEnv = 0x0, 
  instrument_options = 0, tupDesc = 0x0, estate = 0x207f898, planstate = 0x0, already_executed = false, totaltime = 0x0}
(gdb) p eflags
$2 = 16

變數賦值,PlannedStmt的詳細資料結構先前章節已有解釋,請參見相關章節.

(gdb) n
809     PlannedStmt *plannedstmt = queryDesc->plannedstmt;
(gdb) 
810     Plan       *plan = plannedstmt->planTree;
(gdb) 
811     List       *rangeTable = plannedstmt->rtable;
(gdb) n
812     EState     *estate = queryDesc->estate;
(gdb) 
821     ExecCheckRTPerms(rangeTable, true);
(gdb) p *plannedstmt
$3 = {type = T_PlannedStmt, commandType = CMD_SELECT, queryId = 0, hasReturning = false, hasModifyingCTE = false, 
  canSetTag = true, transientPlan = false, dependsOnRole = false, parallelModeNeeded = false, jitFlags = 0, 
  planTree = 0x20788f8, rtable = 0x207c568, resultRelations = 0x0, nonleafResultRelations = 0x0, rootResultRelations = 0x0, 
  subplans = 0x0, rewindPlanIDs = 0x0, rowMarks = 0x0, relationOids = 0x207c5c8, invalItems = 0x0, paramExecTypes = 0x0, 
  utilityStmt = 0x0, stmt_location = 0, stmt_len = 313}
(gdb) p *plan
$4 = {type = T_Sort, startup_cost = 20070.931487218411, total_cost = 20320.931487218411, plan_rows = 100000, 
  plan_width = 47, parallel_aware = false, parallel_safe = true, plan_node_id = 0, targetlist = 0x207cc28, qual = 0x0, 
  lefttree = 0x207c090, righttree = 0x0, initPlan = 0x0, extParam = 0x0, allParam = 0x0}
(gdb) p *estate
$5 = {type = T_EState, es_direction = ForwardScanDirection, es_snapshot = 0x1fba8e0, es_crosscheck_snapshot = 0x0, 
  es_range_table = 0x0, es_plannedstmt = 0x0, 
  es_sourceText = 0x1f96eb8 "select dw.*,grjf.grbh,grjf.xm,grjf.ny,grjf.je \nfrom t_dwxx dw,lateral (select gr.grbh,gr.xm,jf.ny,jf.je \n", ' ' <repeats 24 times>, "from t_grxx gr inner join t_jfxx jf \n", ' ' <repeats 34 times>..., 
  es_junkFilter = 0x0, es_output_cid = 0, es_result_relations = 0x0, es_num_result_relations = 0, 
  es_result_relation_info = 0x0, es_root_result_relations = 0x0, es_num_root_result_relations = 0, 
  es_tuple_routing_result_relations = 0x0, es_trig_target_relations = 0x0, es_trig_tuple_slot = 0x0, 
  es_trig_oldtup_slot = 0x0, es_trig_newtup_slot = 0x0, es_param_list_info = 0x0, es_param_exec_vals = 0x0, 
  es_queryEnv = 0x0, es_query_cxt = 0x207f780, es_tupleTable = 0x0, es_rowMarks = 0x0, es_processed = 0, es_lastoid = 0, 
  es_top_eflags = 16, es_instrument = 0, es_finished = false, es_exprcontexts = 0x0, es_subplanstates = 0x0, 
  es_auxmodifytables = 0x0, es_per_tuple_exprcontext = 0x0, es_epqTuple = 0x0, es_epqTupleSet = 0x0, es_epqScanDone = 0x0, 
  es_use_parallel_mode = false, es_query_dsa = 0x0, es_jit_flags = 0, es_jit = 0x0, es_jit_worker_instr = 0x0}

RTE連結串列,一共有5個Item,3個基礎關係RTE_RELATION(1/3/4),1個RTE_SUBQUERY(2號),1個RTE_JOIN(5號)

(gdb) n
826     estate->es_range_table = rangeTable;
(gdb) p *rangeTable
$6 = {type = T_List, length = 5, head = 0x207c540, tail = 0x207cb28}
(gdb) p *(RangeTblEntry *)rangeTable->head->data.ptr_value
$9 = {type = T_RangeTblEntry, rtekind = RTE_RELATION, relid = 16734, relkind = 114 'r', tablesample = 0x0, subquery = 0x0, 
  security_barrier = false, jointype = JOIN_INNER, joinaliasvars = 0x0, functions = 0x0, funcordinality = false, 
  tablefunc = 0x0, values_lists = 0x0, ctename = 0x0, ctelevelsup = 0, self_reference = false, coltypes = 0x0, 
  coltypmods = 0x0, colcollations = 0x0, enrname = 0x0, enrtuples = 0, alias = 0x1f98448, eref = 0x1fbdd20, 
  lateral = false, inh = false, inFromCl = true, requiredPerms = 2, checkAsUser = 0, selectedCols = 0x2054de8, 
  insertedCols = 0x0, updatedCols = 0x0, securityQuals = 0x0}
...

沒有結果Relation,執行相應的處理邏輯

(gdb) 
835     if (plannedstmt->resultRelations)
(gdb) p plannedstmt->resultRelations
$14 = (List *) 0x0
(gdb) n
922         estate->es_result_relations = NULL;
(gdb) 
923         estate->es_num_result_relations = 0;
(gdb) 
924         estate->es_result_relation_info = NULL;
(gdb) 
925         estate->es_root_result_relations = NULL;
(gdb) 
926         estate->es_num_root_result_relations = 0;

不存在rowMarks(for update)

(gdb) n
939     foreach(l, plannedstmt->rowMarks)
(gdb) p plannedstmt->rowMarks
$15 = (List *) 0x0
(gdb) p plannedstmt->rowMarks
$16 = (List *) 0x0
(gdb) n
1000        estate->es_tupleTable = NIL;

執行賦值

(gdb) n
1001        estate->es_trig_tuple_slot = NULL;
(gdb) 
1002        estate->es_trig_oldtup_slot = NULL;
...

沒有subplans

(gdb) n
1017        foreach(l, plannedstmt->subplans)
(gdb) p *plannedstmt->subplans
Cannot access memory at address 0x0
(gdb) n

初始化節點(執行ExecInitNode)和獲取TupleType

(gdb) n
1046        planstate = ExecInitNode(plan, estate, eflags);
(gdb) n
1051        tupType = ExecGetResultType(planstate);
(gdb) 
1057        if (operation == CMD_SELECT)
(gdb) p *planstate
$17 = {type = T_SortState, plan = 0x20788f8, state = 0x207f898, ExecProcNode = 0x6e41bb <ExecProcNodeFirst>, 
  ExecProcNodeReal = 0x716144 <ExecSort>, instrument = 0x0, worker_instrument = 0x0, worker_jit_instrument = 0x0, 
  qual = 0x0, lefttree = 0x207fbc8, righttree = 0x0, initPlan = 0x0, subPlan = 0x0, chgParam = 0x0, 
  ps_ResultTupleSlot = 0x2090dc0, ps_ExprContext = 0x0, ps_ProjInfo = 0x0, scandesc = 0x208e920}
(gdb) p tupType
$18 = (TupleDesc) 0x20909a8
(gdb) p *tupType
$19 = {natts = 7, tdtypeid = 2249, tdtypmod = -1, tdhasoid = false, tdrefcount = -1, constr = 0x0, attrs = 0x20909c8}

判斷是否需要垃圾過濾器

(gdb) n
1059            bool        junk_filter_needed = false;
(gdb) 
1062            foreach(tlist, plan->targetlist)

不需要junk filter

(gdb) 
1073            if (junk_filter_needed)

賦值,結束呼叫

(gdb) 
1087        queryDesc->tupDesc = tupType;
(gdb) 
1088        queryDesc->planstate = planstate;
(gdb) 
1089    }
(gdb) 
standard_ExecutorStart (queryDesc=0x20838b8, eflags=16) at execMain.c:267
267     MemoryContextSwitchTo(oldcontext);
(gdb) p *queryDesc
$21 = {operation = CMD_SELECT, plannedstmt = 0x207e6c0, 
  sourceText = 0x1f96eb8 "select dw.*,grjf.grbh,grjf.xm,grjf.ny,grjf.je \nfrom t_dwxx dw,lateral (select gr.grbh,gr.xm,jf.ny,jf.je \n", ' ' <repeats 24 times>, "from t_grxx gr inner join t_jfxx jf \n", ' ' <repeats 34 times>..., 
  snapshot = 0x1fba8e0, crosscheck_snapshot = 0x0, dest = 0xf8f280 <donothingDR>, params = 0x0, queryEnv = 0x0, 
  instrument_options = 0, tupDesc = 0x20909a8, estate = 0x207f898, planstate = 0x207fab0, already_executed = false, 
  totaltime = 0x0}

DONE!

四、參考資料

PG Document:Query Planning

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/6906/viewspace-2374806/,如需轉載,請註明出處,否則將追究法律責任。

相關文章