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 
252  /* Analysis not done already */
253  Assert(!IsA(cte->ctequery, Query));
254 
255  query = parse_sub_analyze(cte->ctequery, pstate, cte, false, true);
256  cte->ctequery = (Node *) query;
257 
258  /*
259  * Check that we got something reasonable. These first two cases should
260  * be prevented by the grammar.
261  */
262  if (!IsA(query, Query))
263  elog(ERROR, "unexpected non-Query statement in WITH");
264  if (query->utilityStmt != NULL)
265  elog(ERROR, "unexpected utility statement in WITH");
266 
267  /*
268  * We disallow data-modifying WITH except at the top level of a query,
269  * because it's not clear when such a modification should be executed.
270  */
271  if (query->commandType != CMD_SELECT &&
272  pstate->parentParseState != NULL)
273  ereport(ERROR,
274  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
275  errmsg("WITH clause containing a data-modifying statement must be at the top level"),
276  parser_errposition(pstate, cte->location)));
277 
278  /*
279  * CTE queries are always marked not canSetTag. (Currently this only
280  * matters for data-modifying statements, for which the flag will be
281  * propagated to the ModifyTable plan node.)
282  */
283  query->canSetTag = false;
284 
285  if (!cte->cterecursive)
286  {
287  /* Compute the output column names/types if not done yet */
288  analyzeCTETargetList(pstate, cte, GetCTETargetList(cte));
289  }
290  else
291  {
292  /*
293  * Verify that the previously determined output column types and
294  * collations match what the query really produced. We have to check
295  * this because the recursive term could have overridden the
296  * non-recursive term, and we don't have any easy way to fix that.
297  */
298  ListCell *lctlist,
299  *lctyp,
300  *lctypmod,
301  *lccoll;
302  int varattno;
303 
304  lctyp = list_head(cte->ctecoltypes);
305  lctypmod = list_head(cte->ctecoltypmods);
306  lccoll = list_head(cte->ctecolcollations);
307  varattno = 0;
308  foreach(lctlist, GetCTETargetList(cte))
309  {
310  TargetEntry *te = (TargetEntry *) lfirst(lctlist);
311  Node *texpr;
312 
313  if (te->resjunk)
314  continue;
315  varattno++;
316  Assert(varattno == te->resno);
317  if (lctyp == NULL || lctypmod == NULL || lccoll == NULL) /* shouldn't happen */
318  elog(ERROR, "wrong number of output columns in WITH");
319  texpr = (Node *) te->expr;
320  if (exprType(texpr) != lfirst_oid(lctyp) ||
321  exprTypmod(texpr) != lfirst_int(lctypmod))
322  ereport(ERROR,
323  (errcode(ERRCODE_DATATYPE_MISMATCH),
324  errmsg("recursive query \"%s\" column %d has type %s in non-recursive term but type %s overall",
325  cte->ctename, varattno,
327  lfirst_int(lctypmod)),
329  exprTypmod(texpr))),
330  errhint("Cast the output of the non-recursive term to the correct type."),
331  parser_errposition(pstate, exprLocation(texpr))));
332  if (exprCollation(texpr) != lfirst_oid(lccoll))
333  ereport(ERROR,
334  (errcode(ERRCODE_COLLATION_MISMATCH),
335  errmsg("recursive query \"%s\" column %d has collation \"%s\" in non-recursive term but collation \"%s\" overall",
336  cte->ctename, varattno,
339  errhint("Use the COLLATE clause to set the collation of the non-recursive term."),
340  parser_errposition(pstate, exprLocation(texpr))));
341  lctyp = lnext(cte->ctecoltypes, lctyp);
342  lctypmod = lnext(cte->ctecoltypmods, lctypmod);
343  lccoll = lnext(cte->ctecolcollations, lccoll);
344  }
345  if (lctyp != NULL || lctypmod != NULL || lccoll != NULL) /* shouldn't happen */
346  elog(ERROR, "wrong number of output columns in WITH");
347  }
348 
349  if (cte->search_clause || cte->cycle_clause)
350  {
351  Query *ctequery;
352  SetOperationStmt *sos;
353 
354  if (!cte->cterecursive)
355  ereport(ERROR,
356  (errcode(ERRCODE_SYNTAX_ERROR),
357  errmsg("WITH query is not recursive"),
358  parser_errposition(pstate, cte->location)));
359 
360  /*
361  * SQL requires a WITH list element (CTE) to be "expandable" in order
362  * to allow a search or cycle clause. That is a stronger requirement
363  * than just being recursive. It basically means the query expression
364  * looks like
365  *
366  * non-recursive query UNION [ALL] recursive query
367  *
368  * and that the recursive query is not itself a set operation.
369  *
370  * As of this writing, most of these criteria are already satisfied by
371  * all recursive CTEs allowed by PostgreSQL. In the future, if
372  * further variants recursive CTEs are accepted, there might be
373  * further checks required here to determine what is "expandable".
374  */
375 
376  ctequery = castNode(Query, cte->ctequery);
377  Assert(ctequery->setOperations);
378  sos = castNode(SetOperationStmt, ctequery->setOperations);
379 
380  /*
381  * This left side check is not required for expandability, but
382  * rewriteSearchAndCycle() doesn't currently have support for it, so
383  * we catch it here.
384  */
385  if (!IsA(sos->larg, RangeTblRef))
386  ereport(ERROR,
387  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
388  errmsg("with a SEARCH or CYCLE clause, the left side of the UNION must be a SELECT")));
389 
390  if (!IsA(sos->rarg, RangeTblRef))
391  ereport(ERROR,
392  (errcode(ERRCODE_SYNTAX_ERROR),
393  errmsg("with a SEARCH or CYCLE clause, the right side of the UNION must be a SELECT")));
394  }
395 
396  if (cte->search_clause)
397  {
398  ListCell *lc;
399  List *seen = NIL;
400 
401  foreach(lc, cte->search_clause->search_col_list)
402  {
403  String *colname = lfirst_node(String, lc);
404 
405  if (!list_member(cte->ctecolnames, colname))
406  ereport(ERROR,
407  (errcode(ERRCODE_SYNTAX_ERROR),
408  errmsg("search column \"%s\" not in WITH query column list",
409  strVal(colname)),
410  parser_errposition(pstate, cte->search_clause->location)));
411 
412  if (list_member(seen, colname))
413  ereport(ERROR,
414  (errcode(ERRCODE_DUPLICATE_COLUMN),
415  errmsg("search column \"%s\" specified more than once",
416  strVal(colname)),
417  parser_errposition(pstate, cte->search_clause->location)));
418  seen = lappend(seen, colname);
419  }
420 
422  ereport(ERROR,
423  errcode(ERRCODE_SYNTAX_ERROR),
424  errmsg("search sequence column name \"%s\" already used in WITH query column list",
426  parser_errposition(pstate, cte->search_clause->location));
427  }
428 
429  if (cte->cycle_clause)
430  {
431  ListCell *lc;
432  List *seen = NIL;
433  TypeCacheEntry *typentry;
434  Oid op;
435 
436  foreach(lc, cte->cycle_clause->cycle_col_list)
437  {
438  String *colname = lfirst_node(String, lc);
439 
440  if (!list_member(cte->ctecolnames, colname))
441  ereport(ERROR,
442  (errcode(ERRCODE_SYNTAX_ERROR),
443  errmsg("cycle column \"%s\" not in WITH query column list",
444  strVal(colname)),
445  parser_errposition(pstate, cte->cycle_clause->location)));
446 
447  if (list_member(seen, colname))
448  ereport(ERROR,
449  (errcode(ERRCODE_DUPLICATE_COLUMN),
450  errmsg("cycle column \"%s\" specified more than once",
451  strVal(colname)),
452  parser_errposition(pstate, cte->cycle_clause->location)));
453  seen = lappend(seen, colname);
454  }
455 
457  ereport(ERROR,
458  errcode(ERRCODE_SYNTAX_ERROR),
459  errmsg("cycle mark column name \"%s\" already used in WITH query column list",
461  parser_errposition(pstate, cte->cycle_clause->location));
462 
467 
469  ereport(ERROR,
470  errcode(ERRCODE_SYNTAX_ERROR),
471  errmsg("cycle path column name \"%s\" already used in WITH query column list",
473  parser_errposition(pstate, cte->cycle_clause->location));
474 
475  if (strcmp(cte->cycle_clause->cycle_mark_column,
476  cte->cycle_clause->cycle_path_column) == 0)
477  ereport(ERROR,
478  errcode(ERRCODE_SYNTAX_ERROR),
479  errmsg("cycle mark column name and cycle path column name are the same"),
480  parser_errposition(pstate, cte->cycle_clause->location));
481 
485  "CYCLE", NULL);
489  "CYCLE/SET/TO");
493  "CYCLE/SET/DEFAULT");
494 
499 
503  true);
504 
506  if (!typentry->eq_opr)
507  ereport(ERROR,
508  errcode(ERRCODE_UNDEFINED_FUNCTION),
509  errmsg("could not identify an equality operator for type %s",
511  op = get_negator(typentry->eq_opr);
512  if (!op)
513  ereport(ERROR,
514  errcode(ERRCODE_UNDEFINED_FUNCTION),
515  errmsg("could not identify an inequality operator for type %s",
517 
518  cte->cycle_clause->cycle_mark_neop = op;
519  }
520 
521  if (cte->search_clause && cte->cycle_clause)
522  {
523  if (strcmp(cte->search_clause->search_seq_column,
524  cte->cycle_clause->cycle_mark_column) == 0)
525  ereport(ERROR,
526  errcode(ERRCODE_SYNTAX_ERROR),
527  errmsg("search sequence column name and cycle mark column name are the same"),
528  parser_errposition(pstate, cte->search_clause->location));
529 
530  if (strcmp(cte->search_clause->search_seq_column,
531  cte->cycle_clause->cycle_path_column) == 0)
532  ereport(ERROR,
533  errcode(ERRCODE_SYNTAX_ERROR),
534  errmsg("search sequence column name and cycle path column name are the same"),
535  parser_errposition(pstate, cte->search_clause->location));
536  }
537 }
int errhint(const char *fmt,...)
Definition: elog.c:1193
int errcode(int sqlerrcode)
Definition: elog.c:735
int errmsg(const char *fmt,...)
Definition: elog.c:946
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
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:266
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
@ CMD_SELECT
Definition: nodes.h:265
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
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:552
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
#define GetCTETargetList(cte)
Definition: parsenodes.h:1583
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:223
#define lfirst(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:174
#define NIL
Definition: pg_list.h:66
#define lfirst_int(lc)
Definition: pg_list.h:171
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
#define lfirst_oid(lc)
Definition: pg_list.h:172
#define list_make2(x1, x2)
Definition: pg_list.h:212
unsigned int Oid
Definition: postgres_ext.h:31
char * cycle_path_column
Definition: parsenodes.h:1552
Node * cycle_mark_default
Definition: parsenodes.h:1551
Oid cycle_mark_collation
Definition: parsenodes.h:1557
List * cycle_col_list
Definition: parsenodes.h:1548
char * cycle_mark_column
Definition: parsenodes.h:1549
Node * cycle_mark_value
Definition: parsenodes.h:1550
char * search_seq_column
Definition: parsenodes.h:1541
List * search_col_list
Definition: parsenodes.h:1539
List * ctecoltypes
Definition: parsenodes.h:1577
CTECycleClause * cycle_clause
Definition: parsenodes.h:1570
CTESearchClause * search_clause
Definition: parsenodes.h:1569
List * ctecolcollations
Definition: parsenodes.h:1579
List * ctecolnames
Definition: parsenodes.h:1576
List * ctecoltypmods
Definition: parsenodes.h:1578
Definition: pg_list.h:52
Definition: nodes.h:118
ParseState * parentParseState
Definition: parse_node.h:184
Node * setOperations
Definition: parsenodes.h:191
bool canSetTag
Definition: parsenodes.h:134
CmdType commandType
Definition: parsenodes.h:124
Node * utilityStmt
Definition: parsenodes.h:136
Definition: value.h:64
Expr * expr
Definition: primnodes.h:1555
AttrNumber resno
Definition: primnodes.h:1556
bool resjunk
Definition: primnodes.h:1562
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(), Query::canSetTag, castNode, CMD_SELECT, coerce_to_common_type(), Query::commandType, CommonTableExpr::ctecolcollations, CommonTableExpr::ctecolnames, CommonTableExpr::ctecoltypes, CommonTableExpr::ctecoltypmods, CommonTableExpr::ctename, CommonTableExpr::ctequery, CommonTableExpr::cterecursive, CommonTableExpr::cycle_clause, 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, ParseState::parentParseState, parse_sub_analyze(), parser_errposition(), SetOperationStmt::rarg, TargetEntry::resjunk, TargetEntry::resno, CommonTableExpr::search_clause, 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 552 of file parse_cte.c.

553 {
554  int numaliases;
555  int varattno;
556  ListCell *tlistitem;
557 
558  /* Not done already ... */
559  Assert(cte->ctecolnames == NIL);
560 
561  /*
562  * We need to determine column names, types, and collations. The alias
563  * column names override anything coming from the query itself. (Note:
564  * the SQL spec says that the alias list must be empty or exactly as long
565  * as the output column set; but we allow it to be shorter for consistency
566  * with Alias handling.)
567  */
568  cte->ctecolnames = copyObject(cte->aliascolnames);
569  cte->ctecoltypes = cte->ctecoltypmods = cte->ctecolcollations = NIL;
570  numaliases = list_length(cte->aliascolnames);
571  varattno = 0;
572  foreach(tlistitem, tlist)
573  {
574  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
575  Oid coltype;
576  int32 coltypmod;
577  Oid colcoll;
578 
579  if (te->resjunk)
580  continue;
581  varattno++;
582  Assert(varattno == te->resno);
583  if (varattno > numaliases)
584  {
585  char *attrname;
586 
587  attrname = pstrdup(te->resname);
588  cte->ctecolnames = lappend(cte->ctecolnames, makeString(attrname));
589  }
590  coltype = exprType((Node *) te->expr);
591  coltypmod = exprTypmod((Node *) te->expr);
592  colcoll = exprCollation((Node *) te->expr);
593 
594  /*
595  * If the CTE is recursive, force the exposed column type of any
596  * "unknown" column to "text". We must deal with this here because
597  * we're called on the non-recursive term before there's been any
598  * attempt to force unknown output columns to some other type. We
599  * have to resolve unknowns before looking at the recursive term.
600  *
601  * The column might contain 'foo' COLLATE "bar", so don't override
602  * collation if it's already set.
603  */
604  if (cte->cterecursive && coltype == UNKNOWNOID)
605  {
606  coltype = TEXTOID;
607  coltypmod = -1; /* should be -1 already, but be sure */
608  if (!OidIsValid(colcoll))
609  colcoll = DEFAULT_COLLATION_OID;
610  }
611  cte->ctecoltypes = lappend_oid(cte->ctecoltypes, coltype);
612  cte->ctecoltypmods = lappend_int(cte->ctecoltypmods, coltypmod);
613  cte->ctecolcollations = lappend_oid(cte->ctecolcollations, colcoll);
614  }
615  if (varattno < numaliases)
616  ereport(ERROR,
617  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
618  errmsg("WITH query \"%s\" has %d columns available but %d columns specified",
619  cte->ctename, varattno, numaliases),
620  parser_errposition(pstate, cte->location)));
621 }
signed int int32
Definition: c.h:430
#define OidIsValid(objectId)
Definition: c.h:711
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:1483
#define copyObject(obj)
Definition: nodes.h:233
static int list_length(const List *l)
Definition: pg_list.h:150
List * aliascolnames
Definition: parsenodes.h:1565
char * resname
Definition: primnodes.h:1557

References CommonTableExpr::aliascolnames, Assert(), copyObject, CommonTableExpr::ctecolcollations, CommonTableExpr::ctecolnames, CommonTableExpr::ctecoltypes, CommonTableExpr::ctecoltypmods, CommonTableExpr::ctename, CommonTableExpr::cterecursive, 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(), TargetEntry::resjunk, TargetEntry::resname, and TargetEntry::resno.

Referenced by analyzeCTE(), and determineRecursiveColTypes().

◆ checkWellFormedRecursion()

static void checkWellFormedRecursion ( CteState cstate)
static

Definition at line 831 of file parse_cte.c.

832 {
833  int i;
834 
835  for (i = 0; i < cstate->numitems; i++)
836  {
837  CommonTableExpr *cte = cstate->items[i].cte;
838  SelectStmt *stmt = (SelectStmt *) cte->ctequery;
839 
840  Assert(!IsA(stmt, Query)); /* not analyzed yet */
841 
842  /* Ignore items that weren't found to be recursive */
843  if (!cte->cterecursive)
844  continue;
845 
846  /* Must be a SELECT statement */
847  if (!IsA(stmt, SelectStmt))
848  ereport(ERROR,
849  (errcode(ERRCODE_INVALID_RECURSION),
850  errmsg("recursive query \"%s\" must not contain data-modifying statements",
851  cte->ctename),
852  parser_errposition(cstate->pstate, cte->location)));
853 
854  /* Must have top-level UNION */
855  if (stmt->op != SETOP_UNION)
856  ereport(ERROR,
857  (errcode(ERRCODE_INVALID_RECURSION),
858  errmsg("recursive query \"%s\" does not have the form non-recursive-term UNION [ALL] recursive-term",
859  cte->ctename),
860  parser_errposition(cstate->pstate, cte->location)));
861 
862  /* The left-hand operand mustn't contain self-reference at all */
863  cstate->curitem = i;
864  cstate->innerwiths = NIL;
865  cstate->selfrefcount = 0;
867  checkWellFormedRecursionWalker((Node *) stmt->larg, cstate);
868  Assert(cstate->innerwiths == NIL);
869 
870  /* Right-hand operand should contain one reference in a valid place */
871  cstate->curitem = i;
872  cstate->innerwiths = NIL;
873  cstate->selfrefcount = 0;
874  cstate->context = RECURSION_OK;
875  checkWellFormedRecursionWalker((Node *) stmt->rarg, cstate);
876  Assert(cstate->innerwiths == NIL);
877  if (cstate->selfrefcount != 1) /* shouldn't happen */
878  elog(ERROR, "missing recursive reference");
879 
880  /* WITH mustn't contain self-reference, either */
881  if (stmt->withClause)
882  {
883  cstate->curitem = i;
884  cstate->innerwiths = NIL;
885  cstate->selfrefcount = 0;
886  cstate->context = RECURSION_SUBLINK;
888  cstate);
889  Assert(cstate->innerwiths == NIL);
890  }
891 
892  /*
893  * Disallow ORDER BY and similar decoration atop the UNION. These
894  * don't make sense because it's impossible to figure out what they
895  * mean when we have only part of the recursive query's results. (If
896  * we did allow them, we'd have to check for recursive references
897  * inside these subtrees.)
898  */
899  if (stmt->sortClause)
900  ereport(ERROR,
901  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
902  errmsg("ORDER BY in a recursive query is not implemented"),
903  parser_errposition(cstate->pstate,
904  exprLocation((Node *) stmt->sortClause))));
905  if (stmt->limitOffset)
906  ereport(ERROR,
907  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
908  errmsg("OFFSET in a recursive query is not implemented"),
909  parser_errposition(cstate->pstate,
910  exprLocation(stmt->limitOffset))));
911  if (stmt->limitCount)
912  ereport(ERROR,
913  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
914  errmsg("LIMIT in a recursive query is not implemented"),
915  parser_errposition(cstate->pstate,
916  exprLocation(stmt->limitCount))));
917  if (stmt->lockingClause)
918  ereport(ERROR,
919  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
920  errmsg("FOR UPDATE/SHARE in a recursive query is not implemented"),
921  parser_errposition(cstate->pstate,
922  exprLocation((Node *) stmt->lockingClause))));
923  }
924 }
int i
Definition: isn.c:73
static bool checkWellFormedRecursionWalker(Node *node, CteState *cstate)
Definition: parse_cte.c:930
@ SETOP_UNION
Definition: parsenodes.h:1745
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
List * sortClause
Definition: parsenodes.h:1782
Node * limitOffset
Definition: parsenodes.h:1783
List * lockingClause
Definition: parsenodes.h:1786
Node * limitCount
Definition: parsenodes.h:1784
struct SelectStmt * larg
Definition: parsenodes.h:1794
struct SelectStmt * rarg
Definition: parsenodes.h:1795
SetOperation op
Definition: parsenodes.h:1792
WithClause * withClause
Definition: parsenodes.h:1787
List * ctes
Definition: parsenodes.h:1488

