Skip to content

Latest commit

 

History

History
1119 lines (902 loc) · 46.3 KB

executor.md

File metadata and controls

1119 lines (902 loc) · 46.3 KB

http://www.interdb.jp/pg/pgsql03.html#_3.1. にあるようにPlannerによって、query treeがplan treeに書き換えられる。その後Executorによってplan treeが実行される。 plan treeは複数のplan nodeから成り立っている。plan nodeには例えばソートを行うnodeSortや、シーケンシャルスキャンを行うnodeSeqscanなどがある。

"src/backend/executor/nodeSort.c" "src/backend/executor/nodeSeqscan.c"

これらplan nodeの中心となるデータ構造はXXXStateであり、"src/include/nodes/execnodes.h"で定義されている。

/* ----------------
 *   SortState information
 * ----------------
 */
typedef struct SortState
{
  ScanState ss;       /* its first field is NodeTag */
  bool    randomAccess; /* need random access to sort output? */
  bool    bounded;    /* is the result set bounded? */
  int64   bound;      /* if bounded, how many tuples are needed */
  bool    sort_Done;    /* sort completed yet? */
  bool    bounded_Done; /* value of bounded we did the sort with */
  int64   bound_Done;   /* value of bound we did the sort with */
  void     *tuplesortstate; /* private state of tuplesort.c */
  bool    am_worker;    /* are we a worker? */
  SharedSortInfo *shared_info;  /* one entry per worker */
} SortState;


/* ----------------
 *   ScanState information
 *
 *    ScanState extends PlanState for node types that represent
 *    scans of an underlying relation.  It can also be used for nodes
 *    that scan the output of an underlying plan node --- in that case,
 *    only ScanTupleSlot is actually useful, and it refers to the tuple
 *    retrieved from the subplan.
 *
 *    currentRelation    relation being scanned (NULL if none)
 *    currentScanDesc    current scan descriptor for scan (NULL if none)
 *    ScanTupleSlot    pointer to slot in tuple table holding scan tuple
 * ----------------
 */
typedef struct ScanState
{
  PlanState ps;       /* its first field is NodeTag */
  Relation  ss_currentRelation;
  HeapScanDesc ss_currentScanDesc;
  TupleTableSlot *ss_ScanTupleSlot;
} ScanState;

/* ----------------
 *   SeqScanState information
 * ----------------
 */
typedef struct SeqScanState
{
  ScanState ss;       /* its first field is NodeTag */
  Size    pscan_len;    /* size of parallel heap scan descriptor */
} SeqScanState;

これらのState構造体はみな共通してPlanStateという構造を先頭にもつ。

/* ----------------
 *   ExecProcNodeMtd
 *
 * This is the method called by ExecProcNode to return the next tuple
 * from an executor node.  It returns NULL, or an empty TupleTableSlot,
 * if no more tuples are available.
 * ----------------
 */
typedef TupleTableSlot *(*ExecProcNodeMtd) (struct PlanState *pstate);

/* ----------------
 *    PlanState node
 *
 * We never actually instantiate any PlanState nodes; this is just the common
 * abstract superclass for all PlanState-type nodes.
 * ----------------
 */
typedef struct PlanState
{
  NodeTag   type;

  Plan     *plan;     /* associated Plan node */

  EState     *state;      /* 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; /* actual function, if above is a
                     * wrapper */

  Instrumentation *instrument;  /* Optional runtime stats for this node */
  WorkerInstrumentation *worker_instrument; /* per-worker instrumentation */

  /* Per-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).
   */
  ExprState  *qual;     /* boolean qual condition */
  struct PlanState *lefttree; /* input plan tree(s) */
  struct PlanState *righttree;

  List     *initPlan;   /* Init SubPlanState nodes (un-correlated expr
                 * subselects) */
  List     *subPlan;    /* SubPlanState nodes in my expressions */

  /*
   * State for management of parameter-change-driven rescanning
   */
  Bitmapset  *chgParam;   /* set of IDs of changed Params */

  /*
   * Other run-time state needed by most if not all node types.
   */
  TupleTableSlot *ps_ResultTupleSlot; /* 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.
   */
  TupleDesc scandesc;
} PlanState;

データ構造を初期化するための関数はExecInitXXXである。

SortState *
ExecInitSort(Sort *node, EState *estate, int eflags)
SeqScanState *
ExecInitSeqScan(SeqScan *node, EState *estate, int eflags)

これらStateの初期化/消去関数は"src/backend/executor/execProcnode.c"のExecInitNodeとExecEndNodeで適切な関数が呼び出されるようになっている。Stateごとに異なる関数が設定されているExecProcNodeはtupleを返すことが期待されており、"src/backend/executor/execMain.c"のExecutePlanなどで呼び出される。戻り値がnullのときはそれ以上処理するtupleがないということになる。

例えばnodeSortのExecProcNodeはExecSortになっている。Sortは1 tupleずつの処理ができないので、ExecSortが呼ばれると自分のsourceとなるNodeから全てのtupleを一度に読み込みsortを行う。一度sortを行うとsort_Doneがtrueになる。

