11
* $PostgreSQL: pgsql/src/backend/parser/parse_cte.c,v 2.5 2009/01/01 17:23:45 momjian Exp $
11
* $PostgreSQL: pgsql/src/backend/parser/parse_cte.c,v 2.6 2009/06/11 14:49:00 momjian Exp $
13
13
*-------------------------------------------------------------------------
28
RECURSION_NONRECURSIVETERM, /* inside the left-hand term */
28
RECURSION_NONRECURSIVETERM, /* inside the left-hand term */
29
29
RECURSION_SUBLINK, /* inside a sublink */
30
30
RECURSION_OUTERJOIN, /* inside nullable side of an outer join */
31
31
RECURSION_INTERSECT, /* underneath INTERSECT (ALL) */
33
33
} RecursionContext;
35
35
/* Associated error messages --- each must have one %s for CTE name */
36
static const char * const recursion_errormsgs[] = {
36
static const char *const recursion_errormsgs[] = {
39
39
/* RECURSION_NONRECURSIVETERM */
57
57
typedef struct CteItem
59
CommonTableExpr *cte; /* One CTE to examine */
60
int id; /* Its ID number for dependencies */
61
Node *non_recursive_term; /* Its nonrecursive part, if identified */
62
Bitmapset *depends_on; /* CTEs depended on (not including self) */
59
CommonTableExpr *cte; /* One CTE to examine */
60
int id; /* Its ID number for dependencies */
61
Node *non_recursive_term; /* Its nonrecursive part, if
63
Bitmapset *depends_on; /* CTEs depended on (not including self) */
65
66
/* CteState is what we need to pass around in the tree walkers */
68
69
/* global state: */
69
70
ParseState *pstate; /* global parse state */
70
CteItem *items; /* array of CTEs and extra data */
71
CteItem *items; /* array of CTEs and extra data */
71
72
int numitems; /* number of CTEs */
72
73
/* working state during a tree walk: */
73
74
int curitem; /* index of item currently being examined */
96
97
* transformWithClause -
97
* Transform the list of WITH clause "common table expressions" into
98
* Transform the list of WITH clause "common table expressions" into
100
101
* The result is the list of transformed CTEs to be put into the output
101
102
* Query. (This is in fact the same as the ending value of p_ctenamespace,
111
112
Assert(pstate->p_future_ctes == NIL);
114
* For either type of WITH, there must not be duplicate CTE names in
115
* the list. Check this right away so we needn't worry later.
115
* For either type of WITH, there must not be duplicate CTE names in the
116
* list. Check this right away so we needn't worry later.
117
* Also, tentatively mark each CTE as non-recursive, and initialize
118
* its reference count to zero.
118
* Also, tentatively mark each CTE as non-recursive, and initialize its
119
* reference count to zero.
120
121
foreach(lc, withClause->ctes)
129
130
if (strcmp(cte->ctename, cte2->ctename) == 0)
131
132
(errcode(ERRCODE_DUPLICATE_ALIAS),
132
errmsg("WITH query name \"%s\" specified more than once",
133
errmsg("WITH query name \"%s\" specified more than once",
134
135
parser_errposition(pstate, cte2->location)));
141
142
if (withClause->recursive)
144
* For WITH RECURSIVE, we rearrange the list elements if needed
145
* to eliminate forward references. First, build a work array
146
* and set up the data structure needed by the tree walkers.
145
* For WITH RECURSIVE, we rearrange the list elements if needed to
146
* eliminate forward references. First, build a work array and set up
147
* the data structure needed by the tree walkers.
151
152
cstate.pstate = pstate;
152
153
cstate.numitems = list_length(withClause->ctes);
171
172
checkWellFormedRecursion(&cstate);
174
* Set up the ctenamespace for parse analysis. Per spec, all
175
* the WITH items are visible to all others, so stuff them all in
176
* before parse analysis. We build the list in safe processing
177
* order so that the planner can process the queries in sequence.
175
* Set up the ctenamespace for parse analysis. Per spec, all the WITH
176
* items are visible to all others, so stuff them all in before parse
177
* analysis. We build the list in safe processing order so that the
178
* planner can process the queries in sequence.
179
180
for (i = 0; i < cstate.numitems; i++)
191
192
CommonTableExpr *cte = cstate.items[i].cte;
194
* If it's recursive, we have to do a throwaway parse analysis
195
* of the non-recursive term in order to determine the set of
196
* output columns for the recursive CTE.
195
* If it's recursive, we have to do a throwaway parse analysis of
196
* the non-recursive term in order to determine the set of output
197
* columns for the recursive CTE.
198
199
if (cte->cterecursive)
203
204
if (!cstate.items[i].non_recursive_term)
204
205
elog(ERROR, "could not find non-recursive term for %s",
218
219
* For non-recursive WITH, just analyze each CTE in sequence and then
219
* add it to the ctenamespace. This corresponds to the spec's
220
* definition of the scope of each WITH name. However, to allow
221
* error reports to be aware of the possibility of an erroneous
222
* reference, we maintain a list in p_future_ctes of the
223
* not-yet-visible CTEs.
220
* add it to the ctenamespace. This corresponds to the spec's
221
* definition of the scope of each WITH name. However, to allow error
222
* reports to be aware of the possibility of an erroneous reference,
223
* we maintain a list in p_future_ctes of the not-yet-visible CTEs.
225
225
pstate->p_future_ctes = list_copy(withClause->ctes);
268
268
(errcode(ERRCODE_SYNTAX_ERROR),
269
269
errmsg("subquery in WITH cannot have SELECT INTO"),
270
270
parser_errposition(pstate,
271
exprLocation((Node *) query->intoClause))));
271
exprLocation((Node *) query->intoClause))));
273
273
if (!cte->cterecursive)
281
281
* Verify that the previously determined output column types match
282
* what the query really produced. We have to check this because
283
* the recursive term could have overridden the non-recursive term,
284
* and we don't have any easy way to fix that.
282
* what the query really produced. We have to check this because the
283
* recursive term could have overridden the non-recursive term, and we
284
* don't have any easy way to fix that.
286
286
ListCell *lctlist,
310
310
errmsg("recursive query \"%s\" column %d has type %s in non-recursive term but type %s overall",
311
311
cte->ctename, varattno,
312
312
format_type_with_typemod(lfirst_oid(lctyp),
313
lfirst_int(lctypmod)),
313
lfirst_int(lctypmod)),
314
314
format_type_with_typemod(exprType(texpr),
315
315
exprTypmod(texpr))),
316
316
errhint("Cast the output of the non-recursive term to the correct type."),
318
318
lctyp = lnext(lctyp);
319
319
lctypmod = lnext(lctypmod);
321
if (lctyp != NULL || lctypmod != NULL) /* shouldn't happen */
321
if (lctyp != NULL || lctypmod != NULL) /* shouldn't happen */
322
322
elog(ERROR, "wrong number of output columns in WITH");
337
337
* We need to determine column names and types. The alias column names
338
* override anything coming from the query itself. (Note: the SQL spec
339
* says that the alias list must be empty or exactly as long as the
340
* output column set; but we allow it to be shorter for consistency
341
* with Alias handling.)
338
* override anything coming from the query itself. (Note: the SQL spec
339
* says that the alias list must be empty or exactly as long as the output
340
* column set; but we allow it to be shorter for consistency with Alias
343
343
cte->ctecolnames = copyObject(cte->aliascolnames);
344
344
cte->ctecoltypes = cte->ctecoltypmods = NIL;
364
364
coltype = exprType((Node *) te->expr);
365
365
coltypmod = exprTypmod((Node *) te->expr);
367
368
* If the CTE is recursive, force the exposed column type of any
368
* "unknown" column to "text". This corresponds to the fact that
369
* SELECT 'foo' UNION SELECT 'bar' will ultimately produce text.
370
* We might see "unknown" as a result of an untyped literal in
371
* the non-recursive term's select list, and if we don't convert
372
* to text then we'll have a mismatch against the UNION result.
369
* "unknown" column to "text". This corresponds to the fact that
370
* SELECT 'foo' UNION SELECT 'bar' will ultimately produce text. We
371
* might see "unknown" as a result of an untyped literal in the
372
* non-recursive term's select list, and if we don't convert to text
373
* then we'll have a mismatch against the UNION result.
374
375
if (cte->cterecursive && coltype == UNKNOWNOID)
426
427
/* If unqualified name, might be a CTE reference */
427
428
if (!rv->schemaname)
432
433
/* ... but first see if it's captured by an inner WITH */
433
434
foreach(lc, cstate->innerwiths)
435
List *withlist = (List *) lfirst(lc);
436
List *withlist = (List *) lfirst(lc);
438
439
foreach(lc2, withlist)
440
441
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
442
443
if (strcmp(rv->relname, cte->ctename) == 0)
443
return false; /* yes, so bail out */
444
return false; /* yes, so bail out */
484
485
* In the RECURSIVE case, all query names of the WITH are
485
* visible to all WITH items as well as the main query.
486
* So push them all on, process, pop them all off.
486
* visible to all WITH items as well as the main query. So
487
* push them all on, process, pop them all off.
488
489
cstate->innerwiths = lcons(stmt->withClause->ctes,
489
490
cstate->innerwiths);
504
* In the non-RECURSIVE case, query names are visible to
505
* the WITH items after them and to the main query.
505
* In the non-RECURSIVE case, query names are visible to the
506
* WITH items after them and to the main query.
528
529
if (IsA(node, WithClause))
531
* Prevent raw_expression_tree_walker from recursing directly into
532
* a WITH clause. We need that to happen only under the control
532
* Prevent raw_expression_tree_walker from recursing directly into a
533
* WITH clause. We need that to happen only under the control of the
561
563
if (j >= numitems)
563
565
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
564
errmsg("mutual recursion between WITH items is not implemented"),
566
errmsg("mutual recursion between WITH items is not implemented"),
565
567
parser_errposition(pstate, items[i].cte->location)));
568
* Found one. Move it to front and remove it from every other
569
* item's dependencies.
570
* Found one. Move it to front and remove it from every other item's
576
578
items[i] = items[j];
580
* Items up through i are known to have no dependencies left,
581
* so we can skip them in this loop.
583
* Items up through i are known to have no dependencies left, so we
584
* can skip them in this loop.
583
586
for (j = i + 1; j < numitems; j++)
600
603
for (i = 0; i < cstate->numitems; i++)
602
605
CommonTableExpr *cte = cstate->items[i].cte;
603
SelectStmt *stmt = (SelectStmt *) cte->ctequery;
606
SelectStmt *stmt = (SelectStmt *) cte->ctequery;
605
Assert(IsA(stmt, SelectStmt)); /* not analyzed yet */
608
Assert(IsA(stmt, SelectStmt)); /* not analyzed yet */
607
610
/* Ignore items that weren't found to be recursive */
608
611
if (!cte->cterecursive)
631
634
cstate->context = RECURSION_OK;
632
635
checkWellFormedRecursionWalker((Node *) stmt->rarg, cstate);
633
636
Assert(cstate->innerwiths == NIL);
634
if (cstate->selfrefcount != 1) /* shouldn't happen */
637
if (cstate->selfrefcount != 1) /* shouldn't happen */
635
638
elog(ERROR, "missing recursive reference");
638
* Disallow ORDER BY and similar decoration atop the UNION.
639
* These don't make sense because it's impossible to figure out what
640
* they mean when we have only part of the recursive query's results.
641
* (If we did allow them, we'd have to check for recursive references
641
* Disallow ORDER BY and similar decoration atop the UNION. These
642
* don't make sense because it's impossible to figure out what they
643
* mean when we have only part of the recursive query's results. (If
644
* we did allow them, we'd have to check for recursive references
642
645
* inside these subtrees.)
644
647
if (stmt->sortClause)
646
649
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
647
errmsg("ORDER BY in a recursive query is not implemented"),
650
errmsg("ORDER BY in a recursive query is not implemented"),
648
651
parser_errposition(cstate->pstate,
649
exprLocation((Node *) stmt->sortClause))));
652
exprLocation((Node *) stmt->sortClause))));
650
653
if (stmt->limitOffset)
652
655
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
664
667
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
665
668
errmsg("FOR UPDATE/SHARE in a recursive query is not implemented"),
666
669
parser_errposition(cstate->pstate,
667
exprLocation((Node *) stmt->lockingClause))));
670
exprLocation((Node *) stmt->lockingClause))));
670
673
* Save non_recursive_term.
690
693
/* If unqualified name, might be a CTE reference */
691
694
if (!rv->schemaname)
694
697
CommonTableExpr *mycte;
696
699
/* ... but first see if it's captured by an inner WITH */
697
700
foreach(lc, cstate->innerwiths)
699
List *withlist = (List *) lfirst(lc);
702
List *withlist = (List *) lfirst(lc);
702
705
foreach(lc2, withlist)
704
707
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
706
709
if (strcmp(rv->relname, cte->ctename) == 0)
707
return false; /* yes, so bail out */
710
return false; /* yes, so bail out */
745
748
* In the RECURSIVE case, all query names of the WITH are
746
* visible to all WITH items as well as the main query.
747
* So push them all on, process, pop them all off.
749
* visible to all WITH items as well as the main query. So
750
* push them all on, process, pop them all off.
749
752
cstate->innerwiths = lcons(stmt->withClause->ctes,
750
753
cstate->innerwiths);
763
* In the non-RECURSIVE case, query names are visible to
764
* the WITH items after them and to the main query.
766
* In the non-RECURSIVE case, query names are visible to the
767
* WITH items after them and to the main query.
782
checkWellFormedSelectStmt(stmt, cstate);
785
checkWellFormedSelectStmt(stmt, cstate);
783
786
/* We're done examining the SelectStmt */
786
789
if (IsA(node, WithClause))
789
* Prevent raw_expression_tree_walker from recursing directly into
790
* a WITH clause. We need that to happen only under the control
792
* Prevent raw_expression_tree_walker from recursing directly into a
793
* WITH clause. We need that to happen only under the control of the
795
798
if (IsA(node, JoinExpr))
797
JoinExpr *j = (JoinExpr *) node;
800
JoinExpr *j = (JoinExpr *) node;
799
802
switch (j->jointype)