~ubuntu-branches/ubuntu/trusty/postgresql-8.4/trusty

« back to all changes in this revision

Viewing changes to src/backend/parser/parse_cte.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-07-11 16:59:35 UTC
  • mfrom: (5.1.1 karmic)
  • Revision ID: james.westby@ubuntu.com-20090711165935-jfwin6gfrxf0gfsi
Tags: 8.4.0-2
* debian/libpq-dev.install: Ship catalog/genbki.h. (Closes: #536139)
* debian/rules: Drop --enable-cassert for final release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
8
8
 *
9
9
 *
10
10
 * IDENTIFICATION
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 $
12
12
 *
13
13
 *-------------------------------------------------------------------------
14
14
 */
25
25
typedef enum
26
26
{
27
27
        RECURSION_OK,
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;
34
34
 
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[] = {
37
37
        /* RECURSION_OK */
38
38
        NULL,
39
39
        /* RECURSION_NONRECURSIVETERM */
56
56
 */
57
57
typedef struct CteItem
58
58
{
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
 
62
                                                                                 * identified */
 
63
        Bitmapset  *depends_on;         /* CTEs depended on (not including self) */
63
64
} CteItem;
64
65
 
65
66
/* CteState is what we need to pass around in the tree walkers */
67
68
{
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 */
94
95
 
95
96
/*
96
97
 * transformWithClause -
97
 
 *    Transform the list of WITH clause "common table expressions" into
98
 
 *    Query nodes.
 
98
 *        Transform the list of WITH clause "common table expressions" into
 
99
 *        Query nodes.
99
100
 *
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);
112
113
 
113
114
        /*
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.
116
117
         *
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.
119
120
         */
120
121
        foreach(lc, withClause->ctes)
121
122
        {
129
130
                        if (strcmp(cte->ctename, cte2->ctename) == 0)
130
131
                                ereport(ERROR,
131
132
                                                (errcode(ERRCODE_DUPLICATE_ALIAS),
132
 
                                                 errmsg("WITH query name \"%s\" specified more than once",
133
 
                                                                cte2->ctename),
 
133
                                        errmsg("WITH query name \"%s\" specified more than once",
 
134
                                                   cte2->ctename),
134
135
                                                 parser_errposition(pstate, cte2->location)));
135
136
                }
136
137
 
141
142
        if (withClause->recursive)
142
143
        {
143
144
                /*
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.
147
148
                 */
148
 
                CteState cstate;
149
 
                int             i;
 
149
                CteState        cstate;
 
150
                int                     i;
150
151
 
151
152
                cstate.pstate = pstate;
152
153
                cstate.numitems = list_length(withClause->ctes);
171
172
                checkWellFormedRecursion(&cstate);
172
173
 
173
174
                /*
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.
178
179
                 */
179
180
                for (i = 0; i < cstate.numitems; i++)
180
181
                {
191
192
                        CommonTableExpr *cte = cstate.items[i].cte;
192
193
 
193
194
                        /*
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.
197
198
                         */
198
199
                        if (cte->cterecursive)
199
200
                        {
200
 
                                Node   *nrt;
201
 
                                Query  *nrq;
 
201
                                Node       *nrt;
 
202
                                Query      *nrq;
202
203
 
203
204
                                if (!cstate.items[i].non_recursive_term)
204
205
                                        elog(ERROR, "could not find non-recursive term for %s",
216
217
        {
217
218
                /*
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.
224
224
                 */
225
225
                pstate->p_future_ctes = list_copy(withClause->ctes);
226
226
 
232
232
                        pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
233
233
                        pstate->p_future_ctes = list_delete_first(pstate->p_future_ctes);
234
234
                }
235
 
        }
 
235
        }
236
236
 
237
237
        return pstate->p_ctenamespace;
238
238
}
246
246
static void
247
247
analyzeCTE(ParseState *pstate, CommonTableExpr *cte)
248
248
{
249
 
        Query  *query;
 
249
        Query      *query;
250
250
 
251
251
        /* Analysis not done already */
252
252
        Assert(IsA(cte->ctequery, SelectStmt));
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))));
272
272
 
273
273
        if (!cte->cterecursive)
274
274
        {
279
279
        {
280
280
                /*
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.
285
285
                 */
286
286
                ListCell   *lctlist,
287
287
                                   *lctyp,
294
294
                foreach(lctlist, query->targetList)
295
295
                {
296
296
                        TargetEntry *te = (TargetEntry *) lfirst(lctlist);
297
 
                        Node   *texpr;
 
297
                        Node       *texpr;
298
298
 
299
299
                        if (te->resjunk)
300
300
                                continue;
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);
320
320
                }
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");
323
323
        }
324
324
}
335
335
 
336
336
        /*
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
 
341
         * handling.)
342
342
         */
343
343
        cte->ctecolnames = copyObject(cte->aliascolnames);
344
344
        cte->ctecoltypes = cte->ctecoltypmods = NIL;
363
363
                }