References Assert(), checkWellFormedRecursionWalker(), CteState::context, CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, CommonTableExpr::cterecursive, WithClause::ctes, CteState::curitem, elog(), ereport, errcode(), errmsg(), ERROR, exprLocation(), i, CteState::innerwiths, IsA, CteState::items, SelectStmt::larg, SelectStmt::limitCount, SelectStmt::limitOffset, CommonTableExpr::location, SelectStmt::lockingClause, NIL, CteState::numitems, SelectStmt::op, parser_errposition(), CteState::pstate, SelectStmt::rarg, RECURSION_NONRECURSIVETERM, RECURSION_OK, RECURSION_SUBLINK, CteState::selfrefcount, SETOP_UNION, SelectStmt::sortClause, and SelectStmt::withClause.

Referenced by transformWithClause().

◆ checkWellFormedRecursionWalker()

static bool checkWellFormedRecursionWalker ( Node node,
CteState cstate 
)
static

Definition at line 930 of file parse_cte.c.

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

References checkWellFormedSelectStmt(), CteState::context, CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, WithClause::ctes, 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, WithClause::recursive, RangeVar::relname, RangeVar::schemaname, CteState::selfrefcount, SubLink::subselect, SubLink::testexpr, and SelectStmt::withClause.

Referenced by checkWellFormedRecursion(), and checkWellFormedSelectStmt().

