[code notes] subquery parsing in postgresql

The SQL

select a from (select a from t);

Overview

  • from (select a from t) will map to one RangeTblEntry struct of the outter query.
  • from t will map to one RangeTblEntry struct of the inner query.
  • RangeTblEntry entries together create a range table list. This list will link to Query->rtable or ParseState->p_rtable.
  • Besides RangeTblEntry generated, ParseNamespaceItem items also are generated. Each ParseNamespaceItem correspondes to each table entry after from keyword.
  • subquery is recorded in RangeTblEntry's subquery field.

Parsing

From this article, we could quickly find the semantic rule,

table_ref: select_with_parens opt_alias_clause opt_conversion_clause
    {
      RangeSubselect *n = makeNode(RangeSubselect);
      LtRangeTableRef *cref = (LtRangeTableRef *) $3;
      n->lateral = false;
      n->subquery = $1;
      n->alias = $2;
	  ...
    }
  ;

But RangeSubelect structure is not processed as other structures, we could not find the processing code easily by searching T_RangeSubselect. Anyway, we could search transformFromClause function which will lead you to the implementation function transformRangeSubselect, the core logic is:

static ParseNamespaceItem *
transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
{
  /*
   * `parse_sub_analyze` parses the `r->subquery`, in this case, `select a from t`.
   * Current `pstate` will be a parent ParseState of the subquery.
   */
  Query*query = parse_sub_analyze(r->subquery, pstate, ...);

  /*
   * OK, build an RTE and nsitem for the subquery.
   * After `addRangeTableEntryForSubquery` completed, the parent ParseState(or the current pstate) will have
   * some knowledges about the subquery from its `p_rtable` field. Such as:
   *
   *  What kind of query of the subquery?
   *  How many columns does the subquery return?
   *  Is there a join query in the subquery? 
   */
  return addRangeTableEntryForSubquery(pstate, query, r->alias, r->lateral, true);
}

posted on 2024-04-11 16:09  winter-loo  阅读(1)  评论(0编辑  收藏  举报

导航