364
364
                coltype = exprType((Node *) te->expr);
365
365
                coltypmod = exprTypmod((Node *) te->expr);
 
366
 
366
367
                /*
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.
373
374
                 */
374
375
                if (cte->cterecursive && coltype == UNKNOWNOID)
375
376
                {
426
427
                /* If unqualified name, might be a CTE reference */
427
428
                if (!rv->schemaname)
428
429
                {
429
 
                        ListCell *lc;
430
 
                        int             i;
 
430
                        ListCell   *lc;
 
431
                        int                     i;
431
432
 
432
433
                        /* ... but first see if it's captured by an inner WITH */
433
434
                        foreach(lc, cstate->innerwiths)
434
435
                        {
435
 
                                List   *withlist = (List *) lfirst(lc);
436
 
                                ListCell *lc2;
 
436
                                List       *withlist = (List *) lfirst(lc);
 
437
                                ListCell   *lc2;
437
438
 
438
439
                                foreach(lc2, withlist)
439
440
                                {
440
441
                                        CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
441
442
 
442
443
                                        if (strcmp(rv->relname, cte->ctename) == 0)
443
 
                                                return false;                           /* yes, so bail out */
 
444
                                                return false;   /* yes, so bail out */
444
445
                                }
445
446
                        }
446
447
 
451
452
 
452
453
                                if (strcmp(rv->relname, cte->ctename) == 0)
453
454
                                {
454
 
                                        int             myindex = cstate->curitem;
 
455
                                        int                     myindex = cstate->curitem;
455
456
 
456
457
                                        if (i != myindex)
457
458
                                        {
474
475
        if (IsA(node, SelectStmt))
475
476
        {
476
477
                SelectStmt *stmt = (SelectStmt *) node;
477
 
                ListCell *lc;
 
478
                ListCell   *lc;
478
479
 
479
480
                if (stmt->withClause)
480
481
                {
482
483
                        {
483
484
                                /*
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.
487
488
                                 */
488
489
                                cstate->innerwiths = lcons(stmt->withClause->ctes,
489
490
                                                                                   cstate->innerwiths);
501
502
                        else
502
503
                        {
503
504
                                /*
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.
506
507
                                 */
507
508
                                ListCell   *cell1;
508
509
 
528
529
        if (IsA(node, WithClause))
529
530
        {
530
531
                /*
531
 
                 * Prevent raw_expression_tree_walker from recursing directly into
532
 
                 * a WITH clause.  We need that to happen only under the control
533
 
                 * of the code above.
 
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
 
534
                 * code above.
534
535
                 */
535
536
                return false;
536
537
        }
545
546
static void
546
547
TopologicalSort(ParseState *pstate, CteItem *items, int numitems)
547
548
{
548
 
        int i, j;
 
549
        int                     i,
 
550
                                j;
549
551
 
550
552
        /* for each position in sequence ... */
551
553
        for (i = 0; i < numitems; i++)
561
563
                if (j >= numitems)
562
564
                        ereport(ERROR,
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)));
566
568
 
567
569
                /*
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
 
571
                 * dependencies.
570
572
                 */
571
573
                if (i != j)
572
574
                {
573
 
                        CteItem tmp;
574
 
                                
 
575
                        CteItem         tmp;
 
576
 
575
577
                        tmp = items[i];
576
578
                        items[i] = items[j];
577
579
                        items[j] = tmp;
578
580
                }
 
581
 
579
582
                /*
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.
582
585
                 */
583
586
                for (j = i + 1; j < numitems; j++)
584
587
                {
600
603
        for (i = 0; i < cstate->numitems; i++)
601
604
        {
602
605
                CommonTableExpr *cte = cstate->items[i].cte;
603
 
                SelectStmt              *stmt = (SelectStmt *) cte->ctequery;
 
606
                SelectStmt *stmt = (SelectStmt *) cte->ctequery;
604
607
 
605
 
                Assert(IsA(stmt, SelectStmt));                          /* not analyzed yet */
 
608
                Assert(IsA(stmt, SelectStmt));  /* not analyzed yet */
606
609
 
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");
636
639
 
637
640
                /*
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.)
643
646
                 */
644
647
                if (stmt->sortClause)
645
648
                        ereport(ERROR,
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)
651
654
                        ereport(ERROR,
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))));
668
671
 
669
672
                /*
670
673
                 * Save non_recursive_term.
690
693
                /* If unqualified name, might be a CTE reference */
691
694
                if (!rv->schemaname)
692
695
                {
693
 
                        ListCell *lc;
 
696
                        ListCell   *lc;
694
697
                        CommonTableExpr *mycte;
695
698
 
696
699
                        /* ... but first see if it's captured by an inner WITH */
697
700
                        foreach(lc, cstate->innerwiths)
698
701
                        {
699
 
                                List   *withlist = (List *) lfirst(lc);
700
 
                                ListCell *lc2;
 
702
                                List       *withlist = (List *) lfirst(lc);
 
703
                                ListCell   *lc2;
701
704
 
702
705
                                foreach(lc2, withlist)
703
706
                                {
704
707
                                        CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);
705
708
 
706
709
                                        if (strcmp(rv->relname, cte->ctename) == 0)
707
 
                                                return false;                           /* yes, so bail out */
 
710
                                                return false;   /* yes, so bail out */
708
711
                                }
709
712
                        }
710
713
 
735
738
        if (IsA(node, SelectStmt))
736
739
        {
737
740
                SelectStmt *stmt = (SelectStmt *) node;
738
 
                ListCell *lc;
 
741
                ListCell   *lc;
739
742
 
740
743
                if (stmt->withClause)
741
744
                {
743
746
                        {
744
747
                                /*
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.
748
751
                                 */
749
752
                                cstate->innerwiths = lcons(stmt->withClause->ctes,
750
753
                                                                                   cstate->innerwiths);
760
763
                        else
761
764
                        {
762
765
                                /*
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.
765
768
                                 */
766
769
                                ListCell   *cell1;
767
770
 
779
782
                        }
780
783
                }
781
784
                else
782
 
                                checkWellFormedSelectStmt(stmt, cstate);
 
785
                        checkWellFormedSelectStmt(stmt, cstate);
783
786
                /* We're done examining the SelectStmt */
784
787
                return false;
785
788
        }
786
789
        if (IsA(node, WithClause))
787
790
        {
788
791
                /*
789
 
                 * Prevent raw_expression_tree_walker from recursing directly into
790
 
                 * a WITH clause.  We need that to happen only under the control
791
 
                 * of the code above.
 
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
 
794
                 * code above.
792
795
                 */
793
796
                return false;
794
797
        }
795
798
        if (IsA(node, JoinExpr))
796
799
        {
797
 
                JoinExpr *j = (JoinExpr *) node;
 
800
                JoinExpr   *j = (JoinExpr *) node;
798
801
 
799
802
                switch (j->jointype)
800
803
                {
835
838
        }
836
839
        if (IsA(node, SubLink))
837
840
        {
838
 
                SubLink *sl = (SubLink *) node;
 
841
                SubLink    *sl = (SubLink *) node;
839
842
 
840
843
                /*
841
844
                 * we intentionally override outer context, since subquery is