PostgreSQL Source Code  git master
parse_cte.c File Reference
#include "postgres.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_cte.h"
#include "parser/parse_expr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
Include dependency graph for parse_cte.c:

Go to the source code of this file.

Data Structures

struct  CteItem
 
struct  CteState
 

Typedefs

typedef struct CteItem CteItem
 
typedef struct CteState CteState
 

Enumerations

enum  RecursionContext {
  RECURSION_OK , RECURSION_NONRECURSIVETERM , RECURSION_SUBLINK , RECURSION_OUTERJOIN ,
  RECURSION_INTERSECT , RECURSION_EXCEPT
}
 

Functions

static void analyzeCTE (ParseState *pstate, CommonTableExpr *cte)
 
static void makeDependencyGraph (CteState *cstate)
 
static bool makeDependencyGraphWalker (Node *node, CteState *cstate)
 
static void TopologicalSort (ParseState *pstate, CteItem *items, int numitems)
 
static void checkWellFormedRecursion (CteState *cstate)
 
static bool checkWellFormedRecursionWalker (Node *node, CteState *cstate)
 
static void checkWellFormedSelectStmt (SelectStmt *stmt, CteState *cstate)
 
ListtransformWithClause (ParseState *pstate, WithClause *withClause)
 
void analyzeCTETargetList (ParseState *pstate, CommonTableExpr *cte, List *tlist)
 

Variables

static const char *const recursion_errormsgs []
 

Typedef Documentation

◆ CteItem

typedef struct CteItem CteItem

◆ CteState

typedef struct CteState CteState

Enumeration Type Documentation

◆ RecursionContext

Enumerator
RECURSION_OK 
RECURSION_NONRECURSIVETERM 
RECURSION_SUBLINK 
RECURSION_OUTERJOIN 
RECURSION_INTERSECT 
RECURSION_EXCEPT 

Definition at line 31 of file parse_cte.c.

