1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.87 1998/09/16 14:25:37 thomas Exp $
12 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/memnodes.h"
24 #include "nodes/pg_list.h"
25 #include "parser/analyze.h"
26 #include "parser/parse_agg.h"
27 #include "parser/parse_clause.h"
28 #include "parser/parse_node.h"
29 #include "parser/parse_relation.h"
30 #include "parser/parse_target.h"
31 #include "utils/builtins.h"
32 #include "utils/mcxt.h"
34 #include "nodes/print.h"
37 static Query *transformStmt(ParseState *pstate, Node *stmt);
38 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
39 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
40 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
41 static Query *transformExtendStmt(ParseState *pstate, ExtendStmt *stmt);
42 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt);
43 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
44 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
45 static Query *transformCursorStmt(ParseState *pstate, SelectStmt *stmt);
46 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt);
52 * analyze a list of parse trees and transform them if necessary.
54 * Returns a list of transformed parse trees. Optimizable statements are
55 * all transformed to Query while the rest stays the same.
59 parse_analyze(List *pl, ParseState *parentParseState)
61 QueryTreeList *result;
65 result = malloc(sizeof(QueryTreeList));
66 result->len = length(pl);
67 result->qtrees = (Query **) malloc(result->len * sizeof(Query *));
72 elog(DEBUG, "parse tree from yacc:\n---\n%s\n---\n", nodeToString(lfirst(pl)));
75 pstate = make_parsestate(parentParseState);
76 result->qtrees[i++] = transformStmt(pstate, lfirst(pl));
77 if (pstate->p_target_relation != NULL)
78 heap_close(pstate->p_target_relation);
82 result->len += length(extras);
83 result->qtrees = (Query **) realloc(result->qtrees, result->len * sizeof(Query *));
86 result->qtrees[i++] = transformStmt(pstate, lfirst(extras));
87 if (pstate->p_target_relation != NULL)
88 heap_close(pstate->p_target_relation);
89 extras = lnext(extras);
102 * transform a Parse tree. If it is an optimizable statement, turn it
106 transformStmt(ParseState *pstate, Node *parseTree)
108 Query *result = NULL;
110 switch (nodeTag(parseTree))
112 /*------------------------
113 * Non-optimizable statements
114 *------------------------
117 result = transformCreateStmt(pstate, (CreateStmt *) parseTree);
121 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
125 result = transformExtendStmt(pstate, (ExtendStmt *) parseTree);
129 result = transformRuleStmt(pstate, (RuleStmt *) parseTree);
134 ViewStmt *n = (ViewStmt *) parseTree;
136 n->query = (Query *) transformStmt(pstate, (Node *) n->query);
137 result = makeNode(Query);
138 result->commandType = CMD_UTILITY;
139 result->utilityStmt = (Node *) n;
145 MemoryContext oldcontext;
148 * make sure that this Query is allocated in TopMemory
149 * context because vacuum spans transactions and we don't
150 * want to lose the vacuum Query due to end-of-transaction
153 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
154 result = makeNode(Query);
155 result->commandType = CMD_UTILITY;
156 result->utilityStmt = (Node *) parseTree;
157 MemoryContextSwitchTo(oldcontext);
163 ExplainStmt *n = (ExplainStmt *) parseTree;
165 result = makeNode(Query);
166 result->commandType = CMD_UTILITY;
167 n->query = transformStmt(pstate, (Node *) n->query);
168 result->utilityStmt = (Node *) parseTree;
172 /*------------------------
173 * Optimizable statements
174 *------------------------
177 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
181 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
185 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
189 if (!((SelectStmt *) parseTree)->portalname)
190 result = transformSelectStmt(pstate, (SelectStmt *) parseTree);
192 result = transformCursorStmt(pstate, (SelectStmt *) parseTree);
198 * other statments don't require any transformation-- just
199 * return the original parsetree, yea!
201 result = makeNode(Query);
202 result->commandType = CMD_UTILITY;
203 result->utilityStmt = (Node *) parseTree;
210 * transformDeleteStmt -
211 * transforms a Delete Statement
214 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
216 Query *qry = makeNode(Query);
218 qry->commandType = CMD_DELETE;
220 /* set up a range table */
221 makeRangeTable(pstate, stmt->relname, NULL);
223 qry->uniqueFlag = NULL;
225 /* fix where clause */
226 qry->qual = transformWhereClause(pstate, stmt->whereClause);
227 qry->hasSubLinks = pstate->p_hasSubLinks;
229 qry->rtable = pstate->p_rtable;
230 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
232 qry->hasAggs = pstate->p_hasAggs;
233 if (pstate->p_hasAggs)
234 parseCheckAggregates(pstate, qry);
236 return (Query *) qry;
240 * transformInsertStmt -
241 * transform an Insert Statement
244 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
246 Query *qry = makeNode(Query); /* make a new query tree */
249 qry->commandType = CMD_INSERT;
250 pstate->p_is_insert = true;
252 /* set up a range table */
253 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
255 qry->uniqueFlag = stmt->unique;
257 /* fix the target list */
258 icolumns = pstate->p_insert_columns = makeTargetNames(pstate, stmt->cols);
260 qry->targetList = transformTargetList(pstate, stmt->targetList);
262 /* DEFAULT handling */
263 if (length(qry->targetList) < pstate->p_target_relation->rd_att->natts &&
264 pstate->p_target_relation->rd_att->constr &&
265 pstate->p_target_relation->rd_att->constr->num_defval > 0)
267 Form_pg_attribute *att = pstate->p_target_relation->rd_att->attrs;
268 AttrDefault *defval = pstate->p_target_relation->rd_att->constr->defval;
269 int ndef = pstate->p_target_relation->rd_att->constr->num_defval;
272 * if stmt->cols == NIL then makeTargetNames returns list of all attrs.
273 * May have to shorten icolumns list...
275 if (stmt->cols == NIL)
278 int i = length(qry->targetList);
280 foreach(extrl, icolumns)
283 * decrements first, so if we started with zero items
284 * it will now be negative
290 * this an index into the targetList,
291 * so make sure we had one to start...
295 freeList(lnext(extrl));
310 foreach(tl, icolumns)
312 id = (Ident *) lfirst(tl);
313 if (namestrcmp(&(att[defval[ndef].adnum - 1]->attname), id->name) == 0)
316 if (tl != NIL) /* something given for this attr */
320 * Nothing given for this attr with DEFAULT expr, so add new
321 * TargetEntry to qry->targetList. Note, that we set resno to
322 * defval[ndef].adnum: it's what
323 * transformTargetList()->make_targetlist_expr() does for
324 * INSERT ... SELECT. But for INSERT ... VALUES
325 * pstate->p_last_resno is used. It doesn't matter for
326 * "normal" using (planner creates proper target list in
327 * preptlist.c), but may break RULEs in some way. It seems
328 * better to create proper target list here...
330 te = makeTargetEntry(makeResdom(defval[ndef].adnum,
331 att[defval[ndef].adnum - 1]->atttypid,
332 att[defval[ndef].adnum - 1]->atttypmod,
333 pstrdup(nameout(&(att[defval[ndef].adnum - 1]->attname))),
335 (Node *) stringToNode(defval[ndef].adbin));
336 qry->targetList = lappend(qry->targetList, te);
340 /* fix where clause */
341 qry->qual = transformWhereClause(pstate, stmt->whereClause);
344 * The havingQual has a similar meaning as "qual" in the where
345 * statement. So we can easily use the code from the "where clause"
346 * with some additional traversals done in
347 * .../optimizer/plan/planner.c
349 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
351 qry->hasSubLinks = pstate->p_hasSubLinks;
353 /* now the range table will not change */
354 qry->rtable = pstate->p_rtable;
355 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
357 qry->groupClause = transformGroupClause(pstate,
361 /* fix order clause */
362 qry->sortClause = transformSortClause(pstate,
368 qry->hasAggs = pstate->p_hasAggs;
369 if (pstate->p_hasAggs)
370 parseCheckAggregates(pstate, qry);
373 * The INSERT INTO ... SELECT ... could have a UNION in child, so
374 * unionClause may be false
376 qry->unionall = stmt->unionall;
377 qry->unionClause = transformUnionClause(stmt->unionClause, qry->targetList);
380 * If there is a havingQual but there are no aggregates, then there is
381 * something wrong with the query because having must contain
382 * aggregates in its expressions! Otherwise the query could have been
383 * formulated using the where clause.
385 if ((qry->hasAggs == false) && (qry->havingQual != NULL))
387 elog(ERROR, "This is not a valid having query!");
388 return (Query *) NIL;
391 return (Query *) qry;
396 * Create a table name from a list of fields.
399 makeTableName(void *elem,...)
404 char buf[NAMEDATALEN + 1];
408 va_start(args, elem);
413 /* not enough room for next part? then return nothing */
414 if ((strlen(buf) + strlen(name)) >= (sizeof(buf) - 1))
421 name = va_arg(args, void *);
426 name = palloc(strlen(buf) + 1);
433 CreateIndexName(char *table_name, char *column_name, char *label, List *indices)
439 char name2[NAMEDATALEN + 1];
441 /* use working storage, since we might be trying several possibilities */
442 strcpy(name2, column_name);
443 while (iname == NULL)
445 iname = makeTableName(table_name, name2, label, NULL);
446 /* unable to make a name at all? then quit */
453 index = lfirst(ilist);
454 if (strcasecmp(iname, index->idxname) == 0)
457 ilist = lnext(ilist);
459 /* ran through entire list? then no name conflict found so done */
463 /* the last one conflicted, so try a new name component */
467 sprintf(name2, "%s_%d", column_name, (pass + 1));
474 * transformCreateStmt -
475 * transforms the "create table" statement
476 * SQL92 allows constraints to be scattered all over, so thumb through
477 * the columns and collect all constraints into one place.
478 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
479 * then expand those into multiple IndexStmt blocks.
480 * - thomas 1997-12-02
483 transformCreateStmt(ParseState *pstate, CreateStmt *stmt)
486 int have_pkey = FALSE;
494 Constraint *constraint;
502 q->commandType = CMD_UTILITY;
504 elements = stmt->tableElts;
505 constraints = stmt->constraints;
509 while (elements != NIL)
511 element = lfirst(elements);
512 switch (nodeTag(element))
515 column = (ColumnDef *) element;
516 columns = lappend(columns, column);
518 if (column->is_sequence)
521 CreateSeqStmt *sequence;
523 constraint = makeNode(Constraint);
524 constraint->contype = CONSTR_DEFAULT;
525 constraint->name = makeTableName(stmt->relname, column->colname, "seq", NULL);
526 cstring = palloc(9 + strlen(constraint->name) + 2 + 1);
527 strcpy(cstring, "nextval('");
528 strcat(cstring, constraint->name);
529 strcat(cstring, "')");
530 constraint->def = cstring;
531 constraint->keys = NULL;
533 /* The parser only allows PRIMARY KEY as a constraint for the SERIAL type.
534 * So, if there is a constraint of any kind, assume it is that.
535 * If PRIMARY KEY is specified, then don't need to gin up a UNIQUE constraint
536 * since that will be covered already.
537 * - thomas 1998-09-15
539 if (column->constraints != NIL)
541 column->constraints = lappend(column->constraints, constraint);
545 column->constraints = lcons(constraint, NIL);
547 constraint = makeNode(Constraint);
548 constraint->contype = CONSTR_UNIQUE;
549 constraint->name = makeTableName(stmt->relname, column->colname, "key", NULL);
550 column->constraints = lappend(column->constraints, constraint);
553 sequence = makeNode(CreateSeqStmt);
554 sequence->seqname = pstrdup(constraint->name);
555 sequence->options = NIL;
557 elog(NOTICE, "CREATE TABLE will create implicit sequence %s for SERIAL column %s.%s",
558 sequence->seqname, stmt->relname, column->colname);
560 ilist = lcons(sequence, NIL);
563 if (column->constraints != NIL)
565 clist = column->constraints;
568 constraint = lfirst(clist);
569 switch (constraint->contype)
572 if (column->is_not_null)
573 elog(ERROR, "CREATE TABLE/NOT NULL already specified"
574 " for %s.%s", stmt->relname, column->colname);
575 column->is_not_null = TRUE;
579 if (column->defval != NULL)
580 elog(ERROR, "CREATE TABLE/DEFAULT multiple values specified"
581 " for %s.%s", stmt->relname, column->colname);
582 column->defval = constraint->def;
586 if (constraint->name == NULL)
587 constraint->name = makeTableName(stmt->relname, "pkey", NULL);
588 if (constraint->keys == NIL)
589 constraint->keys = lappend(constraint->keys, column);
590 dlist = lappend(dlist, constraint);
594 if (constraint->name == NULL)
595 constraint->name = makeTableName(stmt->relname, column->colname, "key", NULL);
596 if (constraint->keys == NIL)
597 constraint->keys = lappend(constraint->keys, column);
598 dlist = lappend(dlist, constraint);
602 constraints = lappend(constraints, constraint);
603 if (constraint->name == NULL)
604 constraint->name = makeTableName(stmt->relname, column->colname, NULL);
608 elog(ERROR, "parser: internal error; unrecognized constraint", NULL);
611 clist = lnext(clist);
617 constraint = (Constraint *) element;
618 switch (constraint->contype)
621 if (constraint->name == NULL)
622 constraint->name = makeTableName(stmt->relname, "pkey", NULL);
623 dlist = lappend(dlist, constraint);
628 if (constraint->name == NULL)
629 constraint->name = makeTableName(stmt->relname, "key", NULL);
631 dlist = lappend(dlist, constraint);
635 constraints = lappend(constraints, constraint);
640 elog(ERROR, "parser: internal error; illegal context for constraint", NULL);
643 elog(ERROR, "parser: internal error; unrecognized constraint", NULL);
649 elog(ERROR, "parser: internal error; unrecognized node", NULL);
652 elements = lnext(elements);
655 stmt->tableElts = columns;
656 stmt->constraints = constraints;
658 /* Now run through the "deferred list" to complete the query transformation.
659 * For PRIMARY KEYs, mark each column as NOT NULL and create an index.
660 * For UNIQUE, create an index as for PRIMARY KEYS, but do not insist on NOT NULL.
662 * Note that this code does not currently look for all possible redundant cases
663 * and either ignore or stop with warning. The create might fail later when
664 * names for indices turn out to be redundant, or a user might have specified
665 * extra useless indices which might hurt performance. - thomas 1997-12-08
669 constraint = lfirst(dlist);
670 if (nodeTag(constraint) != T_Constraint)
671 elog(ERROR, "parser: internal error; unrecognized deferred node", NULL);
673 if (constraint->contype == CONSTR_PRIMARY)
676 elog(ERROR, "CREATE TABLE/PRIMARY KEY multiple primary keys"
677 " for table %s are not legal", stmt->relname);
681 else if (constraint->contype != CONSTR_UNIQUE)
682 elog(ERROR, "parser: internal error; unrecognized deferred constraint", NULL);
684 index = makeNode(IndexStmt);
686 index->unique = TRUE;
687 if (constraint->name != NULL)
688 index->idxname = constraint->name;
689 else if (constraint->contype == CONSTR_PRIMARY)
692 elog(ERROR, "CREATE TABLE/PRIMARY KEY multiple keys for table %s are not legal", stmt->relname);
695 index->idxname = makeTableName(stmt->relname, "pkey", NULL);
698 index->idxname = NULL;
700 index->relname = stmt->relname;
701 index->accessMethod = "btree";
702 index->indexParams = NIL;
703 index->withClause = NIL;
704 index->whereClause = NULL;
706 keys = constraint->keys;
710 columns = stmt->tableElts;
712 while (columns != NIL)
714 column = lfirst(columns);
715 if (strcasecmp(column->colname, key->name) == 0)
719 columns = lnext(columns);
722 elog(ERROR, "parser: column '%s' in key does not exist", key->name);
724 if (constraint->contype == CONSTR_PRIMARY)
725 column->is_not_null = TRUE;
726 iparam = makeNode(IndexElem);
727 iparam->name = strcpy(palloc(strlen(column->colname) + 1), column->colname);
729 iparam->class = NULL;
730 iparam->typename = NULL;
731 index->indexParams = lappend(index->indexParams, iparam);
733 if (index->idxname == NULL)
734 index->idxname = CreateIndexName(stmt->relname, iparam->name, "key", ilist);
739 if (index->idxname == NULL)
740 elog(ERROR, "parser: unable to construct implicit index for table %s"
741 "; name too long", stmt->relname);
743 elog(NOTICE, "CREATE TABLE/%s will create implicit index %s for table %s",
744 ((constraint->contype == CONSTR_PRIMARY) ? "PRIMARY KEY" : "UNIQUE"),
745 index->idxname, stmt->relname);
747 ilist = lappend(ilist, index);
748 dlist = lnext(dlist);
751 q->utilityStmt = (Node *) stmt;
758 * transformIndexStmt -
759 * transforms the qualification of the index statement
762 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
766 qry = makeNode(Query);
767 qry->commandType = CMD_UTILITY;
769 /* take care of the where clause */
770 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
771 qry->hasSubLinks = pstate->p_hasSubLinks;
773 stmt->rangetable = pstate->p_rtable;
775 qry->utilityStmt = (Node *) stmt;
781 * transformExtendStmt -
782 * transform the qualifications of the Extend Index Statement
786 transformExtendStmt(ParseState *pstate, ExtendStmt *stmt)
790 qry = makeNode(Query);
791 qry->commandType = CMD_UTILITY;
793 /* take care of the where clause */
794 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
795 qry->hasSubLinks = pstate->p_hasSubLinks;
797 stmt->rangetable = pstate->p_rtable;
799 qry->utilityStmt = (Node *) stmt;
804 * transformRuleStmt -
805 * transform a Create Rule Statement. The actions is a list of parse
806 * trees which is transformed into a list of query trees.
809 transformRuleStmt(ParseState *pstate, RuleStmt *stmt)
815 qry = makeNode(Query);
816 qry->commandType = CMD_UTILITY;
819 * 'instead nothing' rules with a qualification need a query a
820 * rangetable so the rewrite handler can add the negated rule
821 * qualification to the original query. We create a query with the new
822 * command type CMD_NOTHING here that is treated special by the
825 if (stmt->actions == NIL)
827 Query *nothing_qry = makeNode(Query);
829 nothing_qry->commandType = CMD_NOTHING;
831 addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
833 addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
836 nothing_qry->rtable = pstate->p_rtable;
838 stmt->actions = lappend(NIL, nothing_qry);
841 actions = stmt->actions;
844 * transform each statment, like parse_analyze()
846 while (actions != NIL)
850 * NOTE: 'CURRENT' must always have a varno equal to 1 and 'NEW'
853 addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
855 addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
858 pstate->p_last_resno = 1;
859 pstate->p_is_rule = true; /* for expand all */
860 pstate->p_hasAggs = false;
862 action = (Query *) lfirst(actions);
863 if (action->commandType != CMD_NOTHING)
864 lfirst(actions) = transformStmt(pstate, lfirst(actions));
865 actions = lnext(actions);
868 /* take care of the where clause */
869 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
870 qry->hasSubLinks = pstate->p_hasSubLinks;
872 qry->utilityStmt = (Node *) stmt;
878 * transformSelectStmt -
879 * transforms a Select Statement
883 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
885 Query *qry = makeNode(Query);
887 qry->commandType = CMD_SELECT;
889 /* set up a range table */
890 makeRangeTable(pstate, NULL, stmt->fromClause);
892 qry->uniqueFlag = stmt->unique;
894 qry->into = stmt->into;
895 qry->isPortal = FALSE;
897 qry->targetList = transformTargetList(pstate, stmt->targetList);
899 qry->qual = transformWhereClause(pstate, stmt->whereClause);
902 * The havingQual has a similar meaning as "qual" in the where
903 * statement. So we can easily use the code from the "where clause"
904 * with some additional traversals done in
905 * .../optimizer/plan/planner.c
907 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
909 qry->hasSubLinks = pstate->p_hasSubLinks;
911 qry->sortClause = transformSortClause(pstate,
917 qry->groupClause = transformGroupClause(pstate,
920 qry->rtable = pstate->p_rtable;
922 qry->hasAggs = pstate->p_hasAggs;
923 if (pstate->p_hasAggs)
924 parseCheckAggregates(pstate, qry);
927 * The INSERT INTO ... SELECT ... could have a UNION in child, so
928 * unionClause may be false
930 qry->unionall = stmt->unionall;
931 qry->unionClause = transformUnionClause(stmt->unionClause, qry->targetList);
934 * If there is a havingQual but there are no aggregates, then there is
935 * something wrong with the query because having must contain
936 * aggregates in its expressions! Otherwise the query could have been
937 * formulated using the where clause.
939 if ((qry->hasAggs == false) && (qry->havingQual != NULL))
941 elog(ERROR, "This is not a valid having query!");
942 return (Query *) NIL;
945 return (Query *) qry;
949 * transformUpdateStmt -
950 * transforms an update statement
954 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
956 Query *qry = makeNode(Query);
958 qry->commandType = CMD_UPDATE;
959 pstate->p_is_update = true;
962 * the FROM clause is non-standard SQL syntax. We used to be able to
963 * do this with REPLACE in POSTQUEL so we keep the feature.
965 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
967 qry->targetList = transformTargetList(pstate, stmt->targetList);
969 qry->qual = transformWhereClause(pstate, stmt->whereClause);
970 qry->hasSubLinks = pstate->p_hasSubLinks;
972 qry->rtable = pstate->p_rtable;
974 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
976 qry->hasAggs = pstate->p_hasAggs;
977 if (pstate->p_hasAggs)
978 parseCheckAggregates(pstate, qry);
980 return (Query *) qry;
984 * transformCursorStmt -
985 * transform a Create Cursor Statement
989 transformCursorStmt(ParseState *pstate, SelectStmt *stmt)
993 qry = transformSelectStmt(pstate, stmt);
995 qry->into = stmt->portalname;
996 qry->isPortal = TRUE;
997 qry->isBinary = stmt->binary; /* internal portal */