◆ checkWellFormedSelectStmt()

static void checkWellFormedSelectStmt ( SelectStmt stmt,
CteState cstate 
)
static

Definition at line 1110 of file parse_cte.c.

1111 {
1112  RecursionContext save_context = cstate->context;
1113 
1114  if (save_context != RECURSION_OK)
1115  {
1116  /* just recurse without changing state */
1119  (void *) cstate);
1120  }
1121  else
1122  {
1123  switch (stmt->op)
1124  {
1125  case SETOP_NONE:
1126  case SETOP_UNION:
1129  (void *) cstate);
1130  break;
1131  case SETOP_INTERSECT:
1132  if (stmt->all)
1133  cstate->context = RECURSION_INTERSECT;
1134  checkWellFormedRecursionWalker((Node *) stmt->larg,
1135  cstate);
1136  checkWellFormedRecursionWalker((Node *) stmt->rarg,
1137  cstate);
1138  cstate->context = save_context;
1139  checkWellFormedRecursionWalker((Node *) stmt->sortClause,
1140  cstate);
1141  checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
1142  cstate);
1143  checkWellFormedRecursionWalker((Node *) stmt->limitCount,
1144  cstate);
1145  checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
1146  cstate);
1147  /* stmt->withClause is intentionally ignored here */
1148  break;
1149  case SETOP_EXCEPT:
1150  if (stmt->all)
1151  cstate->context = RECURSION_EXCEPT;
1152  checkWellFormedRecursionWalker((Node *) stmt->larg,
1153  cstate);
1154  cstate->context = RECURSION_EXCEPT;
1155  checkWellFormedRecursionWalker((Node *) stmt->rarg,
1156  cstate);
1157  cstate->context = save_context;
1158  checkWellFormedRecursionWalker((Node *) stmt->sortClause,
1159  cstate);
1160  checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
1161  cstate);
1162  checkWellFormedRecursionWalker((Node *) stmt->limitCount,
1163  cstate);
1164  checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
1165  cstate);
1166  /* stmt->withClause is intentionally ignored here */
1167  break;
1168  default:
1169  elog(ERROR, "unrecognized set op: %d",
1170  (int) stmt->op);
1171  }
1172  }
1173 }
@ SETOP_INTERSECT
Definition: parsenodes.h:1746
@ SETOP_EXCEPT
Definition: parsenodes.h:1747
@ SETOP_NONE
Definition: parsenodes.h:1744

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