32 {
34  RECURSION_NONRECURSIVETERM, /* inside the left-hand term */
35  RECURSION_SUBLINK, /* inside a sublink */
36  RECURSION_OUTERJOIN, /* inside nullable side of an outer join */
37  RECURSION_INTERSECT, /* underneath INTERSECT (ALL) */
38  RECURSION_EXCEPT /* underneath EXCEPT (ALL) */
RecursionContext
Definition: parse_cte.c:32
@ RECURSION_INTERSECT
Definition: parse_cte.c:37
@ RECURSION_SUBLINK
Definition: parse_cte.c:35
@ RECURSION_EXCEPT
Definition: parse_cte.c:38
@ RECURSION_OUTERJOIN
Definition: parse_cte.c:36
@ RECURSION_NONRECURSIVETERM
Definition: parse_cte.c:34
@ RECURSION_OK
Definition: parse_cte.c:33

Function Documentation

◆ analyzeCTE()

static void analyzeCTE ( ParseState pstate,
CommonTableExpr cte 
)
static

Definition at line 248 of file parse_cte.c.

249 {
250  Query *query;
251  CTESearchClause *search_clause = cte->search_clause;
252  CTECycleClause *cycle_clause = cte->cycle_clause;
253 
254  /* Analysis not done already */
255  Assert(!IsA(cte->ctequery, Query));
256 
257  /*
258  * Before analyzing the CTE's query, we'd better identify the data type of
259  * the cycle mark column if any, since the query could refer to that.
260  * Other validity checks on the cycle clause will be done afterwards.
261  */
262  if (cycle_clause)
263  {
264  TypeCacheEntry *typentry;
265  Oid op;
266 
267  cycle_clause->cycle_mark_value =
268  transformExpr(pstate, cycle_clause->cycle_mark_value,
270  cycle_clause->cycle_mark_default =
271  transformExpr(pstate, cycle_clause->cycle_mark_default,
273 
274  cycle_clause->cycle_mark_type =
275  select_common_type(pstate,
276  list_make2(cycle_clause->cycle_mark_value,
277  cycle_clause->cycle_mark_default),
278  "CYCLE", NULL);
279  cycle_clause->cycle_mark_value =
280  coerce_to_common_type(pstate,
281  cycle_clause->cycle_mark_value,
282  cycle_clause->cycle_mark_type,
283  "CYCLE/SET/TO");
284  cycle_clause->cycle_mark_default =
285  coerce_to_common_type(pstate,
286  cycle_clause->cycle_mark_default,
287  cycle_clause->cycle_mark_type,
288  "CYCLE/SET/DEFAULT");
289 
290  cycle_clause->cycle_mark_typmod =
291  select_common_typmod(pstate,
292  list_make2(cycle_clause->cycle_mark_value,
293  cycle_clause->cycle_mark_default),
294  cycle_clause->cycle_mark_type);
295 
296  cycle_clause->cycle_mark_collation =
298  list_make2(cycle_clause->cycle_mark_value,
299  cycle_clause->cycle_mark_default),
300  true);
301 
302  /* Might as well look up the relevant <> operator while we are at it */
303  typentry = lookup_type_cache(cycle_clause->cycle_mark_type,
305  if (!OidIsValid(typentry->eq_opr))
306  ereport(ERROR,
307  errcode(ERRCODE_UNDEFINED_FUNCTION),
308  errmsg("could not identify an equality operator for type %s",
309  format_type_be(cycle_clause->cycle_mark_type)));
310  op = get_negator(typentry->eq_opr);
311  if (!OidIsValid(op))
312  ereport(ERROR,
313  errcode(ERRCODE_UNDEFINED_FUNCTION),
314  errmsg("could not identify an inequality operator for type %s",
315  format_type_be(cycle_clause->cycle_mark_type)));
316 
317  cycle_clause->cycle_mark_neop = op;
318  }
319 
320  /* Now we can get on with analyzing the CTE's query */
321  query = parse_sub_analyze(cte->ctequery, pstate, cte, false, true);
322  cte->ctequery = (Node *) query;
323 
324  /*
325  * Check that we got something reasonable. These first two cases should
326  * be prevented by the grammar.
327  */
328  if (!IsA(query, Query))
329  elog(ERROR, "unexpected non-Query statement in WITH");
330  if (query->utilityStmt != NULL)
331  elog(ERROR, "unexpected utility statement in WITH");
332 
333  /*
334  * We disallow data-modifying WITH except at the top level of a query,
335  * because it's not clear when such a modification should be executed.
336  */
337  if (query->commandType != CMD_SELECT &&
338  pstate->parentParseState != NULL)
339  ereport(ERROR,
340  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341  errmsg("WITH clause containing a data-modifying statement must be at the top level"),
342  parser_errposition(pstate, cte->location)));
343 
344  /*
345  * CTE queries are always marked not canSetTag. (Currently this only
346  * matters for data-modifying statements, for which the flag will be
347  * propagated to the ModifyTable plan node.)
348  */
349  query->canSetTag = false;
350 
351  if (!cte->cterecursive)
352  {
353  /* Compute the output column names/types if not done yet */
354  analyzeCTETargetList(pstate, cte, GetCTETargetList(cte));
355  }
356  else
357  {
358  /*
359  * Verify that the previously determined output column types and
360  * collations match what the query really produced. We have to check
361  * this because the recursive term could have overridden the
362  * non-recursive term, and we don't have any easy way to fix that.
363  */
364  ListCell *lctlist,
365  *lctyp,
366  *lctypmod,
367  *lccoll;
368  int varattno;
369 
370  lctyp = list_head(cte->ctecoltypes);
371  lctypmod = list_head(cte->ctecoltypmods);
372  lccoll = list_head(cte->ctecolcollations);
373  varattno = 0;
374  foreach(lctlist, GetCTETargetList(cte))
375  {
376  TargetEntry *te = (TargetEntry *) lfirst(lctlist);
377  Node *texpr;
378 
379  if (te->resjunk)
380  continue;
381  varattno++;
382  Assert(varattno == te->resno);
383  if (lctyp == NULL || lctypmod == NULL || lccoll == NULL) /* shouldn't happen */
384  elog(ERROR, "wrong number of output columns in WITH");
385  texpr = (Node *) te->expr;
386  if (exprType(texpr) != lfirst_oid(lctyp) ||
387  exprTypmod(texpr) != lfirst_int(lctypmod))
388  ereport(ERROR,
389  (errcode(ERRCODE_DATATYPE_MISMATCH),
390  errmsg("recursive query \"%s\" column %d has type %s in non-recursive term but type %s overall",
391  cte->ctename, varattno,
393  lfirst_int(lctypmod)),
395  exprTypmod(texpr))),
396  errhint("Cast the output of the non-recursive term to the correct type."),
397  parser_errposition(pstate, exprLocation(texpr))));
398  if (exprCollation(texpr) != lfirst_oid(lccoll))
399  ereport(ERROR,
400  (errcode(ERRCODE_COLLATION_MISMATCH),
401  errmsg("recursive query \"%s\" column %d has collation \"%s\" in non-recursive term but collation \"%s\" overall",
402  cte->ctename, varattno,
405  errhint("Use the COLLATE clause to set the collation of the non-recursive term."),
406  parser_errposition(pstate, exprLocation(texpr))));
407  lctyp = lnext(cte->ctecoltypes, lctyp);
408  lctypmod = lnext(cte->ctecoltypmods, lctypmod);
409  lccoll = lnext(cte->ctecolcollations, lccoll);
410  }
411  if (lctyp != NULL || lctypmod != NULL || lccoll != NULL) /* shouldn't happen */
412  elog(ERROR, "wrong number of output columns in WITH");
413  }
414 
415  /*
416  * Now make validity checks on the SEARCH and CYCLE clauses, if present.
417  */
418  if (search_clause || cycle_clause)
419  {
420  Query *ctequery;
421  SetOperationStmt *sos;
422 
423  if (!cte->cterecursive)
424  ereport(ERROR,
425  (errcode(ERRCODE_SYNTAX_ERROR),
426  errmsg("WITH query is not recursive"),
427  parser_errposition(pstate, cte->location)));
428 
429  /*
430  * SQL requires a WITH list element (CTE) to be "expandable" in order
431  * to allow a search or cycle clause. That is a stronger requirement
432  * than just being recursive. It basically means the query expression
433  * looks like
434  *
435  * non-recursive query UNION [ALL] recursive query
436  *
437  * and that the recursive query is not itself a set operation.
438  *
439  * As of this writing, most of these criteria are already satisfied by
440  * all recursive CTEs allowed by PostgreSQL. In the future, if
441  * further variants recursive CTEs are accepted, there might be
442  * further checks required here to determine what is "expandable".
443  */
444 
445  ctequery = castNode(Query, cte->ctequery);
446  Assert(ctequery->setOperations);
447  sos = castNode(SetOperationStmt, ctequery->setOperations);
448 
449  /*
450  * This left side check is not required for expandability, but
451  * rewriteSearchAndCycle() doesn't currently have support for it, so
452  * we catch it here.
453  */
454  if (!IsA(sos->larg, RangeTblRef))
455  ereport(ERROR,
456  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
457  errmsg("with a SEARCH or CYCLE clause, the left side of the UNION must be a SELECT")));
458 
459  if (!IsA(sos->rarg, RangeTblRef))
460  ereport(ERROR,
461  (errcode(ERRCODE_SYNTAX_ERROR),
462  errmsg("with a SEARCH or CYCLE clause, the right side of the UNION must be a SELECT")));
463  }
464 
465  if (search_clause)
466  {
467  ListCell *lc;
468  List *seen = NIL;
469 
470  foreach(lc, search_clause->search_col_list)
471  {
472  String *colname = lfirst_node(String, lc);
473 
474  if (!list_member(cte->ctecolnames, colname))
475  ereport(ERROR,
476  (errcode(ERRCODE_SYNTAX_ERROR),
477  errmsg("search column \"%s\" not in WITH query column list",
478  strVal(colname)),
479  parser_errposition(pstate, search_clause->location)));
480 
481  if (list_member(seen, colname))
482  ereport(ERROR,
483  (errcode(ERRCODE_DUPLICATE_COLUMN),
484  errmsg("search column \"%s\" specified more than once",
485  strVal(colname)),
486  parser_errposition(pstate, search_clause->location)));
487  seen = lappend(seen, colname);
488  }
489 
490  if (list_member(cte->ctecolnames, makeString(search_clause->search_seq_column)))
491  ereport(ERROR,
492  errcode(ERRCODE_SYNTAX_ERROR),
493  errmsg("search sequence column name \"%s\" already used in WITH query column list",
494  search_clause->search_seq_column),
495  parser_errposition(pstate, search_clause->location));
496  }
497 
498  if (cycle_clause)
499  {
500  ListCell *lc;
501  List *seen = NIL;
502 
503  foreach(lc, cycle_clause->cycle_col_list)
504  {
505  String *colname = lfirst_node(String, lc);
506 
507  if (!list_member(cte->ctecolnames, colname))
508  ereport(ERROR,
509  (errcode(ERRCODE_SYNTAX_ERROR),
510  errmsg("cycle column \"%s\" not in WITH query column list",
511  strVal(colname)),
512  parser_errposition(pstate, cycle_clause->location)));
513 
514  if (list_member(seen, colname))
515  ereport(ERROR,
516  (errcode(ERRCODE_DUPLICATE_COLUMN),
517  errmsg("cycle column \"%s\" specified more than once",
518  strVal(colname)),
519  parser_errposition(pstate, cycle_clause->location)));
520  seen = lappend(seen, colname);
521  }
522 
523  if (list_member(cte->ctecolnames, makeString(cycle_clause->cycle_mark_column)))
524  ereport(ERROR,
525  errcode(ERRCODE_SYNTAX_ERROR),
526  errmsg("cycle mark column name \"%s\" already used in WITH query column list",
527  cycle_clause->cycle_mark_column),
528  parser_errposition(pstate, cycle_clause->location));
529 
530  if (list_member(cte->ctecolnames, makeString(cycle_clause->cycle_path_column)))
531  ereport(ERROR,
532  errcode(ERRCODE_SYNTAX_ERROR),
533  errmsg("cycle path column name \"%s\" already used in WITH query column list",
534  cycle_clause->cycle_path_column),
535  parser_errposition(pstate, cycle_clause->location));
536 
537  if (strcmp(cycle_clause->cycle_mark_column,
538  cycle_clause->cycle_path_column) == 0)
539  ereport(ERROR,
540  errcode(ERRCODE_SYNTAX_ERROR),
541  errmsg("cycle mark column name and cycle path column name are the same"),
542  parser_errposition(pstate, cycle_clause->location));
543  }
544 
545  if (search_clause && cycle_clause)
546  {
547  if (strcmp(search_clause->search_seq_column,
548  cycle_clause->cycle_mark_column) == 0)
549  ereport(ERROR,
550  errcode(ERRCODE_SYNTAX_ERROR),
551  errmsg("search sequence column name and cycle mark column name are the same"),
552  parser_errposition(pstate, search_clause->location));
553 
554  if (strcmp(search_clause->search_seq_column,
555  cycle_clause->cycle_path_column) == 0)
556  ereport(ERROR,
557  errcode(ERRCODE_SYNTAX_ERROR),
558  errmsg("search sequence column name and cycle path column name are the same"),
559  parser_errposition(pstate, search_clause->location));
560  }
561 }
#define OidIsValid(objectId)
Definition: c.h:759
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
bool list_member(const List *list, const void *datum)
Definition: list.c:660
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1061
Oid get_negator(Oid opno)
Definition: lsyscache.c:1515
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:284
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:788
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1314
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
@ CMD_SELECT
Definition: nodes.h:276
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Oid select_common_collation(ParseState *pstate, List *exprs, bool none_ok)
void analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
Definition: parse_cte.c:576
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
#define GetCTETargetList(cte)
Definition: parsenodes.h:1659
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:224
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
#define lfirst_int(lc)
Definition: pg_list.h:173
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define list_make2(x1, x2)
Definition: pg_list.h:214
unsigned int Oid
Definition: postgres_ext.h:31
char * cycle_path_column
Definition: parsenodes.h:1613
Node * cycle_mark_default
Definition: parsenodes.h:1612
Oid cycle_mark_collation
Definition: parsenodes.h:1618
List * cycle_col_list
Definition: parsenodes.h:1609
char * cycle_mark_column
Definition: parsenodes.h:1610
Node * cycle_mark_value
Definition: parsenodes.h:1611
char * search_seq_column
Definition: parsenodes.h:1602
List * search_col_list
Definition: parsenodes.h:1600
Definition: pg_list.h:54
Definition: nodes.h:129
ParseState * parentParseState
Definition: parse_node.h:191
Node * setOperations
Definition: parsenodes.h:217
CmdType commandType
Definition: parsenodes.h:128
Node * utilityStmt
Definition: parsenodes.h:143
Definition: value.h:64
Expr * expr
Definition: primnodes.h:1886
AttrNumber resno
Definition: primnodes.h:1888
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339
#define TYPECACHE_EQ_OPR
Definition: typcache.h:136
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:82