static TupleTableSlot *
ExecSort(PlanState *pstate)
{
...
    tuplesortstate = tuplesort_begin_heap(tupDesc,
                        plannode->numCols,
                        plannode->sortColIdx,
                        plannode->sortOperators,
                        plannode->collations,
                        plannode->nullsFirst,
                        work_mem,
                        NULL, node->randomAccess);

...

  if (!node->sort_Done)
  {
    ...
    /*
     * Scan the subplan and feed all the tuples to tuplesort.
     */

    for (;;)
    {
      slot = ExecProcNode(outerNode);

      if (TupIsNull(slot))
        break;

      tuplesort_puttupleslot(tuplesortstate, slot);
    }
    ...
    /*
     * finally set the sorted flag to true
     */
    node->sort_Done = true;


    /*
     * Complete the sort.
     */
    tuplesort_performsort(tuplesortstate);

一方でnodeSeqscanの場合、ExecProcNodeはExecSeqScanになっている。ExecSeqScanをみるまえに、SeqScan時のメインのデータ構造であるHeapScanDescDataをみておく。Scan対象のRelation(rs_rd )、Relationのブロック総数(rs_nblocks )、現在のタプル(rs_ctup)、現在のブロック(rs_cblock)、現在のBuffer(rs_cbuf)といった情報を保持している。これがScanStateのss_currentScanDescに保有される。なおss_currentScanDescはSeqNextの初回呼び出し時にheap_beginscanで生成されてセットされる。SeqNextでタプルを取得するのは、heap_getnextとそこから呼ばれるheapgettupで行われる。現在のタプルのpage内での位置などはrs_ctupから計算する。

/* struct definitions appear in relscan.h */
typedef struct HeapScanDescData *HeapScanDesc;

typedef struct HeapScanDescData
{
  /* scan parameters */
  Relation  rs_rd;      /* heap relation descriptor */
  Snapshot  rs_snapshot;  /* snapshot to see */
  int     rs_nkeys;   /* number of scan keys */
  ScanKey   rs_key;     /* array of scan key descriptors */
  bool    rs_bitmapscan;  /* true if this is really a bitmap scan */
  bool    rs_samplescan;  /* true if this is really a sample scan */
  bool    rs_pageatatime; /* verify visibility page-at-a-time? */
  bool    rs_allow_strat; /* allow or disallow use of access strategy */
  bool    rs_allow_sync;  /* allow or disallow use of syncscan */
  bool    rs_temp_snap; /* unregister snapshot at scan end? */

  /* state set up at initscan time */
  BlockNumber rs_nblocks;   /* total number of blocks in rel */
  BlockNumber rs_startblock;  /* block # to start at */
  BlockNumber rs_numblocks; /* max number of blocks to scan */
  /* rs_numblocks is usually InvalidBlockNumber, meaning "scan whole rel" */
  BufferAccessStrategy rs_strategy; /* access strategy for reads */
  bool    rs_syncscan;  /* report location to syncscan logic? */

  /* scan current state */
  bool    rs_inited;    /* false = scan not init'd yet */
  HeapTupleData rs_ctup;    /* current tuple in scan, if any */
  BlockNumber rs_cblock;    /* current block # in scan, if any */
  Buffer    rs_cbuf;    /* current buffer in scan, if any */
  /* NB: if rs_cbuf is not InvalidBuffer, we hold a pin on that buffer */
  ParallelHeapScanDesc rs_parallel; /* parallel scan information */

  /* these fields only used in page-at-a-time mode and for bitmap scans */
  int     rs_cindex;    /* current tuple's index in vistuples */
  int     rs_ntuples;   /* number of visible tuples on page */
  OffsetNumber rs_vistuples[MaxHeapTuplesPerPage];  /* their offsets */
}     HeapScanDescData;

ExecSeqScanの実際の処理はExecScanである。ExecScanではSeqNextでtupleをfetch(ExecScanFetch)し、もし条件が指定されていればExecQualでチェックし条件に合致するときにはそのtupleを返す。条件が指定されてなければ、なにもせずにtupleを返す。という処理になっている。

SortやSeqScanに必要な資源(メモリや一時ファイル)はそれぞれのplan nodeで管理するようになっている。例えばnodeSortの場合、sortする量がすくないときはメモリで、おおいときは一時ファイルを使ってソートを行うが、この管理はSortStateのvoid* tuplesortstate(実際の型はTuplesortstate)で行なっている。例えばsort量の領域にtupleをinsertするputtuple_common関数ではmemtuplesやmemtupcountを使いつつ、場合によっては一時ファイル(ここではtapeと呼ばれている)を使うようにスイッチしている様子がわかる。

/*
 * Shared code for tuple and datum cases.
 */
static void
puttuple_common(Tuplesortstate *state, SortTuple *tuple)
{
  Assert(!LEADER(state));

  switch (state->status)
  {
    case TSS_INITIAL:

      /*
       * Save the tuple into the unsorted array.  First, grow the array
       * as needed.  Note that we try to grow the array when there is
       * still one free slot remaining --- if we fail, there'll still be
       * room to store the incoming tuple, and then we'll switch to
       * tape-based operation.
       */
      if (state->memtupcount >= state->memtupsize - 1)
      {
        (void) grow_memtuples(state);
        Assert(state->memtupcount < state->memtupsize);
      }
      state->memtuples[state->memtupcount++] = *tuple;
...
      /*
       * Done if we still fit in available memory and have array slots.
       */
      if (state->memtupcount < state->memtupsize && !LACKMEM(state))
        return;

      /*
       * Nope; time to switch to tape-based operation.
       */
      inittapes(state, true);

PlanState

PlanStateのメンバーのうち、lefttreeがそのPlanに対する入力となる。

  struct PlanState *lefttree; /* input plan tree(s) */
  struct PlanState *righttree;

count 機能を追加する

以下の実行結果からAggregateがCountの処理を担っているとわかる。

lusiadas=# explain select * from films;
                        QUERY PLAN
----------------------------------------------------------
 Seq Scan on films  (cost=0.00..13.80 rows=380 width=184)
(1 row)

lusiadas=# explain select count(1) from films;
                          QUERY PLAN
--------------------------------------------------------------
 Aggregate  (cost=14.75..14.76 rows=1 width=8)
   ->  Seq Scan on films  (cost=0.00..13.80 rows=380 width=0)
(2 rows)

メインとなる処理は"nodeAgg.c"に記述されている。初期化/消去子は"execProcnode.c"のExecInitNode/ExecEndNodeより、それぞれExecInitAgg/ExecEndAggであるとわかる。またaggstate->ss.ps.ExecProcNode = ExecAgg;とあることから、各tupleに対する処理はExecAggで行うとわかる。 agg_retrieve_directのなかではfetch_input_tupleを呼び出してtupleを取得する。

outerslot = fetch_input_tuple(aggstate);

fetch_input_tupleは以下のようになっており、lefttreeのExecProcNodeを呼び出している。

slot = ExecProcNode(outerPlanState(aggstate));

Aggregatorは入力となるtupleを一度に全部イテレーターするのでagg_retrieve_directではloopしてfetch_input_tupleする。

  while (!aggstate->agg_done)
  {
      ...
          outerslot = fetch_input_tuple(aggstate);
          if (TupIsNull(outerslot))
          {
            /* no more outer-plan tuples available */
            if (hasGroupingSets)
            {
              aggstate->input_done = true;
              break;
            }
            else
            {
              aggstate->agg_done = true;
              break;
            }
          }

レコード削除を実装する

Ref: http://www.interdb.jp/pg/pgsql05.html#_5.3.

lusiadas=# explain delete from films;
                          QUERY PLAN
--------------------------------------------------------------
 Delete on films  (cost=0.00..13.80 rows=380 width=6)
   ->  Seq Scan on films  (cost=0.00..13.80 rows=380 width=6)
(2 rows)

Delete処理はExecDelete関数("nodeModifyTable.c")によって行われる。この関数のメインの処理はheap_delete("heapam.c")である。この関数では

(1) tidからblock番号を取得する (2) block番号とRelationを指定して、bufferにデータを読み込む (3) pageから当該tupleのデータをtuple構造体に読み込む (4) t_infomask2のHEAP_KEYS_UPDATEDをたてる(new_infomask2を参照) (5) HeapTupleHeaderSetXmaxしてt_xmaxをセットする

  block = ItemPointerGetBlockNumber(tid);
  buffer = ReadBuffer(relation, block);
  page = BufferGetPage(buffer);
...
  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
  Assert(ItemIdIsNormal(lp));

  tp.t_tableOid = RelationGetRelid(relation);
  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
  tp.t_len = ItemIdGetLength(lp);
  tp.t_self = *tid;

...

  compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
                tp.t_data->t_infomask, tp.t_data->t_infomask2,
                xid, LockTupleExclusive, true,
                &new_xmax, &new_infomask, &new_infomask2);

...

  /* store transaction information of xact deleting the tuple */
  tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
  tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
  tp.t_data->t_infomask |= new_infomask;
  tp.t_data->t_infomask2 |= new_infomask2;
  HeapTupleHeaderClearHotUpdated(tp.t_data);
  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);

whereを実装する

文法について確認する("gram.y")。

where_clause:
      WHERE a_expr              { $$ = $2; }
      | /*EMPTY*/               { $$ = NULL; }
    ;

a_expr:   c_expr                  { $$ = $1; }
...
      | a_expr '=' a_expr
        { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }

c_expr:   columnref               { $$ = $1; }
      | AexprConst              { $$ = $1; }

/*
 * Constants
 */
AexprConst: Iconst
        {
          $$ = makeIntConst($1, @1);
        }
      | FCONST
        {
          $$ = makeFloatConst($1, @1);
        }

makeSimpleA_ExprではmakeNode(A_Expr)がよばれるので、T_A_Exprというtypeをもったノード(A_Expr)がつくられる。 このようにして作られたwhere_clauseはSelectStmt->whereClauseに格納される。この時点では個々の条件はT_A_Exprというtypeをもったノード(A_Expr "parsenodes.h")である。

simple_select:
      SELECT opt_all_clause opt_target_list
      into_clause from_clause where_clause
      group_clause having_clause window_clause
        {
          SelectStmt *n = makeNode(SelectStmt);
          n->targetList = $3;
          n->intoClause = $4;
          n->fromClause = $5;
          n->whereClause = $6;
          n->groupClause = $7;
          n->havingClause = $8;
          n->windowClause = $9;
          $$ = (Node *)n;
        }

"gram.y"で生成された木は、次にpg_analyze_and_rewriteにかけられる(main.md参照)。 pg_analyze_and_rewrite -> parse_analyze -> transformTopLevelStmt -> transformOptionalSelectInto -> transformStmt と呼び出しが続き、transformStmtではNodeのtypeによる分岐がはいる。T_SelectStmtの場合のtransformSelectStmtをみていくと、transformWhereClause -> transformWhereClause -> transformExpr -> transformExprRecurse と呼び出しが続く。transformExprRecurseでは式の種類による分類がある。T_A_ExprかつAEXPR_OPのケースではtransformAExprOpがよばれる。もっとも汎用的なケースではmake_opがよばれ、この戻り値はOpExprNode("primnodes.h")となる。 ここでtransformSelectStmtの戻り値はQuery("parsenodes.h")となっており、transformWhereClauseの結果はjoinの情報とともにFromExprにくるまれて、Query->jointreeに格納される。

/*****************************************************************************
 *  Query Tree
 *****************************************************************************/

/*
 * Query -
 *    Parse analysis turns all statements into a Query tree
 *    for further processing by the rewriter and planner.
  qry->jointree = makeFromExpr(pstate->p_joinlist, qual);

pg_analyze_and_rewriteで処理された木は、次にpg_plan_queriesにかけられる(main.md参照)。ここでの処理はQuery optimizeがメインとなる。 pg_plan_queriesのコメントにあるように戻り値はPlannedStmtNode("plannodes.h")になる。 処理はpg_plan_queries -> pg_plan_query -> planner -> standard_plannerと進む。subquery_plannerはsub queryの処理を再帰的に行うことを想定したentrypointであり、top levelのstmtを処理するstandard_plannerも主な処理はsubquery_plannerで行う。 subquery_plannerのうち、where(事前の書き換えでここではQuery->jointreeに格納されている)に関連する処理に注目すると、preprocess_qual_conditionsという関数を呼び出していることがわかる(が、ここでは構造が大きく変わったりはしていなさそう)。 standard_planner内部でsubquery_plannerの処理が終わると、その結果はcreate_planに渡される。create_planではPlanつまりPlan nodeが生成される。

  /* primary planning entry point (may recurse for subqueries) */
  root = subquery_planner(glob, parse, NULL,
              false, tuple_fraction);

  /* Select best Path and turn it into a Plan */
  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);

  top_plan = create_plan(root, best_path);

pg_plan_queriesで処理された木は実行に移される(main.md参照)。Portalに対する一連の処理の中でExecutorStartが実行される。ExecutorStart -> standard_ExecutorStart -> InitPlan -> ExecInitNodeと処理が続く。 ここのExecInitNodeはPlanをもとにPlanState("execnodes.h")を作成する。ExecInitNodeの中ではNodeの種類に応じてExecInitXXXという関数が呼ばれる。SeqScanの場合はExecInitSeqScanがよばれる。この関数の最後でPlanState->qualがセットされる。

  /*
   * initialize child expressions
   */
  scanstate->ss.ps.qual =
    ExecInitQual(node->plan.qual, (PlanState *) scanstate);

InitPlanをみるとわかるとおり、QueryDesc *queryDescが各種構造体のハブになっている。例えばInitPlanではPlanをもとにPlanStateを作成するが、これはqueryDesc->plannedstmt->planTreeをもとに作成したPlanStateをqueryDesc->planstateに格納する処理となっている(PlannedStmtがstruct Plan *planTree;を所有している)。

ExecInitQualの中でexpressionがコンパイルされる様子をみていく。ExecInitQualはExprStateをアロケートし初期化する。そしてExecInitExprRecを呼び出してexpressionをstepに変換してExprStateに積んでいく。そして最後にExecReadyExprを呼び出す。ExecReadyExprはExecReadyInterpretedExprを呼び出す。 ExecReadyInterpretedExprではstate->evalfunc = ExecInterpExprStillValid;とセットしたのちに、stepに応じてExprState->evalfunc_privateを決定する。ここで最も汎用的なevalfunc_privateはExecInterpExprである。 なおここで設定されたevalfuncはExecEvalExprもしくはExecEvalExprSwitchContextを使って呼び出すことができる。 たとえばSeqScanの場合、ExecScan (qual = node->ps.qual;) -> ExecQual -> ExecEvalExprSwitchContext (retDatum = state->evalfunc(state, econtext, isNull);) と呼び出される。

"="は実際にはどのような命令になるのか? 前述したようにpg_analyze_and_rewriteの処理の中のmake_opでT_A_ExprだったNodeはOpExprNode("primnodes.h")になっている。これはExecInitExprRecの中ではcase T_OpExpr:に該当するためExecInitFuncが呼ばれる。

case T_OpExpr:
  {
    OpExpr     *op = (OpExpr *) node;

    ExecInitFunc(&scratch, node,
           op->args, op->opfuncid, op->inputcollid,
           state);
    ExprEvalPushStep(state, &scratch);
    break;
  }

ExecInitFuncのなかでscratch->opcodeに代入されうるのは次の4つ:

  • EEOP_FUNCEXPR_STRICT
  • EEOP_FUNCEXPR
  • EEOP_FUNCEXPR_STRICT_FUSAGE
  • EEOP_FUNCEXPR_FUSAGE
  /* Insert appropriate opcode depending on strictness and stats level */
  if (pgstat_track_functions <= flinfo->fn_stats)
  {
    if (flinfo->fn_strict && nargs > 0)
      scratch->opcode = EEOP_FUNCEXPR_STRICT;
    else
      scratch->opcode = EEOP_FUNCEXPR;
  }
  else
  {
    if (flinfo->fn_strict && nargs > 0)
      scratch->opcode = EEOP_FUNCEXPR_STRICT_FUSAGE;
    else
      scratch->opcode = EEOP_FUNCEXPR_FUSAGE;
  }

たとえばEEOP_FUNCEXPRの場合、ExecInterpExprでは以下のようにop->d.func.fn_addrの呼び出しになる。

    /*
     * Function-call implementations. Arguments have previously been
     * evaluated directly into fcinfo->args.
     *
     * As both STRICT checks and function-usage are noticeable performance
     * wise, and function calls are a very hot-path (they also back
     * operators!), it's worth having so many separate opcodes.
     *
     * Note: the reason for using a temporary variable "d", here and in
     * other places, is that some compilers think "*op->resvalue = f();"
     * requires them to evaluate op->resvalue into a register before
     * calling f(), just in case f() is able to modify op->resvalue
     * somehow.  The extra line of code can save a useless register spill
     * and reload across the function call.
     */
    EEO_CASE(EEOP_FUNCEXPR)
    {
      FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
      Datum   d;

      fcinfo->isnull = false;
      d = op->d.func.fn_addr(fcinfo);
      *op->resvalue = d;
      *op->resnull = fcinfo->isnull;

      EEO_NEXT();
    }

このfn_addrがどこからくるのかというと、それはExecInitFuncである。

  /* Set up the primary fmgr lookup information */
  fmgr_info(funcid, flinfo);
  fmgr_info_set_expr((Node *) node, flinfo);

  /* Initialize function call parameter structure too */
  InitFunctionCallInfoData(*fcinfo, flinfo,
               nargs, inputcollid, NULL, NULL);

  /* Keep extra copies of this info to save an indirection at runtime */
  scratch->d.func.fn_addr = flinfo->fn_addr;
  scratch->d.func.nargs = nargs;

もっとも基礎的な組み込み関数の場合、fmgr_info -> fmgr_info_cxt_security -> fmgr_isbuiltinと呼び出され、fmgr_isbuiltinの中で関数のアドレスを解決する。関数のアドレスはfmgr_builtinsに格納されている。fmgr_builtinsは"src/backend/utils/Gen_fmgrtab.pl"からbuild時に生成される、"src/backend/utils/fmgrtab.c"というファイルで定義されている。

const FmgrBuiltin fmgr_builtins[] = {
  { 31, "byteaout", 1, true, false, byteaout },
  { 33, "charout", 1, true, false, charout },
  { 34, "namein", 1, true, false, namein },
  { 35, "nameout", 1, true, false, nameout },
  { 38, "int2in", 1, true, false, int2in },
...
  else
  {
    /* otherwise, binary operator */
    ltypeId = exprType(ltree);
    rtypeId = exprType(rtree);
    tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
  }

  opform = (Form_pg_operator) GETSTRUCT(tup);
...
  result->opfuncid = opform->oprcode;

where id = 10 を実装する

gram.yで作られるNodeはColumnRefである。

where_clause:
      WHERE a_expr              { $$ = $2; }
      | /*EMPTY*/               { $$ = NULL; }
    ;

a_expr:   c_expr                  { $$ = $1; }

c_expr:   columnref               { $$ = $1; }

columnref:  ColId
        {
          $$ = makeColumnRef($1, NIL, @1, yyscanner);
        }
      | ColId indirection
        {
          $$ = makeColumnRef($1, $2, @1, yyscanner);
        }
    ;

static Node *
makeColumnRef(char *colname, List *indirection,
        int location, core_yyscan_t yyscanner)
{
  /*
   * Generate a ColumnRef node, with an A_Indirection node added if there
   * is any subscripting in the specified indirection list.  However,
   * any field selection at the start of the indirection list must be
   * transposed into the "fields" part of the ColumnRef node.
   */
  ColumnRef  *c = makeNode(ColumnRef);

transformExprRecurseではtransformColumnRefがよばれる。ColumnRefはtable.idやdb.table.idなどの指定が可能だが、ここではidのケースをみていく。 transformColumnRef -> colNameToVar -> scanRTEForColumn -> make_var -> makeVarと呼び出しが続き、makeVarでVar Node("primnodes.h")が作られる。 transformColumnRefの時点では引数はColumnRef *crefである。つまりこの時点ではカラム名の文字列が渡ってくる。colNameToVarの時点の引数はconst char *colnameであるので、ここでもカラム名は文字列である。colNameToVarのなかではpstate->p_namespaceリストをイテレートしながらscanRTEForColumnを呼び出していくが、そのときnsitem->p_rteを取り出してscanRTEForColumnに渡している。

    foreach(l, pstate->p_namespace)
    {
      ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
      RangeTblEntry *rte = nsitem->p_rte;
      Node     *newresult;

      /* Ignore table-only items */
      if (!nsitem->p_cols_visible)
        continue;
      /* If not inside LATERAL, ignore lateral-only items */
      if (nsitem->p_lateral_only && !pstate->p_lateral_active)
        continue;

      /* use orig_pstate here to get the right sublevels_up */
      newresult = scanRTEForColumn(orig_pstate, rte, colname, location,
                     0, NULL);

scanRTEForColumnのなかではrte->eref->colnamesを順番にみながら、const char *colnameと一致するものを探し、Var Nodeをつくる。Var Nodeのレベルではcolnameではなくattrnoという数値になっている。varnoはpstate->p_rtableのリストの何個目の要素に当該カラムが含まれているかを表す。make_varのなかでRTERangeTablePosnを使って解決している。

typedef struct Var
{
  Expr    xpr;
  Index   varno;      /* index of this var's relation in the range
                 * table, or INNER_VAR/OUTER_VAR/INDEX_VAR */
  AttrNumber  varattno;   /* attribute number of this var, or zero for
                 * all attrs ("whole-row Var") */
  ...

T_Var NodeはExecInitExprRecによってEEOP_SCAN_VARなどのstepになる。stepの評価は以下のようになっており、現在のtupleの該当するカラムをindexアクセスする。

    EEO_CASE(EEOP_SCAN_VAR)
    {
      int     attnum = op->d.var.attnum;

      /* See EEOP_INNER_VAR comments */

      Assert(attnum >= 0 && attnum < scanslot->tts_nvalid);
      *op->resvalue = scanslot->tts_values[attnum];
      *op->resnull = scanslot->tts_isnull[attnum];

      EEO_NEXT();
    }

ここでscanslotはecontext->ecxt_scantupleのことである。ExprContextは式のevaluationに必要な情報を保持している。ecxt_scantupleは現在処理しているtupleを指しており、例えばExecScanのなかでtupleをfetchするごとに代入される。

    slot = ExecScanFetch(node, accessMtd, recheckMtd);
    ...
    /*
     * place the current tuple into the expr context
     */
    econtext->ecxt_scantuple = slot;

targetlistとTargetEntry

Plan nodeが共通してもつデータ構造であるstruct PlanにはList *targetlist;というメンバーがある。これは TargetEntryという構造体のlistになっている。targetlistはそのPlan nodeが出力するtupleのカラムを表現している。例えば以下のような単純なselectの場合、targetlistには2つのVar nodeが入っており、それぞれtitleとdidを表している。

lusiadas=# set session "psql_inspect.planner_script" = 'p PgInspect::PlannedStmt.current_stmt.plan_tree.targetlist.map(&:expr)';
lusiadas=# select title, did from films;

# => [#<PgInspect::Var:0x7fc2728c69e0>, #<PgInspect::Var:0x7fc2728c68f0>]

lusiadas=# set session "psql_inspect.planner_script" = 'p PgInspect::PlannedStmt.current_stmt.plan_tree.targetlist.map(&:expr).map(&:varattno)';

lusiadas=# select title, did from films;

# => [2, 3]

lusiadas=# \d films
                         Table "public.films"
  Column   |          Type           | Collation | Nullable | Default
-----------+-------------------------+-----------+----------+---------
 code      | character(5)            |           | not null |
 title     | character varying(40)   |           | not null |
 did       | integer                 |           | not null |
 date_prod | date                    |           |          |
 kind      | character varying(10)   |           |          |
 len       | interval hour to minute |           |          |

ParseState

ParseStateはparse analysis時のコンテキストを管理するもので、joinのリストやrange tableのリストをもっている。

/*
 * State information used during parse analysis
 *
...
struct ParseState
{
  struct ParseState *parentParseState;  /* stack link */
  const char *p_sourcetext; /* source text, or NULL if not available */
  List     *p_rtable;   /* range table so far */
  List     *p_joinexprs;  /* JoinExprs for RTE_JOIN p_rtable entries */
  List     *p_joinlist;   /* join items so far (will become FromExpr
                 * node's fromlist) */
  List     *p_namespace;  /* currently-referenceable RTEs (List of
                 * ParseNamespaceItem) */

ParseStateはparse_analyzeのタイミングでつくられる。

Query *
parse_analyze(RawStmt *parseTree, const char *sourceText,
        Oid *paramTypes, int numParams,
        QueryEnvironment *queryEnv)
{
  ParseState *pstate = make_parsestate(NULL);

ParseStateのメンバーのうち、あとのフェーズでColumnRefなどのRelation解決に使われるのがp_namespaceである。p_namespaceはtransformFromClauseなどで拡張される。transformFromClauseの場合、transformFromClause -> transformFromClauseItem -> transformTableEntry -> addRangeTableEntry (ここで戻り値の RangeTblEntry Node を作成) -> parserOpenTable -> heap_openrv_extended -> relation_openrv_extended -> RangeVarGetRelid -> RangeVarGetRelidExtendedとよびだして、RangeVarをもとにRelationのOidを解決する。relation_openrv_extendedでOidからRelationをひき、addRangeTableEntryでRangeTblEntry Nodeに必要な情報をRelationからコピーする。直近必要な情報としてカラム列に関する情報(rte->eref->colnames)がある。これはbuildRelationAliasesのなかで生成される。

RangeTblEntry *
addRangeTableEntry(ParseState *pstate,
           RangeVar *relation,
           Alias *alias,
           bool inh,
           bool inFromCl)
{
  ...
  /*
   * Build the list of effective column names using user-supplied aliases
   * and/or actual column names.
   */
  rte->eref = makeAlias(refname, NIL);
  buildRelationAliases(rel->rd_att, alias, rte->eref);
  ...
  /*
   * Add completed RTE to pstate's range table list, but not to join list
   * nor namespace --- caller must do that if appropriate.
   */
  pstate->p_rtable = lappend(pstate->p_rtable, rte);

またaddRangeTableEntryではpstate->p_rtableに新しく作ったRangeTblEntryをappendする。

transformFromClauseItemではいま作ったRangeTblEntryをもとにParseNamespaceItemをつくり、namespaceの指しているアドレスに代入する。

    /* Check if it's a CTE or tuplestore reference */
    rte = getRTEForSpecialRelationTypes(pstate, rv);

    /* if not found above, must be a table reference */
    if (!rte)
      rte = transformTableEntry(pstate, rv);

    /* assume new rte is at end */
    rtindex = list_length(pstate->p_rtable);
    Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
    *top_rte = rte;
    *top_rti = rtindex;
    *namespace = list_make1(makeDefaultNSItem(rte));

order by を実装する

lusiadas=# explain select * from films;
                        QUERY PLAN
----------------------------------------------------------
 Seq Scan on films  (cost=0.00..13.80 rows=380 width=184)
(1 row)

lusiadas=# explain select * from films order by did;
                           QUERY PLAN
----------------------------------------------------------------
 Sort  (cost=30.08..31.03 rows=380 width=184)
   Sort Key: did
   ->  Seq Scan on films  (cost=0.00..13.80 rows=380 width=184)
(3 rows)
lusiadas=# set session "psql_inspect.planner_script" = 'p PgInspect::PlannedStmt.current_stmt.plan_tree.sort_operators';
SET
lusiadas=# select * from films order by did asc;
# => [97]

lusiadas=# select * from films order by did desc;
# => [521]

Oidは"pg_operator.dat"に定義してある数値であり、97は"'less than'"、521は"greater than"となっている。

Plan treeのレベルではSort Nodeがあり、そのlefttreeにSeqScanがある(righttreeはとくにない)。

ExecのレベルではExecSortが処理を行なっており、memory上もしくは一時fileを利用してソートを行う。

In the sorting operation, if all tuples to be sorted can be stored in work_mem, the quicksort algorithm is used. Otherwise, a temporary file is created and the file merge sort algorithm is used.

Sort処理の中心はExecSortである。tuplesort_begin_heapでセットアップし、全てのtupleをfor loopとExecProcNodeでfetchしてtuplesort_puttupleslotで保存する。最後にtuplesort_performsortを呼び出す。tuplesort_puttupleslotは処理の大半をputtuple_commonに移譲している。puttuple_commonではメモリの使用状況をみて、メモリを消費しすぎる場合にはinittapesを呼び出して、一時ファイルを使うようになる。

group by を実装する

以下の2つのクエリを考えてみる。

(Query. 1)

lusiadas=# explain select did from films group by did;
                          QUERY PLAN
--------------------------------------------------------------
 HashAggregate  (cost=14.75..16.75 rows=200 width=4)
   Group Key: did
   ->  Seq Scan on films  (cost=0.00..13.80 rows=380 width=4)
(3 rows)

(Query. 2)

lusiadas=# explain select count(1) from films group by did;
                          QUERY PLAN
--------------------------------------------------------------
 HashAggregate  (cost=15.70..17.70 rows=200 width=12)
   Group Key: did
   ->  Seq Scan on films  (cost=0.00..13.80 rows=380 width=4)
(3 rows)

explainの結果は同じだが、plan treeも同じなのだろうか?

(Query. 1)

grp_col_idx: どのカラムでgroupingするかの情報をもつ。 resjunk: 最終的に使わない(内部的な事情で追加されている)カラムの場合trueになる。

lusiadas=# set session "psql_inspect.planner_script" = 'pt = PgInspect::PlannedStmt.current_stmt.plan_tree; p [pt, pt.grp_col_idx, pt.targetlist.map(&:expr), pt.targetlist.map(&:expr).map(&:varattno), pt.targetlist.map(&:resjunk)]';
lusiadas=# select did from films group by did;

# 3 means did column
# => [#<PgInspect::Agg:0x7fc27103acf0>, [3], [#<PgInspect::Var:0x7fc27103aa80>], [3], [false]]
lusiadas=# set session "psql_inspect.planner_script" = 'pt = PgInspect::PlannedStmt.current_stmt.plan_tree; p [pt, pt.grp_col_idx, pt.targetlist.map(&:expr), pt.targetlist.map(&:expr).map(&:varattno), pt.targetlist.map(&:resjunk)]';
lusiadas=# select did from films group by did, title;

# 3 means did column, 2 means title
# => [#<PgInspect::Agg:0x7fc27103cee0>, [3, 2], [#<PgInspect::Var:0x7fc27103cc40>, #<PgInspect::Var:0x7fc27103cb50>], [3, 2], [false, true]]

(Query. 2)

lusiadas=# set session "psql_inspect.planner_script" = 'pt = PgInspect::PlannedStmt.current_stmt.plan_tree; p [pt, pt.grp_col_idx, pt.targetlist.map(&:expr), [pt.targetlist.map(&:expr)[0].args, pt.targetlist.map(&:expr)[1].varattno], pt.targetlist.map(&:resjunk)]';
lusiadas=# select count(1) from films group by did;

# 3 means did column
# => [#<PgInspect::Agg:0x7fc271034630>, [3], [#<PgInspect::Aggref:0x7fc271034390>, #<PgInspect::Var:0x7fc2710342a0>], [[#<PgInspect::TargetEntry:0x7fc271033ee0>], 3], [false, true]]

lusiadas=# set session "psql_inspect.planner_script" = 'pt = PgInspect::PlannedStmt.current_stmt.plan_tree; aggref = pt.targetlist.map(&:expr)[0]; p [aggref.args.map(&:expr), aggref.args.map(&:expr).map(&:constvalue), aggref.aggfnoid]';

lusiadas=# select count(1) from films group by did;
# => [[#<PgInspect::Const:0x7fc272034ff0>], [1], 2147]

lusiadas=# select avg(1) from films group by did;
[[#<PgInspect::Const:0x7fc272033fd0>], [1], 2101]

aggfnoidはアグリゲーションに使う関数のOidを表しており、2147はcount、2101はavgのことである("src/include/catalog/pg_proc.dat"参照)。アグリゲーション関数の実態はForm_pg_aggregateであり、レコード定義は"pg_aggregate.dat"にある。

ExecInitAggでNodeの実行に必要な情報を集める。SearchSysCache1(AGGFNOIDの箇所はpg_aggregateからデータを引いてくることになるのでForm_pg_aggregateにキャストしてよい。aggfnoidの型はregprocであるがこれはOidのエイリアスである(コンソールでselectしたときの表示は"pg_catalog.count"のようになる)。

    /* Fetch the pg_aggregate row */
    aggTuple = SearchSysCache1(AGGFNOID,
                   ObjectIdGetDatum(aggref->aggfnoid));
    if (!HeapTupleIsValid(aggTuple))
      elog(ERROR, "cache lookup failed for aggregate %u",
         aggref->aggfnoid);
    aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
typedef Oid regproc;

count(2147)を引いてみると以下のようになり、"pg_aggregate.dat"で定義されたデータが返ってくる。

lusiadas=# select * from pg_aggregate where aggfnoid = 2147;
     aggfnoid     | aggkind | aggnumdirectargs | aggtransfn  | aggfinalfn | aggcombinefn | aggserialfn | aggdeserialfn | aggmtransfn | aggminvtransfn | aggmfinalfn | aggfinalextra | aggmfinalextra | aggfinalmodify | aggmfinalmodify | aggsortop | aggtranstype | aggtransspace | aggmtranstype | aggmtransspace | agginitval | aggminitval
------------------+---------+------------------+-------------+------------+--------------+-------------+---------------+-------------+----------------+-------------+---------------+----------------+----------------+-----------------+-----------+--------------+---------------+---------------+----------------+------------+-------------
 pg_catalog.count | n       |                0 | int8inc_any | -          | int8pl       | -           | -             | int8inc_any | int8dec_any    | -           | f             | f              | r              | r               |         0 |           20 |             0 |            20 |              0 | 0          | 0
(1 row)

ExecInitAggのなかで使用されているaggformのメンバーは以下のとおり:

  • transfn_oid = aggform->aggcombinefn;
  • transfn_oid = aggform->aggtransfn;
  • peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
  • shareable = (aggform->aggfinalmodify != AGGMODIFY_READ_WRITE) ||
  • serialfn_oid = aggform->aggserialfn;
  • deserialfn_oid = aggform->aggdeserialfn;
  • if (aggform->aggfinalextra)
  • Anum_pg_aggregate_agginitval (= agginitval)

"nodeAgg.c"の実行時に必要なデータ構造であるAggStateのフィールドについてみておく。

  • int num_hashes
  • AggStatePerHash perhash

Hash法でアグリゲーションするときに使うデータ。groupingSetsの数によって変わるが初期値は1。

ExecInitAggのなかでaggstate->ss.ps.ExecProcNode = ExecAgg;していることからも明らかに"nodeAgg.c"でtupleを生成するための関数はExecAggである。 ExecAggはaggstrategyによってaggregationの方法が変化する。。ここではAGG_HASHEDのケースをみていく。

  • ExecAgg -- agg_fill_hash_table --- fetch_input_tuple: outer planからtupleをfetchする --- lookup_hash_entries: aggstate->hash_pergroupをセットする --- advance_aggregates: aggstate->phase->evaltransを評価する --- select_current_set: aggstate->curaggcontextとaggstate->current_setを調整する -- agg_retrieve_hash_table

"nodeAgg.c"でouter planからtupleをfetchするのはfetch_input_tupleだけ。

gram.yではExpr Nodeのlistが作られて、groupClauseに代入される。

simple_select:
      SELECT opt_all_clause opt_target_list
      into_clause from_clause where_clause
      group_clause having_clause window_clause
        {
          SelectStmt *n = makeNode(SelectStmt);
          n->targetList = $3;
          n->intoClause = $4;
          n->fromClause = $5;
          n->whereClause = $6;
          n->groupClause = $7;
          n->havingClause = $8;
          n->windowClause = $9;
          $$ = (Node *)n;
        }
...

 * Each item in the group_clause list is either an expression tree or a
 * GroupingSet node of some type.
 */
group_clause:
      GROUP_P BY group_by_list        { $$ = $3; }
      | /*EMPTY*/               { $$ = NIL; }
    ;

group_by_list:
      group_by_item             { $$ = list_make1($1); }
      | group_by_list ',' group_by_item   { $$ = lappend($1,$3); }
    ;

group_by_item:
      a_expr                  { $$ = $1; }
      | empty_grouping_set          { $$ = $1; }
      | cube_clause             { $$ = $1; }
      | rollup_clause             { $$ = $1; }
      | grouping_sets_clause          { $$ = $1; }
    ;

transformSelectStmtではtransformGroupClauseがよばれ、その結果がgroupClauseに代入される。またgroupClauseがあるときは、parseCheckAggregatesがよばれる。

  qry->groupClause = transformGroupClause(pstate,
                      stmt->groupClause,
                      &qry->groupingSets,
                      &qry->targetList,
                      qry->sortClause,
                      EXPR_KIND_GROUP_BY,
                      false /* allow SQL92 rules */ );

...
  if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
    parseCheckAggregates(pstate, qry);

transformGroupClauseのなかではgroupClauseをflattenしたのちにイテレートする。今回はIsA(gexpr, GroupingSet)ではないケースなので、transformGroupClauseExprがよばれる。

subquery_planner -> grouping_planner -> preprocess_groupclause で Query->groupClauseに格納。

UPPERREL_GROUP_AGG fetch_upper_rel root->upper_rels

create_grouping_paths -> make_grouping_rel/create_ordinary_grouping_paths set_cheapest

typedef struct Path
{
  NodeTag   type;

  NodeTag   pathtype;   /* tag identifying scan/join method */  <- THIS!

executorの初期化

Plan TreeのNodeをPlanState Node(Exec Node)のTreeに変換する必要がある。ExecInitNodeがこの変換を行うための関数である。ExecInitNodeはNodeの種類で分岐し、ExecInitResultやExecInitProjectSetなどNodeの種類に応じた関数を呼び出し、ExecNodeをつくる。各種ExecInitXXXのなかでは必要に応じて再帰的にExecInitNodeがよばれる。例えばExecInitSortのなかでは以下のようにExecInitNodeを呼び出し、outerをセットする。PlanState (node)はPlanState系のNodeの抽象クラスのような存在であるが、これはPlan Nodeと同じようにstruct PlanState *lefttreeとstruct PlanState *righttreeをもつ。Plan Node同様にlefttreeがinputに相当する。

outerPlanState(sortstate) = ExecInitNode(outerPlan(node), estate, eflags);
#define outerPlanState(node)    (((PlanState *)(node))->lefttree)

有益コメント集

コメントがかわいい。

/*
 * Productions that can be used in both a_expr and b_expr.
 *
 * Note: productions that refer recursively to a_expr or b_expr mostly
 * cannot appear here.  However, it's OK to refer to a_exprs that occur
 * inside parentheses, such as function arguments; that cannot introduce
 * ambiguity to the b_expr syntax.
 */
c_expr:   columnref               { $$ = $1; }

うける

  /*
   * Special-case "foo = NULL" and "NULL = foo" for compatibility with
   * standards-broken products (like Microsoft's).  Turn these into IS NULL
   * exprs. (If either side is a CaseTestExpr, then the expression was
   * generated internally from a CASE-WHEN expression, and
   * transform_null_equals does not apply.)
   */
 * When using direct threading, ExecReadyInterpretedExpr will replace
 * each step's opcode field with the address of the relevant code block and
 * ExprState->flags will contain EEO_FLAG_DIRECT_THREADED to remember that
 * that's been done.