Referenced by checkWellFormedRecursionWalker().

◆ makeDependencyGraph()

static void makeDependencyGraph ( CteState cstate)
static

Definition at line 629 of file parse_cte.c.

630 {
631  int i;
632 
633  for (i = 0; i < cstate->numitems; i++)
634  {
635  CommonTableExpr *cte = cstate->items[i].cte;
636 
637  cstate->curitem = i;
638  cstate->innerwiths = NIL;
639  makeDependencyGraphWalker((Node *) cte->ctequery, cstate);
640  Assert(cstate->innerwiths == NIL);
641  }
642 
643  TopologicalSort(cstate->pstate, cstate->items, cstate->numitems);
644 }
static void TopologicalSort(ParseState *pstate, CteItem *items, int numitems)
Definition: parse_cte.c:779
static bool makeDependencyGraphWalker(Node *node, CteState *cstate)
Definition: parse_cte.c:651

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 651 of file parse_cte.c.

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

Referenced by makeDependencyGraph().

◆ TopologicalSort()

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

Definition at line 779 of file parse_cte.c.

780 {
781  int i,
782  j;
783 
784  /* for each position in sequence ... */
785  for (i = 0; i < numitems; i++)
786  {
787  /* ... scan the remaining items to find one that has no dependencies */
788  for (j = i; j < numitems; j++)
789  {
790  if (bms_is_empty(items[j].depends_on))
791  break;
792  }
793 
794  /* if we didn't find one, the dependency graph has a cycle */
795  if (j >= numitems)
796  ereport(ERROR,
797  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
798  errmsg("mutual recursion between WITH items is not implemented"),
799  parser_errposition(pstate, items[i].cte->location)));
800 
801  /*
802  * Found one. Move it to front and remove it from every other item's
803  * dependencies.
804  */
805  if (i != j)
806  {
807  CteItem tmp;
808 
809  tmp = items[i];
810  items[i] = items[j];
811  items[j] = tmp;
812  }
813 
814  /*
815  * Items up through i are known to have no dependencies left, so we
816  * can skip them in this loop.
817  */
818  for (j = i + 1; j < numitems; j++)
819  {
820  items[j].depends_on = bms_del_member(items[j].depends_on,
821  items[i].id);
822  }
823  }
824 }
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:776
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704

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:1230
static void makeDependencyGraph(CteState *cstate)
Definition: parse_cte.c:629
static void checkWellFormedRecursion(CteState *cstate)
Definition: parse_cte.c:831
static void analyzeCTE(ParseState *pstate, CommonTableExpr *cte)
Definition: parse_cte.c:248
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:436
List * p_ctenamespace
Definition: parse_node.h:195
bool p_hasModifyingCTE
Definition: parse_node.h:218
List * p_future_ctes
Definition: parse_node.h:196

References analyzeCTE(), Assert(), checkWellFormedRecursion(), CteItem::cte, CommonTableExpr::ctename, CommonTableExpr::ctequery, CommonTableExpr::cterecursive, CommonTableExpr::cterefcount, 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:1135

Definition at line 42 of file parse_cte.c.

Referenced by checkWellFormedRecursionWalker().