References analyzeCTETargetList(), Assert(), castNode, CMD_SELECT, coerce_to_common_type(), Query::commandType, CommonTableExpr::ctename, CommonTableExpr::ctequery, CTECycleClause::cycle_col_list, CTECycleClause::cycle_mark_collation, CTECycleClause::cycle_mark_column, CTECycleClause::cycle_mark_default, CTECycleClause::cycle_mark_neop, CTECycleClause::cycle_mark_type, CTECycleClause::cycle_mark_typmod, CTECycleClause::cycle_mark_value, CTECycleClause::cycle_path_column, elog(), TypeCacheEntry::eq_opr, ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, EXPR_KIND_CYCLE_MARK, exprCollation(), exprLocation(), exprType(), exprTypmod(), format_type_be(), format_type_with_typemod(), get_collation_name(), get_negator(), GetCTETargetList, if(), IsA, lappend(), SetOperationStmt::larg, lfirst, lfirst_int, lfirst_node, lfirst_oid, list_head(), list_make2, list_member(), lnext(), CTESearchClause::location, CTECycleClause::location, CommonTableExpr::location, lookup_type_cache(), makeString(), NIL, OidIsValid, ParseState::parentParseState, parse_sub_analyze(), parser_errposition(), SetOperationStmt::rarg, TargetEntry::resno, CTESearchClause::search_col_list, CTESearchClause::search_seq_column, select_common_collation(), select_common_type(), select_common_typmod(), Query::setOperations, strVal, transformExpr(), TYPECACHE_EQ_OPR, and Query::utilityStmt.

Referenced by transformWithClause().

◆ analyzeCTETargetList()

void analyzeCTETargetList ( ParseState pstate,
CommonTableExpr cte,
List tlist 
)

