1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * $Header: /cvsroot/pgsql/src/backend/parser/analyze.c,v 1.274 2003/06/15 16:42:07 tgl Exp $
11 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/catname.h"
18 #include "catalog/heap.h"
19 #include "catalog/index.h"
20 #include "catalog/namespace.h"
21 #include "catalog/pg_index.h"
22 #include "catalog/pg_type.h"
23 #include "commands/prepare.h"
24 #include "nodes/makefuncs.h"
25 #include "optimizer/clauses.h"
26 #include "optimizer/var.h"
27 #include "parser/analyze.h"
28 #include "parser/gramparse.h"
29 #include "parser/parsetree.h"
30 #include "parser/parse_agg.h"
31 #include "parser/parse_clause.h"
32 #include "parser/parse_coerce.h"
33 #include "parser/parse_expr.h"
34 #include "parser/parse_oper.h"
35 #include "parser/parse_relation.h"
36 #include "parser/parse_target.h"
37 #include "parser/parse_type.h"
38 #include "parser/parse_expr.h"
39 #include "rewrite/rewriteManip.h"
40 #include "utils/builtins.h"
41 #include "utils/fmgroids.h"
42 #include "utils/lsyscache.h"
43 #include "utils/relcache.h"
44 #include "utils/syscache.h"
45 #include "mb/pg_wchar.h"
48 /* State shared by transformCreateSchemaStmt and its subroutines */
51 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
52 char *schemaname; /* name of schema */
53 char *authid; /* owner of schema */
54 List *tables; /* CREATE TABLE items */
55 List *views; /* CREATE VIEW items */
56 List *grants; /* GRANT items */
57 List *fwconstraints; /* Forward referencing FOREIGN KEY
59 List *alters; /* Generated ALTER items (from the above) */
60 List *ixconstraints; /* index-creating constraints */
61 List *blist; /* "before list" of things to do before
62 * creating the schema */
63 List *alist; /* "after list" of things to do after
64 * creating the schema */
65 } CreateSchemaStmtContext;
67 /* State shared by transformCreateStmt and its subroutines */
70 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
71 RangeVar *relation; /* relation to create */
72 List *inhRelations; /* relations to inherit from */
73 bool hasoids; /* does relation have an OID column? */
74 Oid relOid; /* OID of table, if ALTER TABLE case */
75 List *columns; /* ColumnDef items */
76 List *ckconstraints; /* CHECK constraints */
77 List *fkconstraints; /* FOREIGN KEY constraints */
78 List *ixconstraints; /* index-creating constraints */
79 List *blist; /* "before list" of things to do before
80 * creating the table */
81 List *alist; /* "after list" of things to do after
82 * creating the table */
83 IndexStmt *pkey; /* PRIMARY KEY index, if any */
90 } check_parameter_resolution_context;
93 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
94 static Query *transformStmt(ParseState *pstate, Node *stmt,
95 List **extras_before, List **extras_after);
96 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
97 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
98 List **extras_before, List **extras_after);
99 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
100 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
101 List **extras_before, List **extras_after);
102 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
103 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
104 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
105 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
106 static Query *transformDeclareCursorStmt(ParseState *pstate,
107 DeclareCursorStmt *stmt);
108 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
109 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
110 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
111 List **extras_before, List **extras_after);
112 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
113 List **extras_before, List **extras_after);
114 static void transformColumnDefinition(ParseState *pstate,
115 CreateStmtContext *cxt,
117 static void transformTableConstraint(ParseState *pstate,
118 CreateStmtContext *cxt,
119 Constraint *constraint);
120 static void transformIndexConstraints(ParseState *pstate,
121 CreateStmtContext *cxt);
122 static void transformFKConstraints(ParseState *pstate,
123 CreateStmtContext *cxt,
124 bool isAddConstraint);
125 static void applyColumnNames(List *dst, List *src);
126 static List *getSetColTypes(ParseState *pstate, Node *node);
127 static void transformForUpdate(Query *qry, List *forUpdate);
128 static void transformConstraintAttrs(List *constraintList);
129 static void transformColumnType(ParseState *pstate, ColumnDef *column);
130 static bool relationHasPrimaryKey(Oid relationOid);
131 static void release_pstate_resources(ParseState *pstate);
132 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
133 static bool check_parameter_resolution_walker(Node *node,
134 check_parameter_resolution_context *context);
139 * Analyze a raw parse tree and transform it to Query form.
141 * Optionally, information about $n parameter types can be supplied.
142 * References to $n indexes not defined by paramTypes[] are disallowed.
144 * The result is a List of Query nodes (we need a list since some commands
145 * produce multiple Queries). Optimizable statements require considerable
146 * transformation, while many utility-type statements are simply hung off
147 * a dummy CMD_UTILITY Query node.
150 parse_analyze(Node *parseTree, Oid *paramTypes, int numParams)
152 ParseState *pstate = make_parsestate(NULL);
155 pstate->p_paramtypes = paramTypes;
156 pstate->p_numparams = numParams;
157 pstate->p_variableparams = false;
159 result = do_parse_analyze(parseTree, pstate);
167 * parse_analyze_varparams
169 * This variant is used when it's okay to deduce information about $n
170 * symbol datatypes from context. The passed-in paramTypes[] array can
171 * be modified or enlarged (via repalloc).
174 parse_analyze_varparams(Node *parseTree, Oid **paramTypes, int *numParams)
176 ParseState *pstate = make_parsestate(NULL);
179 pstate->p_paramtypes = *paramTypes;
180 pstate->p_numparams = *numParams;
181 pstate->p_variableparams = true;
183 result = do_parse_analyze(parseTree, pstate);
185 *paramTypes = pstate->p_paramtypes;
186 *numParams = pstate->p_numparams;
190 /* make sure all is well with parameter types */
193 check_parameter_resolution_context context;
195 context.paramTypes = *paramTypes;
196 context.numParams = *numParams;
197 check_parameter_resolution_walker((Node *) result, &context);
205 * Entry point for recursively analyzing a sub-statement.
208 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
210 ParseState *pstate = make_parsestate(parentParseState);
213 result = do_parse_analyze(parseTree, pstate);
222 * Workhorse code shared by the above variants of parse_analyze.
225 do_parse_analyze(Node *parseTree, ParseState *pstate)
228 /* Lists to return extra commands from transformation */
229 List *extras_before = NIL;
230 List *extras_after = NIL;
234 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
236 /* don't need to access result relation any more */
237 release_pstate_resources(pstate);
239 while (extras_before != NIL)
241 result = nconc(result,
242 parse_sub_analyze(lfirst(extras_before), pstate));
243 extras_before = lnext(extras_before);
246 result = lappend(result, query);
248 while (extras_after != NIL)
250 result = nconc(result,
251 parse_sub_analyze(lfirst(extras_after), pstate));
252 extras_after = lnext(extras_after);
256 * Make sure that only the original query is marked original. We have
257 * to do this explicitly since recursive calls of do_parse_analyze will
258 * have marked some of the added-on queries as "original". Also mark
259 * only the original query as allowed to set the command-result tag.
261 foreach(listscan, result)
263 Query *q = lfirst(listscan);
267 q->querySource = QSRC_ORIGINAL;
272 q->querySource = QSRC_PARSER;
273 q->canSetTag = false;
281 release_pstate_resources(ParseState *pstate)
283 if (pstate->p_target_relation != NULL)
284 heap_close(pstate->p_target_relation, NoLock);
285 pstate->p_target_relation = NULL;
286 pstate->p_target_rangetblentry = NULL;
291 * transform a Parse tree into a Query tree.
294 transformStmt(ParseState *pstate, Node *parseTree,
295 List **extras_before, List **extras_after)
297 Query *result = NULL;
299 switch (nodeTag(parseTree))
302 * Non-optimizable statements
305 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
306 extras_before, extras_after);
310 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
314 result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
315 extras_before, extras_after);
320 ViewStmt *n = (ViewStmt *) parseTree;
322 n->query = transformStmt(pstate, (Node *) n->query,
323 extras_before, extras_after);
326 * If a list of column names was given, run through and
327 * insert these into the actual query tree. - thomas
330 * Outer loop is over targetlist to make it easier to skip
331 * junk targetlist entries.
333 if (n->aliases != NIL)
335 List *aliaslist = n->aliases;
338 foreach(targetList, n->query->targetList)
340 TargetEntry *te = (TargetEntry *) lfirst(targetList);
343 Assert(IsA(te, TargetEntry));
345 Assert(IsA(rd, Resdom));
346 /* junk columns don't get aliases */
349 rd->resname = pstrdup(strVal(lfirst(aliaslist)));
350 aliaslist = lnext(aliaslist);
351 if (aliaslist == NIL)
352 break; /* done assigning aliases */
355 if (aliaslist != NIL)
356 elog(ERROR, "CREATE VIEW specifies more column names than columns");
358 result = makeNode(Query);
359 result->commandType = CMD_UTILITY;
360 result->utilityStmt = (Node *) n;
366 ExplainStmt *n = (ExplainStmt *) parseTree;
368 result = makeNode(Query);
369 result->commandType = CMD_UTILITY;
370 n->query = transformStmt(pstate, (Node *) n->query,
371 extras_before, extras_after);
372 result->utilityStmt = (Node *) parseTree;
376 case T_AlterTableStmt:
377 result = transformAlterTableStmt(pstate, (AlterTableStmt *) parseTree,
378 extras_before, extras_after);
382 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
386 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
390 * Optimizable statements
393 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
394 extras_before, extras_after);
398 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
402 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
406 if (((SelectStmt *) parseTree)->op == SETOP_NONE)
407 result = transformSelectStmt(pstate,
408 (SelectStmt *) parseTree);
410 result = transformSetOperationStmt(pstate,
411 (SelectStmt *) parseTree);
414 case T_DeclareCursorStmt:
415 result = transformDeclareCursorStmt(pstate,
416 (DeclareCursorStmt *) parseTree);
422 * other statements don't require any transformation-- just
423 * return the original parsetree, yea!
425 result = makeNode(Query);
426 result->commandType = CMD_UTILITY;
427 result->utilityStmt = (Node *) parseTree;
431 /* Mark as original query until we learn differently */
432 result->querySource = QSRC_ORIGINAL;
433 result->canSetTag = true;
439 * transformDeleteStmt -
440 * transforms a Delete Statement
443 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
445 Query *qry = makeNode(Query);
448 qry->commandType = CMD_DELETE;
450 /* set up range table with just the result rel */
451 qry->resultRelation = setTargetTable(pstate, stmt->relation,
452 interpretInhOption(stmt->relation->inhOpt),
455 qry->distinctClause = NIL;
457 /* fix where clause */
458 qual = transformWhereClause(pstate, stmt->whereClause);
460 /* done building the range table and jointree */
461 qry->rtable = pstate->p_rtable;
462 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
464 qry->hasSubLinks = pstate->p_hasSubLinks;
465 qry->hasAggs = pstate->p_hasAggs;
466 if (pstate->p_hasAggs)
467 parseCheckAggregates(pstate, qry);
473 * transformInsertStmt -
474 * transform an Insert Statement
477 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
478 List **extras_before, List **extras_after)
480 Query *qry = makeNode(Query);
488 qry->commandType = CMD_INSERT;
489 pstate->p_is_insert = true;
492 * If a non-nil rangetable/namespace was passed in, and we are doing
493 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
494 * SELECT. This can only happen if we are inside a CREATE RULE, and
495 * in that case we want the rule's OLD and NEW rtable entries to
496 * appear as part of the SELECT's rtable, not as outer references for
497 * it. (Kluge!) The SELECT's joinlist is not affected however. We
498 * must do this before adding the target table to the INSERT's rtable.
500 if (stmt->selectStmt)
502 sub_rtable = pstate->p_rtable;
503 pstate->p_rtable = NIL;
504 sub_namespace = pstate->p_namespace;
505 pstate->p_namespace = NIL;
509 sub_rtable = NIL; /* not used, but keep compiler quiet */
514 * Must get write lock on INSERT target table before scanning SELECT,
515 * else we will grab the wrong kind of initial lock if the target
516 * table is also mentioned in the SELECT part. Note that the target
517 * table is not added to the joinlist or namespace.
519 qry->resultRelation = setTargetTable(pstate, stmt->relation,
523 * Is it INSERT ... SELECT or INSERT ... VALUES?
525 if (stmt->selectStmt)
528 * We make the sub-pstate a child of the outer pstate so that it
529 * can see any Param definitions supplied from above. Since the
530 * outer pstate's rtable and namespace are presently empty, there
531 * are no side-effects of exposing names the sub-SELECT shouldn't
534 ParseState *sub_pstate = make_parsestate(pstate);
540 * Process the source SELECT.
542 * It is important that this be handled just like a standalone
543 * SELECT; otherwise the behavior of SELECT within INSERT might be
544 * different from a stand-alone SELECT. (Indeed, Postgres up
545 * through 6.5 had bugs of just that nature...)
547 sub_pstate->p_rtable = sub_rtable;
548 sub_pstate->p_namespace = sub_namespace;
551 * Note: we are not expecting that extras_before and extras_after
552 * are going to be used by the transformation of the SELECT
555 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
556 extras_before, extras_after);
558 release_pstate_resources(sub_pstate);
561 Assert(IsA(selectQuery, Query));
562 Assert(selectQuery->commandType == CMD_SELECT);
563 if (selectQuery->into)
564 elog(ERROR, "INSERT ... SELECT may not specify INTO");
567 * Make the source be a subquery in the INSERT's rangetable, and
568 * add it to the INSERT's joinlist.
570 rte = addRangeTableEntryForSubquery(pstate,
572 makeAlias("*SELECT*", NIL),
574 rtr = makeNode(RangeTblRef);
575 /* assume new rte is at end */
576 rtr->rtindex = length(pstate->p_rtable);
577 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
578 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
581 * Generate a targetlist for the INSERT that selects all the
582 * non-resjunk columns from the subquery. (We need this to be
583 * separate from the subquery's tlist because we may add columns,
584 * insert datatype coercions, etc.)
586 * HACK: unknown-type constants and params in the INSERT's targetlist
587 * are copied up as-is rather than being referenced as subquery
588 * outputs. This is to ensure that when we try to coerce them
589 * to the target column's datatype, the right things happen (see
590 * special cases in coerce_type). Otherwise, this fails:
591 * INSERT INTO foo SELECT 'bar', ... FROM baz
593 qry->targetList = NIL;
594 foreach(tl, selectQuery->targetList)
596 TargetEntry *tle = (TargetEntry *) lfirst(tl);
597 Resdom *resnode = tle->resdom;
600 if (resnode->resjunk)
603 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
604 exprType((Node *) tle->expr) == UNKNOWNOID)
607 expr = (Expr *) makeVar(rtr->rtindex,
612 resnode = copyObject(resnode);
613 resnode->resno = (AttrNumber) pstate->p_next_resno++;
614 qry->targetList = lappend(qry->targetList,
615 makeTargetEntry(resnode, expr));
621 * For INSERT ... VALUES, transform the given list of values to
622 * form a targetlist for the INSERT.
624 qry->targetList = transformTargetList(pstate, stmt->targetList);
628 * Now we are done with SELECT-like processing, and can get on with
629 * transforming the target list to match the INSERT target columns.
632 /* Prepare to assign non-conflicting resnos to resjunk attributes */
633 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
634 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
636 /* Validate stmt->cols list, or build default list if no list given */
637 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
640 * Prepare columns for assignment to target table.
643 /* cannot use foreach here because of possible lremove */
644 tl = qry->targetList;
647 TargetEntry *tle = (TargetEntry *) lfirst(tl);
650 /* must advance tl before lremove possibly pfree's it */
653 if (icolumns == NIL || attnos == NIL)
654 elog(ERROR, "INSERT has more expressions than target columns");
656 col = (ResTarget *) lfirst(icolumns);
657 Assert(IsA(col, ResTarget));
660 * When the value is to be set to the column default we can simply
661 * drop the TLE now and handle it later on using methods for missing
664 if (IsA(tle, InsertDefault))
666 qry->targetList = lremove(tle, qry->targetList);
667 /* Note: the stmt->cols list is not adjusted to match */
672 Assert(!tle->resdom->resjunk);
673 updateTargetListEntry(pstate, tle, col->name, lfirsti(attnos),
677 icolumns = lnext(icolumns);
678 attnos = lnext(attnos);
682 * Ensure that the targetlist has the same number of entries that
683 * were present in the columns list. Don't do the check unless
684 * an explicit columns list was given, though.
687 if (stmt->cols != NIL && (icolumns != NIL || attnos != NIL))
688 elog(ERROR, "INSERT has more target columns than expressions");
690 /* done building the range table and jointree */
691 qry->rtable = pstate->p_rtable;
692 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
694 qry->hasSubLinks = pstate->p_hasSubLinks;
695 qry->hasAggs = pstate->p_hasAggs;
696 if (pstate->p_hasAggs)
697 parseCheckAggregates(pstate, qry);
705 * Create a name for an implicitly created index, sequence, constraint, etc.
707 * The parameters are: the original table name, the original field name, and
708 * a "type" string (such as "seq" or "pkey"). The field name and/or type
709 * can be NULL if not relevant.
711 * The result is a palloc'd string.
713 * The basic result we want is "name1_name2_type", omitting "_name2" or
714 * "_type" when those parameters are NULL. However, we must generate
715 * a name with less than NAMEDATALEN characters! So, we truncate one or
716 * both names if necessary to make a short-enough string. The type part
717 * is never truncated (so it had better be reasonably short).
719 * To reduce the probability of collisions, we might someday add more
720 * smarts to this routine, like including some "hash" characters computed
721 * from the truncated characters. Currently it seems best to keep it simple,
722 * so that the generated names are easily predictable by a person.
725 makeObjectName(char *name1, char *name2, char *typename)
728 int overhead = 0; /* chars needed for type and underscores */
729 int availchars; /* chars available for name(s) */
730 int name1chars; /* chars allocated to name1 */
731 int name2chars; /* chars allocated to name2 */
734 name1chars = strlen(name1);
737 name2chars = strlen(name2);
738 overhead++; /* allow for separating underscore */
743 overhead += strlen(typename) + 1;
745 availchars = NAMEDATALEN - 1 - overhead;
748 * If we must truncate, preferentially truncate the longer name. This
749 * logic could be expressed without a loop, but it's simple and
752 while (name1chars + name2chars > availchars)
754 if (name1chars > name2chars)
761 name1chars = pg_mbcliplen(name1, name1chars, name1chars);
763 name2chars = pg_mbcliplen(name2, name2chars, name2chars);
765 /* Now construct the string using the chosen lengths */
766 name = palloc(name1chars + name2chars + overhead + 1);
767 strncpy(name, name1, name1chars);
772 strncpy(name + ndx, name2, name2chars);
778 strcpy(name + ndx, typename);
787 CreateIndexName(char *table_name, char *column_name,
788 char *label, List *indices)
793 char typename[NAMEDATALEN];
796 * The type name for makeObjectName is label, or labelN if that's
797 * necessary to prevent collisions among multiple indexes for the same
798 * table. Note there is no check for collisions with already-existing
799 * indexes, only among the indexes we're about to create now; this
800 * ought to be improved someday.
802 strncpy(typename, label, sizeof(typename));
806 iname = makeObjectName(table_name, column_name, typename);
808 foreach(ilist, indices)
810 IndexStmt *index = lfirst(ilist);
812 if (index->idxname != NULL &&
813 strcmp(iname, index->idxname) == 0)
816 /* ran through entire list? then no name conflict found so done */
820 /* found a conflict, so try a new name component */
822 snprintf(typename, sizeof(typename), "%s%d", label, ++pass);
829 * transformCreateStmt -
830 * transforms the "create table" statement
831 * SQL92 allows constraints to be scattered all over, so thumb through
832 * the columns and collect all constraints into one place.
833 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
834 * then expand those into multiple IndexStmt blocks.
835 * - thomas 1997-12-02
838 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
839 List **extras_before, List **extras_after)
841 CreateStmtContext cxt;
845 cxt.stmtType = "CREATE TABLE";
846 cxt.relation = stmt->relation;
847 cxt.inhRelations = stmt->inhRelations;
848 cxt.hasoids = stmt->hasoids;
849 cxt.relOid = InvalidOid;
851 cxt.ckconstraints = NIL;
852 cxt.fkconstraints = NIL;
853 cxt.ixconstraints = NIL;
859 * Run through each primary element in the table creation clause.
860 * Separate column defs from constraints, and do preliminary analysis.
862 foreach(elements, stmt->tableElts)
864 Node *element = lfirst(elements);
866 switch (nodeTag(element))
869 transformColumnDefinition(pstate, &cxt,
870 (ColumnDef *) element);
874 transformTableConstraint(pstate, &cxt,
875 (Constraint *) element);
879 /* No pre-transformation needed */
880 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
884 elog(ERROR, "parser: unrecognized node (internal error)");
888 Assert(stmt->constraints == NIL);
891 * Postprocess constraints that give rise to index definitions.
893 transformIndexConstraints(pstate, &cxt);
896 * Postprocess foreign-key constraints.
898 transformFKConstraints(pstate, &cxt, false);
904 q->commandType = CMD_UTILITY;
905 q->utilityStmt = (Node *) stmt;
906 stmt->tableElts = cxt.columns;
907 stmt->constraints = cxt.ckconstraints;
908 *extras_before = nconc(*extras_before, cxt.blist);
909 *extras_after = nconc(cxt.alist, *extras_after);
915 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
920 Constraint *constraint;
923 cxt->columns = lappend(cxt->columns, column);
925 /* Check for SERIAL pseudo-types */
927 if (length(column->typename->names) == 1)
929 char *typname = strVal(lfirst(column->typename->names));
931 if (strcmp(typname, "serial") == 0 ||
932 strcmp(typname, "serial4") == 0)
935 column->typename->names = NIL;
936 column->typename->typeid = INT4OID;
938 else if (strcmp(typname, "bigserial") == 0 ||
939 strcmp(typname, "serial8") == 0)
942 column->typename->names = NIL;
943 column->typename->typeid = INT8OID;
947 /* Do necessary work on the column type declaration */
948 transformColumnType(pstate, column);
950 /* Special actions for SERIAL pseudo-types */
957 FuncCall *funccallnode;
958 CreateSeqStmt *seqstmt;
961 * Determine name and namespace to use for the sequence.
963 sname = makeObjectName(cxt->relation->relname, column->colname, "seq");
964 snamespace = get_namespace_name(RangeVarGetCreationNamespace(cxt->relation));
966 elog(NOTICE, "%s will create implicit sequence '%s' for SERIAL column '%s.%s'",
967 cxt->stmtType, sname, cxt->relation->relname, column->colname);
970 * Build a CREATE SEQUENCE command to create the sequence object,
971 * and add it to the list of things to be done before this
972 * CREATE/ALTER TABLE.
974 seqstmt = makeNode(CreateSeqStmt);
975 seqstmt->sequence = makeRangeVar(snamespace, sname);
976 seqstmt->options = NIL;
978 cxt->blist = lappend(cxt->blist, seqstmt);
981 * Mark the ColumnDef so that during execution, an appropriate
982 * dependency will be added from the sequence to the column.
984 column->support = makeRangeVar(snamespace, sname);
987 * Create appropriate constraints for SERIAL. We do this in full,
988 * rather than shortcutting, so that we will detect any
989 * conflicting constraints the user wrote (like a different
992 * Create an expression tree representing the function call
993 * nextval('"sequencename"')
995 qstring = quote_qualified_identifier(snamespace, sname);
996 snamenode = makeNode(A_Const);
997 snamenode->val.type = T_String;
998 snamenode->val.val.str = qstring;
999 funccallnode = makeNode(FuncCall);
1000 funccallnode->funcname = SystemFuncName("nextval");
1001 funccallnode->args = makeList1(snamenode);
1002 funccallnode->agg_star = false;
1003 funccallnode->agg_distinct = false;
1005 constraint = makeNode(Constraint);
1006 constraint->contype = CONSTR_DEFAULT;
1007 constraint->name = sname;
1008 constraint->raw_expr = (Node *) funccallnode;
1009 constraint->cooked_expr = NULL;
1010 constraint->keys = NIL;
1011 column->constraints = lappend(column->constraints, constraint);
1013 constraint = makeNode(Constraint);
1014 constraint->contype = CONSTR_NOTNULL;
1015 column->constraints = lappend(column->constraints, constraint);
1018 /* Process column constraints, if any... */
1019 transformConstraintAttrs(column->constraints);
1021 saw_nullable = false;
1023 foreach(clist, column->constraints)
1025 constraint = lfirst(clist);
1028 * If this column constraint is a FOREIGN KEY constraint, then we
1029 * fill in the current attribute's name and throw it into the list
1030 * of FK constraints to be processed later.
1032 if (IsA(constraint, FkConstraint))
1034 FkConstraint *fkconstraint = (FkConstraint *) constraint;
1036 fkconstraint->fk_attrs = makeList1(makeString(column->colname));
1037 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
1041 Assert(IsA(constraint, Constraint));
1043 switch (constraint->contype)
1046 if (saw_nullable && column->is_not_null)
1047 elog(ERROR, "%s/(NOT) NULL conflicting declaration for '%s.%s'",
1048 cxt->stmtType, cxt->relation->relname, column->colname);
1049 column->is_not_null = FALSE;
1050 saw_nullable = true;
1053 case CONSTR_NOTNULL:
1054 if (saw_nullable && !column->is_not_null)
1055 elog(ERROR, "%s/(NOT) NULL conflicting declaration for '%s.%s'",
1056 cxt->stmtType, cxt->relation->relname, column->colname);
1057 column->is_not_null = TRUE;
1058 saw_nullable = true;
1061 case CONSTR_DEFAULT:
1062 if (column->raw_default != NULL)
1063 elog(ERROR, "%s/DEFAULT multiple values specified for '%s.%s'",
1064 cxt->stmtType, cxt->relation->relname, column->colname);
1065 column->raw_default = constraint->raw_expr;
1066 Assert(constraint->cooked_expr == NULL);
1069 case CONSTR_PRIMARY:
1070 if (constraint->name == NULL)
1071 constraint->name = makeObjectName(cxt->relation->relname,
1074 if (constraint->keys == NIL)
1075 constraint->keys = makeList1(makeString(column->colname));
1076 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1080 if (constraint->name == NULL)
1081 constraint->name = makeObjectName(cxt->relation->relname,
1084 if (constraint->keys == NIL)
1085 constraint->keys = makeList1(makeString(column->colname));
1086 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1090 if (constraint->name == NULL)
1091 constraint->name = makeObjectName(cxt->relation->relname,
1094 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1097 case CONSTR_ATTR_DEFERRABLE:
1098 case CONSTR_ATTR_NOT_DEFERRABLE:
1099 case CONSTR_ATTR_DEFERRED:
1100 case CONSTR_ATTR_IMMEDIATE:
1101 /* transformConstraintAttrs took care of these */
1105 elog(ERROR, "parser: unrecognized constraint (internal error)");
1112 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1113 Constraint *constraint)
1115 switch (constraint->contype)
1117 case CONSTR_PRIMARY:
1118 if (constraint->name == NULL)
1119 constraint->name = makeObjectName(cxt->relation->relname,
1122 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1126 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1130 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1134 case CONSTR_NOTNULL:
1135 case CONSTR_DEFAULT:
1136 case CONSTR_ATTR_DEFERRABLE:
1137 case CONSTR_ATTR_NOT_DEFERRABLE:
1138 case CONSTR_ATTR_DEFERRED:
1139 case CONSTR_ATTR_IMMEDIATE:
1140 elog(ERROR, "parser: illegal context for constraint (internal error)");
1144 elog(ERROR, "parser: unrecognized constraint (internal error)");
1150 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1158 List *indexlist = NIL;
1161 * Run through the constraints that need to generate an index. For
1162 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
1163 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1166 foreach(listptr, cxt->ixconstraints)
1168 Constraint *constraint = lfirst(listptr);
1170 Assert(IsA(constraint, Constraint));
1171 Assert((constraint->contype == CONSTR_PRIMARY)
1172 || (constraint->contype == CONSTR_UNIQUE));
1174 index = makeNode(IndexStmt);
1176 index->unique = true;
1177 index->primary = (constraint->contype == CONSTR_PRIMARY);
1180 /* In ALTER TABLE case, a primary index might already exist */
1181 if (cxt->pkey != NULL ||
1182 (OidIsValid(cxt->relOid) &&
1183 relationHasPrimaryKey(cxt->relOid)))
1184 elog(ERROR, "%s / PRIMARY KEY multiple primary keys"
1185 " for table '%s' are not allowed",
1186 cxt->stmtType, cxt->relation->relname);
1189 index->isconstraint = true;
1191 if (constraint->name != NULL)
1192 index->idxname = pstrdup(constraint->name);
1193 else if (constraint->contype == CONSTR_PRIMARY)
1194 index->idxname = makeObjectName(cxt->relation->relname, NULL, "pkey");
1196 index->idxname = NULL; /* will set it later */
1198 index->relation = cxt->relation;
1199 index->accessMethod = DEFAULT_INDEX_TYPE;
1200 index->indexParams = NIL;
1201 index->whereClause = NULL;
1204 * Make sure referenced keys exist. If we are making a PRIMARY
1205 * KEY index, also make sure they are NOT NULL, if possible.
1206 * (Although we could leave it to DefineIndex to mark the columns NOT
1207 * NULL, it's more efficient to get it right the first time.)
1209 foreach(keys, constraint->keys)
1211 char *key = strVal(lfirst(keys));
1215 foreach(columns, cxt->columns)
1217 column = lfirst(columns);
1218 Assert(IsA(column, ColumnDef));
1219 if (strcmp(column->colname, key) == 0)
1227 /* found column in the new table; force it to be NOT NULL */
1228 if (constraint->contype == CONSTR_PRIMARY)
1229 column->is_not_null = TRUE;
1231 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1234 * column will be a system column in the new table, so
1235 * accept it. System columns can't ever be null, so no
1236 * need to worry about PRIMARY/NOT NULL constraint.
1240 else if (cxt->inhRelations)
1242 /* try inherited tables */
1245 foreach(inher, cxt->inhRelations)
1247 RangeVar *inh = lfirst(inher);
1251 Assert(IsA(inh, RangeVar));
1252 rel = heap_openrv(inh, AccessShareLock);
1253 if (rel->rd_rel->relkind != RELKIND_RELATION)
1254 elog(ERROR, "inherited table \"%s\" is not a relation",
1256 for (count = 0; count < rel->rd_att->natts; count++)
1258 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1259 char *inhname = NameStr(inhattr->attname);
1261 if (inhattr->attisdropped)
1263 if (strcmp(key, inhname) == 0)
1267 * We currently have no easy way to force an
1268 * inherited column to be NOT NULL at creation, if
1269 * its parent wasn't so already. We leave it to
1270 * DefineIndex to fix things up in this case.
1275 heap_close(rel, NoLock);
1280 else if (OidIsValid(cxt->relOid))
1282 /* ALTER TABLE case: does column already exist? */
1285 atttuple = SearchSysCacheAttName(cxt->relOid, key);
1286 if (HeapTupleIsValid(atttuple))
1290 * If it's not already NOT NULL, leave it to DefineIndex
1293 ReleaseSysCache(atttuple);
1298 elog(ERROR, "%s: column \"%s\" named in key does not exist",
1299 cxt->stmtType, key);
1301 /* Check for PRIMARY KEY(foo, foo) */
1302 foreach(columns, index->indexParams)
1304 iparam = (IndexElem *) lfirst(columns);
1305 if (iparam->name && strcmp(key, iparam->name) == 0)
1306 elog(ERROR, "%s: column \"%s\" appears twice in %s constraint",
1308 index->primary ? "PRIMARY KEY" : "UNIQUE");
1311 /* OK, add it to the index definition */
1312 iparam = makeNode(IndexElem);
1313 iparam->name = pstrdup(key);
1314 iparam->expr = NULL;
1315 iparam->opclass = NIL;
1316 index->indexParams = lappend(index->indexParams, iparam);
1319 indexlist = lappend(indexlist, index);
1323 * Scan the index list and remove any redundant index specifications.
1324 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1325 * KEY. A strict reading of SQL92 would suggest raising an error
1326 * instead, but that strikes me as too anal-retentive. - tgl
1329 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1330 * pre-existing indexes, too.
1333 if (cxt->pkey != NULL)
1335 /* Make sure we keep the PKEY index in preference to others... */
1336 cxt->alist = makeList1(cxt->pkey);
1338 while (indexlist != NIL)
1340 index = lfirst(indexlist);
1342 /* if it's pkey, it's already in cxt->alist */
1343 if (index != cxt->pkey)
1348 foreach(priorlist, cxt->alist)
1350 IndexStmt *priorindex = lfirst(priorlist);
1352 if (equal(index->indexParams, priorindex->indexParams))
1355 * If the prior index is as yet unnamed, and this one
1356 * is named, then transfer the name to the prior
1357 * index. This ensures that if we have named and
1358 * unnamed constraints, we'll use (at least one of)
1359 * the names for the index.
1361 if (priorindex->idxname == NULL)
1362 priorindex->idxname = index->idxname;
1369 cxt->alist = lappend(cxt->alist, index);
1372 indexlist = lnext(indexlist);
1376 * Finally, select unique names for all not-previously-named indices,
1377 * and display NOTICE messages.
1379 * XXX in ALTER TABLE case, we fail to consider name collisions against
1380 * pre-existing indexes.
1382 foreach(indexlist, cxt->alist)
1384 index = lfirst(indexlist);
1386 if (index->idxname == NULL && index->indexParams != NIL)
1388 iparam = (IndexElem *) lfirst(index->indexParams);
1389 /* we should never see an expression item here */
1390 Assert(iparam->expr == NULL);
1391 index->idxname = CreateIndexName(cxt->relation->relname,
1396 if (index->idxname == NULL) /* should not happen */
1397 elog(ERROR, "%s: failed to make implicit index name",
1400 elog(NOTICE, "%s / %s%s will create implicit index '%s' for table '%s'",
1402 (strcmp(cxt->stmtType, "ALTER TABLE") == 0) ? "ADD " : "",
1403 (index->primary ? "PRIMARY KEY" : "UNIQUE"),
1404 index->idxname, cxt->relation->relname);
1409 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1410 bool isAddConstraint)
1412 if (cxt->fkconstraints == NIL)
1415 elog(NOTICE, "%s will create implicit trigger(s) for FOREIGN KEY check(s)",
1419 * For ALTER TABLE ADD CONSTRAINT, nothing to do. For CREATE TABLE or
1420 * ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD CONSTRAINT command
1421 * to execute after the basic command is complete.
1423 * Note: the ADD CONSTRAINT command must also execute after any index
1424 * creation commands. Thus, this should run after
1425 * transformIndexConstraints, so that the CREATE INDEX commands are
1426 * already in cxt->alist.
1428 if (!isAddConstraint)
1430 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1433 alterstmt->subtype = 'c'; /* preprocessed add constraint */
1434 alterstmt->relation = cxt->relation;
1435 alterstmt->name = NULL;
1436 alterstmt->def = (Node *) cxt->fkconstraints;
1438 /* Don't need to scan the table contents in this case */
1439 foreach(fkclist, cxt->fkconstraints)
1441 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1443 fkconstraint->skip_validation = true;
1446 cxt->alist = lappend(cxt->alist, (Node *) alterstmt);
1451 * transformIndexStmt -
1452 * transforms the qualification of the index statement
1455 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1458 RangeTblEntry *rte = NULL;
1461 qry = makeNode(Query);
1462 qry->commandType = CMD_UTILITY;
1464 /* take care of the where clause */
1465 if (stmt->whereClause)
1468 * Put the parent table into the rtable so that the WHERE clause
1469 * can refer to its fields without qualification. Note that this
1470 * only works if the parent table already exists --- so we can't
1471 * easily support predicates on indexes created implicitly by
1472 * CREATE TABLE. Fortunately, that's not necessary.
1474 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1476 /* no to join list, yes to namespace */
1477 addRTEtoQuery(pstate, rte, false, true);
1479 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1482 /* take care of any index expressions */
1483 foreach(l, stmt->indexParams)
1485 IndexElem *ielem = (IndexElem *) lfirst(l);
1489 /* Set up rtable as for predicate, see notes above */
1492 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1494 /* no to join list, yes to namespace */
1495 addRTEtoQuery(pstate, rte, false, true);
1497 ielem->expr = transformExpr(pstate, ielem->expr);
1499 * We check only that the result type is legitimate; this is
1500 * for consistency with what transformWhereClause() checks for
1501 * the predicate. DefineIndex() will make more checks.
1503 if (expression_returns_set(ielem->expr))
1504 elog(ERROR, "index expression may not return a set");
1508 qry->hasSubLinks = pstate->p_hasSubLinks;
1509 stmt->rangetable = pstate->p_rtable;
1511 qry->utilityStmt = (Node *) stmt;
1517 * transformRuleStmt -
1518 * transform a Create Rule Statement. The actions is a list of parse
1519 * trees which is transformed into a list of query trees.
1522 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1523 List **extras_before, List **extras_after)
1526 RangeTblEntry *oldrte;
1527 RangeTblEntry *newrte;
1529 qry = makeNode(Query);
1530 qry->commandType = CMD_UTILITY;
1531 qry->utilityStmt = (Node *) stmt;
1534 * To avoid deadlock, make sure the first thing we do is grab
1535 * AccessExclusiveLock on the target relation. This will be needed by
1536 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1537 * beforehand. We don't need to hold a refcount on the relcache
1540 heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1544 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1545 * 2. Set up their RTEs in the main pstate for use in parsing the
1546 * rule qualification.
1548 Assert(pstate->p_rtable == NIL);
1549 oldrte = addRangeTableEntry(pstate, stmt->relation,
1550 makeAlias("*OLD*", NIL),
1552 newrte = addRangeTableEntry(pstate, stmt->relation,
1553 makeAlias("*NEW*", NIL),
1555 /* Must override addRangeTableEntry's default access-check flags */
1556 oldrte->checkForRead = false;
1557 newrte->checkForRead = false;
1560 * They must be in the namespace too for lookup purposes, but only add
1561 * the one(s) that are relevant for the current kind of rule. In an
1562 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1563 * unambiguous, but there's no need to be so picky for INSERT &
1564 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1565 * unqualified references to their fields.) We do not add them to the
1568 switch (stmt->event)
1571 addRTEtoQuery(pstate, oldrte, false, true);
1574 addRTEtoQuery(pstate, oldrte, false, true);
1575 addRTEtoQuery(pstate, newrte, false, true);
1578 addRTEtoQuery(pstate, newrte, false, true);
1581 addRTEtoQuery(pstate, oldrte, false, true);
1584 elog(ERROR, "transformRuleStmt: unexpected event type %d",
1589 /* take care of the where clause */
1590 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1592 if (length(pstate->p_rtable) != 2) /* naughty, naughty... */
1593 elog(ERROR, "Rule WHERE condition may not contain references to other relations");
1595 /* aggregates not allowed (but subselects are okay) */
1596 if (pstate->p_hasAggs)
1597 elog(ERROR, "Rule WHERE condition may not contain aggregate functions");
1599 /* save info about sublinks in where clause */
1600 qry->hasSubLinks = pstate->p_hasSubLinks;
1603 * 'instead nothing' rules with a qualification need a query
1604 * rangetable so the rewrite handler can add the negated rule
1605 * qualification to the original query. We create a query with the new
1606 * command type CMD_NOTHING here that is treated specially by the
1609 if (stmt->actions == NIL)
1611 Query *nothing_qry = makeNode(Query);
1613 nothing_qry->commandType = CMD_NOTHING;
1614 nothing_qry->rtable = pstate->p_rtable;
1615 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1617 stmt->actions = makeList1(nothing_qry);
1622 List *newactions = NIL;
1625 * transform each statement, like parse_sub_analyze()
1627 foreach(oldactions, stmt->actions)
1629 Node *action = (Node *) lfirst(oldactions);
1630 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1637 * Set up OLD/NEW in the rtable for this statement. The
1638 * entries are marked not inFromCl because we don't want them
1639 * to be referred to by unqualified field names nor "*" in the
1640 * rule actions. We must add them to the namespace, however,
1641 * or they won't be accessible at all. We decide later
1642 * whether to put them in the joinlist.
1644 oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1645 makeAlias("*OLD*", NIL),
1647 newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1648 makeAlias("*NEW*", NIL),
1650 oldrte->checkForRead = false;
1651 newrte->checkForRead = false;
1652 addRTEtoQuery(sub_pstate, oldrte, false, true);
1653 addRTEtoQuery(sub_pstate, newrte, false, true);
1655 /* Transform the rule action statement */
1656 top_subqry = transformStmt(sub_pstate, action,
1657 extras_before, extras_after);
1660 * We cannot support utility-statement actions (eg NOTIFY)
1661 * with nonempty rule WHERE conditions, because there's no way
1662 * to make the utility action execute conditionally.
1664 if (top_subqry->commandType == CMD_UTILITY &&
1665 stmt->whereClause != NULL)
1666 elog(ERROR, "Rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions");
1669 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1670 * down into the SELECT, and that's what we need to look at.
1671 * (Ugly kluge ... try to fix this when we redesign
1674 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1677 * Validate action's use of OLD/NEW, qual too
1680 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1681 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1683 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1684 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1686 switch (stmt->event)
1690 elog(ERROR, "ON SELECT rule may not use OLD");
1692 elog(ERROR, "ON SELECT rule may not use NEW");
1699 elog(ERROR, "ON INSERT rule may not use OLD");
1703 elog(ERROR, "ON DELETE rule may not use NEW");
1706 elog(ERROR, "transformRuleStmt: unexpected event type %d",
1712 * For efficiency's sake, add OLD to the rule action's
1713 * jointree only if it was actually referenced in the
1714 * statement or qual.
1716 * For INSERT, NEW is not really a relation (only a reference to
1717 * the to-be-inserted tuple) and should never be added to the
1720 * For UPDATE, we treat NEW as being another kind of reference to
1721 * OLD, because it represents references to *transformed*
1722 * tuples of the existing relation. It would be wrong to
1723 * enter NEW separately in the jointree, since that would
1724 * cause a double join of the updated relation. It's also
1725 * wrong to fail to make a jointree entry if only NEW and not
1728 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1730 /* hack so we can use addRTEtoQuery() */
1731 sub_pstate->p_rtable = sub_qry->rtable;
1732 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1733 addRTEtoQuery(sub_pstate, oldrte, true, false);
1734 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1737 newactions = lappend(newactions, top_subqry);
1739 release_pstate_resources(sub_pstate);
1743 stmt->actions = newactions;
1751 * transformSelectStmt -
1752 * transforms a Select Statement
1754 * Note: this is also used for DECLARE CURSOR statements.
1757 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1759 Query *qry = makeNode(Query);
1762 qry->commandType = CMD_SELECT;
1764 /* make FOR UPDATE clause available to addRangeTableEntry */
1765 pstate->p_forUpdate = stmt->forUpdate;
1767 /* process the FROM clause */
1768 transformFromClause(pstate, stmt->fromClause);
1770 /* transform targetlist */
1771 qry->targetList = transformTargetList(pstate, stmt->targetList);
1773 /* handle any SELECT INTO/CREATE TABLE AS spec */
1774 qry->into = stmt->into;
1775 if (stmt->intoColNames)
1776 applyColumnNames(qry->targetList, stmt->intoColNames);
1778 /* mark column origins */
1779 markTargetListOrigins(pstate, qry->targetList);
1781 /* transform WHERE */
1782 qual = transformWhereClause(pstate, stmt->whereClause);
1785 * Initial processing of HAVING clause is just like WHERE clause.
1786 * Additional work will be done in optimizer/plan/planner.c.
1788 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
1791 * Transform sorting/grouping stuff. Do ORDER BY first because both
1792 * transformGroupClause and transformDistinctClause need the results.
1794 qry->sortClause = transformSortClause(pstate,
1798 qry->groupClause = transformGroupClause(pstate,
1803 qry->distinctClause = transformDistinctClause(pstate,
1804 stmt->distinctClause,
1808 qry->limitOffset = stmt->limitOffset;
1809 qry->limitCount = stmt->limitCount;
1811 qry->rtable = pstate->p_rtable;
1812 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1814 qry->hasSubLinks = pstate->p_hasSubLinks;
1815 qry->hasAggs = pstate->p_hasAggs;
1816 if (pstate->p_hasAggs || qry->groupClause)
1817 parseCheckAggregates(pstate, qry);
1819 if (stmt->forUpdate != NIL)
1820 transformForUpdate(qry, stmt->forUpdate);
1826 * transformSetOperationsStmt -
1827 * transforms a set-operations tree
1829 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1830 * structure to it. We must transform each leaf SELECT and build up a top-
1831 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1832 * The tree of set operations is converted into the setOperations field of
1833 * the top-level Query.
1836 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1838 Query *qry = makeNode(Query);
1839 SelectStmt *leftmostSelect;
1841 Query *leftmostQuery;
1842 SetOperationStmt *sostmt;
1856 RangeTblEntry *jrte;
1860 qry->commandType = CMD_SELECT;
1863 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1864 * it and from the top-level node.
1866 leftmostSelect = stmt->larg;
1867 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1868 leftmostSelect = leftmostSelect->larg;
1869 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1870 leftmostSelect->larg == NULL);
1871 into = leftmostSelect->into;
1872 intoColNames = leftmostSelect->intoColNames;
1874 /* clear them to prevent complaints in transformSetOperationTree() */
1875 leftmostSelect->into = NULL;
1876 leftmostSelect->intoColNames = NIL;
1879 * These are not one-time, exactly, but we want to process them here
1880 * and not let transformSetOperationTree() see them --- else it'll
1881 * just recurse right back here!
1883 sortClause = stmt->sortClause;
1884 limitOffset = stmt->limitOffset;
1885 limitCount = stmt->limitCount;
1886 forUpdate = stmt->forUpdate;
1888 stmt->sortClause = NIL;
1889 stmt->limitOffset = NULL;
1890 stmt->limitCount = NULL;
1891 stmt->forUpdate = NIL;
1893 /* We don't support forUpdate with set ops at the moment. */
1895 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
1898 * Recursively transform the components of the tree.
1900 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1901 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1902 qry->setOperations = (Node *) sostmt;
1905 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1907 node = sostmt->larg;
1908 while (node && IsA(node, SetOperationStmt))
1909 node = ((SetOperationStmt *) node)->larg;
1910 Assert(node && IsA(node, RangeTblRef));
1911 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1912 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1913 Assert(leftmostQuery != NULL);
1916 * Generate dummy targetlist for outer query using column names of
1917 * leftmost select and common datatypes of topmost set operation. Also
1918 * make lists of the dummy vars and their names for use in parsing
1921 * Note: we use leftmostRTI as the varno of the dummy variables.
1922 * It shouldn't matter too much which RT index they have, as long
1923 * as they have one that corresponds to a real RT entry; else funny
1924 * things may happen when the tree is mashed by rule rewriting.
1926 qry->targetList = NIL;
1929 lefttl = leftmostQuery->targetList;
1930 foreach(dtlist, sostmt->colTypes)
1932 Oid colType = lfirsto(dtlist);
1933 Resdom *leftResdom = ((TargetEntry *) lfirst(lefttl))->resdom;
1934 char *colName = pstrdup(leftResdom->resname);
1938 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1943 expr = (Expr *) makeVar(leftmostRTI,
1948 qry->targetList = lappend(qry->targetList,
1949 makeTargetEntry(resdom, expr));
1950 targetvars = lappend(targetvars, expr);
1951 targetnames = lappend(targetnames, makeString(colName));
1952 lefttl = lnext(lefttl);
1956 * Handle SELECT INTO/CREATE TABLE AS.
1958 * Any column names from CREATE TABLE AS need to be attached to both
1959 * the top level and the leftmost subquery. We do not do this earlier
1960 * because we do *not* want the targetnames list to be affected.
1965 applyColumnNames(qry->targetList, intoColNames);
1966 applyColumnNames(leftmostQuery->targetList, intoColNames);
1970 * As a first step towards supporting sort clauses that are
1971 * expressions using the output columns, generate a namespace entry
1972 * that makes the output columns visible. A Join RTE node is handy
1973 * for this, since we can easily control the Vars generated upon
1976 * Note: we don't yet do anything useful with such cases, but at least
1977 * "ORDER BY upper(foo)" will draw the right error message rather than
1980 jrte = addRangeTableEntryForJoin(NULL,
1986 jrtr = makeNode(RangeTblRef);
1987 jrtr->rtindex = 1; /* only entry in dummy rtable */
1989 sv_rtable = pstate->p_rtable;
1990 pstate->p_rtable = makeList1(jrte);
1992 sv_namespace = pstate->p_namespace;
1993 pstate->p_namespace = makeList1(jrtr);
1996 * For now, we don't support resjunk sort clauses on the output of a
1997 * setOperation tree --- you can only use the SQL92-spec options of
1998 * selecting an output column by name or number. Enforce by checking
1999 * that transformSortClause doesn't add any items to tlist.
2001 tllen = length(qry->targetList);
2003 qry->sortClause = transformSortClause(pstate,
2007 pstate->p_namespace = sv_namespace;
2008 pstate->p_rtable = sv_rtable;
2010 if (tllen != length(qry->targetList))
2011 elog(ERROR, "ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns");
2013 qry->limitOffset = limitOffset;
2014 qry->limitCount = limitCount;
2016 qry->rtable = pstate->p_rtable;
2017 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2019 qry->hasSubLinks = pstate->p_hasSubLinks;
2020 qry->hasAggs = pstate->p_hasAggs;
2021 if (pstate->p_hasAggs || qry->groupClause)
2022 parseCheckAggregates(pstate, qry);
2024 if (forUpdate != NIL)
2025 transformForUpdate(qry, forUpdate);
2031 * transformSetOperationTree
2032 * Recursively transform leaves and internal nodes of a set-op tree
2035 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2039 Assert(stmt && IsA(stmt, SelectStmt));
2042 * Validity-check both leaf and internal SELECTs for disallowed ops.
2045 elog(ERROR, "INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT");
2046 /* We don't support forUpdate with set ops at the moment. */
2047 if (stmt->forUpdate)
2048 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2051 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2052 * clauses attached, we need to treat it like a leaf node to generate
2053 * an independent sub-Query tree. Otherwise, it can be represented by
2054 * a SetOperationStmt node underneath the parent Query.
2056 if (stmt->op == SETOP_NONE)
2058 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2063 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2064 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2073 /* Process leaf SELECT */
2076 char selectName[32];
2081 * Transform SelectStmt into a Query.
2083 * Note: previously transformed sub-queries don't affect the parsing
2084 * of this sub-query, because they are not in the toplevel
2085 * pstate's namespace list.
2087 selectList = parse_sub_analyze((Node *) stmt, pstate);
2089 Assert(length(selectList) == 1);
2090 selectQuery = (Query *) lfirst(selectList);
2091 Assert(IsA(selectQuery, Query));
2094 * Check for bogus references to Vars on the current query level
2095 * (but upper-level references are okay).
2096 * Normally this can't happen because the namespace will be empty,
2097 * but it could happen if we are inside a rule.
2099 if (pstate->p_namespace)
2101 if (contain_vars_of_level((Node *) selectQuery, 1))
2102 elog(ERROR, "UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level");
2106 * Make the leaf query be a subquery in the top-level rangetable.
2108 snprintf(selectName, sizeof(selectName), "*SELECT* %d", length(pstate->p_rtable) + 1);
2109 rte = addRangeTableEntryForSubquery(pstate,
2111 makeAlias(selectName, NIL),
2115 * Return a RangeTblRef to replace the SelectStmt in the set-op
2118 rtr = makeNode(RangeTblRef);
2119 /* assume new rte is at end */
2120 rtr->rtindex = length(pstate->p_rtable);
2121 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2122 return (Node *) rtr;
2126 /* Process an internal node (set operation node) */
2127 SetOperationStmt *op = makeNode(SetOperationStmt);
2130 const char *context;
2132 context = (stmt->op == SETOP_UNION ? "UNION" :
2133 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2137 op->all = stmt->all;
2140 * Recursively transform the child nodes.
2142 op->larg = transformSetOperationTree(pstate, stmt->larg);
2143 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2146 * Verify that the two children have the same number of non-junk
2147 * columns, and determine the types of the merged output columns.
2149 lcoltypes = getSetColTypes(pstate, op->larg);
2150 rcoltypes = getSetColTypes(pstate, op->rarg);
2151 if (length(lcoltypes) != length(rcoltypes))
2152 elog(ERROR, "Each %s query must have the same number of columns",
2155 while (lcoltypes != NIL)
2157 Oid lcoltype = lfirsto(lcoltypes);
2158 Oid rcoltype = lfirsto(rcoltypes);
2161 rescoltype = select_common_type(makeListo2(lcoltype, rcoltype),
2163 op->colTypes = lappendo(op->colTypes, rescoltype);
2164 lcoltypes = lnext(lcoltypes);
2165 rcoltypes = lnext(rcoltypes);
2174 * Get output column types of an (already transformed) set-op node
2177 getSetColTypes(ParseState *pstate, Node *node)
2179 if (IsA(node, RangeTblRef))
2181 RangeTblRef *rtr = (RangeTblRef *) node;
2182 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2183 Query *selectQuery = rte->subquery;
2187 Assert(selectQuery != NULL);
2188 /* Get types of non-junk columns */
2189 foreach(tl, selectQuery->targetList)
2191 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2192 Resdom *resnode = tle->resdom;
2194 if (resnode->resjunk)
2196 result = lappendo(result, resnode->restype);
2200 else if (IsA(node, SetOperationStmt))
2202 SetOperationStmt *op = (SetOperationStmt *) node;
2204 /* Result already computed during transformation of node */
2205 Assert(op->colTypes != NIL);
2206 return op->colTypes;
2210 elog(ERROR, "getSetColTypes: unexpected node %d",
2211 (int) nodeTag(node));
2212 return NIL; /* keep compiler quiet */
2216 /* Attach column names from a ColumnDef list to a TargetEntry list */
2218 applyColumnNames(List *dst, List *src)
2220 if (length(src) > length(dst))
2221 elog(ERROR, "CREATE TABLE AS specifies too many column names");
2223 while (src != NIL && dst != NIL)
2225 TargetEntry *d = (TargetEntry *) lfirst(dst);
2226 ColumnDef *s = (ColumnDef *) lfirst(src);
2228 Assert(d->resdom && !d->resdom->resjunk);
2230 d->resdom->resname = pstrdup(s->colname);
2239 * transformUpdateStmt -
2240 * transforms an update statement
2243 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2245 Query *qry = makeNode(Query);
2247 List *origTargetList;
2250 qry->commandType = CMD_UPDATE;
2251 pstate->p_is_update = true;
2253 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2254 interpretInhOption(stmt->relation->inhOpt),
2258 * the FROM clause is non-standard SQL syntax. We used to be able to
2259 * do this with REPLACE in POSTQUEL so we keep the feature.
2261 transformFromClause(pstate, stmt->fromClause);
2263 qry->targetList = transformTargetList(pstate, stmt->targetList);
2265 qual = transformWhereClause(pstate, stmt->whereClause);
2267 qry->rtable = pstate->p_rtable;
2268 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2270 qry->hasSubLinks = pstate->p_hasSubLinks;
2271 qry->hasAggs = pstate->p_hasAggs;
2272 if (pstate->p_hasAggs)
2273 parseCheckAggregates(pstate, qry);
2276 * Now we are done with SELECT-like processing, and can get on with
2277 * transforming the target list to match the UPDATE target columns.
2280 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2281 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2282 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2284 /* Prepare non-junk columns for assignment to target table */
2285 origTargetList = stmt->targetList;
2286 foreach(tl, qry->targetList)
2288 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2289 Resdom *resnode = tle->resdom;
2290 ResTarget *origTarget;
2292 if (resnode->resjunk)
2295 * Resjunk nodes need no additional processing, but be sure
2296 * they have names and resnos that do not match any target
2297 * columns; else rewriter or planner might get confused.
2299 resnode->resname = "?resjunk?";
2300 resnode->resno = (AttrNumber) pstate->p_next_resno++;
2303 if (origTargetList == NIL)
2304 elog(ERROR, "UPDATE target count mismatch --- internal error");
2305 origTarget = (ResTarget *) lfirst(origTargetList);
2306 updateTargetListEntry(pstate, tle, origTarget->name,
2307 attnameAttNum(pstate->p_target_relation,
2308 origTarget->name, true),
2309 origTarget->indirection);
2310 origTargetList = lnext(origTargetList);
2312 if (origTargetList != NIL)
2313 elog(ERROR, "UPDATE target count mismatch --- internal error");
2319 * tranformAlterTableStmt -
2320 * transform an Alter Table Statement
2323 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2324 List **extras_before, List **extras_after)
2327 CreateStmtContext cxt;
2331 * The only subtypes that currently require parse transformation
2332 * handling are 'A'dd column and Add 'C'onstraint. These largely
2333 * re-use code from CREATE TABLE.
2335 * If we need to do any parse transformation, get exclusive lock on
2336 * the relation to make sure it won't change before we execute the
2339 switch (stmt->subtype)
2342 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2344 cxt.stmtType = "ALTER TABLE";
2345 cxt.relation = stmt->relation;
2346 cxt.inhRelations = NIL;
2347 cxt.relOid = RelationGetRelid(rel);
2348 cxt.hasoids = SearchSysCacheExists(ATTNUM,
2349 ObjectIdGetDatum(cxt.relOid),
2350 Int16GetDatum(ObjectIdAttributeNumber),
2353 cxt.ckconstraints = NIL;
2354 cxt.fkconstraints = NIL;
2355 cxt.ixconstraints = NIL;
2360 Assert(IsA(stmt->def, ColumnDef));
2361 transformColumnDefinition(pstate, &cxt,
2362 (ColumnDef *) stmt->def);
2364 transformIndexConstraints(pstate, &cxt);
2365 transformFKConstraints(pstate, &cxt, false);
2367 ((ColumnDef *) stmt->def)->constraints = cxt.ckconstraints;
2368 *extras_before = nconc(*extras_before, cxt.blist);
2369 *extras_after = nconc(cxt.alist, *extras_after);
2371 heap_close(rel, NoLock); /* close rel, keep lock */
2375 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2377 cxt.stmtType = "ALTER TABLE";
2378 cxt.relation = stmt->relation;
2379 cxt.inhRelations = NIL;
2380 cxt.relOid = RelationGetRelid(rel);
2381 cxt.hasoids = SearchSysCacheExists(ATTNUM,
2382 ObjectIdGetDatum(cxt.relOid),
2383 Int16GetDatum(ObjectIdAttributeNumber),
2386 cxt.ckconstraints = NIL;
2387 cxt.fkconstraints = NIL;
2388 cxt.ixconstraints = NIL;
2393 if (IsA(stmt->def, Constraint))
2394 transformTableConstraint(pstate, &cxt,
2395 (Constraint *) stmt->def);
2396 else if (IsA(stmt->def, FkConstraint))
2397 cxt.fkconstraints = lappend(cxt.fkconstraints, stmt->def);
2399 elog(ERROR, "Unexpected node type in ALTER TABLE ADD CONSTRAINT");
2401 transformIndexConstraints(pstate, &cxt);
2402 transformFKConstraints(pstate, &cxt, true);
2404 Assert(cxt.columns == NIL);
2405 /* fkconstraints should be put into my own stmt in this case */
2406 stmt->def = (Node *) nconc(cxt.ckconstraints, cxt.fkconstraints);
2407 *extras_before = nconc(*extras_before, cxt.blist);
2408 *extras_after = nconc(cxt.alist, *extras_after);
2410 heap_close(rel, NoLock); /* close rel, keep lock */
2416 * Already-transformed ADD CONSTRAINT, so just make it look
2417 * like the standard case.
2419 stmt->subtype = 'C';
2426 qry = makeNode(Query);
2427 qry->commandType = CMD_UTILITY;
2428 qry->utilityStmt = (Node *) stmt;
2434 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2436 Query *result = makeNode(Query);
2437 List *extras_before = NIL,
2438 *extras_after = NIL;
2440 result->commandType = CMD_UTILITY;
2441 result->utilityStmt = (Node *) stmt;
2444 * Don't allow both SCROLL and NO SCROLL to be specified
2446 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2447 (stmt->options & CURSOR_OPT_NO_SCROLL))
2448 elog(ERROR, "Cannot specify both SCROLL and NO SCROLL");
2450 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2451 &extras_before, &extras_after);
2453 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2454 if (extras_before || extras_after)
2455 elog(ERROR, "transformDeclareCursorStmt: internal error");
2462 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2464 Query *result = makeNode(Query);
2465 List *argtype_oids = NIL; /* argtype OIDs in a list */
2466 Oid *argtoids = NULL; /* and as an array */
2470 result->commandType = CMD_UTILITY;
2471 result->utilityStmt = (Node *) stmt;
2473 /* Transform list of TypeNames to list (and array) of type OIDs */
2474 nargs = length(stmt->argtypes);
2481 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2483 foreach(l, stmt->argtypes)
2485 TypeName *tn = lfirst(l);
2486 Oid toid = typenameTypeId(tn);
2488 argtype_oids = lappendo(argtype_oids, toid);
2489 argtoids[i++] = toid;
2493 stmt->argtype_oids = argtype_oids;
2496 * Analyze the statement using these parameter types (any parameters
2497 * passed in from above us will not be visible to it).
2499 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2502 * Shouldn't get any extra statements, since grammar only allows
2505 if (length(queries) != 1)
2506 elog(ERROR, "transformPrepareStmt: internal error");
2508 stmt->query = lfirst(queries);
2514 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2516 Query *result = makeNode(Query);
2519 result->commandType = CMD_UTILITY;
2520 result->utilityStmt = (Node *) stmt;
2522 paramtypes = FetchPreparedStatementParams(stmt->name);
2524 if (stmt->params || paramtypes)
2526 int nparams = length(stmt->params);
2527 int nexpected = length(paramtypes);
2531 if (nparams != nexpected)
2532 elog(ERROR, "Wrong number of parameters, expected %d but got %d",
2533 nexpected, nparams);
2535 foreach(l, stmt->params)
2537 Node *expr = lfirst(l);
2538 Oid expected_type_id,
2541 expr = transformExpr(pstate, expr);
2543 /* Cannot contain subselects or aggregates */
2544 if (pstate->p_hasSubLinks)
2545 elog(ERROR, "Cannot use subselects in EXECUTE parameters");
2546 if (pstate->p_hasAggs)
2547 elog(ERROR, "Cannot use aggregates in EXECUTE parameters");
2549 given_type_id = exprType(expr);
2550 expected_type_id = lfirsto(paramtypes);
2552 expr = coerce_to_target_type(pstate, expr, given_type_id,
2553 expected_type_id, -1,
2554 COERCION_ASSIGNMENT,
2555 COERCE_IMPLICIT_CAST);
2558 elog(ERROR, "Parameter $%d of type %s cannot be coerced into the expected type %s"
2559 "\n\tYou will need to rewrite or cast the expression",
2561 format_type_be(given_type_id),
2562 format_type_be(expected_type_id));
2566 paramtypes = lnext(paramtypes);
2574 /* exported so planner can check again after rewriting, query pullup, etc */
2576 CheckSelectForUpdate(Query *qry)
2578 if (qry->setOperations)
2579 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2580 if (qry->distinctClause != NIL)
2581 elog(ERROR, "SELECT FOR UPDATE is not allowed with DISTINCT clause");
2582 if (qry->groupClause != NIL)
2583 elog(ERROR, "SELECT FOR UPDATE is not allowed with GROUP BY clause");
2585 elog(ERROR, "SELECT FOR UPDATE is not allowed with AGGREGATE");
2589 transformForUpdate(Query *qry, List *forUpdate)
2591 List *rowMarks = qry->rowMarks;
2596 CheckSelectForUpdate(qry);
2598 if (lfirst(forUpdate) == NULL)
2600 /* all tables used in query */
2602 foreach(rt, qry->rtable)
2604 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2607 if (rte->rtekind == RTE_SUBQUERY)
2609 /* FOR UPDATE of subquery is propagated to subquery's rels */
2610 transformForUpdate(rte->subquery, makeList1(NULL));
2614 if (!intMember(i, rowMarks)) /* avoid duplicates */
2615 rowMarks = lappendi(rowMarks, i);
2616 rte->checkForWrite = true;
2622 /* just the named tables */
2623 foreach(l, forUpdate)
2625 char *relname = strVal(lfirst(l));
2628 foreach(rt, qry->rtable)
2630 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2633 if (strcmp(rte->eref->aliasname, relname) == 0)
2635 if (rte->rtekind == RTE_SUBQUERY)
2637 /* propagate to subquery */
2638 transformForUpdate(rte->subquery, makeList1(NULL));
2642 if (!intMember(i, rowMarks)) /* avoid duplicates */
2643 rowMarks = lappendi(rowMarks, i);
2644 rte->checkForWrite = true;
2650 elog(ERROR, "FOR UPDATE: relation \"%s\" not found in FROM clause",
2655 qry->rowMarks = rowMarks;
2660 * relationHasPrimaryKey -
2662 * See whether an existing relation has a primary key.
2665 relationHasPrimaryKey(Oid relationOid)
2667 bool result = false;
2672 rel = heap_open(relationOid, AccessShareLock);
2675 * Get the list of index OIDs for the table from the relcache, and
2676 * look up each one in the pg_index syscache until we find one marked
2677 * primary key (hopefully there isn't more than one such).
2679 indexoidlist = RelationGetIndexList(rel);
2681 foreach(indexoidscan, indexoidlist)
2683 Oid indexoid = lfirsto(indexoidscan);
2684 HeapTuple indexTuple;
2686 indexTuple = SearchSysCache(INDEXRELID,
2687 ObjectIdGetDatum(indexoid),
2689 if (!HeapTupleIsValid(indexTuple))
2690 elog(ERROR, "relationHasPrimaryKey: index %u not found",
2692 result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
2693 ReleaseSysCache(indexTuple);
2698 freeList(indexoidlist);
2700 heap_close(rel, AccessShareLock);
2706 * Preprocess a list of column constraint clauses
2707 * to attach constraint attributes to their primary constraint nodes
2708 * and detect inconsistent/misplaced constraint attributes.
2710 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2711 * constraints, but someday they ought to be supported for other constraints.
2714 transformConstraintAttrs(List *constraintList)
2716 Node *lastprimarynode = NULL;
2717 bool saw_deferrability = false;
2718 bool saw_initially = false;
2721 foreach(clist, constraintList)
2723 Node *node = lfirst(clist);
2725 if (!IsA(node, Constraint))
2727 lastprimarynode = node;
2728 /* reset flags for new primary node */
2729 saw_deferrability = false;
2730 saw_initially = false;
2734 Constraint *con = (Constraint *) node;
2736 switch (con->contype)
2738 case CONSTR_ATTR_DEFERRABLE:
2739 if (lastprimarynode == NULL ||
2740 !IsA(lastprimarynode, FkConstraint))
2741 elog(ERROR, "Misplaced DEFERRABLE clause");
2742 if (saw_deferrability)
2743 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2744 saw_deferrability = true;
2745 ((FkConstraint *) lastprimarynode)->deferrable = true;
2747 case CONSTR_ATTR_NOT_DEFERRABLE:
2748 if (lastprimarynode == NULL ||
2749 !IsA(lastprimarynode, FkConstraint))
2750 elog(ERROR, "Misplaced NOT DEFERRABLE clause");
2751 if (saw_deferrability)
2752 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2753 saw_deferrability = true;
2754 ((FkConstraint *) lastprimarynode)->deferrable = false;
2755 if (saw_initially &&
2756 ((FkConstraint *) lastprimarynode)->initdeferred)
2757 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2759 case CONSTR_ATTR_DEFERRED:
2760 if (lastprimarynode == NULL ||
2761 !IsA(lastprimarynode, FkConstraint))
2762 elog(ERROR, "Misplaced INITIALLY DEFERRED clause");
2764 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2765 saw_initially = true;
2766 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2769 * If only INITIALLY DEFERRED appears, assume
2772 if (!saw_deferrability)
2773 ((FkConstraint *) lastprimarynode)->deferrable = true;
2774 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2775 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2777 case CONSTR_ATTR_IMMEDIATE:
2778 if (lastprimarynode == NULL ||
2779 !IsA(lastprimarynode, FkConstraint))
2780 elog(ERROR, "Misplaced INITIALLY IMMEDIATE clause");
2782 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2783 saw_initially = true;
2784 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2787 /* Otherwise it's not an attribute */
2788 lastprimarynode = node;
2789 /* reset flags for new primary node */
2790 saw_deferrability = false;
2791 saw_initially = false;
2798 /* Build a FromExpr node */
2800 makeFromExpr(List *fromlist, Node *quals)
2802 FromExpr *f = makeNode(FromExpr);
2804 f->fromlist = fromlist;
2810 * Special handling of type definition for a column
2813 transformColumnType(ParseState *pstate, ColumnDef *column)
2815 TypeName *typename = column->typename;
2816 Type ctype = typenameType(typename);
2819 * Is this the name of a complex type? If so, implement it as a set.
2821 * XXX this is a hangover from ancient Berkeley code that probably
2822 * doesn't work anymore anyway.
2824 if (typeTypeRelid(ctype) != InvalidOid)
2827 * (Eventually add in here that the set can only contain one
2830 typename->setof = true;
2833 ReleaseSysCache(ctype);
2837 * analyzeCreateSchemaStmt -
2838 * analyzes the "create schema" statement
2840 * Split the schema element list into individual commands and place
2841 * them in the result list in an order such that there are no
2842 * forward references (e.g. GRANT to a table created later in the list).
2844 * SQL92 also allows constraints to make forward references, so thumb through
2845 * the table columns and move forward references to a posterior alter-table
2848 * The result is a list of parse nodes that still need to be analyzed ---
2849 * but we can't analyze the later commands until we've executed the earlier
2850 * ones, because of possible inter-object references.
2852 * Note: Called from commands/command.c
2855 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
2857 CreateSchemaStmtContext cxt;
2861 cxt.stmtType = "CREATE SCHEMA";
2862 cxt.schemaname = stmt->schemaname;
2863 cxt.authid = stmt->authid;
2867 cxt.fwconstraints = NIL;
2873 * Run through each schema element in the schema element list.
2874 * Separate statements by type, and do preliminary analysis.
2876 foreach(elements, stmt->schemaElts)
2878 Node *element = lfirst(elements);
2880 switch (nodeTag(element))
2884 CreateStmt *elp = (CreateStmt *) element;
2886 if (elp->relation->schemaname == NULL)
2887 elp->relation->schemaname = cxt.schemaname;
2888 else if (strcmp(cxt.schemaname, elp->relation->schemaname) != 0)
2889 elog(ERROR, "New table specifies a schema (%s)"
2890 " different from the one being created (%s)",
2891 elp->relation->schemaname, cxt.schemaname);
2894 * XXX todo: deal with constraints
2897 cxt.tables = lappend(cxt.tables, element);
2903 ViewStmt *elp = (ViewStmt *) element;
2905 if (elp->view->schemaname == NULL)
2906 elp->view->schemaname = cxt.schemaname;
2907 else if (strcmp(cxt.schemaname, elp->view->schemaname) != 0)
2908 elog(ERROR, "New view specifies a schema (%s)"
2909 " different from the one being created (%s)",
2910 elp->view->schemaname, cxt.schemaname);
2913 * XXX todo: deal with references between views
2916 cxt.views = lappend(cxt.views, element);
2921 cxt.grants = lappend(cxt.grants, element);
2925 elog(ERROR, "parser: unsupported schema node (internal error)");
2930 result = nconc(result, cxt.tables);
2931 result = nconc(result, cxt.views);
2932 result = nconc(result, cxt.grants);
2938 * Traverse a fully-analyzed tree to verify that parameter symbols
2939 * match their types. We need this because some Params might still
2940 * be UNKNOWN, if there wasn't anything to force their coercion,
2941 * and yet other instances seen later might have gotten coerced.
2944 check_parameter_resolution_walker(Node *node,
2945 check_parameter_resolution_context *context)
2949 if (IsA(node, Param))
2951 Param *param = (Param *) node;
2953 if (param->paramkind == PARAM_NUM)
2955 int paramno = param->paramid;
2957 if (paramno <= 0 || /* shouldn't happen, but... */
2958 paramno > context->numParams)
2959 elog(ERROR, "Parameter '$%d' is out of range", paramno);
2961 if (param->paramtype != context->paramTypes[paramno-1])
2962 elog(ERROR, "Could not determine datatype of parameter $%d",
2967 if (IsA(node, Query))
2969 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2970 return query_tree_walker((Query *) node,
2971 check_parameter_resolution_walker,
2972 (void *) context, 0);
2974 return expression_tree_walker(node, check_parameter_resolution_walker,