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.271 2003/05/06 00:20:32 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->funcname = NIL;
1316 iparam->opclass = NIL;
1317 index->indexParams = lappend(index->indexParams, iparam);
1320 indexlist = lappend(indexlist, index);
1324 * Scan the index list and remove any redundant index specifications.
1325 * This can happen if, for instance, the user writes UNIQUE PRIMARY
1326 * KEY. A strict reading of SQL92 would suggest raising an error
1327 * instead, but that strikes me as too anal-retentive. - tgl
1330 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1331 * pre-existing indexes, too.
1334 if (cxt->pkey != NULL)
1336 /* Make sure we keep the PKEY index in preference to others... */
1337 cxt->alist = makeList1(cxt->pkey);
1339 while (indexlist != NIL)
1341 index = lfirst(indexlist);
1343 /* if it's pkey, it's already in cxt->alist */
1344 if (index != cxt->pkey)
1349 foreach(priorlist, cxt->alist)
1351 IndexStmt *priorindex = lfirst(priorlist);
1353 if (equal(index->indexParams, priorindex->indexParams))
1356 * If the prior index is as yet unnamed, and this one
1357 * is named, then transfer the name to the prior
1358 * index. This ensures that if we have named and
1359 * unnamed constraints, we'll use (at least one of)
1360 * the names for the index.
1362 if (priorindex->idxname == NULL)
1363 priorindex->idxname = index->idxname;
1370 cxt->alist = lappend(cxt->alist, index);
1373 indexlist = lnext(indexlist);
1377 * Finally, select unique names for all not-previously-named indices,
1378 * and display NOTICE messages.
1380 * XXX in ALTER TABLE case, we fail to consider name collisions against
1381 * pre-existing indexes.
1383 foreach(indexlist, cxt->alist)
1385 index = lfirst(indexlist);
1387 if (index->idxname == NULL && index->indexParams != NIL)
1389 iparam = lfirst(index->indexParams);
1390 index->idxname = CreateIndexName(cxt->relation->relname,
1391 iparam->name ? iparam->name :
1392 strVal(llast(iparam->funcname)),
1395 if (index->idxname == NULL) /* should not happen */
1396 elog(ERROR, "%s: failed to make implicit index name",
1399 elog(NOTICE, "%s / %s%s will create implicit index '%s' for table '%s'",
1401 (strcmp(cxt->stmtType, "ALTER TABLE") == 0) ? "ADD " : "",
1402 (index->primary ? "PRIMARY KEY" : "UNIQUE"),
1403 index->idxname, cxt->relation->relname);
1408 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1409 bool isAddConstraint)
1411 if (cxt->fkconstraints == NIL)
1414 elog(NOTICE, "%s will create implicit trigger(s) for FOREIGN KEY check(s)",
1418 * For ALTER TABLE ADD CONSTRAINT, nothing to do. For CREATE TABLE or
1419 * ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD CONSTRAINT command
1420 * to execute after the basic command is complete.
1422 * Note: the ADD CONSTRAINT command must also execute after any index
1423 * creation commands. Thus, this should run after
1424 * transformIndexConstraints, so that the CREATE INDEX commands are
1425 * already in cxt->alist.
1427 if (!isAddConstraint)
1429 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1432 alterstmt->subtype = 'c'; /* preprocessed add constraint */
1433 alterstmt->relation = cxt->relation;
1434 alterstmt->name = NULL;
1435 alterstmt->def = (Node *) cxt->fkconstraints;
1437 /* Don't need to scan the table contents in this case */
1438 foreach(fkclist, cxt->fkconstraints)
1440 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1442 fkconstraint->skip_validation = true;
1445 cxt->alist = lappend(cxt->alist, (Node *) alterstmt);
1450 * transformIndexStmt -
1451 * transforms the qualification of the index statement
1454 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1459 qry = makeNode(Query);
1460 qry->commandType = CMD_UTILITY;
1462 /* take care of the where clause */
1463 if (stmt->whereClause)
1466 * Put the parent table into the rtable so that the WHERE clause
1467 * can refer to its fields without qualification. Note that this
1468 * only works if the parent table already exists --- so we can't
1469 * easily support predicates on indexes created implicitly by
1470 * CREATE TABLE. Fortunately, that's not necessary.
1472 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1474 /* no to join list, yes to namespace */
1475 addRTEtoQuery(pstate, rte, false, true);
1477 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1480 qry->hasSubLinks = pstate->p_hasSubLinks;
1481 stmt->rangetable = pstate->p_rtable;
1483 qry->utilityStmt = (Node *) stmt;
1489 * transformRuleStmt -
1490 * transform a Create Rule Statement. The actions is a list of parse
1491 * trees which is transformed into a list of query trees.
1494 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1495 List **extras_before, List **extras_after)
1498 RangeTblEntry *oldrte;
1499 RangeTblEntry *newrte;
1501 qry = makeNode(Query);
1502 qry->commandType = CMD_UTILITY;
1503 qry->utilityStmt = (Node *) stmt;
1506 * To avoid deadlock, make sure the first thing we do is grab
1507 * AccessExclusiveLock on the target relation. This will be needed by
1508 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1509 * beforehand. We don't need to hold a refcount on the relcache
1512 heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1516 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1517 * 2. Set up their RTEs in the main pstate for use in parsing the
1518 * rule qualification.
1520 Assert(pstate->p_rtable == NIL);
1521 oldrte = addRangeTableEntry(pstate, stmt->relation,
1522 makeAlias("*OLD*", NIL),
1524 newrte = addRangeTableEntry(pstate, stmt->relation,
1525 makeAlias("*NEW*", NIL),
1527 /* Must override addRangeTableEntry's default access-check flags */
1528 oldrte->checkForRead = false;
1529 newrte->checkForRead = false;
1532 * They must be in the namespace too for lookup purposes, but only add
1533 * the one(s) that are relevant for the current kind of rule. In an
1534 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1535 * unambiguous, but there's no need to be so picky for INSERT &
1536 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1537 * unqualified references to their fields.) We do not add them to the
1540 switch (stmt->event)
1543 addRTEtoQuery(pstate, oldrte, false, true);
1546 addRTEtoQuery(pstate, oldrte, false, true);
1547 addRTEtoQuery(pstate, newrte, false, true);
1550 addRTEtoQuery(pstate, newrte, false, true);
1553 addRTEtoQuery(pstate, oldrte, false, true);
1556 elog(ERROR, "transformRuleStmt: unexpected event type %d",
1561 /* take care of the where clause */
1562 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1564 if (length(pstate->p_rtable) != 2) /* naughty, naughty... */
1565 elog(ERROR, "Rule WHERE condition may not contain references to other relations");
1567 /* aggregates not allowed (but subselects are okay) */
1568 if (contain_agg_clause(stmt->whereClause))
1569 elog(ERROR, "Rule WHERE condition may not contain aggregate functions");
1571 /* save info about sublinks in where clause */
1572 qry->hasSubLinks = pstate->p_hasSubLinks;
1575 * 'instead nothing' rules with a qualification need a query
1576 * rangetable so the rewrite handler can add the negated rule
1577 * qualification to the original query. We create a query with the new
1578 * command type CMD_NOTHING here that is treated specially by the
1581 if (stmt->actions == NIL)
1583 Query *nothing_qry = makeNode(Query);
1585 nothing_qry->commandType = CMD_NOTHING;
1586 nothing_qry->rtable = pstate->p_rtable;
1587 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1589 stmt->actions = makeList1(nothing_qry);
1594 List *newactions = NIL;
1597 * transform each statement, like parse_sub_analyze()
1599 foreach(oldactions, stmt->actions)
1601 Node *action = (Node *) lfirst(oldactions);
1602 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1609 * Set up OLD/NEW in the rtable for this statement. The
1610 * entries are marked not inFromCl because we don't want them
1611 * to be referred to by unqualified field names nor "*" in the
1612 * rule actions. We must add them to the namespace, however,
1613 * or they won't be accessible at all. We decide later
1614 * whether to put them in the joinlist.
1616 oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1617 makeAlias("*OLD*", NIL),
1619 newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1620 makeAlias("*NEW*", NIL),
1622 oldrte->checkForRead = false;
1623 newrte->checkForRead = false;
1624 addRTEtoQuery(sub_pstate, oldrte, false, true);
1625 addRTEtoQuery(sub_pstate, newrte, false, true);
1627 /* Transform the rule action statement */
1628 top_subqry = transformStmt(sub_pstate, action,
1629 extras_before, extras_after);
1632 * We cannot support utility-statement actions (eg NOTIFY)
1633 * with nonempty rule WHERE conditions, because there's no way
1634 * to make the utility action execute conditionally.
1636 if (top_subqry->commandType == CMD_UTILITY &&
1637 stmt->whereClause != NULL)
1638 elog(ERROR, "Rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions");
1641 * If the action is INSERT...SELECT, OLD/NEW have been pushed
1642 * down into the SELECT, and that's what we need to look at.
1643 * (Ugly kluge ... try to fix this when we redesign
1646 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1649 * Validate action's use of OLD/NEW, qual too
1652 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1653 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1655 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1656 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1658 switch (stmt->event)
1662 elog(ERROR, "ON SELECT rule may not use OLD");
1664 elog(ERROR, "ON SELECT rule may not use NEW");
1671 elog(ERROR, "ON INSERT rule may not use OLD");
1675 elog(ERROR, "ON DELETE rule may not use NEW");
1678 elog(ERROR, "transformRuleStmt: unexpected event type %d",
1684 * For efficiency's sake, add OLD to the rule action's
1685 * jointree only if it was actually referenced in the
1686 * statement or qual.
1688 * For INSERT, NEW is not really a relation (only a reference to
1689 * the to-be-inserted tuple) and should never be added to the
1692 * For UPDATE, we treat NEW as being another kind of reference to
1693 * OLD, because it represents references to *transformed*
1694 * tuples of the existing relation. It would be wrong to
1695 * enter NEW separately in the jointree, since that would
1696 * cause a double join of the updated relation. It's also
1697 * wrong to fail to make a jointree entry if only NEW and not
1700 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1702 /* hack so we can use addRTEtoQuery() */
1703 sub_pstate->p_rtable = sub_qry->rtable;
1704 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1705 addRTEtoQuery(sub_pstate, oldrte, true, false);
1706 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1709 newactions = lappend(newactions, top_subqry);
1711 release_pstate_resources(sub_pstate);
1715 stmt->actions = newactions;
1723 * transformSelectStmt -
1724 * transforms a Select Statement
1726 * Note: this is also used for DECLARE CURSOR statements.
1729 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1731 Query *qry = makeNode(Query);
1734 qry->commandType = CMD_SELECT;
1736 /* make FOR UPDATE clause available to addRangeTableEntry */
1737 pstate->p_forUpdate = stmt->forUpdate;
1739 /* process the FROM clause */
1740 transformFromClause(pstate, stmt->fromClause);
1742 /* transform targetlist */
1743 qry->targetList = transformTargetList(pstate, stmt->targetList);
1745 /* handle any SELECT INTO/CREATE TABLE AS spec */
1746 qry->into = stmt->into;
1747 if (stmt->intoColNames)
1748 applyColumnNames(qry->targetList, stmt->intoColNames);
1750 /* mark column origins */
1751 markTargetListOrigins(pstate, qry->targetList);
1753 /* transform WHERE */
1754 qual = transformWhereClause(pstate, stmt->whereClause);
1757 * Initial processing of HAVING clause is just like WHERE clause.
1758 * Additional work will be done in optimizer/plan/planner.c.
1760 qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
1762 qry->groupClause = transformGroupClause(pstate,
1766 qry->sortClause = transformSortClause(pstate,
1770 qry->distinctClause = transformDistinctClause(pstate,
1771 stmt->distinctClause,
1775 qry->limitOffset = stmt->limitOffset;
1776 qry->limitCount = stmt->limitCount;
1778 qry->rtable = pstate->p_rtable;
1779 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1781 qry->hasSubLinks = pstate->p_hasSubLinks;
1782 qry->hasAggs = pstate->p_hasAggs;
1783 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1784 parseCheckAggregates(pstate, qry);
1786 if (stmt->forUpdate != NIL)
1787 transformForUpdate(qry, stmt->forUpdate);
1793 * transformSetOperationsStmt -
1794 * transforms a set-operations tree
1796 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1797 * structure to it. We must transform each leaf SELECT and build up a top-
1798 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1799 * The tree of set operations is converted into the setOperations field of
1800 * the top-level Query.
1803 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1805 Query *qry = makeNode(Query);
1806 SelectStmt *leftmostSelect;
1808 Query *leftmostQuery;
1809 SetOperationStmt *sostmt;
1823 RangeTblEntry *jrte;
1827 qry->commandType = CMD_SELECT;
1830 * Find leftmost leaf SelectStmt; extract the one-time-only items from
1831 * it and from the top-level node.
1833 leftmostSelect = stmt->larg;
1834 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1835 leftmostSelect = leftmostSelect->larg;
1836 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1837 leftmostSelect->larg == NULL);
1838 into = leftmostSelect->into;
1839 intoColNames = leftmostSelect->intoColNames;
1841 /* clear them to prevent complaints in transformSetOperationTree() */
1842 leftmostSelect->into = NULL;
1843 leftmostSelect->intoColNames = NIL;
1846 * These are not one-time, exactly, but we want to process them here
1847 * and not let transformSetOperationTree() see them --- else it'll
1848 * just recurse right back here!
1850 sortClause = stmt->sortClause;
1851 limitOffset = stmt->limitOffset;
1852 limitCount = stmt->limitCount;
1853 forUpdate = stmt->forUpdate;
1855 stmt->sortClause = NIL;
1856 stmt->limitOffset = NULL;
1857 stmt->limitCount = NULL;
1858 stmt->forUpdate = NIL;
1860 /* We don't support forUpdate with set ops at the moment. */
1862 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
1865 * Recursively transform the components of the tree.
1867 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1868 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1869 qry->setOperations = (Node *) sostmt;
1872 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1874 node = sostmt->larg;
1875 while (node && IsA(node, SetOperationStmt))
1876 node = ((SetOperationStmt *) node)->larg;
1877 Assert(node && IsA(node, RangeTblRef));
1878 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1879 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1880 Assert(leftmostQuery != NULL);
1883 * Generate dummy targetlist for outer query using column names of
1884 * leftmost select and common datatypes of topmost set operation. Also
1885 * make lists of the dummy vars and their names for use in parsing
1888 * Note: we use leftmostRTI as the varno of the dummy variables.
1889 * It shouldn't matter too much which RT index they have, as long
1890 * as they have one that corresponds to a real RT entry; else funny
1891 * things may happen when the tree is mashed by rule rewriting.
1893 qry->targetList = NIL;
1896 lefttl = leftmostQuery->targetList;
1897 foreach(dtlist, sostmt->colTypes)
1899 Oid colType = lfirsto(dtlist);
1900 Resdom *leftResdom = ((TargetEntry *) lfirst(lefttl))->resdom;
1901 char *colName = pstrdup(leftResdom->resname);
1905 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1910 expr = (Expr *) makeVar(leftmostRTI,
1915 qry->targetList = lappend(qry->targetList,
1916 makeTargetEntry(resdom, expr));
1917 targetvars = lappend(targetvars, expr);
1918 targetnames = lappend(targetnames, makeString(colName));
1919 lefttl = lnext(lefttl);
1923 * Handle SELECT INTO/CREATE TABLE AS.
1925 * Any column names from CREATE TABLE AS need to be attached to both
1926 * the top level and the leftmost subquery. We do not do this earlier
1927 * because we do *not* want the targetnames list to be affected.
1932 applyColumnNames(qry->targetList, intoColNames);
1933 applyColumnNames(leftmostQuery->targetList, intoColNames);
1937 * As a first step towards supporting sort clauses that are
1938 * expressions using the output columns, generate a namespace entry
1939 * that makes the output columns visible. A Join RTE node is handy
1940 * for this, since we can easily control the Vars generated upon
1943 * Note: we don't yet do anything useful with such cases, but at least
1944 * "ORDER BY upper(foo)" will draw the right error message rather than
1947 jrte = addRangeTableEntryForJoin(NULL,
1953 jrtr = makeNode(RangeTblRef);
1954 jrtr->rtindex = 1; /* only entry in dummy rtable */
1956 sv_rtable = pstate->p_rtable;
1957 pstate->p_rtable = makeList1(jrte);
1959 sv_namespace = pstate->p_namespace;
1960 pstate->p_namespace = makeList1(jrtr);
1963 * For now, we don't support resjunk sort clauses on the output of a
1964 * setOperation tree --- you can only use the SQL92-spec options of
1965 * selecting an output column by name or number. Enforce by checking
1966 * that transformSortClause doesn't add any items to tlist.
1968 tllen = length(qry->targetList);
1970 qry->sortClause = transformSortClause(pstate,
1974 pstate->p_namespace = sv_namespace;
1975 pstate->p_rtable = sv_rtable;
1977 if (tllen != length(qry->targetList))
1978 elog(ERROR, "ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns");
1980 qry->limitOffset = limitOffset;
1981 qry->limitCount = limitCount;
1983 qry->rtable = pstate->p_rtable;
1984 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1986 qry->hasSubLinks = pstate->p_hasSubLinks;
1987 qry->hasAggs = pstate->p_hasAggs;
1988 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1989 parseCheckAggregates(pstate, qry);
1991 if (forUpdate != NIL)
1992 transformForUpdate(qry, forUpdate);
1998 * transformSetOperationTree
1999 * Recursively transform leaves and internal nodes of a set-op tree
2002 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2006 Assert(stmt && IsA(stmt, SelectStmt));
2009 * Validity-check both leaf and internal SELECTs for disallowed ops.
2012 elog(ERROR, "INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT");
2013 /* We don't support forUpdate with set ops at the moment. */
2014 if (stmt->forUpdate)
2015 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2018 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2019 * clauses attached, we need to treat it like a leaf node to generate
2020 * an independent sub-Query tree. Otherwise, it can be represented by
2021 * a SetOperationStmt node underneath the parent Query.
2023 if (stmt->op == SETOP_NONE)
2025 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2030 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2031 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2040 /* Process leaf SELECT */
2043 char selectName[32];
2048 * Transform SelectStmt into a Query.
2050 * Note: previously transformed sub-queries don't affect the parsing
2051 * of this sub-query, because they are not in the toplevel
2052 * pstate's namespace list.
2054 selectList = parse_sub_analyze((Node *) stmt, pstate);
2056 Assert(length(selectList) == 1);
2057 selectQuery = (Query *) lfirst(selectList);
2058 Assert(IsA(selectQuery, Query));
2061 * Check for bogus references to Vars on the current query level
2062 * (but upper-level references are okay).
2063 * Normally this can't happen because the namespace will be empty,
2064 * but it could happen if we are inside a rule.
2066 if (pstate->p_namespace)
2068 if (contain_vars_of_level((Node *) selectQuery, 1))
2069 elog(ERROR, "UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level");
2073 * Make the leaf query be a subquery in the top-level rangetable.
2075 snprintf(selectName, sizeof(selectName), "*SELECT* %d", length(pstate->p_rtable) + 1);
2076 rte = addRangeTableEntryForSubquery(pstate,
2078 makeAlias(selectName, NIL),
2082 * Return a RangeTblRef to replace the SelectStmt in the set-op
2085 rtr = makeNode(RangeTblRef);
2086 /* assume new rte is at end */
2087 rtr->rtindex = length(pstate->p_rtable);
2088 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2089 return (Node *) rtr;
2093 /* Process an internal node (set operation node) */
2094 SetOperationStmt *op = makeNode(SetOperationStmt);
2097 const char *context;
2099 context = (stmt->op == SETOP_UNION ? "UNION" :
2100 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2104 op->all = stmt->all;
2107 * Recursively transform the child nodes.
2109 op->larg = transformSetOperationTree(pstate, stmt->larg);
2110 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2113 * Verify that the two children have the same number of non-junk
2114 * columns, and determine the types of the merged output columns.
2116 lcoltypes = getSetColTypes(pstate, op->larg);
2117 rcoltypes = getSetColTypes(pstate, op->rarg);
2118 if (length(lcoltypes) != length(rcoltypes))
2119 elog(ERROR, "Each %s query must have the same number of columns",
2122 while (lcoltypes != NIL)
2124 Oid lcoltype = lfirsto(lcoltypes);
2125 Oid rcoltype = lfirsto(rcoltypes);
2128 rescoltype = select_common_type(makeListo2(lcoltype, rcoltype),
2130 op->colTypes = lappendo(op->colTypes, rescoltype);
2131 lcoltypes = lnext(lcoltypes);
2132 rcoltypes = lnext(rcoltypes);
2141 * Get output column types of an (already transformed) set-op node
2144 getSetColTypes(ParseState *pstate, Node *node)
2146 if (IsA(node, RangeTblRef))
2148 RangeTblRef *rtr = (RangeTblRef *) node;
2149 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2150 Query *selectQuery = rte->subquery;
2154 Assert(selectQuery != NULL);
2155 /* Get types of non-junk columns */
2156 foreach(tl, selectQuery->targetList)
2158 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2159 Resdom *resnode = tle->resdom;
2161 if (resnode->resjunk)
2163 result = lappendo(result, resnode->restype);
2167 else if (IsA(node, SetOperationStmt))
2169 SetOperationStmt *op = (SetOperationStmt *) node;
2171 /* Result already computed during transformation of node */
2172 Assert(op->colTypes != NIL);
2173 return op->colTypes;
2177 elog(ERROR, "getSetColTypes: unexpected node %d",
2178 (int) nodeTag(node));
2179 return NIL; /* keep compiler quiet */
2183 /* Attach column names from a ColumnDef list to a TargetEntry list */
2185 applyColumnNames(List *dst, List *src)
2187 if (length(src) > length(dst))
2188 elog(ERROR, "CREATE TABLE AS specifies too many column names");
2190 while (src != NIL && dst != NIL)
2192 TargetEntry *d = (TargetEntry *) lfirst(dst);
2193 ColumnDef *s = (ColumnDef *) lfirst(src);
2195 Assert(d->resdom && !d->resdom->resjunk);
2197 d->resdom->resname = pstrdup(s->colname);
2206 * transformUpdateStmt -
2207 * transforms an update statement
2210 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2212 Query *qry = makeNode(Query);
2214 List *origTargetList;
2217 qry->commandType = CMD_UPDATE;
2218 pstate->p_is_update = true;
2220 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2221 interpretInhOption(stmt->relation->inhOpt),
2225 * the FROM clause is non-standard SQL syntax. We used to be able to
2226 * do this with REPLACE in POSTQUEL so we keep the feature.
2228 transformFromClause(pstate, stmt->fromClause);
2230 qry->targetList = transformTargetList(pstate, stmt->targetList);
2232 qual = transformWhereClause(pstate, stmt->whereClause);
2234 qry->rtable = pstate->p_rtable;
2235 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2237 qry->hasSubLinks = pstate->p_hasSubLinks;
2238 qry->hasAggs = pstate->p_hasAggs;
2239 if (pstate->p_hasAggs)
2240 parseCheckAggregates(pstate, qry);
2243 * Now we are done with SELECT-like processing, and can get on with
2244 * transforming the target list to match the UPDATE target columns.
2247 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2248 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2249 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2251 /* Prepare non-junk columns for assignment to target table */
2252 origTargetList = stmt->targetList;
2253 foreach(tl, qry->targetList)
2255 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2256 Resdom *resnode = tle->resdom;
2257 ResTarget *origTarget;
2259 if (resnode->resjunk)
2262 * Resjunk nodes need no additional processing, but be sure
2263 * they have names and resnos that do not match any target
2264 * columns; else rewriter or planner might get confused.
2266 resnode->resname = "?resjunk?";
2267 resnode->resno = (AttrNumber) pstate->p_next_resno++;
2270 if (origTargetList == NIL)
2271 elog(ERROR, "UPDATE target count mismatch --- internal error");
2272 origTarget = (ResTarget *) lfirst(origTargetList);
2273 updateTargetListEntry(pstate, tle, origTarget->name,
2274 attnameAttNum(pstate->p_target_relation,
2275 origTarget->name, true),
2276 origTarget->indirection);
2277 origTargetList = lnext(origTargetList);
2279 if (origTargetList != NIL)
2280 elog(ERROR, "UPDATE target count mismatch --- internal error");
2286 * tranformAlterTableStmt -
2287 * transform an Alter Table Statement
2290 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2291 List **extras_before, List **extras_after)
2294 CreateStmtContext cxt;
2298 * The only subtypes that currently require parse transformation
2299 * handling are 'A'dd column and Add 'C'onstraint. These largely
2300 * re-use code from CREATE TABLE.
2302 * If we need to do any parse transformation, get exclusive lock on
2303 * the relation to make sure it won't change before we execute the
2306 switch (stmt->subtype)
2309 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2311 cxt.stmtType = "ALTER TABLE";
2312 cxt.relation = stmt->relation;
2313 cxt.inhRelations = NIL;
2314 cxt.relOid = RelationGetRelid(rel);
2315 cxt.hasoids = SearchSysCacheExists(ATTNUM,
2316 ObjectIdGetDatum(cxt.relOid),
2317 Int16GetDatum(ObjectIdAttributeNumber),
2320 cxt.ckconstraints = NIL;
2321 cxt.fkconstraints = NIL;
2322 cxt.ixconstraints = NIL;
2327 Assert(IsA(stmt->def, ColumnDef));
2328 transformColumnDefinition(pstate, &cxt,
2329 (ColumnDef *) stmt->def);
2331 transformIndexConstraints(pstate, &cxt);
2332 transformFKConstraints(pstate, &cxt, false);
2334 ((ColumnDef *) stmt->def)->constraints = cxt.ckconstraints;
2335 *extras_before = nconc(*extras_before, cxt.blist);
2336 *extras_after = nconc(cxt.alist, *extras_after);
2338 heap_close(rel, NoLock); /* close rel, keep lock */
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 if (IsA(stmt->def, Constraint))
2361 transformTableConstraint(pstate, &cxt,
2362 (Constraint *) stmt->def);
2363 else if (IsA(stmt->def, FkConstraint))
2364 cxt.fkconstraints = lappend(cxt.fkconstraints, stmt->def);
2366 elog(ERROR, "Unexpected node type in ALTER TABLE ADD CONSTRAINT");
2368 transformIndexConstraints(pstate, &cxt);
2369 transformFKConstraints(pstate, &cxt, true);
2371 Assert(cxt.columns == NIL);
2372 /* fkconstraints should be put into my own stmt in this case */
2373 stmt->def = (Node *) nconc(cxt.ckconstraints, cxt.fkconstraints);
2374 *extras_before = nconc(*extras_before, cxt.blist);
2375 *extras_after = nconc(cxt.alist, *extras_after);
2377 heap_close(rel, NoLock); /* close rel, keep lock */
2383 * Already-transformed ADD CONSTRAINT, so just make it look
2384 * like the standard case.
2386 stmt->subtype = 'C';
2393 qry = makeNode(Query);
2394 qry->commandType = CMD_UTILITY;
2395 qry->utilityStmt = (Node *) stmt;
2401 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2403 Query *result = makeNode(Query);
2404 List *extras_before = NIL,
2405 *extras_after = NIL;
2407 result->commandType = CMD_UTILITY;
2408 result->utilityStmt = (Node *) stmt;
2411 * Don't allow both SCROLL and NO SCROLL to be specified
2413 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2414 (stmt->options & CURSOR_OPT_NO_SCROLL))
2415 elog(ERROR, "Cannot specify both SCROLL and NO SCROLL");
2417 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2418 &extras_before, &extras_after);
2420 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2421 if (extras_before || extras_after)
2422 elog(ERROR, "transformDeclareCursorStmt: internal error");
2429 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2431 Query *result = makeNode(Query);
2432 List *argtype_oids = NIL; /* argtype OIDs in a list */
2433 Oid *argtoids = NULL; /* and as an array */
2437 result->commandType = CMD_UTILITY;
2438 result->utilityStmt = (Node *) stmt;
2440 /* Transform list of TypeNames to list (and array) of type OIDs */
2441 nargs = length(stmt->argtypes);
2448 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2450 foreach(l, stmt->argtypes)
2452 TypeName *tn = lfirst(l);
2453 Oid toid = typenameTypeId(tn);
2455 argtype_oids = lappendo(argtype_oids, toid);
2456 argtoids[i++] = toid;
2460 stmt->argtype_oids = argtype_oids;
2463 * Analyze the statement using these parameter types (any parameters
2464 * passed in from above us will not be visible to it).
2466 queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2469 * Shouldn't get any extra statements, since grammar only allows
2472 if (length(queries) != 1)
2473 elog(ERROR, "transformPrepareStmt: internal error");
2475 stmt->query = lfirst(queries);
2481 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2483 Query *result = makeNode(Query);
2486 result->commandType = CMD_UTILITY;
2487 result->utilityStmt = (Node *) stmt;
2489 paramtypes = FetchPreparedStatementParams(stmt->name);
2491 if (stmt->params || paramtypes)
2493 int nparams = length(stmt->params);
2494 int nexpected = length(paramtypes);
2498 if (nparams != nexpected)
2499 elog(ERROR, "Wrong number of parameters, expected %d but got %d",
2500 nexpected, nparams);
2502 foreach(l, stmt->params)
2504 Node *expr = lfirst(l);
2505 Oid expected_type_id,
2508 expr = transformExpr(pstate, expr);
2510 /* Cannot contain subselects or aggregates */
2511 if (contain_subplans(expr))
2512 elog(ERROR, "Cannot use subselects in EXECUTE parameters");
2513 if (contain_agg_clause(expr))
2514 elog(ERROR, "Cannot use aggregates in EXECUTE parameters");
2516 given_type_id = exprType(expr);
2517 expected_type_id = lfirsto(paramtypes);
2519 expr = coerce_to_target_type(pstate, expr, given_type_id,
2520 expected_type_id, -1,
2521 COERCION_ASSIGNMENT,
2522 COERCE_IMPLICIT_CAST);
2525 elog(ERROR, "Parameter $%d of type %s cannot be coerced into the expected type %s"
2526 "\n\tYou will need to rewrite or cast the expression",
2528 format_type_be(given_type_id),
2529 format_type_be(expected_type_id));
2533 paramtypes = lnext(paramtypes);
2541 /* exported so planner can check again after rewriting, query pullup, etc */
2543 CheckSelectForUpdate(Query *qry)
2545 if (qry->setOperations)
2546 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2547 if (qry->distinctClause != NIL)
2548 elog(ERROR, "SELECT FOR UPDATE is not allowed with DISTINCT clause");
2549 if (qry->groupClause != NIL)
2550 elog(ERROR, "SELECT FOR UPDATE is not allowed with GROUP BY clause");
2552 elog(ERROR, "SELECT FOR UPDATE is not allowed with AGGREGATE");
2556 transformForUpdate(Query *qry, List *forUpdate)
2558 List *rowMarks = qry->rowMarks;
2563 CheckSelectForUpdate(qry);
2565 if (lfirst(forUpdate) == NULL)
2567 /* all tables used in query */
2569 foreach(rt, qry->rtable)
2571 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2574 if (rte->rtekind == RTE_SUBQUERY)
2576 /* FOR UPDATE of subquery is propagated to subquery's rels */
2577 transformForUpdate(rte->subquery, makeList1(NULL));
2581 if (!intMember(i, rowMarks)) /* avoid duplicates */
2582 rowMarks = lappendi(rowMarks, i);
2583 rte->checkForWrite = true;
2589 /* just the named tables */
2590 foreach(l, forUpdate)
2592 char *relname = strVal(lfirst(l));
2595 foreach(rt, qry->rtable)
2597 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2600 if (strcmp(rte->eref->aliasname, relname) == 0)
2602 if (rte->rtekind == RTE_SUBQUERY)
2604 /* propagate to subquery */
2605 transformForUpdate(rte->subquery, makeList1(NULL));
2609 if (!intMember(i, rowMarks)) /* avoid duplicates */
2610 rowMarks = lappendi(rowMarks, i);
2611 rte->checkForWrite = true;
2617 elog(ERROR, "FOR UPDATE: relation \"%s\" not found in FROM clause",
2622 qry->rowMarks = rowMarks;
2627 * relationHasPrimaryKey -
2629 * See whether an existing relation has a primary key.
2632 relationHasPrimaryKey(Oid relationOid)
2634 bool result = false;
2639 rel = heap_open(relationOid, AccessShareLock);
2642 * Get the list of index OIDs for the table from the relcache, and
2643 * look up each one in the pg_index syscache until we find one marked
2644 * primary key (hopefully there isn't more than one such).
2646 indexoidlist = RelationGetIndexList(rel);
2648 foreach(indexoidscan, indexoidlist)
2650 Oid indexoid = lfirsto(indexoidscan);
2651 HeapTuple indexTuple;
2653 indexTuple = SearchSysCache(INDEXRELID,
2654 ObjectIdGetDatum(indexoid),
2656 if (!HeapTupleIsValid(indexTuple))
2657 elog(ERROR, "relationHasPrimaryKey: index %u not found",
2659 result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
2660 ReleaseSysCache(indexTuple);
2665 freeList(indexoidlist);
2667 heap_close(rel, AccessShareLock);
2673 * Preprocess a list of column constraint clauses
2674 * to attach constraint attributes to their primary constraint nodes
2675 * and detect inconsistent/misplaced constraint attributes.
2677 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2678 * constraints, but someday they ought to be supported for other constraints.
2681 transformConstraintAttrs(List *constraintList)
2683 Node *lastprimarynode = NULL;
2684 bool saw_deferrability = false;
2685 bool saw_initially = false;
2688 foreach(clist, constraintList)
2690 Node *node = lfirst(clist);
2692 if (!IsA(node, Constraint))
2694 lastprimarynode = node;
2695 /* reset flags for new primary node */
2696 saw_deferrability = false;
2697 saw_initially = false;
2701 Constraint *con = (Constraint *) node;
2703 switch (con->contype)
2705 case CONSTR_ATTR_DEFERRABLE:
2706 if (lastprimarynode == NULL ||
2707 !IsA(lastprimarynode, FkConstraint))
2708 elog(ERROR, "Misplaced DEFERRABLE clause");
2709 if (saw_deferrability)
2710 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2711 saw_deferrability = true;
2712 ((FkConstraint *) lastprimarynode)->deferrable = true;
2714 case CONSTR_ATTR_NOT_DEFERRABLE:
2715 if (lastprimarynode == NULL ||
2716 !IsA(lastprimarynode, FkConstraint))
2717 elog(ERROR, "Misplaced NOT DEFERRABLE clause");
2718 if (saw_deferrability)
2719 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2720 saw_deferrability = true;
2721 ((FkConstraint *) lastprimarynode)->deferrable = false;
2722 if (saw_initially &&
2723 ((FkConstraint *) lastprimarynode)->initdeferred)
2724 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2726 case CONSTR_ATTR_DEFERRED:
2727 if (lastprimarynode == NULL ||
2728 !IsA(lastprimarynode, FkConstraint))
2729 elog(ERROR, "Misplaced INITIALLY DEFERRED clause");
2731 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2732 saw_initially = true;
2733 ((FkConstraint *) lastprimarynode)->initdeferred = true;
2736 * If only INITIALLY DEFERRED appears, assume
2739 if (!saw_deferrability)
2740 ((FkConstraint *) lastprimarynode)->deferrable = true;
2741 else if (!((FkConstraint *) lastprimarynode)->deferrable)
2742 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2744 case CONSTR_ATTR_IMMEDIATE:
2745 if (lastprimarynode == NULL ||
2746 !IsA(lastprimarynode, FkConstraint))
2747 elog(ERROR, "Misplaced INITIALLY IMMEDIATE clause");
2749 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2750 saw_initially = true;
2751 ((FkConstraint *) lastprimarynode)->initdeferred = false;
2754 /* Otherwise it's not an attribute */
2755 lastprimarynode = node;
2756 /* reset flags for new primary node */
2757 saw_deferrability = false;
2758 saw_initially = false;
2765 /* Build a FromExpr node */
2767 makeFromExpr(List *fromlist, Node *quals)
2769 FromExpr *f = makeNode(FromExpr);
2771 f->fromlist = fromlist;
2777 * Special handling of type definition for a column
2780 transformColumnType(ParseState *pstate, ColumnDef *column)
2782 TypeName *typename = column->typename;
2783 Type ctype = typenameType(typename);
2786 * Is this the name of a complex type? If so, implement it as a set.
2788 * XXX this is a hangover from ancient Berkeley code that probably
2789 * doesn't work anymore anyway.
2791 if (typeTypeRelid(ctype) != InvalidOid)
2794 * (Eventually add in here that the set can only contain one
2797 typename->setof = true;
2800 ReleaseSysCache(ctype);
2804 * analyzeCreateSchemaStmt -
2805 * analyzes the "create schema" statement
2807 * Split the schema element list into individual commands and place
2808 * them in the result list in an order such that there are no
2809 * forward references (e.g. GRANT to a table created later in the list).
2811 * SQL92 also allows constraints to make forward references, so thumb through
2812 * the table columns and move forward references to a posterior alter-table
2815 * The result is a list of parse nodes that still need to be analyzed ---
2816 * but we can't analyze the later commands until we've executed the earlier
2817 * ones, because of possible inter-object references.
2819 * Note: Called from commands/command.c
2822 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
2824 CreateSchemaStmtContext cxt;
2828 cxt.stmtType = "CREATE SCHEMA";
2829 cxt.schemaname = stmt->schemaname;
2830 cxt.authid = stmt->authid;
2834 cxt.fwconstraints = NIL;
2840 * Run through each schema element in the schema element list.
2841 * Separate statements by type, and do preliminary analysis.
2843 foreach(elements, stmt->schemaElts)
2845 Node *element = lfirst(elements);
2847 switch (nodeTag(element))
2851 CreateStmt *elp = (CreateStmt *) element;
2853 if (elp->relation->schemaname == NULL)
2854 elp->relation->schemaname = cxt.schemaname;
2855 else if (strcmp(cxt.schemaname, elp->relation->schemaname) != 0)
2856 elog(ERROR, "New table specifies a schema (%s)"
2857 " different from the one being created (%s)",
2858 elp->relation->schemaname, cxt.schemaname);
2861 * XXX todo: deal with constraints
2864 cxt.tables = lappend(cxt.tables, element);
2870 ViewStmt *elp = (ViewStmt *) element;
2872 if (elp->view->schemaname == NULL)
2873 elp->view->schemaname = cxt.schemaname;
2874 else if (strcmp(cxt.schemaname, elp->view->schemaname) != 0)
2875 elog(ERROR, "New view specifies a schema (%s)"
2876 " different from the one being created (%s)",
2877 elp->view->schemaname, cxt.schemaname);
2880 * XXX todo: deal with references between views
2883 cxt.views = lappend(cxt.views, element);
2888 cxt.grants = lappend(cxt.grants, element);
2892 elog(ERROR, "parser: unsupported schema node (internal error)");
2897 result = nconc(result, cxt.tables);
2898 result = nconc(result, cxt.views);
2899 result = nconc(result, cxt.grants);
2905 * Traverse a fully-analyzed tree to verify that parameter symbols
2906 * match their types. We need this because some Params might still
2907 * be UNKNOWN, if there wasn't anything to force their coercion,
2908 * and yet other instances seen later might have gotten coerced.
2911 check_parameter_resolution_walker(Node *node,
2912 check_parameter_resolution_context *context)
2916 if (IsA(node, Param))
2918 Param *param = (Param *) node;
2920 if (param->paramkind == PARAM_NUM)
2922 int paramno = param->paramid;
2924 if (paramno <= 0 || /* shouldn't happen, but... */
2925 paramno > context->numParams)
2926 elog(ERROR, "Parameter '$%d' is out of range", paramno);
2928 if (param->paramtype != context->paramTypes[paramno-1])
2929 elog(ERROR, "Could not determine datatype of parameter $%d",
2934 if (IsA(node, Query))
2936 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2937 return query_tree_walker((Query *) node,
2938 check_parameter_resolution_walker,
2939 (void *) context, 0);
2941 return expression_tree_walker(node, check_parameter_resolution_walker,