Definition at line 576 of file parse_cte.c.

577 {
578  int numaliases;
579  int varattno;
580  ListCell *tlistitem;
581 
582  /* Not done already ... */
583  Assert(cte->ctecolnames == NIL);
584 
585  /*
586  * We need to determine column names, types, and collations. The alias
587  * column names override anything coming from the query itself. (Note:
588  * the SQL spec says that the alias list must be empty or exactly as long
589  * as the output column set; but we allow it to be shorter for consistency
590  * with Alias handling.)
591  */
592  cte->ctecolnames = copyObject(cte->aliascolnames);
593  cte->ctecoltypes = cte->ctecoltypmods = cte->ctecolcollations = NIL;
594  numaliases = list_length(cte->aliascolnames);
595  varattno = 0;
596  foreach(tlistitem, tlist)
597  {
598  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
599  Oid coltype;
600  int32 coltypmod;
601  Oid colcoll;
602 
603  if (te->resjunk)
604  continue;
605  varattno++;
606  Assert(varattno == te->resno);
607  if (varattno > numaliases)
608  {
609  char *attrname;
610 
611  attrname = pstrdup(te->resname);
612  cte->ctecolnames = lappend(cte->ctecolnames, makeString(attrname));
613  }
614  coltype = exprType((Node *) te->expr);
615  coltypmod = exprTypmod((Node *) te->expr);
616  colcoll = exprCollation((Node *) te->expr);
617 
618  /*
619  * If the CTE is recursive, force the exposed column type of any
620  * "unknown" column to "text". We must deal with this here because
621  * we're called on the non-recursive term before there's been any
622  * attempt to force unknown output columns to some other type. We
623  * have to resolve unknowns before looking at the recursive term.
624  *
625  * The column might contain 'foo' COLLATE "bar", so don't override
626  * collation if it's already set.
627  */
628  if (cte->cterecursive && coltype == UNKNOWNOID)
629  {
630  coltype = TEXTOID;
631  coltypmod = -1; /* should be -1 already, but be sure */
632  if (!OidIsValid(colcoll))
633  colcoll = DEFAULT_COLLATION_OID;
634  }
635  cte->ctecoltypes = lappend_oid(cte->ctecoltypes, coltype);
636  cte->ctecoltypmods = lappend_int(cte->ctecoltypmods, coltypmod);
637  cte->ctecolcollations = lappend_oid(cte->ctecolcollations, colcoll);
638  }
639  if (varattno < numaliases)
640  ereport(ERROR,
641  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
642  errmsg("WITH query \"%s\" has %d columns available but %d columns specified",
643  cte->ctename, varattno, numaliases),
644  parser_errposition(pstate, cte->location)));
645 }
signed int int32
Definition: c.h:478
List * lappend_int(List *list, int datum)
Definition: list.c:356
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
char * pstrdup(const char *in)
Definition: mcxt.c:1644
#define copyObject(obj)
Definition: nodes.h:244
static int list_length(const List *l)
Definition: pg_list.h:152

References Assert(), copyObject, CommonTableExpr::ctename, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), lappend(), lappend_int(), lappend_oid(), lfirst, list_length(), CommonTableExpr::location, makeString(), NIL, OidIsValid, parser_errposition(), pstrdup(), and TargetEntry::resno.

Referenced by analyzeCTE(), and determineRecursiveColTypes().

◆ checkWellFormedRecursion()

static void checkWellFormedRecursion ( CteState cstate)
static

Definition at line 855 of file parse_cte.c.

856 {
857  int i;
858 
859  for (i = 0; i < cstate->numitems; i++)
860  {
861  CommonTableExpr *cte = cstate->items[i].cte;
862  SelectStmt *stmt = (SelectStmt *) cte->ctequery;
863 
864  Assert(!IsA(stmt, Query)); /* not analyzed yet */
865 
866  /* Ignore items that weren't found to be recursive */
867  if (!cte->cterecursive)
868  continue;
869 
870  /* Must be a SELECT statement */
871  if (!IsA(stmt, SelectStmt))
872  ereport(ERROR,
873  (errcode(ERRCODE_INVALID_RECURSION),
874  errmsg("recursive query \"%s\" must not contain data-modifying statements",
875  cte->ctename),
876  parser_errposition(cstate->pstate, cte->location)));
877 
878  /* Must have top-level UNION */
879  if (stmt->op != SETOP_UNION)
880  ereport(ERROR,
881  (errcode(ERRCODE_INVALID_RECURSION),
882  errmsg("recursive query \"%s\" does not have the form non-recursive-term UNION [ALL] recursive-term",
883  cte->ctename),
884  parser_errposition(cstate->pstate, cte->location)));
885 
886  /* The left-hand operand mustn't contain self-reference at all */
887  cstate->curitem = i;
888  cstate->innerwiths = NIL;
889  cstate->selfrefcount = 0;
891  checkWellFormedRecursionWalker((Node *) stmt->larg, cstate);
892  Assert(cstate->innerwiths == NIL);
893 
894  /* Right-hand operand should contain one reference in a valid place */
895  cstate->curitem = i;
896  cstate->innerwiths = NIL;
897  cstate->selfrefcount = 0;
898  cstate->context = RECURSION_OK;
899  checkWellFormedRecursionWalker((Node *) stmt->rarg, cstate);
900  Assert(cstate->innerwiths == NIL);
901  if (cstate->selfrefcount != 1) /* shouldn't happen */
902  elog(ERROR, "missing recursive reference");
903 
904  /* WITH mustn't contain self-reference, either */
905  if (stmt->withClause)
906  {
907  cstate->curitem = i;
908  cstate->innerwiths = NIL;
909  cstate->selfrefcount = 0;
910  cstate->context = RECURSION_SUBLINK;
911  checkWellFormedRecursionWalker((Node *) stmt->withClause->ctes,
912  cstate);
913  Assert(cstate->innerwiths == NIL);
914  }
915 
916  /*
917  * Disallow ORDER BY and similar decoration atop the UNION. These
918  * don't make sense because it's impossible to figure out what they
919  * mean when we have only part of the recursive query's results. (If
920  * we did allow them, we'd have to check for recursive references
921  * inside these subtrees.)
922  */
923  if (stmt->sortClause)
924  ereport(ERROR,
925  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
926  errmsg("ORDER BY in a recursive query is not implemented"),
927  parser_errposition(cstate->pstate,
928  exprLocation((Node *) stmt->sortClause))));
929  if (stmt->limitOffset)
930  ereport(ERROR,
931  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
932  errmsg("OFFSET in a recursive query is not implemented"),
933  parser_errposition(cstate->pstate,
934  exprLocation(stmt->limitOffset))));
935  if (stmt->limitCount)
936  ereport(ERROR,
937  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
938  errmsg("LIMIT in a recursive query is not implemented"),
939  parser_errposition(cstate->pstate,
940  exprLocation(stmt->limitCount))));
941  if (stmt->lockingClause)
942  ereport(ERROR,
943  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
944  errmsg("FOR UPDATE/SHARE in a recursive query is not implemented"),
945  parser_errposition(cstate->pstate,
946  exprLocation((Node *) stmt->lockingClause))));
947  }
948 }
#define stmt
Definition: indent_codes.h:59
int i
Definition: isn.c:73
static bool checkWellFormedRecursionWalker(Node *node, CteState *cstate)
Definition: parse_cte.c:954
@ SETOP_UNION
Definition: parsenodes.h:1935
CommonTableExpr * cte
Definition: parse_cte.c:65
int selfrefcount
Definition: parse_cte.c:81
RecursionContext context
Definition: parse_cte.c:82
ParseState * pstate
Definition: parse_cte.c:74
int curitem
Definition: parse_cte.c:78
int numitems
Definition: parse_cte.c:76
List * innerwiths
Definition: parse_cte.c:79
CteItem * items
Definition: parse_cte.c:75

