[code notes] subquery parsing in postgresql
The SQL
select a from (select a from t);
Overview
from (select a from t)will map to oneRangeTblEntrystruct of the outter query.from twill map to oneRangeTblEntrystruct of the inner query.RangeTblEntryentries together create a range table list. This list will link toQuery->rtableorParseState->p_rtable.- Besides
RangeTblEntrygenerated,ParseNamespaceItemitems also are generated. EachParseNamespaceItemcorrespondes to each table entry afterfromkeyword. - subquery is recorded in
RangeTblEntry'ssubqueryfield.
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 阅读(9) 评论(0) 收藏 举报
浙公网安备 33010602011771号