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.88 1998/09/25 13:36:00 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 static Query *transformStmt(ParseState *pstate, Node *stmt);
35 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
36 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
37 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
38 static Query *transformExtendStmt(ParseState *pstate, ExtendStmt *stmt);
39 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt);
40 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
41 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
42 static Query *transformCursorStmt(ParseState *pstate, SelectStmt *stmt);
43 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt);
49 * analyze a list of parse trees and transform them if necessary.
51 * Returns a list of transformed parse trees. Optimizable statements are
52 * all transformed to Query while the rest stays the same.
56 parse_analyze(List *pl, ParseState *parentParseState)
58 QueryTreeList *result;
62 result = malloc(sizeof(QueryTreeList));
63 result->len = length(pl);
64 result->qtrees = (Query **) malloc(result->len * sizeof(Query *));
68 pstate = make_parsestate(parentParseState);
69 result->qtrees[i++] = transformStmt(pstate, lfirst(pl));
70 if (pstate->p_target_relation != NULL)
71 heap_close(pstate->p_target_relation);
75 result->len += length(extras);
76 result->qtrees = (Query **) realloc(result->qtrees, result->len * sizeof(Query *));
79 result->qtrees[i++] = transformStmt(pstate, lfirst(extras));
80 if (pstate->p_target_relation != NULL)
81 heap_close(pstate->p_target_relation);
82 extras = lnext(extras);
95 * transform a Parse tree. If it is an optimizable statement, turn it
99 transformStmt(ParseState *pstate, Node *parseTree)
101 Query *result = NULL;
103 switch (nodeTag(parseTree))
105 /*------------------------
106 * Non-optimizable statements
107 *------------------------
110 result = transformCreateStmt(pstate, (CreateStmt *) parseTree);
114 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
118 result = transformExtendStmt(pstate, (ExtendStmt *) parseTree);
122 result = transformRuleStmt(pstate, (RuleStmt *) parseTree);
127 ViewStmt *n = (ViewStmt *) parseTree;
129 n->query = (Query *) transformStmt(pstate, (Node *) n->query);
130 result = makeNode(Query);
131 result->commandType = CMD_UTILITY;
132 result->utilityStmt = (Node *) n;
138 MemoryContext oldcontext;
141 * make sure that this Query is allocated in TopMemory
142 * context because vacuum spans transactions and we don't
143 * want to lose the vacuum Query due to end-of-transaction
146 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
147 result = makeNode(Query);
148 result->commandType = CMD_UTILITY;
149 result->utilityStmt = (Node *) parseTree;
150 MemoryContextSwitchTo(oldcontext);
156 ExplainStmt *n = (ExplainStmt *) parseTree;
158 result = makeNode(Query);
159 result->commandType = CMD_UTILITY;
160 n->query = transformStmt(pstate, (Node *) n->query);
161 result->utilityStmt = (Node *) parseTree;
165 /*------------------------
166 * Optimizable statements
167 *------------------------
170 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
174 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
178 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
182 if (!((SelectStmt *) parseTree)->portalname)
183 result = transformSelectStmt(pstate, (SelectStmt *) parseTree);
185 result = transformCursorStmt(pstate, (SelectStmt *) parseTree);
191 * other statments don't require any transformation-- just
192 * return the original parsetree, yea!
194 result = makeNode(Query);
195 result->commandType = CMD_UTILITY;
196 result->utilityStmt = (Node *) parseTree;
203 * transformDeleteStmt -
204 * transforms a Delete Statement
207 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
209 Query *qry = makeNode(Query);
211 qry->commandType = CMD_DELETE;
213 /* set up a range table */
214 makeRangeTable(pstate, stmt->relname, NULL);
216 qry->uniqueFlag = NULL;
218 /* fix where clause */
219 qry->qual = transformWhereClause(pstate, stmt->whereClause);
220 qry->hasSubLinks = pstate->p_hasSubLinks;
222 qry->rtable = pstate->p_rtable;
223 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
225 qry->hasAggs = pstate->p_hasAggs;
226 if (pstate->p_hasAggs)
227 parseCheckAggregates(pstate, qry);
229 return (Query *) qry;
233 * transformInsertStmt -
234 * transform an Insert Statement
237 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
239 Query *qry = makeNode(Query); /* make a new query tree */
242 qry->commandType = CMD_INSERT;
243 pstate->p_is_insert = true;
245 /* set up a range table */
246 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
248 qry->uniqueFlag = stmt->unique;
250 /* fix the target list */
251 icolumns = pstate->p_insert_columns = makeTargetNames(pstate, stmt->cols);
253 qry->targetList = transformTargetList(pstate, stmt->targetList);
255 /* DEFAULT handling */
256 if (length(qry->targetList) < pstate->p_target_relation->rd_att->natts &&
257 pstate->p_target_relation->rd_att->constr &&
258 pstate->p_target_relation->rd_att->constr->num_defval > 0)
260 Form_pg_attribute *att = pstate->p_target_relation->rd_att->attrs;
261 AttrDefault *defval = pstate->p_target_relation->rd_att->constr->defval;
262 int ndef = pstate->p_target_relation->rd_att->constr->num_defval;
265 * if stmt->cols == NIL then makeTargetNames returns list of all attrs.
266 * May have to shorten icolumns list...
268 if (stmt->cols == NIL)
271 int i = length(qry->targetList);
273 foreach(extrl, icolumns)
276 * decrements first, so if we started with zero items
277 * it will now be negative
283 * this an index into the targetList,
284 * so make sure we had one to start...
288 freeList(lnext(extrl));
303 foreach(tl, icolumns)
305 id = (Ident *) lfirst(tl);
306 if (namestrcmp(&(att[defval[ndef].adnum - 1]->attname), id->name) == 0)
309 if (tl != NIL) /* something given for this attr */
313 * Nothing given for this attr with DEFAULT expr, so add new
314 * TargetEntry to qry->targetList. Note, that we set resno to
315 * defval[ndef].adnum: it's what
316 * transformTargetList()->make_targetlist_expr() does for
317 * INSERT ... SELECT. But for INSERT ... VALUES
318 * pstate->p_last_resno is used. It doesn't matter for
319 * "normal" using (planner creates proper target list in
320 * preptlist.c), but may break RULEs in some way. It seems
321 * better to create proper target list here...
323 te = makeTargetEntry(makeResdom(defval[ndef].adnum,
324 att[defval[ndef].adnum - 1]->atttypid,
325 att[defval[ndef].adnum - 1]->atttypmod,
326 pstrdup(nameout(&(att[defval[ndef].adnum - 1]->attname))),
328 (Node *) stringToNode(defval[ndef].adbin));
329 qry->targetList = lappend(qry->targetList, te);
333 /* fix where clause */
334 qry->qual = transformWhereClause(pstate, stmt->whereClause);
337 * The havingQual has a similar meaning as "qual" in the where
338 * statement. So we can easily use the code from the "where clause"
339 * with some additional traversals done in
340 * .../optimizer/plan/planner.c
342 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
344 qry->hasSubLinks = pstate->p_hasSubLinks;
346 /* now the range table will not change */
347 qry->rtable = pstate->p_rtable;
348 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
350 qry->groupClause = transformGroupClause(pstate,
354 /* fix order clause */
355 qry->sortClause = transformSortClause(pstate,
361 qry->hasAggs = pstate->p_hasAggs;
362 if (pstate->p_hasAggs)
363 parseCheckAggregates(pstate, qry);
366 * The INSERT INTO ... SELECT ... could have a UNION in child, so
367 * unionClause may be false
369 qry->unionall = stmt->unionall;
370 qry->unionClause = transformUnionClause(stmt->unionClause, qry->targetList);
373 * If there is a havingQual but there are no aggregates, then there is
374 * something wrong with the query because having must contain
375 * aggregates in its expressions! Otherwise the query could have been
376 * formulated using the where clause.
378 if ((qry->hasAggs == false) && (qry->havingQual != NULL))
380 elog(ERROR, "This is not a valid having query!");
381 return (Query *) NIL;
384 return (Query *) qry;
389 * Create a table name from a list of fields.
392 makeTableName(void *elem,...)
397 char buf[NAMEDATALEN + 1];
401 va_start(args, elem);
406 /* not enough room for next part? then return nothing */
407 if ((strlen(buf) + strlen(name)) >= (sizeof(buf) - 1))
414 name = va_arg(args, void *);
419 name = palloc(strlen(buf) + 1);
426 CreateIndexName(char *table_name, char *column_name, char *label, List *indices)
432 char name2[NAMEDATALEN + 1];
434 /* use working storage, since we might be trying several possibilities */
435 strcpy(name2, column_name);
436 while (iname == NULL)
438 iname = makeTableName(table_name, name2, label, NULL);
439 /* unable to make a name at all? then quit */
446 index = lfirst(ilist);
447 if (strcasecmp(iname, index->idxname) == 0)
450 ilist = lnext(ilist);
452 /* ran through entire list? then no name conflict found so done */
456 /* the last one conflicted, so try a new name component */
460 sprintf(name2, "%s_%d", column_name, (pass + 1));
467 * transformCreateStmt -
468 * transforms the "create table" statement
469 * SQL92 allows constraints to be scattered all over, so thumb through
470 * the columns and collect all constraints into one place.
471 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
472 * then expand those into multiple IndexStmt blocks.
473 * - thomas 1997-12-02
476 transformCreateStmt(ParseState *pstate, CreateStmt *stmt)
479 int have_pkey = FALSE;
487 Constraint *constraint;
495 q->commandType = CMD_UTILITY;
497 elements = stmt->tableElts;
498 constraints = stmt->constraints;
502 while (elements != NIL)
504 element = lfirst(elements);
505 switch (nodeTag(element))
508 column = (ColumnDef *) element;
509 columns = lappend(columns, column);
511 if (column->is_sequence)
515 CreateSeqStmt *sequence;
517 sname = makeTableName(stmt->relname, column->colname, "seq", NULL);
519 constraint = makeNode(Constraint);
520 constraint->contype = CONSTR_DEFAULT;
521 constraint->name = sname;
522 cstring = palloc(9 + strlen(constraint->name) + 2 + 1);
523 strcpy(cstring, "nextval('");
524 strcat(cstring, constraint->name);
525 strcat(cstring, "')");
526 constraint->def = cstring;
527 constraint->keys = NULL;
529 /* The parser only allows PRIMARY KEY as a constraint for the SERIAL type.
530 * So, if there is a constraint of any kind, assume it is that.
531 * If PRIMARY KEY is specified, then don't need to gin up a UNIQUE constraint
532 * since that will be covered already.
533 * - thomas 1998-09-15
535 if (column->constraints != NIL)
537 column->constraints = lappend(column->constraints, constraint);
541 column->constraints = lcons(constraint, NIL);
543 constraint = makeNode(Constraint);
544 constraint->contype = CONSTR_UNIQUE;
545 constraint->name = makeTableName(stmt->relname, column->colname, "key", NULL);
546 column->constraints = lappend(column->constraints, constraint);
549 sequence = makeNode(CreateSeqStmt);
550 sequence->seqname = pstrdup(sname);
551 sequence->options = NIL;
553 elog(NOTICE, "CREATE TABLE will create implicit sequence %s for SERIAL column %s.%s",
554 sequence->seqname, stmt->relname, column->colname);
556 ilist = lcons(sequence, NIL);
559 if (column->constraints != NIL)
561 clist = column->constraints;
564 constraint = lfirst(clist);
565 switch (constraint->contype)
568 if (column->is_not_null)
569 elog(ERROR, "CREATE TABLE/NOT NULL already specified"
570 " for %s.%s", stmt->relname, column->colname);
571 column->is_not_null = TRUE;
575 if (column->defval != NULL)
576 elog(ERROR, "CREATE TABLE/DEFAULT multiple values specified"
577 " for %s.%s", stmt->relname, column->colname);
578 column->defval = constraint->def;
582 if (constraint->name == NULL)
583 constraint->name = makeTableName(stmt->relname, "pkey", NULL);
584 if (constraint->keys == NIL)
585 constraint->keys = lappend(constraint->keys, column);
586 dlist = lappend(dlist, constraint);
590 if (constraint->name == NULL)
591 constraint->name = makeTableName(stmt->relname, column->colname, "key", NULL);
592 if (constraint->keys == NIL)
593 constraint->keys = lappend(constraint->keys, column);
594 dlist = lappend(dlist, constraint);
598 constraints = lappend(constraints, constraint);
599 if (constraint->name == NULL)
600 constraint->name = makeTableName(stmt->relname, column->colname, NULL);
604 elog(ERROR, "parser: internal error; unrecognized constraint", NULL);
607 clist = lnext(clist);
613 constraint = (Constraint *) element;
614 switch (constraint->contype)
617 if (constraint->name == NULL)
618 constraint->name = makeTableName(stmt->relname, "pkey", NULL);
619 dlist = lappend(dlist, constraint);
624 if (constraint->name == NULL)
625 constraint->name = makeTableName(stmt->relname, "key", NULL);
627 dlist = lappend(dlist, constraint);
631 constraints = lappend(constraints, constraint);
636 elog(ERROR, "parser: internal error; illegal context for constraint", NULL);
639 elog(ERROR, "parser: internal error; unrecognized constraint", NULL);
645 elog(ERROR, "parser: internal error; unrecognized node", NULL);
648 elements = lnext(elements);
651 stmt->tableElts = columns;
652 stmt->constraints = constraints;
654 /* Now run through the "deferred list" to complete the query transformation.
655 * For PRIMARY KEYs, mark each column as NOT NULL and create an index.
656 * For UNIQUE, create an index as for PRIMARY KEYS, but do not insist on NOT NULL.
658 * Note that this code does not currently look for all possible redundant cases
659 * and either ignore or stop with warning. The create might fail later when
660 * names for indices turn out to be redundant, or a user might have specified
661 * extra useless indices which might hurt performance. - thomas 1997-12-08
665 constraint = lfirst(dlist);
666 if (nodeTag(constraint) != T_Constraint)
667 elog(ERROR, "parser: internal error; unrecognized deferred node", NULL);
669 if (constraint->contype == CONSTR_PRIMARY)
672 elog(ERROR, "CREATE TABLE/PRIMARY KEY multiple primary keys"
673 " for table %s are not legal", stmt->relname);
677 else if (constraint->contype != CONSTR_UNIQUE)
678 elog(ERROR, "parser: internal error; unrecognized deferred constraint", NULL);
680 index = makeNode(IndexStmt);
682 index->unique = TRUE;
683 if (constraint->name != NULL)
684 index->idxname = constraint->name;
685 else if (constraint->contype == CONSTR_PRIMARY)
688 elog(ERROR, "CREATE TABLE/PRIMARY KEY multiple keys for table %s are not legal", stmt->relname);
691 index->idxname = makeTableName(stmt->relname, "pkey", NULL);
694 index->idxname = NULL;
696 index->relname = stmt->relname;
697 index->accessMethod = "btree";
698 index->indexParams = NIL;
699 index->withClause = NIL;
700 index->whereClause = NULL;
702 keys = constraint->keys;
706 columns = stmt->tableElts;
708 while (columns != NIL)
710 column = lfirst(columns);
711 if (strcasecmp(column->colname, key->name) == 0)
715 columns = lnext(columns);
718 elog(ERROR, "parser: column '%s' in key does not exist", key->name);
720 if (constraint->contype == CONSTR_PRIMARY)
721 column->is_not_null = TRUE;
722 iparam = makeNode(IndexElem);
723 iparam->name = strcpy(palloc(strlen(column->colname) + 1), column->colname);
725 iparam->class = NULL;
726 iparam->typename = NULL;
727 index->indexParams = lappend(index->indexParams, iparam);
729 if (index->idxname == NULL)
730 index->idxname = CreateIndexName(stmt->relname, iparam->name, "key", ilist);
735 if (index->idxname == NULL)
736 elog(ERROR, "parser: unable to construct implicit index for table %s"
737 "; name too long", stmt->relname);
739 elog(NOTICE, "CREATE TABLE/%s will create implicit index %s for table %s",
740 ((constraint->contype == CONSTR_PRIMARY) ? "PRIMARY KEY" : "UNIQUE"),
741 index->idxname, stmt->relname);
743 ilist = lappend(ilist, index);
744 dlist = lnext(dlist);
747 q->utilityStmt = (Node *) stmt;
754 * transformIndexStmt -
755 * transforms the qualification of the index statement
758 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
762 qry = makeNode(Query);
763 qry->commandType = CMD_UTILITY;
765 /* take care of the where clause */
766 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
767 qry->hasSubLinks = pstate->p_hasSubLinks;
769 stmt->rangetable = pstate->p_rtable;
771 qry->utilityStmt = (Node *) stmt;
777 * transformExtendStmt -
778 * transform the qualifications of the Extend Index Statement
782 transformExtendStmt(ParseState *pstate, ExtendStmt *stmt)
786 qry = makeNode(Query);
787 qry->commandType = CMD_UTILITY;
789 /* take care of the where clause */
790 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
791 qry->hasSubLinks = pstate->p_hasSubLinks;
793 stmt->rangetable = pstate->p_rtable;
795 qry->utilityStmt = (Node *) stmt;
800 * transformRuleStmt -
801 * transform a Create Rule Statement. The actions is a list of parse
802 * trees which is transformed into a list of query trees.
805 transformRuleStmt(ParseState *pstate, RuleStmt *stmt)
811 qry = makeNode(Query);
812 qry->commandType = CMD_UTILITY;
815 * 'instead nothing' rules with a qualification need a query a
816 * rangetable so the rewrite handler can add the negated rule
817 * qualification to the original query. We create a query with the new
818 * command type CMD_NOTHING here that is treated special by the
821 if (stmt->actions == NIL)
823 Query *nothing_qry = makeNode(Query);
825 nothing_qry->commandType = CMD_NOTHING;
827 addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
829 addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
832 nothing_qry->rtable = pstate->p_rtable;
834 stmt->actions = lappend(NIL, nothing_qry);
837 actions = stmt->actions;
840 * transform each statment, like parse_analyze()
842 while (actions != NIL)
846 * NOTE: 'CURRENT' must always have a varno equal to 1 and 'NEW'
849 addRangeTableEntry(pstate, stmt->object->relname, "*CURRENT*",
851 addRangeTableEntry(pstate, stmt->object->relname, "*NEW*",
854 pstate->p_last_resno = 1;
855 pstate->p_is_rule = true; /* for expand all */
856 pstate->p_hasAggs = false;
858 action = (Query *) lfirst(actions);
859 if (action->commandType != CMD_NOTHING)
860 lfirst(actions) = transformStmt(pstate, lfirst(actions));
861 actions = lnext(actions);
864 /* take care of the where clause */
865 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
866 qry->hasSubLinks = pstate->p_hasSubLinks;
868 qry->utilityStmt = (Node *) stmt;
874 * transformSelectStmt -
875 * transforms a Select Statement
879 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
881 Query *qry = makeNode(Query);
883 qry->commandType = CMD_SELECT;
885 /* set up a range table */
886 makeRangeTable(pstate, NULL, stmt->fromClause);
888 qry->uniqueFlag = stmt->unique;
890 qry->into = stmt->into;
891 qry->isPortal = FALSE;
893 qry->targetList = transformTargetList(pstate, stmt->targetList);
895 qry->qual = transformWhereClause(pstate, stmt->whereClause);
898 * The havingQual has a similar meaning as "qual" in the where
899 * statement. So we can easily use the code from the "where clause"
900 * with some additional traversals done in
901 * .../optimizer/plan/planner.c
903 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
905 qry->hasSubLinks = pstate->p_hasSubLinks;
907 qry->sortClause = transformSortClause(pstate,
913 qry->groupClause = transformGroupClause(pstate,
916 qry->rtable = pstate->p_rtable;
918 qry->hasAggs = pstate->p_hasAggs;
919 if (pstate->p_hasAggs)
920 parseCheckAggregates(pstate, qry);
923 * The INSERT INTO ... SELECT ... could have a UNION in child, so
924 * unionClause may be false
926 qry->unionall = stmt->unionall;
927 qry->unionClause = transformUnionClause(stmt->unionClause, qry->targetList);
930 * If there is a havingQual but there are no aggregates, then there is
931 * something wrong with the query because having must contain
932 * aggregates in its expressions! Otherwise the query could have been
933 * formulated using the where clause.
935 if ((qry->hasAggs == false) && (qry->havingQual != NULL))
937 elog(ERROR, "This is not a valid having query!");
938 return (Query *) NIL;
941 return (Query *) qry;
945 * transformUpdateStmt -
946 * transforms an update statement
950 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
952 Query *qry = makeNode(Query);
954 qry->commandType = CMD_UPDATE;
955 pstate->p_is_update = true;
958 * the FROM clause is non-standard SQL syntax. We used to be able to
959 * do this with REPLACE in POSTQUEL so we keep the feature.
961 makeRangeTable(pstate, stmt->relname, stmt->fromClause);
963 qry->targetList = transformTargetList(pstate, stmt->targetList);
965 qry->qual = transformWhereClause(pstate, stmt->whereClause);
966 qry->hasSubLinks = pstate->p_hasSubLinks;
968 qry->rtable = pstate->p_rtable;
970 qry->resultRelation = refnameRangeTablePosn(pstate, stmt->relname, NULL);
972 qry->hasAggs = pstate->p_hasAggs;
973 if (pstate->p_hasAggs)
974 parseCheckAggregates(pstate, qry);
976 return (Query *) qry;
980 * transformCursorStmt -
981 * transform a Create Cursor Statement
985 transformCursorStmt(ParseState *pstate, SelectStmt *stmt)
989 qry = transformSelectStmt(pstate, stmt);
991 qry->into = stmt->portalname;
992 qry->isPortal = TRUE;
993 qry->isBinary = stmt->binary; /* internal portal */