References Assert(), checkWellFormedRecursionWalker(), CteState::context, CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, CteState::curitem, elog(), ereport, errcode(), errmsg(), ERROR, exprLocation(), i, CteState::innerwiths, IsA, CteState::items, CommonTableExpr::location, NIL, CteState::numitems, parser_errposition(), CteState::pstate, RECURSION_NONRECURSIVETERM, RECURSION_OK, RECURSION_SUBLINK, CteState::selfrefcount, SETOP_UNION, and stmt.

Referenced by transformWithClause().

◆ checkWellFormedRecursionWalker()

static bool checkWellFormedRecursionWalker ( Node node,
CteState cstate 
)
static

Definition at line 954 of file parse_cte.c.

955 {
956  RecursionContext save_context = cstate->context;
957 
958  if (node == NULL)
959  return false;
960  if (IsA(node, RangeVar))
961  {
962  RangeVar *rv = (RangeVar *) node;
963 
964  /* If unqualified name, might be a CTE reference */
965  if (!rv->schemaname)
966  {
967  ListCell *lc;
968  CommonTableExpr *mycte;
969 
970  /* ... but first see if it's captured by an inner WITH */
971  foreach(lc, cstate->innerwiths)
972  {
973  List *withlist = (List *) lfirst(lc);
974  ListCell *lc2;
975 
976  foreach(lc2, withlist)
977  {
978  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
979 
980  if (strcmp(rv->relname, cte->ctename) == 0)
981  return false; /* yes, so bail out */
982  }
983  }
984 
985  /* No, could be a reference to the query level we are working on */
986  mycte = cstate->items[cstate->curitem].cte;
987  if (strcmp(rv->relname, mycte->ctename) == 0)
988  {
989  /* Found a recursive reference to the active query */
990  if (cstate->context != RECURSION_OK)
991  ereport(ERROR,
992  (errcode(ERRCODE_INVALID_RECURSION),
994  mycte->ctename),
995  parser_errposition(cstate->pstate,
996  rv->location)));
997  /* Count references */
998  if (++(cstate->selfrefcount) > 1)
999  ereport(ERROR,
1000  (errcode(ERRCODE_INVALID_RECURSION),
1001  errmsg("recursive reference to query \"%s\" must not appear more than once",
1002  mycte->ctename),
1003  parser_errposition(cstate->pstate,
1004  rv->location)));
1005  }
1006  }
1007  return false;
1008  }
1009  if (IsA(node, SelectStmt))
1010  {
1011  SelectStmt *stmt = (SelectStmt *) node;
1012  ListCell *lc;
1013 
1014  if (stmt->withClause)
1015  {
1016  if (stmt->withClause->recursive)
1017  {
1018  /*
1019  * In the RECURSIVE case, all query names of the WITH are
1020  * visible to all WITH items as well as the main query. So
1021  * push them all on, process, pop them all off.
1022  */
1023  cstate->innerwiths = lcons(stmt->withClause->ctes,
1024  cstate->innerwiths);
1025  foreach(lc, stmt->withClause->ctes)
1026  {
1027  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1028 
1029  (void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
1030  }
1032  cstate->innerwiths = list_delete_first(cstate->innerwiths);
1033  }
1034  else
1035  {
1036  /*
1037  * In the non-RECURSIVE case, query names are visible to the
1038  * WITH items after them and to the main query.
1039  */
1040  cstate->innerwiths = lcons(NIL, cstate->innerwiths);
1041  foreach(lc, stmt->withClause->ctes)
1042  {
1043  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1044  ListCell *cell1;
1045 
1046  (void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
1047  /* note that recursion could mutate innerwiths list */
1048  cell1 = list_head(cstate->innerwiths);
1049  lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
1050  }
1052  cstate->innerwiths = list_delete_first(cstate->innerwiths);
1053  }
1054  }
1055  else
1057  /* We're done examining the SelectStmt */
1058  return false;
1059  }
1060  if (IsA(node, WithClause))
1061  {
1062  /*
1063  * Prevent raw_expression_tree_walker from recursing directly into a
1064  * WITH clause. We need that to happen only under the control of the
1065  * code above.
1066  */
1067  return false;
1068  }
1069  if (IsA(node, JoinExpr))
1070  {
1071  JoinExpr *j = (JoinExpr *) node;
1072 
1073  switch (j->jointype)
1074  {
1075  case JOIN_INNER:
1076  checkWellFormedRecursionWalker(j->larg, cstate);
1077  checkWellFormedRecursionWalker(j->rarg, cstate);
1078  checkWellFormedRecursionWalker(j->quals, cstate);
1079  break;
1080  case JOIN_LEFT:
1081  checkWellFormedRecursionWalker(j->larg, cstate);
1082  if (save_context == RECURSION_OK)
1083  cstate->context = RECURSION_OUTERJOIN;
1084  checkWellFormedRecursionWalker(j->rarg, cstate);
1085  cstate->context = save_context;
1086  checkWellFormedRecursionWalker(j->quals, cstate);
1087  break;
1088  case JOIN_FULL:
1089  if (save_context == RECURSION_OK)
1090  cstate->context = RECURSION_OUTERJOIN;
1091  checkWellFormedRecursionWalker(j->larg, cstate);
1092  checkWellFormedRecursionWalker(j->rarg, cstate);
1093  cstate->context = save_context;
1094  checkWellFormedRecursionWalker(j->quals, cstate);
1095  break;
1096  case JOIN_RIGHT:
1097  if (save_context == RECURSION_OK)
1098  cstate->context = RECURSION_OUTERJOIN;
1099  checkWellFormedRecursionWalker(j->larg, cstate);
1100  cstate->context = save_context;
1101  checkWellFormedRecursionWalker(j->rarg, cstate);
1102  checkWellFormedRecursionWalker(j->quals, cstate);
1103  break;
1104  default:
1105  elog(ERROR, "unrecognized join type: %d",
1106  (int) j->jointype);
1107  }
1108  return false;
1109  }
1110  if (IsA(node, SubLink))
1111  {
1112  SubLink *sl = (SubLink *) node;
1113 
1114  /*
1115  * we intentionally override outer context, since subquery is
1116  * independent
1117  */
1118  cstate->context = RECURSION_SUBLINK;
1120  cstate->context = save_context;
1122  return false;
1123  }
1124  return raw_expression_tree_walker(node,
1126  (void *) cstate);
1127 }
int j
Definition: isn.c:74
List * list_delete_first(List *list)
Definition: list.c:942
List * lcons(void *datum, List *list)
Definition: list.c:494
#define raw_expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:174
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_INNER
Definition: nodes.h:304
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305
static void checkWellFormedSelectStmt(SelectStmt *stmt, CteState *cstate)
Definition: parse_cte.c:1134
static const char *const recursion_errormsgs[]
Definition: parse_cte.c:42
int location
Definition: primnodes.h:86
char * relname
Definition: primnodes.h:74
char * schemaname
Definition: primnodes.h:71

References checkWellFormedSelectStmt(), CteState::context, CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, CteState::curitem, elog(), ereport, errcode(), errmsg(), ERROR, CteState::innerwiths, IsA, CteState::items, j, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, lappend(), lcons(), lfirst, list_delete_first(), list_head(), RangeVar::location, NIL, parser_errposition(), CteState::pstate, raw_expression_tree_walker, recursion_errormsgs, RECURSION_OK, RECURSION_OUTERJOIN, RECURSION_SUBLINK, RangeVar::relname, RangeVar::schemaname, CteState::selfrefcount, stmt, SubLink::subselect, and SubLink::testexpr.

Referenced by checkWellFormedRecursion(), and checkWellFormedSelectStmt().

◆ checkWellFormedSelectStmt()

static void checkWellFormedSelectStmt ( SelectStmt stmt,
CteState cstate 
)
static

Definition at line 1134 of file parse_cte.c.

1135 {
1136  RecursionContext save_context = cstate->context;
1137 
1138  if (save_context != RECURSION_OK)
1139  {
1140  /* just recurse without changing state */
1143  (void *) cstate);
1144  }
1145  else
1146  {
1147  switch (stmt->op)
1148  {
1149  case SETOP_NONE:
1150  case SETOP_UNION:
1153  (void *) cstate);
1154  break;
1155  case SETOP_INTERSECT:
1156  if (stmt->all)
1157  cstate->context = RECURSION_INTERSECT;
1159  cstate);
1161  cstate);
1162  cstate->context = save_context;
1163  checkWellFormedRecursionWalker((Node *) stmt->sortClause,
1164  cstate);
1165  checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
1166  cstate);
1167  checkWellFormedRecursionWalker((Node *) stmt->limitCount,
1168  cstate);
1169  checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
1170  cstate);
1171  /* stmt->withClause is intentionally ignored here */
1172  break;
1173  case SETOP_EXCEPT:
1174  if (stmt->all)
1175  cstate->context = RECURSION_EXCEPT;
1177  cstate);
1178  cstate->context = RECURSION_EXCEPT;
1180  cstate);
1181  cstate->context = save_context;
1182  checkWellFormedRecursionWalker((Node *) stmt->sortClause,
1183  cstate);
1184  checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
1185  cstate);
1186  checkWellFormedRecursionWalker((Node *) stmt->limitCount,
1187  cstate);
1188  checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
1189  cstate);
1190  /* stmt->withClause is intentionally ignored here */
1191  break;
1192  default:
1193  elog(ERROR, "unrecognized set op: %d",
1194  (int) stmt->op);
1195  }
1196  }
1197 }
@ SETOP_INTERSECT
Definition: parsenodes.h:1936
@ SETOP_EXCEPT
Definition: parsenodes.h:1937
@ SETOP_NONE
Definition: parsenodes.h:1934

