The SQL
select a from (select a from t);
Overview
from (select a from t)
will map to oneRangeTblEntry
struct of the outter query.from t
will map to oneRangeTblEntry
struct of the inner query.RangeTblEntry
entries together create a range table list. This list will link toQuery->rtable
orParseState->p_rtable
.- Besides
RangeTblEntry
generated,ParseNamespaceItem
items also are generated. EachParseNamespaceItem
correspondes to each table entry afterfrom
keyword. - subquery is recorded in
RangeTblEntry
'ssubquery
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);
}
标签:pstate,code,postgresql,notes,will,subquery,RangeTblEntry,query,select
From: https://www.cnblogs.com/lddcool/p/18129457