LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_cte.c (source / functions) Coverage Total Hit UBC CBC
Current: Differential Code Coverage HEAD vs 15 Lines: 91.2 % 407 371 36 371
Current Date: 2023-04-08 17:13:01 Functions: 100.0 % 9 9 9
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 (60,120] days: 97.6 % 42 41 1 41
Legend: Lines: hit not hit (180,240] days: 100.0 % 2 2 2
(240..) days: 90.4 % 363 328 35 328
Function coverage date bins:
(240..) days: 100.0 % 9 9 9

 Age         Owner                  TLA  Line data    Source code
                                  1                 : /*-------------------------------------------------------------------------
                                  2                 :  *
                                  3                 :  * parse_cte.c
                                  4                 :  *    handle CTEs (common table expressions) in parser
                                  5                 :  *
                                  6                 :  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
                                  7                 :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :  *
                                  9                 :  *
                                 10                 :  * IDENTIFICATION
                                 11                 :  *    src/backend/parser/parse_cte.c
                                 12                 :  *
                                 13                 :  *-------------------------------------------------------------------------
                                 14                 :  */
                                 15                 : #include "postgres.h"
                                 16                 : 
                                 17                 : #include "catalog/pg_collation.h"
                                 18                 : #include "catalog/pg_type.h"
                                 19                 : #include "nodes/nodeFuncs.h"
                                 20                 : #include "parser/analyze.h"
                                 21                 : #include "parser/parse_coerce.h"
                                 22                 : #include "parser/parse_collate.h"
                                 23                 : #include "parser/parse_cte.h"
                                 24                 : #include "parser/parse_expr.h"
                                 25                 : #include "utils/builtins.h"
                                 26                 : #include "utils/lsyscache.h"
                                 27                 : #include "utils/typcache.h"
                                 28                 : 
                                 29                 : 
                                 30                 : /* Enumeration of contexts in which a self-reference is disallowed */
                                 31                 : typedef enum
                                 32                 : {
                                 33                 :     RECURSION_OK,
                                 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) */
                                 39                 : } RecursionContext;
                                 40                 : 
                                 41                 : /* Associated error messages --- each must have one %s for CTE name */
                                 42                 : static const char *const recursion_errormsgs[] = {
                                 43                 :     /* RECURSION_OK */
                                 44                 :     NULL,
                                 45                 :     /* RECURSION_NONRECURSIVETERM */
                                 46                 :     gettext_noop("recursive reference to query \"%s\" must not appear within its non-recursive term"),
                                 47                 :     /* RECURSION_SUBLINK */
                                 48                 :     gettext_noop("recursive reference to query \"%s\" must not appear within a subquery"),
                                 49                 :     /* RECURSION_OUTERJOIN */
                                 50                 :     gettext_noop("recursive reference to query \"%s\" must not appear within an outer join"),
                                 51                 :     /* RECURSION_INTERSECT */
                                 52                 :     gettext_noop("recursive reference to query \"%s\" must not appear within INTERSECT"),
                                 53                 :     /* RECURSION_EXCEPT */
                                 54                 :     gettext_noop("recursive reference to query \"%s\" must not appear within EXCEPT")
                                 55                 : };
                                 56                 : 
                                 57                 : /*
                                 58                 :  * For WITH RECURSIVE, we have to find an ordering of the clause members
                                 59                 :  * with no forward references, and determine which members are recursive
                                 60                 :  * (i.e., self-referential).  It is convenient to do this with an array
                                 61                 :  * of CteItems instead of a list of CommonTableExprs.
                                 62                 :  */
                                 63                 : typedef struct CteItem
                                 64                 : {
                                 65                 :     CommonTableExpr *cte;       /* One CTE to examine */
                                 66                 :     int         id;             /* Its ID number for dependencies */
                                 67                 :     Bitmapset  *depends_on;     /* CTEs depended on (not including self) */
                                 68                 : } CteItem;
                                 69                 : 
                                 70                 : /* CteState is what we need to pass around in the tree walkers */
                                 71                 : typedef struct CteState
                                 72                 : {
                                 73                 :     /* global state: */
                                 74                 :     ParseState *pstate;         /* global parse state */
                                 75                 :     CteItem    *items;          /* array of CTEs and extra data */
                                 76                 :     int         numitems;       /* number of CTEs */
                                 77                 :     /* working state during a tree walk: */
                                 78                 :     int         curitem;        /* index of item currently being examined */
                                 79                 :     List       *innerwiths;     /* list of lists of CommonTableExpr */
                                 80                 :     /* working state for checkWellFormedRecursion walk only: */
                                 81                 :     int         selfrefcount;   /* number of self-references detected */
                                 82                 :     RecursionContext context;   /* context to allow or disallow self-ref */
                                 83                 : } CteState;
                                 84                 : 
                                 85                 : 
                                 86                 : static void analyzeCTE(ParseState *pstate, CommonTableExpr *cte);
                                 87                 : 
                                 88                 : /* Dependency processing functions */
                                 89                 : static void makeDependencyGraph(CteState *cstate);
                                 90                 : static bool makeDependencyGraphWalker(Node *node, CteState *cstate);
                                 91                 : static void TopologicalSort(ParseState *pstate, CteItem *items, int numitems);
                                 92                 : 
                                 93                 : /* Recursion validity checker functions */
                                 94                 : static void checkWellFormedRecursion(CteState *cstate);
                                 95                 : static bool checkWellFormedRecursionWalker(Node *node, CteState *cstate);
                                 96                 : static void checkWellFormedSelectStmt(SelectStmt *stmt, CteState *cstate);
                                 97                 : 
                                 98                 : 
                                 99                 : /*
                                100                 :  * transformWithClause -
                                101                 :  *    Transform the list of WITH clause "common table expressions" into
                                102                 :  *    Query nodes.
                                103                 :  *
                                104                 :  * The result is the list of transformed CTEs to be put into the output
                                105                 :  * Query.  (This is in fact the same as the ending value of p_ctenamespace,
                                106                 :  * but it seems cleaner to not expose that in the function's API.)
                                107                 :  */
                                108                 : List *
 5300 tgl                       109 CBC        1500 : transformWithClause(ParseState *pstate, WithClause *withClause)
                                110                 : {
                                111                 :     ListCell   *lc;
                                112                 : 
                                113                 :     /* Only one WITH clause per query level */
                                114            1500 :     Assert(pstate->p_ctenamespace == NIL);
 5296                           115            1500 :     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                 :      */
 5300                           124            3379 :     foreach(lc, withClause->ctes)
                                125                 :     {
                                126            1882 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                                127                 :         ListCell   *rest;
                                128                 : 
                                129                 :         /* MERGE is allowed by parser, but unimplemented. Reject for now */
  240 alvherre                  130            1882 :         if (IsA(cte->ctequery, MergeStmt))
                                131               3 :             ereport(ERROR,
                                132                 :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                133                 :                     errmsg("MERGE not supported in WITH query"),
                                134                 :                     parser_errposition(pstate, cte->location));
                                135                 : 
 1364 tgl                       136            2690 :         for_each_cell(rest, withClause->ctes, lnext(withClause->ctes, lc))
                                137                 :         {
 5300                           138             811 :             CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(rest);
                                139                 : 
                                140             811 :             if (strcmp(cte->ctename, cte2->ctename) == 0)
 5300 tgl                       141 UBC           0 :                 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                 : 
 5300 tgl                       148 CBC        1879 :         cte->cterecursive = false;
                                149            1879 :         cte->cterefcount = 0;
                                150                 : 
 4426                           151            1879 :         if (!IsA(cte->ctequery, SelectStmt))
                                152                 :         {
                                153                 :             /* must be a data-modifying statement */
                                154             165 :             Assert(IsA(cte->ctequery, InsertStmt) ||
                                155                 :                    IsA(cte->ctequery, UpdateStmt) ||
                                156                 :                    IsA(cte->ctequery, DeleteStmt));
                                157                 : 
                                158             165 :             pstate->p_hasModifyingCTE = true;
                                159                 :         }
                                160                 :     }
                                161                 : 
 5300                           162            1497 :     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             504 :         cstate.pstate = pstate;
                                173             504 :         cstate.numitems = list_length(withClause->ctes);
                                174             504 :         cstate.items = (CteItem *) palloc0(cstate.numitems * sizeof(CteItem));
                                175             504 :         i = 0;
                                176            1056 :         foreach(lc, withClause->ctes)
                                177                 :         {
                                178             552 :             cstate.items[i].cte = (CommonTableExpr *) lfirst(lc);
                                179             552 :             cstate.items[i].id = i;
                                180             552 :             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             504 :         makeDependencyGraph(&cstate);
                                188                 : 
                                189                 :         /*
                                190                 :          * Check that recursive queries are well-formed.
                                191                 :          */
                                192             501 :         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             927 :         for (i = 0; i < cstate.numitems; i++)
                                201                 :         {
                                202             486 :             CommonTableExpr *cte = cstate.items[i].cte;
                                203                 : 
                                204             486 :             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             861 :         for (i = 0; i < cstate.numitems; i++)
                                211                 :         {
                                212             486 :             CommonTableExpr *cte = cstate.items[i].cte;
                                213                 : 
                                214             486 :             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                 :          */
 5296                           226             993 :         pstate->p_future_ctes = list_copy(withClause->ctes);
                                227                 : 
 5300                           228            2310 :         foreach(lc, withClause->ctes)
                                229                 :         {
                                230            1327 :             CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                                231                 : 
                                232            1327 :             analyzeCTE(pstate, cte);
                                233            1317 :             pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
 5296                           234            1317 :             pstate->p_future_ctes = list_delete_first(pstate->p_future_ctes);
                                235                 :         }
                                236                 :     }
                                237                 : 
 5300                           238            1358 :     return pstate->p_ctenamespace;
                                239                 : }
                                240                 : 
                                241                 : 
                                242                 : /*
                                243                 :  * Perform the actual parse analysis transformation of one CTE.  All
                                244                 :  * CTEs it depends on have already been loaded into pstate->p_ctenamespace,
                                245                 :  * and have been marked with the correct output column names/types.
                                246                 :  */
                                247                 : static void
                                248            1813 : analyzeCTE(ParseState *pstate, CommonTableExpr *cte)
                                249                 : {
                                250                 :     Query      *query;
  114                           251            1813 :     CTESearchClause *search_clause = cte->search_clause;
                                252            1813 :     CTECycleClause *cycle_clause = cte->cycle_clause;
                                253                 : 
                                254                 :     /* Analysis not done already */
 4426                           255            1813 :     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                 :      */
  114                           262            1813 :     if (cycle_clause)
                                263                 :     {
                                264                 :         TypeCacheEntry *typentry;
                                265                 :         Oid         op;
                                266                 : 
                                267              63 :         cycle_clause->cycle_mark_value =
                                268              63 :             transformExpr(pstate, cycle_clause->cycle_mark_value,
                                269                 :                           EXPR_KIND_CYCLE_MARK);
                                270              63 :         cycle_clause->cycle_mark_default =
                                271              63 :             transformExpr(pstate, cycle_clause->cycle_mark_default,
                                272                 :                           EXPR_KIND_CYCLE_MARK);
                                273                 : 
                                274              60 :         cycle_clause->cycle_mark_type =
                                275              63 :             select_common_type(pstate,
                                276              63 :                                list_make2(cycle_clause->cycle_mark_value,
                                277                 :                                           cycle_clause->cycle_mark_default),
                                278                 :                                "CYCLE", NULL);
                                279              60 :         cycle_clause->cycle_mark_value =
                                280              60 :             coerce_to_common_type(pstate,
                                281                 :                                   cycle_clause->cycle_mark_value,
                                282                 :                                   cycle_clause->cycle_mark_type,
                                283                 :                                   "CYCLE/SET/TO");
                                284              60 :         cycle_clause->cycle_mark_default =
                                285              60 :             coerce_to_common_type(pstate,
                                286                 :                                   cycle_clause->cycle_mark_default,
                                287                 :                                   cycle_clause->cycle_mark_type,
                                288                 :                                   "CYCLE/SET/DEFAULT");
                                289                 : 
                                290              60 :         cycle_clause->cycle_mark_typmod =
                                291              60 :             select_common_typmod(pstate,
                                292              60 :                                  list_make2(cycle_clause->cycle_mark_value,
                                293                 :                                             cycle_clause->cycle_mark_default),
                                294                 :                                  cycle_clause->cycle_mark_type);
                                295                 : 
                                296              60 :         cycle_clause->cycle_mark_collation =
                                297              60 :             select_common_collation(pstate,
                                298              60 :                                     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              60 :         typentry = lookup_type_cache(cycle_clause->cycle_mark_type,
                                304                 :                                      TYPECACHE_EQ_OPR);
                                305              60 :         if (!OidIsValid(typentry->eq_opr))
                                306               3 :             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              57 :         op = get_negator(typentry->eq_opr);
                                311              57 :         if (!OidIsValid(op))
  114 tgl                       312 UBC           0 :             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                 : 
  114 tgl                       317 CBC          57 :         cycle_clause->cycle_mark_neop = op;
                                318                 :     }
                                319                 : 
                                320                 :     /* Now we can get on with analyzing the CTE's query */
 2265                           321            1807 :     query = parse_sub_analyze(cte->ctequery, pstate, cte, false, true);
 5300                           322            1794 :     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                 :      */
 4426                           328            1794 :     if (!IsA(query, Query))
 4426 tgl                       329 UBC           0 :         elog(ERROR, "unexpected non-Query statement in WITH");
 4426 tgl                       330 CBC        1794 :     if (query->utilityStmt != NULL)
 4426 tgl                       331 UBC           0 :         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                 :      */
 4426 tgl                       337 CBC        1794 :     if (query->commandType != CMD_SELECT &&
                                338             162 :         pstate->parentParseState != NULL)
                                339               3 :         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            1791 :     query->canSetTag = false;
                                350                 : 
 5300                           351            1791 :     if (!cte->cterecursive)
                                352                 :     {
                                353                 :         /* Compute the output column names/types if not done yet */
 4426                           354            1374 :         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                 : 
 5300                           370             417 :         lctyp = list_head(cte->ctecoltypes);
                                371             417 :         lctypmod = list_head(cte->ctecoltypmods);
 4443 peter_e                   372             417 :         lccoll = list_head(cte->ctecolcollations);
 5300 tgl                       373             417 :         varattno = 0;
 4426                           374            1326 :         foreach(lctlist, GetCTETargetList(cte))
                                375                 :         {
 5300                           376             924 :             TargetEntry *te = (TargetEntry *) lfirst(lctlist);
                                377                 :             Node       *texpr;
                                378                 : 
                                379             924 :             if (te->resjunk)
 5300 tgl                       380 UBC           0 :                 continue;
 5300 tgl                       381 CBC         924 :             varattno++;
                                382             924 :             Assert(varattno == te->resno);
 4382 bruce                     383             924 :             if (lctyp == NULL || lctypmod == NULL || lccoll == NULL)    /* shouldn't happen */
 5300 tgl                       384 UBC           0 :                 elog(ERROR, "wrong number of output columns in WITH");
 5300 tgl                       385 CBC         924 :             texpr = (Node *) te->expr;
                                386             924 :             if (exprType(texpr) != lfirst_oid(lctyp) ||
                                387             921 :                 exprTypmod(texpr) != lfirst_int(lctypmod))
                                388               6 :                 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,
                                392                 :                                 format_type_with_typemod(lfirst_oid(lctyp),
                                393                 :                                                          lfirst_int(lctypmod)),
                                394                 :                                 format_type_with_typemod(exprType(texpr),
                                395                 :                                                          exprTypmod(texpr))),
                                396                 :                          errhint("Cast the output of the non-recursive term to the correct type."),
                                397                 :                          parser_errposition(pstate, exprLocation(texpr))));
 4443 peter_e                   398             918 :             if (exprCollation(texpr) != lfirst_oid(lccoll))
                                399               9 :                 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,
                                403                 :                                 get_collation_name(lfirst_oid(lccoll)),
                                404                 :                                 get_collation_name(exprCollation(texpr))),
                                405                 :                          errhint("Use the COLLATE clause to set the collation of the non-recursive term."),
                                406                 :                          parser_errposition(pstate, exprLocation(texpr))));
 1364 tgl                       407             909 :             lctyp = lnext(cte->ctecoltypes, lctyp);
                                408             909 :             lctypmod = lnext(cte->ctecoltypmods, lctypmod);
                                409             909 :             lccoll = lnext(cte->ctecolcollations, lccoll);
                                410                 :         }
 2118                           411             402 :         if (lctyp != NULL || lctypmod != NULL || lccoll != NULL)    /* shouldn't happen */
 5300 tgl                       412 UBC           0 :             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                 :      */
  114 tgl                       418 CBC        1773 :     if (search_clause || cycle_clause)
                                419                 :     {
                                420                 :         Query      *ctequery;
                                421                 :         SetOperationStmt *sos;
                                422                 : 
  797 peter                     423             108 :         if (!cte->cterecursive)
  797 peter                     424 UBC           0 :             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                 : 
  797 peter                     445 CBC         108 :         ctequery = castNode(Query, cte->ctequery);
                                446             108 :         Assert(ctequery->setOperations);
                                447             108 :         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             108 :         if (!IsA(sos->larg, RangeTblRef))
                                455               3 :             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             105 :         if (!IsA(sos->rarg, RangeTblRef))
                                460               3 :             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                 : 
  114 tgl                       465            1767 :     if (search_clause)
                                466                 :     {
                                467                 :         ListCell   *lc;
  797 peter                     468              57 :         List       *seen = NIL;
                                469                 : 
  114 tgl                       470             150 :         foreach(lc, search_clause->search_col_list)
                                471                 :         {
  577 peter                     472              99 :             String     *colname = lfirst_node(String, lc);
                                473                 : 
  797                           474              99 :             if (!list_member(cte->ctecolnames, colname))
                                475               3 :                 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              96 :             if (list_member(seen, colname))
                                482               3 :                 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              93 :             seen = lappend(seen, colname);
                                488                 :         }
                                489                 : 
  114 tgl                       490              51 :         if (list_member(cte->ctecolnames, makeString(search_clause->search_seq_column)))
  797 peter                     491               3 :             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                 : 
  114 tgl                       498            1758 :     if (cycle_clause)
                                499                 :     {
                                500                 :         ListCell   *lc;
  797 peter                     501              57 :         List       *seen = NIL;
                                502                 : 
  114 tgl                       503             153 :         foreach(lc, cycle_clause->cycle_col_list)
                                504                 :         {
  577 peter                     505             102 :             String     *colname = lfirst_node(String, lc);
                                506                 : 
  797                           507             102 :             if (!list_member(cte->ctecolnames, colname))
                                508               3 :                 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              99 :             if (list_member(seen, colname))
                                515               3 :                 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              96 :             seen = lappend(seen, colname);
                                521                 :         }
                                522                 : 
  114 tgl                       523              51 :         if (list_member(cte->ctecolnames, makeString(cycle_clause->cycle_mark_column)))
  797 peter                     524               3 :             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                 : 
  114 tgl                       530              48 :         if (list_member(cte->ctecolnames, makeString(cycle_clause->cycle_path_column)))
  797 peter                     531               3 :             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                 : 
  114 tgl                       537              45 :         if (strcmp(cycle_clause->cycle_mark_column,
                                538              45 :                    cycle_clause->cycle_path_column) == 0)
  797 peter                     539               3 :             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                 : 
  114 tgl                       545            1743 :     if (search_clause && cycle_clause)
                                546                 :     {
                                547              12 :         if (strcmp(search_clause->search_seq_column,
                                548              12 :                    cycle_clause->cycle_mark_column) == 0)
  797 peter                     549               3 :             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                 : 
  114 tgl                       554               9 :         if (strcmp(search_clause->search_seq_column,
                                555               9 :                    cycle_clause->cycle_path_column) == 0)
  797 peter                     556               3 :             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                 :     }
 5300 tgl                       561            1737 : }
                                562                 : 
                                563                 : /*
                                564                 :  * Compute derived fields of a CTE, given the transformed output targetlist
                                565                 :  *
                                566                 :  * For a nonrecursive CTE, this is called after transforming the CTE's query.
                                567                 :  * For a recursive CTE, we call it after transforming the non-recursive term,
                                568                 :  * and pass the targetlist emitted by the non-recursive term only.
                                569                 :  *
                                570                 :  * Note: in the recursive case, the passed pstate is actually the one being
                                571                 :  * used to analyze the CTE's query, so it is one level lower down than in
                                572                 :  * the nonrecursive case.  This doesn't matter since we only use it for
                                573                 :  * error message context anyway.
                                574                 :  */
                                575                 : void
                                576            1800 : analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
                                577                 : {
                                578                 :     int         numaliases;
                                579                 :     int         varattno;
                                580                 :     ListCell   *tlistitem;
                                581                 : 
                                582                 :     /* Not done already ... */
 4960                           583            1800 :     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                 :      */
 5300                           592            1800 :     cte->ctecolnames = copyObject(cte->aliascolnames);
 4443 peter_e                   593            1800 :     cte->ctecoltypes = cte->ctecoltypmods = cte->ctecolcollations = NIL;
 5300 tgl                       594            1800 :     numaliases = list_length(cte->aliascolnames);
                                595            1800 :     varattno = 0;
                                596            6176 :     foreach(tlistitem, tlist)
                                597                 :     {
                                598            4376 :         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
                                599                 :         Oid         coltype;
                                600                 :         int32       coltypmod;
                                601                 :         Oid         colcoll;
                                602                 : 
                                603            4376 :         if (te->resjunk)
                                604               3 :             continue;
                                605            4373 :         varattno++;
                                606            4373 :         Assert(varattno == te->resno);
                                607            4373 :         if (varattno > numaliases)
                                608                 :         {
                                609                 :             char       *attrname;
                                610                 : 
                                611            2255 :             attrname = pstrdup(te->resname);
                                612            2255 :             cte->ctecolnames = lappend(cte->ctecolnames, makeString(attrname));
                                613                 :         }
 5299                           614            4373 :         coltype = exprType((Node *) te->expr);
                                615            4373 :         coltypmod = exprTypmod((Node *) te->expr);
 4443 peter_e                   616            4373 :         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                 :          */
 5299 tgl                       628            4373 :         if (cte->cterecursive && coltype == UNKNOWNOID)
                                629                 :         {
                                630              18 :             coltype = TEXTOID;
                                631              18 :             coltypmod = -1;     /* should be -1 already, but be sure */
 4404                           632              18 :             if (!OidIsValid(colcoll))
                                633              18 :                 colcoll = DEFAULT_COLLATION_OID;
                                634                 :         }
 5299                           635            4373 :         cte->ctecoltypes = lappend_oid(cte->ctecoltypes, coltype);
                                636            4373 :         cte->ctecoltypmods = lappend_int(cte->ctecoltypmods, coltypmod);
 4443 peter_e                   637            4373 :         cte->ctecolcollations = lappend_oid(cte->ctecolcollations, colcoll);
                                638                 :     }
 5300 tgl                       639            1800 :     if (varattno < numaliases)
                                640               3 :         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            1797 : }
                                646                 : 
                                647                 : 
                                648                 : /*
                                649                 :  * Identify the cross-references of a list of WITH RECURSIVE items,
                                650                 :  * and sort into an order that has no forward references.
                                651                 :  */
                                652                 : static void
                                653             504 : makeDependencyGraph(CteState *cstate)
                                654                 : {
                                655                 :     int         i;
                                656                 : 
                                657            1056 :     for (i = 0; i < cstate->numitems; i++)
                                658                 :     {
                                659             552 :         CommonTableExpr *cte = cstate->items[i].cte;
                                660                 : 
                                661             552 :         cstate->curitem = i;
                                662             552 :         cstate->innerwiths = NIL;
                                663             552 :         makeDependencyGraphWalker((Node *) cte->ctequery, cstate);
                                664             552 :         Assert(cstate->innerwiths == NIL);
                                665                 :     }
                                666                 : 
                                667             504 :     TopologicalSort(cstate->pstate, cstate->items, cstate->numitems);
                                668             501 : }
                                669                 : 
                                670                 : /*
                                671                 :  * Tree walker function to detect cross-references and self-references of the
                                672                 :  * CTEs in a WITH RECURSIVE list.
                                673                 :  */
                                674                 : static bool
                                675           54093 : makeDependencyGraphWalker(Node *node, CteState *cstate)
                                676                 : {
                                677           54093 :     if (node == NULL)
                                678           31398 :         return false;
                                679           22695 :     if (IsA(node, RangeVar))
                                680                 :     {
                                681            2166 :         RangeVar   *rv = (RangeVar *) node;
                                682                 : 
                                683                 :         /* If unqualified name, might be a CTE reference */
                                684            2166 :         if (!rv->schemaname)
                                685                 :         {
                                686                 :             ListCell   *lc;
                                687                 :             int         i;
                                688                 : 
                                689                 :             /* ... but first see if it's captured by an inner WITH */
                                690            2022 :             foreach(lc, cstate->innerwiths)
                                691                 :             {
 5050 bruce                     692             288 :                 List       *withlist = (List *) lfirst(lc);
                                693                 :                 ListCell   *lc2;
                                694                 : 
 5300 tgl                       695             342 :                 foreach(lc2, withlist)
                                696                 :                 {
                                697             261 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
                                698                 : 
                                699             261 :                     if (strcmp(rv->relname, cte->ctename) == 0)
 5050 bruce                     700             207 :                         return false;   /* yes, so bail out */
                                701                 :                 }
                                702                 :             }
                                703                 : 
                                704                 :             /* No, could be a reference to the query level we are working on */
 5300 tgl                       705            2961 :             for (i = 0; i < cstate->numitems; i++)
                                706                 :             {
                                707            1803 :                 CommonTableExpr *cte = cstate->items[i].cte;
                                708                 : 
                                709            1803 :                 if (strcmp(rv->relname, cte->ctename) == 0)
                                710                 :                 {
 5050 bruce                     711             576 :                     int         myindex = cstate->curitem;
                                712                 : 
 5300 tgl                       713             576 :                     if (i != myindex)
                                714                 :                     {
                                715                 :                         /* Add cross-item dependency */
                                716              63 :                         cstate->items[myindex].depends_on =
                                717              63 :                             bms_add_member(cstate->items[myindex].depends_on,
                                718              63 :                                            cstate->items[i].id);
                                719                 :                     }
                                720                 :                     else
                                721                 :                     {
                                722                 :                         /* Found out this one is self-referential */
                                723             513 :                         cte->cterecursive = true;
                                724                 :                     }
                                725             576 :                     break;
                                726                 :                 }
                                727                 :             }
                                728                 :         }
                                729            1959 :         return false;
                                730                 :     }
                                731           20529 :     if (IsA(node, SelectStmt))
                                732                 :     {
                                733            2004 :         SelectStmt *stmt = (SelectStmt *) node;
                                734                 :         ListCell   *lc;
                                735                 : 
                                736            2004 :         if (stmt->withClause)
                                737                 :         {
                                738             105 :             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               9 :                 cstate->innerwiths = lcons(stmt->withClause->ctes,
                                746                 :                                            cstate->innerwiths);
                                747              18 :                 foreach(lc, stmt->withClause->ctes)
                                748                 :                 {
                                749               9 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                                750                 : 
                                751               9 :                     (void) makeDependencyGraphWalker(cte->ctequery, cstate);
                                752                 :                 }
                                753               9 :                 (void) raw_expression_tree_walker(node,
                                754                 :                                                   makeDependencyGraphWalker,
                                755                 :                                                   (void *) cstate);
                                756               9 :                 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              96 :                 cstate->innerwiths = lcons(NIL, cstate->innerwiths);
                                765             204 :                 foreach(lc, stmt->withClause->ctes)
                                766                 :                 {
                                767             108 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                                768                 :                     ListCell   *cell1;
                                769                 : 
                                770             108 :                     (void) makeDependencyGraphWalker(cte->ctequery, cstate);
                                771                 :                     /* note that recursion could mutate innerwiths list */
  773                           772             108 :                     cell1 = list_head(cstate->innerwiths);
 5300                           773             108 :                     lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
                                774                 :                 }
                                775              96 :                 (void) raw_expression_tree_walker(node,
                                776                 :                                                   makeDependencyGraphWalker,
                                777                 :                                                   (void *) cstate);
                                778              96 :                 cstate->innerwiths = list_delete_first(cstate->innerwiths);
                                779                 :             }
                                780                 :             /* We're done examining the SelectStmt */
                                781             105 :             return false;
                                782                 :         }
                                783                 :         /* if no WITH clause, just fall through for normal processing */
                                784                 :     }
                                785           20424 :     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             105 :         return false;
                                793                 :     }
                                794           20319 :     return raw_expression_tree_walker(node,
                                795                 :                                       makeDependencyGraphWalker,
                                796                 :                                       (void *) cstate);
                                797                 : }
                                798                 : 
                                799                 : /*
                                800                 :  * Sort by dependencies, using a standard topological sort operation
                                801                 :  */
                                802                 : static void
                                803             504 : TopologicalSort(ParseState *pstate, CteItem *items, int numitems)
                                804                 : {
                                805                 :     int         i,
                                806                 :                 j;
                                807                 : 
                                808                 :     /* for each position in sequence ... */
                                809            1050 :     for (i = 0; i < numitems; i++)
                                810                 :     {
                                811                 :         /* ... scan the remaining items to find one that has no dependencies */
                                812             564 :         for (j = i; j < numitems; j++)
                                813                 :         {
                                814             561 :             if (bms_is_empty(items[j].depends_on))
                                815             546 :                 break;
                                816                 :         }
                                817                 : 
                                818                 :         /* if we didn't find one, the dependency graph has a cycle */
                                819             549 :         if (j >= numitems)
                                820               3 :             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             546 :         if (i != j)
                                830                 :         {
                                831                 :             CteItem     tmp;
                                832                 : 
                                833               9 :             tmp = items[i];
                                834               9 :             items[i] = items[j];
                                835               9 :             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             597 :         for (j = i + 1; j < numitems; j++)
                                843                 :         {
                                844              51 :             items[j].depends_on = bms_del_member(items[j].depends_on,
                                845              51 :                                                  items[i].id);
                                846                 :         }
                                847                 :     }
                                848             501 : }
                                849                 : 
                                850                 : 
                                851                 : /*
                                852                 :  * Check that recursive queries are well-formed.
                                853                 :  */
                                854                 : static void
                                855             501 : checkWellFormedRecursion(CteState *cstate)
                                856                 : {
                                857                 :     int         i;
                                858                 : 
                                859             987 :     for (i = 0; i < cstate->numitems; i++)
                                860                 :     {
                                861             546 :         CommonTableExpr *cte = cstate->items[i].cte;
 5050 bruce                     862             546 :         SelectStmt *stmt = (SelectStmt *) cte->ctequery;
                                863                 : 
 2118 tgl                       864             546 :         Assert(!IsA(stmt, Query));  /* not analyzed yet */
                                865                 : 
                                866                 :         /* Ignore items that weren't found to be recursive */
 5300                           867             546 :         if (!cte->cterecursive)
                                868              54 :             continue;
                                869                 : 
                                870                 :         /* Must be a SELECT statement */
 4426                           871             492 :         if (!IsA(stmt, SelectStmt))
                                872               3 :             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 */
 5297                           879             489 :         if (stmt->op != SETOP_UNION)
 5300                           880              15 :             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             474 :         cstate->curitem = i;
                                888             474 :         cstate->innerwiths = NIL;
                                889             474 :         cstate->selfrefcount = 0;
                                890             474 :         cstate->context = RECURSION_NONRECURSIVETERM;
                                891             474 :         checkWellFormedRecursionWalker((Node *) stmt->larg, cstate);
                                892             471 :         Assert(cstate->innerwiths == NIL);
                                893                 : 
                                894                 :         /* Right-hand operand should contain one reference in a valid place */
                                895             471 :         cstate->curitem = i;
                                896             471 :         cstate->innerwiths = NIL;
                                897             471 :         cstate->selfrefcount = 0;
                                898             471 :         cstate->context = RECURSION_OK;
                                899             471 :         checkWellFormedRecursionWalker((Node *) stmt->rarg, cstate);
                                900             444 :         Assert(cstate->innerwiths == NIL);
 5050 bruce                     901             444 :         if (cstate->selfrefcount != 1)   /* shouldn't happen */
 5300 tgl                       902 UBC           0 :             elog(ERROR, "missing recursive reference");
                                903                 : 
                                904                 :         /* WITH mustn't contain self-reference, either */
 3904 tgl                       905 CBC         444 :         if (stmt->withClause)
                                906                 :         {
                                907               6 :             cstate->curitem = i;
                                908               6 :             cstate->innerwiths = NIL;
                                909               6 :             cstate->selfrefcount = 0;
                                910               6 :             cstate->context = RECURSION_SUBLINK;
                                911               6 :             checkWellFormedRecursionWalker((Node *) stmt->withClause->ctes,
                                912                 :                                            cstate);
                                913               3 :             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                 :          */
 5300                           923             441 :         if (stmt->sortClause)
                                924               3 :             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             438 :         if (stmt->limitOffset)
                                930               3 :             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             435 :         if (stmt->limitCount)
 5300 tgl                       936 UBC           0 :             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))));
 5300 tgl                       941 CBC         435 :         if (stmt->lockingClause)
                                942               3 :             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             441 : }
                                949                 : 
                                950                 : /*
                                951                 :  * Tree walker function to detect invalid self-references in a recursive query.
                                952                 :  */
                                953                 : static bool
                                954           41910 : checkWellFormedRecursionWalker(Node *node, CteState *cstate)
                                955                 : {
                                956           41910 :     RecursionContext save_context = cstate->context;
                                957                 : 
                                958           41910 :     if (node == NULL)
                                959           20958 :         return false;
                                960           20952 :     if (IsA(node, RangeVar))
                                961                 :     {
                                962            2046 :         RangeVar   *rv = (RangeVar *) node;
                                963                 : 
                                964                 :         /* If unqualified name, might be a CTE reference */
                                965            2046 :         if (!rv->schemaname)
                                966                 :         {
                                967                 :             ListCell   *lc;
                                968                 :             CommonTableExpr *mycte;
                                969                 : 
                                970                 :             /* ... but first see if it's captured by an inner WITH */
                                971            1893 :             foreach(lc, cstate->innerwiths)
                                972                 :             {
 5050 bruce                     973             243 :                 List       *withlist = (List *) lfirst(lc);
                                974                 :                 ListCell   *lc2;
                                975                 : 
 5300 tgl                       976             291 :                 foreach(lc2, withlist)
                                977                 :                 {
                                978             219 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
                                979                 : 
                                980             219 :                     if (strcmp(rv->relname, cte->ctename) == 0)
 5050 bruce                     981             171 :                         return false;   /* yes, so bail out */
                                982                 :                 }
                                983                 :             }
                                984                 : 
                                985                 :             /* No, could be a reference to the query level we are working on */
 5300 tgl                       986            1650 :             mycte = cstate->items[cstate->curitem].cte;
                                987            1650 :             if (strcmp(rv->relname, mycte->ctename) == 0)
                                988                 :             {
                                989                 :                 /* Found a recursive reference to the active query */
                                990             492 :                 if (cstate->context != RECURSION_OK)
                                991              24 :                     ereport(ERROR,
                                992                 :                             (errcode(ERRCODE_INVALID_RECURSION),
                                993                 :                              errmsg(recursion_errormsgs[cstate->context],
                                994                 :                                     mycte->ctename),
                                995                 :                              parser_errposition(cstate->pstate,
                                996                 :                                                 rv->location)));
                                997                 :                 /* Count references */
                                998             468 :                 if (++(cstate->selfrefcount) > 1)
                                999               9 :                     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            1842 :         return false;
                               1008                 :     }
                               1009           18906 :     if (IsA(node, SelectStmt))
                               1010                 :     {
                               1011            1371 :         SelectStmt *stmt = (SelectStmt *) node;
                               1012                 :         ListCell   *lc;
                               1013                 : 
                               1014            1371 :         if (stmt->withClause)
                               1015                 :         {
                               1016              72 :             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               3 :                 cstate->innerwiths = lcons(stmt->withClause->ctes,
                               1024                 :                                            cstate->innerwiths);
                               1025               6 :                 foreach(lc, stmt->withClause->ctes)
                               1026                 :                 {
                               1027               3 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                               1028                 : 
                               1029               3 :                     (void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
                               1030                 :                 }
                               1031               3 :                 checkWellFormedSelectStmt(stmt, cstate);
                               1032               3 :                 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              69 :                 cstate->innerwiths = lcons(NIL, cstate->innerwiths);
                               1041             150 :                 foreach(lc, stmt->withClause->ctes)
                               1042                 :                 {
                               1043              81 :                     CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
                               1044                 :                     ListCell   *cell1;
                               1045                 : 
                               1046              81 :                     (void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
                               1047                 :                     /* note that recursion could mutate innerwiths list */
  773                          1048              81 :                     cell1 = list_head(cstate->innerwiths);
 5300                          1049              81 :                     lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
                               1050                 :                 }
                               1051              69 :                 checkWellFormedSelectStmt(stmt, cstate);
                               1052              69 :                 cstate->innerwiths = list_delete_first(cstate->innerwiths);
                               1053                 :             }
                               1054                 :         }
                               1055                 :         else
 5050 bruce                    1056            1299 :             checkWellFormedSelectStmt(stmt, cstate);
                               1057                 :         /* We're done examining the SelectStmt */
 5300 tgl                      1058            1317 :         return false;
                               1059                 :     }
                               1060           17535 :     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              72 :         return false;
                               1068                 :     }
                               1069           17463 :     if (IsA(node, JoinExpr))
                               1070                 :     {
 5050 bruce                    1071             813 :         JoinExpr   *j = (JoinExpr *) node;
                               1072                 : 
 5300 tgl                      1073             813 :         switch (j->jointype)
                               1074                 :         {
                               1075             789 :             case JOIN_INNER:
                               1076             789 :                 checkWellFormedRecursionWalker(j->larg, cstate);
                               1077             789 :                 checkWellFormedRecursionWalker(j->rarg, cstate);
                               1078             789 :                 checkWellFormedRecursionWalker(j->quals, cstate);
                               1079             789 :                 break;
                               1080              18 :             case JOIN_LEFT:
                               1081              18 :                 checkWellFormedRecursionWalker(j->larg, cstate);
                               1082              18 :                 if (save_context == RECURSION_OK)
                               1083               3 :                     cstate->context = RECURSION_OUTERJOIN;
                               1084              18 :                 checkWellFormedRecursionWalker(j->rarg, cstate);
                               1085              15 :                 cstate->context = save_context;
                               1086              15 :                 checkWellFormedRecursionWalker(j->quals, cstate);
                               1087              15 :                 break;
                               1088               3 :             case JOIN_FULL:
                               1089               3 :                 if (save_context == RECURSION_OK)
                               1090               3 :                     cstate->context = RECURSION_OUTERJOIN;
                               1091               3 :                 checkWellFormedRecursionWalker(j->larg, cstate);
 5300 tgl                      1092 UBC           0 :                 checkWellFormedRecursionWalker(j->rarg, cstate);
                               1093               0 :                 cstate->context = save_context;
                               1094               0 :                 checkWellFormedRecursionWalker(j->quals, cstate);
                               1095               0 :                 break;
 5300 tgl                      1096 CBC           3 :             case JOIN_RIGHT:
                               1097               3 :                 if (save_context == RECURSION_OK)
                               1098               3 :                     cstate->context = RECURSION_OUTERJOIN;
                               1099               3 :                 checkWellFormedRecursionWalker(j->larg, cstate);
 5300 tgl                      1100 UBC           0 :                 cstate->context = save_context;
                               1101               0 :                 checkWellFormedRecursionWalker(j->rarg, cstate);
                               1102               0 :                 checkWellFormedRecursionWalker(j->quals, cstate);
                               1103               0 :                 break;
                               1104               0 :             default:
                               1105               0 :                 elog(ERROR, "unrecognized join type: %d",
                               1106                 :                      (int) j->jointype);
                               1107                 :         }
 5300 tgl                      1108 CBC         804 :         return false;
                               1109                 :     }
                               1110           16650 :     if (IsA(node, SubLink))
                               1111                 :     {
 5050 bruce                    1112              21 :         SubLink    *sl = (SubLink *) node;
                               1113                 : 
                               1114                 :         /*
                               1115                 :          * we intentionally override outer context, since subquery is
                               1116                 :          * independent
                               1117                 :          */
 5300 tgl                      1118              21 :         cstate->context = RECURSION_SUBLINK;
                               1119              21 :         checkWellFormedRecursionWalker(sl->subselect, cstate);
                               1120              15 :         cstate->context = save_context;
                               1121              15 :         checkWellFormedRecursionWalker(sl->testexpr, cstate);
                               1122              15 :         return false;
                               1123                 :     }
                               1124           16629 :     return raw_expression_tree_walker(node,
                               1125                 :                                       checkWellFormedRecursionWalker,
                               1126                 :                                       (void *) cstate);
                               1127                 : }
                               1128                 : 
                               1129                 : /*
                               1130                 :  * subroutine for checkWellFormedRecursionWalker: process a SelectStmt
                               1131                 :  * without worrying about its WITH clause
                               1132                 :  */
                               1133                 : static void
                               1134            1371 : checkWellFormedSelectStmt(SelectStmt *stmt, CteState *cstate)
                               1135                 : {
                               1136            1371 :     RecursionContext save_context = cstate->context;
                               1137                 : 
                               1138            1371 :     if (save_context != RECURSION_OK)
                               1139                 :     {
                               1140                 :         /* just recurse without changing state */
                               1141             537 :         raw_expression_tree_walker((Node *) stmt,
                               1142                 :                                    checkWellFormedRecursionWalker,
                               1143                 :                                    (void *) cstate);
                               1144                 :     }
                               1145                 :     else
                               1146                 :     {
                               1147             834 :         switch (stmt->op)
                               1148                 :         {
                               1149             828 :             case SETOP_NONE:
                               1150                 :             case SETOP_UNION:
                               1151             828 :                 raw_expression_tree_walker((Node *) stmt,
                               1152                 :                                            checkWellFormedRecursionWalker,
                               1153                 :                                            (void *) cstate);
                               1154             795 :                 break;
                               1155               3 :             case SETOP_INTERSECT:
                               1156               3 :                 if (stmt->all)
 5300 tgl                      1157 UBC           0 :                     cstate->context = RECURSION_INTERSECT;
 5300 tgl                      1158 CBC           3 :                 checkWellFormedRecursionWalker((Node *) stmt->larg,
                               1159                 :                                                cstate);
                               1160               3 :                 checkWellFormedRecursionWalker((Node *) stmt->rarg,
                               1161                 :                                                cstate);
 5300 tgl                      1162 UBC           0 :                 cstate->context = save_context;
                               1163               0 :                 checkWellFormedRecursionWalker((Node *) stmt->sortClause,
                               1164                 :                                                cstate);
                               1165               0 :                 checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
                               1166                 :                                                cstate);
                               1167               0 :                 checkWellFormedRecursionWalker((Node *) stmt->limitCount,
                               1168                 :                                                cstate);
                               1169               0 :                 checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
                               1170                 :                                                cstate);
                               1171                 :                 /* stmt->withClause is intentionally ignored here */
                               1172               0 :                 break;
 5300 tgl                      1173 CBC           3 :             case SETOP_EXCEPT:
                               1174               3 :                 if (stmt->all)
 5300 tgl                      1175 UBC           0 :                     cstate->context = RECURSION_EXCEPT;
 5300 tgl                      1176 CBC           3 :                 checkWellFormedRecursionWalker((Node *) stmt->larg,
                               1177                 :                                                cstate);
                               1178               3 :                 cstate->context = RECURSION_EXCEPT;
                               1179               3 :                 checkWellFormedRecursionWalker((Node *) stmt->rarg,
                               1180                 :                                                cstate);
 5300 tgl                      1181 UBC           0 :                 cstate->context = save_context;
                               1182               0 :                 checkWellFormedRecursionWalker((Node *) stmt->sortClause,
                               1183                 :                                                cstate);
                               1184               0 :                 checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
                               1185                 :                                                cstate);
                               1186               0 :                 checkWellFormedRecursionWalker((Node *) stmt->limitCount,
                               1187                 :                                                cstate);
                               1188               0 :                 checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
                               1189                 :                                                cstate);
                               1190                 :                 /* stmt->withClause is intentionally ignored here */
                               1191               0 :                 break;
                               1192               0 :             default:
                               1193               0 :                 elog(ERROR, "unrecognized set op: %d",
                               1194                 :                      (int) stmt->op);
                               1195                 :         }
                               1196                 :     }
 5300 tgl                      1197 CBC        1317 : }
        

Generated by: LCOV version v1.16-55-g56c0a2a