References checkWellFormedRecursionWalker(), CteState::context, elog(), ERROR, raw_expression_tree_walker, RECURSION_EXCEPT, RECURSION_INTERSECT, RECURSION_OK, SETOP_EXCEPT, SETOP_INTERSECT, SETOP_NONE, SETOP_UNION, and stmt.

Referenced by checkWellFormedRecursionWalker().

◆ makeDependencyGraph()

static void makeDependencyGraph ( CteState cstate)
static

Definition at line 653 of file parse_cte.c.

654 {
655  int i;
656 
657  for (i = 0; i < cstate->numitems; i++)
658  {
659  CommonTableExpr *cte = cstate->items[i].cte;
660 
661  cstate->curitem = i;
662  cstate->innerwiths = NIL;
663  makeDependencyGraphWalker((Node *) cte->ctequery, cstate);
664  Assert(cstate->innerwiths == NIL);
665  }
666 
667  TopologicalSort(cstate->pstate, cstate->items, cstate->numitems);
668 }
static void TopologicalSort(ParseState *pstate, CteItem *items, int numitems)
Definition: parse_cte.c:803
static bool makeDependencyGraphWalker(Node *node, CteState *cstate)
Definition: parse_cte.c:675

References Assert(), CteItem::cte, CommonTableExpr::ctequery, CteState::curitem, i, CteState::innerwiths, CteState::items, makeDependencyGraphWalker(), NIL, CteState::numitems, CteState::pstate, and TopologicalSort().

Referenced by transformWithClause().

◆ makeDependencyGraphWalker()

static bool makeDependencyGraphWalker ( Node node,
CteState cstate 
)
static

Definition at line 675 of file parse_cte.c.

676 {
677  if (node == NULL)
678  return false;
679  if (IsA(node, RangeVar))
680  {
681  RangeVar *rv = (RangeVar *) node;
682 
683  /* If unqualified name, might be a CTE reference */
684  if (!rv->schemaname)
685  {
686  ListCell *lc;
687  int i;
688 
689  /* ... but first see if it's captured by an inner WITH */
690  foreach(lc, cstate->innerwiths)
691  {
692  List *withlist = (List *) lfirst(lc);
693  ListCell *lc2;
694 
695  foreach(lc2, withlist)
696  {
697  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
698 
699  if (strcmp(rv->relname, cte->ctename) == 0)
700  return false; /* yes, so bail out */
701  }
702  }
703 
704  /* No, could be a reference to the query level we are working on */
705  for (i = 0; i < cstate->numitems; i++)
706  {
707  CommonTableExpr *cte = cstate->items[i].cte;
708 
709  if (strcmp(rv->relname, cte->ctename) == 0)
710  {
711  int myindex = cstate->curitem;
712 
713  if (i != myindex)
714  {
715  /* Add cross-item dependency */
716  cstate->items[myindex].depends_on =
717  bms_add_member(cstate->items[myindex].depends_on,
718  cstate->items[i].id);
719  }
720  else
721  {
722  /* Found out this one is self-referential */
723  cte->cterecursive = true;
724  }
725  break;
726  }
727  }
728  }
729  return false;
730  }
731  if (IsA(node, SelectStmt))
732  {
733  SelectStmt *stmt = (SelectStmt *) node;
734  ListCell *lc;
735 
736  if (stmt->withClause)
737  {
738  if (stmt->withClause->recursive)
739  {
740  /*
741  * In the RECURSIVE case, all query names of the WITH are
742  * visible to all WITH items as well as the main query. So
743  * push them all on, process, pop them all off.
744  */
745  cstate->innerwiths = lcons(stmt->withClause->ctes,
746  cstate->innerwiths);
747  foreach(lc, stmt->withClause->ctes)
748  {
749  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
750 
751  (void) makeDependencyGraphWalker(cte->ctequery, cstate);
752  }
753  (void) raw_expression_tree_walker(node,
755  (void *) cstate);
756  cstate->innerwiths = list_delete_first(cstate->innerwiths);
757  }
758  else
759  {
760  /*
761  * In the non-RECURSIVE case, query names are visible to the
762  * WITH items after them and to the main query.
763  */
764  cstate->innerwiths = lcons(NIL, cstate->innerwiths);
765  foreach(lc, stmt->withClause->ctes)
766  {
767  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
768  ListCell *cell1;
769 
770  (void) makeDependencyGraphWalker(cte->ctequery, cstate);
771  /* note that recursion could mutate innerwiths list */
772  cell1 = list_head(cstate->innerwiths);
773  lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
774  }
775  (void) raw_expression_tree_walker(node,
777  (void *) cstate);
778  cstate->innerwiths = list_delete_first(cstate->innerwiths);
779  }
780  /* We're done examining the SelectStmt */
781  return false;
782  }
783  /* if no WITH clause, just fall through for normal processing */
784  }
785  if (IsA(node, WithClause))
786  {
787  /*
788  * Prevent raw_expression_tree_walker from recursing directly into a
789  * WITH clause. We need that to happen only under the control of the
790  * code above.
791  */
792  return false;
793  }
794  return raw_expression_tree_walker(node,
796  (void *) cstate);
797 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:755
int id
Definition: parse_cte.c:66
Bitmapset * depends_on
Definition: parse_cte.c:67

References bms_add_member(), CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, CteState::curitem, CteItem::depends_on, i, CteItem::id, CteState::innerwiths, IsA, CteState::items, lappend(), lcons(), lfirst, list_delete_first(), list_head(), NIL, CteState::numitems, raw_expression_tree_walker, RangeVar::relname, RangeVar::schemaname, and stmt.

Referenced by makeDependencyGraph().

◆ TopologicalSort()

static void TopologicalSort ( ParseState pstate,
CteItem items,
int  numitems 
)
static

Definition at line 803 of file parse_cte.c.

804 {
805  int i,
806  j;
807 
808  /* for each position in sequence ... */
809  for (i = 0; i < numitems; i++)
810  {
811  /* ... scan the remaining items to find one that has no dependencies */
812  for (j = i; j < numitems; j++)
813  {
814  if (bms_is_empty(items[j].depends_on))
815  break;
816  }
817 
818  /* if we didn't find one, the dependency graph has a cycle */
819  if (j >= numitems)
820  ereport(ERROR,
821  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
822  errmsg("mutual recursion between WITH items is not implemented"),
823  parser_errposition(pstate, items[i].cte->location)));
824 
825  /*
826  * Found one. Move it to front and remove it from every other item's
827  * dependencies.
828  */
829  if (i != j)
830  {
831  CteItem tmp;
832 
833  tmp = items[i];
834  items[i] = items[j];
835  items[j] = tmp;
836  }
837 
838  /*
839  * Items up through i are known to have no dependencies left, so we
840  * can skip them in this loop.
841  */
842  for (j = i + 1; j < numitems; j++)
843  {
844  items[j].depends_on = bms_del_member(items[j].depends_on,
845  items[i].id);
846  }
847  }
848 }
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:792
#define bms_is_empty(a)
Definition: bitmapset.h:105

References bms_del_member(), bms_is_empty, CteItem::depends_on, ereport, errcode(), errmsg(), ERROR, i, j, and parser_errposition().

Referenced by makeDependencyGraph().

◆ transformWithClause()

List* transformWithClause ( ParseState pstate,
WithClause withClause 
)

Definition at line 109 of file parse_cte.c.

110 {
111  ListCell *lc;
112 
113  /* Only one WITH clause per query level */
114  Assert(pstate->p_ctenamespace == NIL);
115  Assert(pstate->p_future_ctes == NIL);
116 
117  /*
118  * For either type of WITH, there must not be duplicate CTE names in the
119  * list. Check this right away so we needn't worry later.
120  *
121  * Also, tentatively mark each CTE as non-recursive, and initialize its
122  * reference count to zero, and set pstate->p_hasModifyingCTE if needed.
123  */
124  foreach(lc, withClause->ctes)
125  {
126  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
127  ListCell *rest;
128 
129  /* MERGE is allowed by parser, but unimplemented. Reject for now */
130  if (IsA(cte->ctequery, MergeStmt))
131  ereport(ERROR,
132  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
133  errmsg("MERGE not supported in WITH query"),
134  parser_errposition(pstate, cte->location));
135 
136  for_each_cell(rest, withClause->ctes, lnext(withClause->ctes, lc))
137  {
138  CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(rest);
139 
140  if (strcmp(cte->ctename, cte2->ctename) == 0)
141  ereport(ERROR,
142  (errcode(ERRCODE_DUPLICATE_ALIAS),
143  errmsg("WITH query name \"%s\" specified more than once",
144  cte2->ctename),
145  parser_errposition(pstate, cte2->location)));
146  }
147 
148  cte->cterecursive = false;
149  cte->cterefcount = 0;
150 
151  if (!IsA(cte->ctequery, SelectStmt))
152  {
153  /* must be a data-modifying statement */
154  Assert(IsA(cte->ctequery, InsertStmt) ||
155  IsA(cte->ctequery, UpdateStmt) ||
156  IsA(cte->ctequery, DeleteStmt));
157 
158  pstate->p_hasModifyingCTE = true;
159  }
160  }
161 
162  if (withClause->recursive)
163  {
164  /*
165  * For WITH RECURSIVE, we rearrange the list elements if needed to
166  * eliminate forward references. First, build a work array and set up
167  * the data structure needed by the tree walkers.
168  */
169  CteState cstate;
170  int i;
171 
172  cstate.pstate = pstate;
173  cstate.numitems = list_length(withClause->ctes);
174  cstate.items = (CteItem *) palloc0(cstate.numitems * sizeof(CteItem));
175  i = 0;
176  foreach(lc, withClause->ctes)
177  {
178  cstate.items[i].cte = (CommonTableExpr *) lfirst(lc);
179  cstate.items[i].id = i;
180  i++;
181  }
182 
183  /*
184  * Find all the dependencies and sort the CteItems into a safe
185  * processing order. Also, mark CTEs that contain self-references.
186  */
187  makeDependencyGraph(&cstate);
188 
189  /*
190  * Check that recursive queries are well-formed.
191  */
192  checkWellFormedRecursion(&cstate);
193 
194  /*
195  * Set up the ctenamespace for parse analysis. Per spec, all the WITH
196  * items are visible to all others, so stuff them all in before parse
197  * analysis. We build the list in safe processing order so that the
198  * planner can process the queries in sequence.
199  */
200  for (i = 0; i < cstate.numitems; i++)
201  {
202  CommonTableExpr *cte = cstate.items[i].cte;
203 
204  pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
205  }
206 
207  /*
208  * Do parse analysis in the order determined by the topological sort.
209  */
210  for (i = 0; i < cstate.numitems; i++)
211  {
212  CommonTableExpr *cte = cstate.items[i].cte;
213 
214  analyzeCTE(pstate, cte);
215  }
216  }
217  else
218  {
219  /*
220  * For non-recursive WITH, just analyze each CTE in sequence and then
221  * add it to the ctenamespace. This corresponds to the spec's
222  * definition of the scope of each WITH name. However, to allow error
223  * reports to be aware of the possibility of an erroneous reference,
224  * we maintain a list in p_future_ctes of the not-yet-visible CTEs.
225  */
226  pstate->p_future_ctes = list_copy(withClause->ctes);
227 
228  foreach(lc, withClause->ctes)
229  {
230  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
231 
232  analyzeCTE(pstate, cte);
233  pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
234  pstate->p_future_ctes = list_delete_first(pstate->p_future_ctes);
235  }
236  }
237 
238  return pstate->p_ctenamespace;
239 }
List * list_copy(const List *oldlist)
Definition: list.c:1572
void * palloc0(Size size)
Definition: mcxt.c:1257
static void makeDependencyGraph(CteState *cstate)
Definition: parse_cte.c:653
static void checkWellFormedRecursion(CteState *cstate)
Definition: parse_cte.c:855
static void analyzeCTE(ParseState *pstate, CommonTableExpr *cte)
Definition: parse_cte.c:248
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438
List * p_ctenamespace
Definition: parse_node.h:203
bool p_hasModifyingCTE
Definition: parse_node.h:226
List * p_future_ctes
Definition: parse_node.h:204
List * ctes
Definition: parsenodes.h:1549
bool recursive
Definition: parsenodes.h:1550

References analyzeCTE(), Assert(), checkWellFormedRecursion(), CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, WithClause::ctes, ereport, errcode(), errmsg(), ERROR, for_each_cell, i, CteItem::id, IsA, CteState::items, lappend(), lfirst, list_copy(), list_delete_first(), list_length(), lnext(), CommonTableExpr::location, makeDependencyGraph(), NIL, CteState::numitems, ParseState::p_ctenamespace, ParseState::p_future_ctes, ParseState::p_hasModifyingCTE, palloc0(), parser_errposition(), CteState::pstate, and WithClause::recursive.

Referenced by transformDeleteStmt(), transformInsertStmt(), transformMergeStmt(), transformSelectStmt(), transformSetOperationStmt(), transformUpdateStmt(), and transformValuesClause().

Variable Documentation

◆ recursion_errormsgs

const char* const recursion_errormsgs[]
static
Initial value:
= {
NULL,
gettext_noop("recursive reference to query \"%s\" must not appear within its non-recursive term"),
gettext_noop("recursive reference to query \"%s\" must not appear within a subquery"),
gettext_noop("recursive reference to query \"%s\" must not appear within an outer join"),
gettext_noop("recursive reference to query \"%s\" must not appear within INTERSECT"),
gettext_noop("recursive reference to query \"%s\" must not appear within EXCEPT")
}
#define gettext_noop(x)
Definition: c.h:1204

Definition at line 42 of file parse_cte.c.

Referenced by checkWellFormedRecursionWalker().