1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.339 2006/07/11 16:35:31 momjian Exp $
11 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/heap.h"
18 #include "catalog/index.h"
19 #include "catalog/namespace.h"
20 #include "catalog/pg_index.h"
21 #include "catalog/pg_type.h"
22 #include "commands/defrem.h"
23 #include "commands/prepare.h"
24 #include "commands/tablecmds.h"
25 #include "miscadmin.h"
26 #include "nodes/makefuncs.h"
27 #include "optimizer/clauses.h"
28 #include "optimizer/var.h"
29 #include "parser/analyze.h"
30 #include "parser/gramparse.h"
31 #include "parser/parse_agg.h"
32 #include "parser/parse_clause.h"
33 #include "parser/parse_coerce.h"
34 #include "parser/parse_expr.h"
35 #include "parser/parse_expr.h"
36 #include "parser/parse_oper.h"
37 #include "parser/parse_relation.h"
38 #include "parser/parse_target.h"
39 #include "parser/parse_type.h"
40 #include "parser/parsetree.h"
41 #include "rewrite/rewriteManip.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/fmgroids.h"
45 #include "utils/guc.h"
46 #include "utils/lsyscache.h"
47 #include "utils/relcache.h"
48 #include "utils/syscache.h"
51 /* State shared by transformCreateSchemaStmt and its subroutines */
54 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
55 char *schemaname; /* name of schema */
56 char *authid; /* owner of schema */
57 List *sequences; /* CREATE SEQUENCE items */
58 List *tables; /* CREATE TABLE items */
59 List *views; /* CREATE VIEW items */
60 List *indexes; /* CREATE INDEX items */
61 List *triggers; /* CREATE TRIGGER items */
62 List *grants; /* GRANT items */
63 List *fwconstraints; /* Forward referencing FOREIGN KEY constraints */
64 List *alters; /* Generated ALTER items (from the above) */
65 List *ixconstraints; /* index-creating constraints */
66 List *blist; /* "before list" of things to do before
67 * creating the schema */
68 List *alist; /* "after list" of things to do after creating
70 } CreateSchemaStmtContext;
72 /* State shared by transformCreateStmt and its subroutines */
75 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
76 RangeVar *relation; /* relation to create */
77 List *inhRelations; /* relations to inherit from */
78 bool hasoids; /* does relation have an OID column? */
79 bool isalter; /* true if altering existing table */
80 List *columns; /* ColumnDef items */
81 List *ckconstraints; /* CHECK constraints */
82 List *fkconstraints; /* FOREIGN KEY constraints */
83 List *ixconstraints; /* index-creating constraints */
84 List *blist; /* "before list" of things to do before
85 * creating the table */
86 List *alist; /* "after list" of things to do after creating
88 IndexStmt *pkey; /* PRIMARY KEY index, if any */
95 } check_parameter_resolution_context;
98 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
99 static Query *transformStmt(ParseState *pstate, Node *stmt,
100 List **extras_before, List **extras_after);
101 static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
102 List **extras_before, List **extras_after);
103 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
104 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
105 List **extras_before, List **extras_after);
106 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
107 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
108 List **extras_before, List **extras_after);
109 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
110 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
111 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
112 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
113 static Query *transformDeclareCursorStmt(ParseState *pstate,
114 DeclareCursorStmt *stmt);
115 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
116 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
117 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
118 List **extras_before, List **extras_after);
119 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
120 List **extras_before, List **extras_after);
121 static void transformColumnDefinition(ParseState *pstate,
122 CreateStmtContext *cxt,
124 static void transformTableConstraint(ParseState *pstate,
125 CreateStmtContext *cxt,
126 Constraint *constraint);
127 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
128 InhRelation *inhrelation);
129 static void transformIndexConstraints(ParseState *pstate,
130 CreateStmtContext *cxt);
131 static void transformFKConstraints(ParseState *pstate,
132 CreateStmtContext *cxt,
134 bool isAddConstraint);
135 static void applyColumnNames(List *dst, List *src);
136 static List *getSetColTypes(ParseState *pstate, Node *node);
137 static void transformLockingClause(Query *qry, LockingClause *lc);
138 static void transformConstraintAttrs(List *constraintList);
139 static void transformColumnType(ParseState *pstate, ColumnDef *column);
140 static void release_pstate_resources(ParseState *pstate);
141 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
142 static bool check_parameter_resolution_walker(Node *node,
143 check_parameter_resolution_context *context);
148 * Analyze a raw parse tree and transform it to Query form.
150 * If available, pass the source text from which the raw parse tree was
151 * generated; it's OK to pass NULL if this is not available.
153 * Optionally, information about $n parameter types can be supplied.
154 * References to $n indexes not defined by paramTypes[] are disallowed.
156 * The result is a List of Query nodes (we need a list since some commands
157 * produce multiple Queries). Optimizable statements require considerable
158 * transformation, while many utility-type statements are simply hung off
159 * a dummy CMD_UTILITY Query node.
162 parse_analyze(Node *parseTree, const char *sourceText,
163 Oid *paramTypes, int numParams)
165 ParseState *pstate = make_parsestate(NULL);
168 pstate->p_sourcetext = sourceText;
169 pstate->p_paramtypes = paramTypes;
170 pstate->p_numparams = numParams;
171 pstate->p_variableparams = false;
173 result = do_parse_analyze(parseTree, pstate);
181 * parse_analyze_varparams
183 * This variant is used when it's okay to deduce information about $n
184 * symbol datatypes from context. The passed-in paramTypes[] array can
185 * be modified or enlarged (via repalloc).
188 parse_analyze_varparams(Node *parseTree, const char *sourceText,
189 Oid **paramTypes, int *numParams)
191 ParseState *pstate = make_parsestate(NULL);
194 pstate->p_sourcetext = sourceText;
195 pstate->p_paramtypes = *paramTypes;
196 pstate->p_numparams = *numParams;
197 pstate->p_variableparams = true;
199 result = do_parse_analyze(parseTree, pstate);
201 *paramTypes = pstate->p_paramtypes;
202 *numParams = pstate->p_numparams;
206 /* make sure all is well with parameter types */
209 check_parameter_resolution_context context;
211 context.paramTypes = *paramTypes;
212 context.numParams = *numParams;
213 check_parameter_resolution_walker((Node *) result, &context);
221 * Entry point for recursively analyzing a sub-statement.
224 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
226 ParseState *pstate = make_parsestate(parentParseState);
229 result = do_parse_analyze(parseTree, pstate);
238 * Workhorse code shared by the above variants of parse_analyze.
241 do_parse_analyze(Node *parseTree, ParseState *pstate)
245 /* Lists to return extra commands from transformation */
246 List *extras_before = NIL;
247 List *extras_after = NIL;
251 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
253 /* don't need to access result relation any more */
254 release_pstate_resources(pstate);
256 foreach(l, extras_before)
257 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
259 result = lappend(result, query);
261 foreach(l, extras_after)
262 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
265 * Make sure that only the original query is marked original. We have to
266 * do this explicitly since recursive calls of do_parse_analyze will have
267 * marked some of the added-on queries as "original". Also mark only the
268 * original query as allowed to set the command-result tag.
272 Query *q = lfirst(l);
276 q->querySource = QSRC_ORIGINAL;
281 q->querySource = QSRC_PARSER;
282 q->canSetTag = false;
290 release_pstate_resources(ParseState *pstate)
292 if (pstate->p_target_relation != NULL)
293 heap_close(pstate->p_target_relation, NoLock);
294 pstate->p_target_relation = NULL;
295 pstate->p_target_rangetblentry = NULL;
300 * transform a Parse tree into a Query tree.
303 transformStmt(ParseState *pstate, Node *parseTree,
304 List **extras_before, List **extras_after)
306 Query *result = NULL;
308 switch (nodeTag(parseTree))
311 * Non-optimizable statements
314 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
315 extras_before, extras_after);
319 result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
323 result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
324 extras_before, extras_after);
328 result = transformViewStmt(pstate, (ViewStmt *) parseTree,
329 extras_before, extras_after);
334 ExplainStmt *n = (ExplainStmt *) parseTree;
336 result = makeNode(Query);
337 result->commandType = CMD_UTILITY;
338 n->query = transformStmt(pstate, (Node *) n->query,
339 extras_before, extras_after);
340 result->utilityStmt = (Node *) parseTree;
344 case T_AlterTableStmt:
345 result = transformAlterTableStmt(pstate,
346 (AlterTableStmt *) parseTree,
347 extras_before, extras_after);
351 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
355 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
359 * Optimizable statements
362 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
363 extras_before, extras_after);
367 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
371 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
375 if (((SelectStmt *) parseTree)->op == SETOP_NONE)
376 result = transformSelectStmt(pstate,
377 (SelectStmt *) parseTree);
379 result = transformSetOperationStmt(pstate,
380 (SelectStmt *) parseTree);
383 case T_DeclareCursorStmt:
384 result = transformDeclareCursorStmt(pstate,
385 (DeclareCursorStmt *) parseTree);
391 * other statements don't require any transformation-- just return
392 * the original parsetree, yea!
394 result = makeNode(Query);
395 result->commandType = CMD_UTILITY;
396 result->utilityStmt = (Node *) parseTree;
400 /* Mark as original query until we learn differently */
401 result->querySource = QSRC_ORIGINAL;
402 result->canSetTag = true;
405 * Check that we did not produce too many resnos; at the very least we
406 * cannot allow more than 2^16, since that would exceed the range of a
407 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
409 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
411 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
412 errmsg("target lists can have at most %d entries",
413 MaxTupleAttributeNumber)));
419 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
420 List **extras_before, List **extras_after)
422 Query *result = makeNode(Query);
424 result->commandType = CMD_UTILITY;
425 result->utilityStmt = (Node *) stmt;
427 stmt->query = transformStmt(pstate, (Node *) stmt->query,
428 extras_before, extras_after);
431 * If a list of column names was given, run through and insert these into
432 * the actual query tree. - thomas 2000-03-08
434 * Outer loop is over targetlist to make it easier to skip junk targetlist
437 if (stmt->aliases != NIL)
439 ListCell *alist_item = list_head(stmt->aliases);
440 ListCell *targetList;
442 foreach(targetList, stmt->query->targetList)
444 TargetEntry *te = (TargetEntry *) lfirst(targetList);
446 Assert(IsA(te, TargetEntry));
447 /* junk columns don't get aliases */
450 te->resname = pstrdup(strVal(lfirst(alist_item)));
451 alist_item = lnext(alist_item);
452 if (alist_item == NULL)
453 break; /* done assigning aliases */
456 if (alist_item != NULL)
458 (errcode(ERRCODE_SYNTAX_ERROR),
459 errmsg("CREATE VIEW specifies more column "
460 "names than columns")));
467 * transformDeleteStmt -
468 * transforms a Delete Statement
471 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
473 Query *qry = makeNode(Query);
476 qry->commandType = CMD_DELETE;
478 /* set up range table with just the result rel */
479 qry->resultRelation = setTargetTable(pstate, stmt->relation,
480 interpretInhOption(stmt->relation->inhOpt),
484 qry->distinctClause = NIL;
487 * The USING clause is non-standard SQL syntax, and is equivalent in
488 * functionality to the FROM list that can be specified for UPDATE. The
489 * USING keyword is used rather than FROM because FROM is already a
490 * keyword in the DELETE syntax.
492 transformFromClause(pstate, stmt->usingClause);
494 /* fix where clause */
495 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
497 /* done building the range table and jointree */
498 qry->rtable = pstate->p_rtable;
499 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
501 qry->hasSubLinks = pstate->p_hasSubLinks;
502 qry->hasAggs = pstate->p_hasAggs;
503 if (pstate->p_hasAggs)
504 parseCheckAggregates(pstate, qry);
510 * transformInsertStmt -
511 * transform an Insert Statement
514 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
515 List **extras_before, List **extras_after)
517 Query *qry = makeNode(Query);
518 Query *selectQuery = NULL;
520 List *sub_relnamespace;
521 List *sub_varnamespace;
528 qry->commandType = CMD_INSERT;
529 pstate->p_is_insert = true;
532 * If a non-nil rangetable/namespace was passed in, and we are doing
533 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
534 * SELECT. This can only happen if we are inside a CREATE RULE, and in
535 * that case we want the rule's OLD and NEW rtable entries to appear as
536 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
537 * The SELECT's joinlist is not affected however. We must do this before
538 * adding the target table to the INSERT's rtable.
540 if (stmt->selectStmt)
542 sub_rtable = pstate->p_rtable;
543 pstate->p_rtable = NIL;
544 sub_relnamespace = pstate->p_relnamespace;
545 pstate->p_relnamespace = NIL;
546 sub_varnamespace = pstate->p_varnamespace;
547 pstate->p_varnamespace = NIL;
551 sub_rtable = NIL; /* not used, but keep compiler quiet */
552 sub_relnamespace = NIL;
553 sub_varnamespace = NIL;
557 * Must get write lock on INSERT target table before scanning SELECT, else
558 * we will grab the wrong kind of initial lock if the target table is also
559 * mentioned in the SELECT part. Note that the target table is not added
560 * to the joinlist or namespace.
562 qry->resultRelation = setTargetTable(pstate, stmt->relation,
563 false, false, ACL_INSERT);
566 * Is it INSERT ... SELECT or INSERT ... VALUES?
568 if (stmt->selectStmt)
571 * We make the sub-pstate a child of the outer pstate so that it can
572 * see any Param definitions supplied from above. Since the outer
573 * pstate's rtable and namespace are presently empty, there are no
574 * side-effects of exposing names the sub-SELECT shouldn't be able to
577 ParseState *sub_pstate = make_parsestate(pstate);
582 * Process the source SELECT.
584 * It is important that this be handled just like a standalone SELECT;
585 * otherwise the behavior of SELECT within INSERT might be different
586 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
587 * bugs of just that nature...)
589 sub_pstate->p_rtable = sub_rtable;
590 sub_pstate->p_relnamespace = sub_relnamespace;
591 sub_pstate->p_varnamespace = sub_varnamespace;
594 * Note: we are not expecting that extras_before and extras_after are
595 * going to be used by the transformation of the SELECT statement.
597 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
598 extras_before, extras_after);
600 release_pstate_resources(sub_pstate);
603 Assert(IsA(selectQuery, Query));
604 Assert(selectQuery->commandType == CMD_SELECT);
605 if (selectQuery->into)
607 (errcode(ERRCODE_SYNTAX_ERROR),
608 errmsg("INSERT ... SELECT may not specify INTO")));
611 * Make the source be a subquery in the INSERT's rangetable, and add
612 * it to the INSERT's joinlist.
614 rte = addRangeTableEntryForSubquery(pstate,
616 makeAlias("*SELECT*", NIL),
618 rtr = makeNode(RangeTblRef);
619 /* assume new rte is at end */
620 rtr->rtindex = list_length(pstate->p_rtable);
621 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
622 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
625 * Generate a targetlist for the INSERT that selects all the
626 * non-resjunk columns from the subquery. (We need this to be
627 * separate from the subquery's tlist because we may add columns,
628 * insert datatype coercions, etc.)
630 * HACK: unknown-type constants and params in the SELECT's targetlist
631 * are copied up as-is rather than being referenced as subquery
632 * outputs. This is to ensure that when we try to coerce them to
633 * the target column's datatype, the right things happen (see
634 * special cases in coerce_type). Otherwise, this fails:
635 * INSERT INTO foo SELECT 'bar', ... FROM baz
638 qry->targetList = NIL;
639 foreach(tl, selectQuery->targetList)
641 TargetEntry *tle = (TargetEntry *) lfirst(tl);
647 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
648 exprType((Node *) tle->expr) == UNKNOWNOID)
651 expr = (Expr *) makeVar(rtr->rtindex,
653 exprType((Node *) tle->expr),
654 exprTypmod((Node *) tle->expr),
656 tle = makeTargetEntry(expr,
657 (AttrNumber) pstate->p_next_resno++,
660 qry->targetList = lappend(qry->targetList, tle);
666 * For INSERT ... VALUES, transform the given list of values to form a
667 * targetlist for the INSERT.
669 qry->targetList = transformTargetList(pstate, stmt->targetList);
673 * Now we are done with SELECT-like processing, and can get on with
674 * transforming the target list to match the INSERT target columns.
677 /* Prepare to assign non-conflicting resnos to resjunk attributes */
678 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
679 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
681 /* Validate stmt->cols list, or build default list if no list given */
682 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
685 * Prepare columns for assignment to target table.
687 icols = list_head(icolumns);
688 attnos = list_head(attrnos);
689 foreach(tl, qry->targetList)
691 TargetEntry *tle = (TargetEntry *) lfirst(tl);
694 if (icols == NULL || attnos == NULL)
696 (errcode(ERRCODE_SYNTAX_ERROR),
697 errmsg("INSERT has more expressions than target columns")));
699 col = (ResTarget *) lfirst(icols);
700 Assert(IsA(col, ResTarget));
702 Assert(!tle->resjunk);
703 updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
704 col->indirection, col->location);
706 icols = lnext(icols);
707 attnos = lnext(attnos);
711 * Ensure that the targetlist has the same number of entries that were
712 * present in the columns list. Don't do the check unless an explicit
713 * columns list was given, though.
715 if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
717 (errcode(ERRCODE_SYNTAX_ERROR),
718 errmsg("INSERT has more target columns than expressions")));
720 /* done building the range table and jointree */
721 qry->rtable = pstate->p_rtable;
722 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
724 qry->hasSubLinks = pstate->p_hasSubLinks;
725 qry->hasAggs = pstate->p_hasAggs;
726 if (pstate->p_hasAggs)
727 parseCheckAggregates(pstate, qry);
733 * transformCreateStmt -
734 * transforms the "create table" statement
735 * SQL92 allows constraints to be scattered all over, so thumb through
736 * the columns and collect all constraints into one place.
737 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
738 * then expand those into multiple IndexStmt blocks.
739 * - thomas 1997-12-02
742 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
743 List **extras_before, List **extras_after)
745 CreateStmtContext cxt;
749 cxt.stmtType = "CREATE TABLE";
750 cxt.relation = stmt->relation;
751 cxt.inhRelations = stmt->inhRelations;
754 cxt.ckconstraints = NIL;
755 cxt.fkconstraints = NIL;
756 cxt.ixconstraints = NIL;
760 cxt.hasoids = interpretOidsOption(stmt->options);
763 * Run through each primary element in the table creation clause. Separate
764 * column defs from constraints, and do preliminary analysis.
766 foreach(elements, stmt->tableElts)
768 Node *element = lfirst(elements);
770 switch (nodeTag(element))
773 transformColumnDefinition(pstate, &cxt,
774 (ColumnDef *) element);
778 transformTableConstraint(pstate, &cxt,
779 (Constraint *) element);
783 /* No pre-transformation needed */
784 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
788 transformInhRelation(pstate, &cxt,
789 (InhRelation *) element);
793 elog(ERROR, "unrecognized node type: %d",
794 (int) nodeTag(element));
799 Assert(stmt->constraints == NIL);
802 * Postprocess constraints that give rise to index definitions.
804 transformIndexConstraints(pstate, &cxt);
807 * Postprocess foreign-key constraints.
809 transformFKConstraints(pstate, &cxt, true, false);
815 q->commandType = CMD_UTILITY;
816 q->utilityStmt = (Node *) stmt;
817 stmt->tableElts = cxt.columns;
818 stmt->constraints = cxt.ckconstraints;
819 *extras_before = list_concat(*extras_before, cxt.blist);
820 *extras_after = list_concat(cxt.alist, *extras_after);
826 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
831 Constraint *constraint;
834 cxt->columns = lappend(cxt->columns, column);
836 /* Check for SERIAL pseudo-types */
838 if (list_length(column->typename->names) == 1)
840 char *typname = strVal(linitial(column->typename->names));
842 if (strcmp(typname, "serial") == 0 ||
843 strcmp(typname, "serial4") == 0)
846 column->typename->names = NIL;
847 column->typename->typeid = INT4OID;
849 else if (strcmp(typname, "bigserial") == 0 ||
850 strcmp(typname, "serial8") == 0)
853 column->typename->names = NIL;
854 column->typename->typeid = INT8OID;
858 /* Do necessary work on the column type declaration */
859 transformColumnType(pstate, column);
861 /* Special actions for SERIAL pseudo-types */
869 FuncCall *funccallnode;
870 CreateSeqStmt *seqstmt;
873 * Determine namespace and name to use for the sequence.
875 * Although we use ChooseRelationName, it's not guaranteed that the
876 * selected sequence name won't conflict; given sufficiently long
877 * field names, two different serial columns in the same table could
878 * be assigned the same sequence name, and we'd not notice since we
879 * aren't creating the sequence quite yet. In practice this seems
880 * quite unlikely to be a problem, especially since few people would
881 * need two serial columns in one table.
883 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
884 snamespace = get_namespace_name(snamespaceid);
885 sname = ChooseRelationName(cxt->relation->relname,
891 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
892 cxt->stmtType, sname,
893 cxt->relation->relname, column->colname)));
896 * Build a CREATE SEQUENCE command to create the sequence object, and
897 * add it to the list of things to be done before this CREATE/ALTER
900 seqstmt = makeNode(CreateSeqStmt);
901 seqstmt->sequence = makeRangeVar(snamespace, sname);
902 seqstmt->options = NIL;
904 cxt->blist = lappend(cxt->blist, seqstmt);
907 * Mark the ColumnDef so that during execution, an appropriate
908 * dependency will be added from the sequence to the column.
910 column->support = makeRangeVar(snamespace, sname);
913 * Create appropriate constraints for SERIAL. We do this in full,
914 * rather than shortcutting, so that we will detect any conflicting
915 * constraints the user wrote (like a different DEFAULT).
917 * Create an expression tree representing the function call
918 * nextval('sequencename'). We cannot reduce the raw tree to cooked
919 * form until after the sequence is created, but there's no need to do
922 qstring = quote_qualified_identifier(snamespace, sname);
923 snamenode = makeNode(A_Const);
924 snamenode->val.type = T_String;
925 snamenode->val.val.str = qstring;
926 snamenode->typename = SystemTypeName("regclass");
927 funccallnode = makeNode(FuncCall);
928 funccallnode->funcname = SystemFuncName("nextval");
929 funccallnode->args = list_make1(snamenode);
930 funccallnode->agg_star = false;
931 funccallnode->agg_distinct = false;
932 funccallnode->location = -1;
934 constraint = makeNode(Constraint);
935 constraint->contype = CONSTR_DEFAULT;
936 constraint->raw_expr = (Node *) funccallnode;
937 constraint->cooked_expr = NULL;
938 constraint->keys = NIL;
939 column->constraints = lappend(column->constraints, constraint);
941 constraint = makeNode(Constraint);
942 constraint->contype = CONSTR_NOTNULL;
943 column->constraints = lappend(column->constraints, constraint);
946 /* Process column constraints, if any... */
947 transformConstraintAttrs(column->constraints);
949 saw_nullable = false;
951 foreach(clist, column->constraints)
953 constraint = lfirst(clist);
956 * If this column constraint is a FOREIGN KEY constraint, then we fill
957 * in the current attribute's name and throw it into the list of FK
958 * constraints to be processed later.
960 if (IsA(constraint, FkConstraint))
962 FkConstraint *fkconstraint = (FkConstraint *) constraint;
964 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
965 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
969 Assert(IsA(constraint, Constraint));
971 switch (constraint->contype)
974 if (saw_nullable && column->is_not_null)
976 (errcode(ERRCODE_SYNTAX_ERROR),
977 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
978 column->colname, cxt->relation->relname)));
979 column->is_not_null = FALSE;
984 if (saw_nullable && !column->is_not_null)
986 (errcode(ERRCODE_SYNTAX_ERROR),
987 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
988 column->colname, cxt->relation->relname)));
989 column->is_not_null = TRUE;
994 if (column->raw_default != NULL)
996 (errcode(ERRCODE_SYNTAX_ERROR),
997 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
998 column->colname, cxt->relation->relname)));
999 column->raw_default = constraint->raw_expr;
1000 Assert(constraint->cooked_expr == NULL);
1003 case CONSTR_PRIMARY:
1005 if (constraint->keys == NIL)
1006 constraint->keys = list_make1(makeString(column->colname));
1007 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1011 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1014 case CONSTR_ATTR_DEFERRABLE:
1015 case CONSTR_ATTR_NOT_DEFERRABLE:
1016 case CONSTR_ATTR_DEFERRED:
1017 case CONSTR_ATTR_IMMEDIATE:
1018 /* transformConstraintAttrs took care of these */
1022 elog(ERROR, "unrecognized constraint type: %d",
1023 constraint->contype);
1030 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1031 Constraint *constraint)
1033 switch (constraint->contype)
1035 case CONSTR_PRIMARY:
1037 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1041 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1045 case CONSTR_NOTNULL:
1046 case CONSTR_DEFAULT:
1047 case CONSTR_ATTR_DEFERRABLE:
1048 case CONSTR_ATTR_NOT_DEFERRABLE:
1049 case CONSTR_ATTR_DEFERRED:
1050 case CONSTR_ATTR_IMMEDIATE:
1051 elog(ERROR, "invalid context for constraint type %d",
1052 constraint->contype);
1056 elog(ERROR, "unrecognized constraint type: %d",
1057 constraint->contype);
1063 * transformInhRelation
1065 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1066 * column definitions which recreate the user defined column portions of <subtable>.
1069 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1070 InhRelation *inhRelation)
1072 AttrNumber parent_attno;
1075 TupleDesc tupleDesc;
1076 TupleConstr *constr;
1077 AclResult aclresult;
1079 bool including_defaults = false;
1080 bool including_constraints = false;
1081 bool including_indexes = false;
1084 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1086 if (relation->rd_rel->relkind != RELKIND_RELATION)
1088 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1089 errmsg("inherited relation \"%s\" is not a table",
1090 inhRelation->relation->relname)));
1093 * Check for SELECT privilages
1095 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1097 if (aclresult != ACLCHECK_OK)
1098 aclcheck_error(aclresult, ACL_KIND_CLASS,
1099 RelationGetRelationName(relation));
1101 tupleDesc = RelationGetDescr(relation);
1102 constr = tupleDesc->constr;
1104 foreach(elem, inhRelation->options)
1106 int option = lfirst_int(elem);
1109 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
1110 including_defaults = true;
1112 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
1113 including_defaults = false;
1115 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
1116 including_constraints = true;
1118 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
1119 including_constraints = false;
1121 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
1122 including_indexes = true;
1124 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
1125 including_indexes = false;
1128 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d", option);
1132 if (including_indexes)
1133 elog(ERROR, "TODO");
1136 * Insert the inherited attributes into the cxt for the new table
1139 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1142 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1143 char *attributeName = NameStr(attribute->attname);
1147 * Ignore dropped columns in the parent.
1149 if (attribute->attisdropped)
1153 * Create a new inherited column.
1155 * For constraints, ONLY the NOT NULL constraint is inherited by the
1156 * new column definition per SQL99.
1158 def = makeNode(ColumnDef);
1159 def->colname = pstrdup(attributeName);
1160 def->typename = makeTypeNameFromOid(attribute->atttypid,
1161 attribute->atttypmod);
1163 def->is_local = true;
1164 def->is_not_null = attribute->attnotnull;
1165 def->raw_default = NULL;
1166 def->cooked_default = NULL;
1167 def->constraints = NIL;
1168 def->support = NULL;
1171 * Add to column list
1173 cxt->columns = lappend(cxt->columns, def);
1176 * Copy default if any, and the default has been requested
1178 if (attribute->atthasdef && including_defaults)
1180 char *this_default = NULL;
1181 AttrDefault *attrdef;
1184 /* Find default in constraint structure */
1185 Assert(constr != NULL);
1186 attrdef = constr->defval;
1187 for (i = 0; i < constr->num_defval; i++)
1189 if (attrdef[i].adnum == parent_attno)
1191 this_default = attrdef[i].adbin;
1195 Assert(this_default != NULL);
1198 * If default expr could contain any vars, we'd need to fix 'em,
1199 * but it can't; so default is ready to apply to child.
1202 def->cooked_default = pstrdup(this_default);
1206 if (including_constraints && tupleDesc->constr) {
1208 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
1210 for(ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++) {
1211 char *ccname = tupleDesc->constr->check[ccnum].ccname;
1212 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1213 Node *ccbin_node = stringToNode(ccbin);
1214 Constraint *n = makeNode(Constraint);
1216 change_varattnos_of_a_node(ccbin_node, attmap);
1218 n->contype = CONSTR_CHECK;
1219 n->name = pstrdup(ccname);
1220 n->raw_expr = ccbin_node;
1221 n->cooked_expr = NULL;
1222 n->indexspace = NULL;
1223 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node*)n);
1228 * Close the parent rel, but keep our AccessShareLock on it until xact
1229 * commit. That will prevent someone else from deleting or ALTERing the
1230 * parent before the child is committed.
1232 heap_close(relation, NoLock);
1236 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1239 List *indexlist = NIL;
1244 * Run through the constraints that need to generate an index. For PRIMARY
1245 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1246 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1248 foreach(listptr, cxt->ixconstraints)
1250 Constraint *constraint = lfirst(listptr);
1254 Assert(IsA(constraint, Constraint));
1255 Assert((constraint->contype == CONSTR_PRIMARY)
1256 || (constraint->contype == CONSTR_UNIQUE));
1258 index = makeNode(IndexStmt);
1260 index->unique = true;
1261 index->primary = (constraint->contype == CONSTR_PRIMARY);
1264 if (cxt->pkey != NULL)
1266 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1267 errmsg("multiple primary keys for table \"%s\" are not allowed",
1268 cxt->relation->relname)));
1272 * In ALTER TABLE case, a primary index might already exist, but
1273 * DefineIndex will check for it.
1276 index->isconstraint = true;
1278 if (constraint->name != NULL)
1279 index->idxname = pstrdup(constraint->name);
1281 index->idxname = NULL; /* DefineIndex will choose name */
1283 index->relation = cxt->relation;
1284 index->accessMethod = DEFAULT_INDEX_TYPE;
1285 index->options = constraint->options;
1286 index->tableSpace = constraint->indexspace;
1287 index->indexParams = NIL;
1288 index->whereClause = NULL;
1291 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1292 * index, also make sure they are NOT NULL, if possible. (Although we
1293 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1294 * more efficient to get it right the first time.)
1296 foreach(keys, constraint->keys)
1298 char *key = strVal(lfirst(keys));
1300 ColumnDef *column = NULL;
1303 foreach(columns, cxt->columns)
1305 column = (ColumnDef *) lfirst(columns);
1306 Assert(IsA(column, ColumnDef));
1307 if (strcmp(column->colname, key) == 0)
1315 /* found column in the new table; force it to be NOT NULL */
1316 if (constraint->contype == CONSTR_PRIMARY)
1317 column->is_not_null = TRUE;
1319 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1322 * column will be a system column in the new table, so accept
1323 * it. System columns can't ever be null, so no need to worry
1324 * about PRIMARY/NOT NULL constraint.
1328 else if (cxt->inhRelations)
1330 /* try inherited tables */
1333 foreach(inher, cxt->inhRelations)
1335 RangeVar *inh = (RangeVar *) lfirst(inher);
1339 Assert(IsA(inh, RangeVar));
1340 rel = heap_openrv(inh, AccessShareLock);
1341 if (rel->rd_rel->relkind != RELKIND_RELATION)
1343 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1344 errmsg("inherited relation \"%s\" is not a table",
1346 for (count = 0; count < rel->rd_att->natts; count++)
1348 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1349 char *inhname = NameStr(inhattr->attname);
1351 if (inhattr->attisdropped)
1353 if (strcmp(key, inhname) == 0)
1358 * We currently have no easy way to force an
1359 * inherited column to be NOT NULL at creation, if
1360 * its parent wasn't so already. We leave it to
1361 * DefineIndex to fix things up in this case.
1366 heap_close(rel, NoLock);
1373 * In the ALTER TABLE case, don't complain about index keys not
1374 * created in the command; they may well exist already.
1375 * DefineIndex will complain about them if not, and will also take
1376 * care of marking them NOT NULL.
1378 if (!found && !cxt->isalter)
1380 (errcode(ERRCODE_UNDEFINED_COLUMN),
1381 errmsg("column \"%s\" named in key does not exist",
1384 /* Check for PRIMARY KEY(foo, foo) */
1385 foreach(columns, index->indexParams)
1387 iparam = (IndexElem *) lfirst(columns);
1388 if (iparam->name && strcmp(key, iparam->name) == 0)
1392 (errcode(ERRCODE_DUPLICATE_COLUMN),
1393 errmsg("column \"%s\" appears twice in primary key constraint",
1397 (errcode(ERRCODE_DUPLICATE_COLUMN),
1398 errmsg("column \"%s\" appears twice in unique constraint",
1403 /* OK, add it to the index definition */
1404 iparam = makeNode(IndexElem);
1405 iparam->name = pstrdup(key);
1406 iparam->expr = NULL;
1407 iparam->opclass = NIL;
1408 index->indexParams = lappend(index->indexParams, iparam);
1411 indexlist = lappend(indexlist, index);
1415 * Scan the index list and remove any redundant index specifications. This
1416 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1417 * strict reading of SQL92 would suggest raising an error instead, but
1418 * that strikes me as too anal-retentive. - tgl 2001-02-14
1420 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1421 * pre-existing indexes, too.
1424 if (cxt->pkey != NULL)
1426 /* Make sure we keep the PKEY index in preference to others... */
1427 cxt->alist = list_make1(cxt->pkey);
1430 foreach(l, indexlist)
1437 /* if it's pkey, it's already in cxt->alist */
1438 if (index == cxt->pkey)
1441 foreach(k, cxt->alist)
1443 IndexStmt *priorindex = lfirst(k);
1445 if (equal(index->indexParams, priorindex->indexParams))
1448 * If the prior index is as yet unnamed, and this one is
1449 * named, then transfer the name to the prior index. This
1450 * ensures that if we have named and unnamed constraints,
1451 * we'll use (at least one of) the names for the index.
1453 if (priorindex->idxname == NULL)
1454 priorindex->idxname = index->idxname;
1461 cxt->alist = lappend(cxt->alist, index);
1466 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1467 bool skipValidation, bool isAddConstraint)
1471 if (cxt->fkconstraints == NIL)
1475 * If CREATE TABLE or adding a column with NULL default, we can safely
1476 * skip validation of the constraint.
1480 foreach(fkclist, cxt->fkconstraints)
1482 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1484 fkconstraint->skip_validation = true;
1489 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1490 * CONSTRAINT command to execute after the basic command is complete. (If
1491 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1492 * its own subcommand list.)
1494 * Note: the ADD CONSTRAINT command must also execute after any index
1495 * creation commands. Thus, this should run after
1496 * transformIndexConstraints, so that the CREATE INDEX commands are
1497 * already in cxt->alist.
1499 if (!isAddConstraint)
1501 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1503 alterstmt->relation = cxt->relation;
1504 alterstmt->cmds = NIL;
1505 alterstmt->relkind = OBJECT_TABLE;
1507 foreach(fkclist, cxt->fkconstraints)
1509 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1510 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1512 altercmd->subtype = AT_ProcessedConstraint;
1513 altercmd->name = NULL;
1514 altercmd->def = (Node *) fkconstraint;
1515 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1518 cxt->alist = lappend(cxt->alist, alterstmt);
1523 * transformIndexStmt -
1524 * transforms the qualification of the index statement
1527 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1530 RangeTblEntry *rte = NULL;
1533 qry = makeNode(Query);
1534 qry->commandType = CMD_UTILITY;
1536 /* take care of the where clause */
1537 if (stmt->whereClause)
1540 * Put the parent table into the rtable so that the WHERE clause can
1541 * refer to its fields without qualification. Note that this only
1542 * works if the parent table already exists --- so we can't easily
1543 * support predicates on indexes created implicitly by CREATE TABLE.
1544 * Fortunately, that's not necessary.
1546 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1548 /* no to join list, yes to namespaces */
1549 addRTEtoQuery(pstate, rte, false, true, true);
1551 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1555 /* take care of any index expressions */
1556 foreach(l, stmt->indexParams)
1558 IndexElem *ielem = (IndexElem *) lfirst(l);
1562 /* Set up rtable as for predicate, see notes above */
1565 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1567 /* no to join list, yes to namespaces */
1568 addRTEtoQuery(pstate, rte, false, true, true);
1570 ielem->expr = transformExpr(pstate, ielem->expr);
1573 * We check only that the result type is legitimate; this is for
1574 * consistency with what transformWhereClause() checks for the
1575 * predicate. DefineIndex() will make more checks.
1577 if (expression_returns_set(ielem->expr))
1579 (errcode(ERRCODE_DATATYPE_MISMATCH),
1580 errmsg("index expression may not return a set")));
1584 qry->hasSubLinks = pstate->p_hasSubLinks;
1585 stmt->rangetable = pstate->p_rtable;
1587 qry->utilityStmt = (Node *) stmt;
1593 * transformRuleStmt -
1594 * transform a Create Rule Statement. The actions is a list of parse
1595 * trees which is transformed into a list of query trees.
1598 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1599 List **extras_before, List **extras_after)
1603 RangeTblEntry *oldrte;
1604 RangeTblEntry *newrte;
1606 qry = makeNode(Query);
1607 qry->commandType = CMD_UTILITY;
1608 qry->utilityStmt = (Node *) stmt;
1611 * To avoid deadlock, make sure the first thing we do is grab
1612 * AccessExclusiveLock on the target relation. This will be needed by
1613 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1616 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1619 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1620 * Set up their RTEs in the main pstate for use in parsing the rule
1623 Assert(pstate->p_rtable == NIL);
1624 oldrte = addRangeTableEntryForRelation(pstate, rel,
1625 makeAlias("*OLD*", NIL),
1627 newrte = addRangeTableEntryForRelation(pstate, rel,
1628 makeAlias("*NEW*", NIL),
1630 /* Must override addRangeTableEntry's default access-check flags */
1631 oldrte->requiredPerms = 0;
1632 newrte->requiredPerms = 0;
1635 * They must be in the namespace too for lookup purposes, but only add the
1636 * one(s) that are relevant for the current kind of rule. In an UPDATE
1637 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1638 * there's no need to be so picky for INSERT & DELETE. We do not add them
1641 switch (stmt->event)
1644 addRTEtoQuery(pstate, oldrte, false, true, true);
1647 addRTEtoQuery(pstate, oldrte, false, true, true);
1648 addRTEtoQuery(pstate, newrte, false, true, true);
1651 addRTEtoQuery(pstate, newrte, false, true, true);
1654 addRTEtoQuery(pstate, oldrte, false, true, true);
1657 elog(ERROR, "unrecognized event type: %d",
1662 /* take care of the where clause */
1663 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1666 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1668 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1669 errmsg("rule WHERE condition may not contain references to other relations")));
1671 /* aggregates not allowed (but subselects are okay) */
1672 if (pstate->p_hasAggs)
1674 (errcode(ERRCODE_GROUPING_ERROR),
1675 errmsg("cannot use aggregate function in rule WHERE condition")));
1677 /* save info about sublinks in where clause */
1678 qry->hasSubLinks = pstate->p_hasSubLinks;
1681 * 'instead nothing' rules with a qualification need a query rangetable so
1682 * the rewrite handler can add the negated rule qualification to the
1683 * original query. We create a query with the new command type CMD_NOTHING
1684 * here that is treated specially by the rewrite system.
1686 if (stmt->actions == NIL)
1688 Query *nothing_qry = makeNode(Query);
1690 nothing_qry->commandType = CMD_NOTHING;
1691 nothing_qry->rtable = pstate->p_rtable;
1692 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1694 stmt->actions = list_make1(nothing_qry);
1699 List *newactions = NIL;
1702 * transform each statement, like parse_sub_analyze()
1704 foreach(l, stmt->actions)
1706 Node *action = (Node *) lfirst(l);
1707 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1714 * Set up OLD/NEW in the rtable for this statement. The entries
1715 * are added only to relnamespace, not varnamespace, because we
1716 * don't want them to be referred to by unqualified field names
1717 * nor "*" in the rule actions. We decide later whether to put
1718 * them in the joinlist.
1720 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1721 makeAlias("*OLD*", NIL),
1723 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1724 makeAlias("*NEW*", NIL),
1726 oldrte->requiredPerms = 0;
1727 newrte->requiredPerms = 0;
1728 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1729 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1731 /* Transform the rule action statement */
1732 top_subqry = transformStmt(sub_pstate, action,
1733 extras_before, extras_after);
1736 * We cannot support utility-statement actions (eg NOTIFY) with
1737 * nonempty rule WHERE conditions, because there's no way to make
1738 * the utility action execute conditionally.
1740 if (top_subqry->commandType == CMD_UTILITY &&
1741 stmt->whereClause != NULL)
1743 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1744 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1747 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1748 * into the SELECT, and that's what we need to look at. (Ugly
1749 * kluge ... try to fix this when we redesign querytrees.)
1751 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1754 * If the sub_qry is a setop, we cannot attach any qualifications
1755 * to it, because the planner won't notice them. This could
1756 * perhaps be relaxed someday, but for now, we may as well reject
1757 * such a rule immediately.
1759 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1761 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1762 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1765 * Validate action's use of OLD/NEW, qual too
1768 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1769 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1771 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1772 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1774 switch (stmt->event)
1779 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1780 errmsg("ON SELECT rule may not use OLD")));
1783 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1784 errmsg("ON SELECT rule may not use NEW")));
1792 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1793 errmsg("ON INSERT rule may not use OLD")));
1798 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1799 errmsg("ON DELETE rule may not use NEW")));
1802 elog(ERROR, "unrecognized event type: %d",
1808 * For efficiency's sake, add OLD to the rule action's jointree
1809 * only if it was actually referenced in the statement or qual.
1811 * For INSERT, NEW is not really a relation (only a reference to
1812 * the to-be-inserted tuple) and should never be added to the
1815 * For UPDATE, we treat NEW as being another kind of reference to
1816 * OLD, because it represents references to *transformed* tuples
1817 * of the existing relation. It would be wrong to enter NEW
1818 * separately in the jointree, since that would cause a double
1819 * join of the updated relation. It's also wrong to fail to make
1820 * a jointree entry if only NEW and not OLD is mentioned.
1822 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1825 * If sub_qry is a setop, manipulating its jointree will do no
1826 * good at all, because the jointree is dummy. (This should be
1827 * a can't-happen case because of prior tests.)
1829 if (sub_qry->setOperations != NULL)
1831 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1832 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1833 /* hack so we can use addRTEtoQuery() */
1834 sub_pstate->p_rtable = sub_qry->rtable;
1835 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1836 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1837 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1840 newactions = lappend(newactions, top_subqry);
1842 release_pstate_resources(sub_pstate);
1846 stmt->actions = newactions;
1849 /* Close relation, but keep the exclusive lock */
1850 heap_close(rel, NoLock);
1857 * transformSelectStmt -
1858 * transforms a Select Statement
1860 * Note: this is also used for DECLARE CURSOR statements.
1863 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1865 Query *qry = makeNode(Query);
1869 qry->commandType = CMD_SELECT;
1871 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1872 pstate->p_locking_clause = stmt->lockingClause;
1874 /* process the FROM clause */
1875 transformFromClause(pstate, stmt->fromClause);
1877 /* transform targetlist */
1878 qry->targetList = transformTargetList(pstate, stmt->targetList);
1880 /* handle any SELECT INTO/CREATE TABLE AS spec */
1881 qry->into = stmt->into;
1882 if (stmt->intoColNames)
1883 applyColumnNames(qry->targetList, stmt->intoColNames);
1885 qry->intoOptions = copyObject(stmt->intoOptions);
1886 qry->intoOnCommit = stmt->intoOnCommit;
1887 qry->intoTableSpaceName = stmt->intoTableSpaceName;
1889 /* mark column origins */
1890 markTargetListOrigins(pstate, qry->targetList);
1892 /* transform WHERE */
1893 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1896 * Initial processing of HAVING clause is just like WHERE clause.
1898 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1902 * Transform sorting/grouping stuff. Do ORDER BY first because both
1903 * transformGroupClause and transformDistinctClause need the results.
1905 qry->sortClause = transformSortClause(pstate,
1908 true /* fix unknowns */ );
1910 qry->groupClause = transformGroupClause(pstate,
1915 qry->distinctClause = transformDistinctClause(pstate,
1916 stmt->distinctClause,
1920 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1922 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1925 qry->rtable = pstate->p_rtable;
1926 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1928 qry->hasSubLinks = pstate->p_hasSubLinks;
1929 qry->hasAggs = pstate->p_hasAggs;
1930 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1931 parseCheckAggregates(pstate, qry);
1933 foreach(l, stmt->lockingClause)
1935 transformLockingClause(qry, (LockingClause *) lfirst(l));
1942 * transformSetOperationsStmt -
1943 * transforms a set-operations tree
1945 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1946 * structure to it. We must transform each leaf SELECT and build up a top-
1947 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1948 * The tree of set operations is converted into the setOperations field of
1949 * the top-level Query.
1952 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1954 Query *qry = makeNode(Query);
1955 SelectStmt *leftmostSelect;
1957 Query *leftmostQuery;
1958 SetOperationStmt *sostmt;
1964 List *lockingClause;
1966 ListCell *left_tlist,
1974 RangeTblEntry *jrte;
1977 qry->commandType = CMD_SELECT;
1980 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1981 * and from the top-level node.
1983 leftmostSelect = stmt->larg;
1984 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1985 leftmostSelect = leftmostSelect->larg;
1986 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1987 leftmostSelect->larg == NULL);
1988 into = leftmostSelect->into;
1989 intoColNames = leftmostSelect->intoColNames;
1991 /* clear them to prevent complaints in transformSetOperationTree() */
1992 leftmostSelect->into = NULL;
1993 leftmostSelect->intoColNames = NIL;
1996 * These are not one-time, exactly, but we want to process them here and
1997 * not let transformSetOperationTree() see them --- else it'll just
1998 * recurse right back here!
2000 sortClause = stmt->sortClause;
2001 limitOffset = stmt->limitOffset;
2002 limitCount = stmt->limitCount;
2003 lockingClause = stmt->lockingClause;
2005 stmt->sortClause = NIL;
2006 stmt->limitOffset = NULL;
2007 stmt->limitCount = NULL;
2008 stmt->lockingClause = NIL;
2010 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2013 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2014 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2017 * Recursively transform the components of the tree.
2019 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
2020 Assert(sostmt && IsA(sostmt, SetOperationStmt));
2021 qry->setOperations = (Node *) sostmt;
2024 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2026 node = sostmt->larg;
2027 while (node && IsA(node, SetOperationStmt))
2028 node = ((SetOperationStmt *) node)->larg;
2029 Assert(node && IsA(node, RangeTblRef));
2030 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2031 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2032 Assert(leftmostQuery != NULL);
2035 * Generate dummy targetlist for outer query using column names of
2036 * leftmost select and common datatypes of topmost set operation. Also
2037 * make lists of the dummy vars and their names for use in parsing ORDER
2040 * Note: we use leftmostRTI as the varno of the dummy variables. It
2041 * shouldn't matter too much which RT index they have, as long as they
2042 * have one that corresponds to a real RT entry; else funny things may
2043 * happen when the tree is mashed by rule rewriting.
2045 qry->targetList = NIL;
2048 left_tlist = list_head(leftmostQuery->targetList);
2050 foreach(dtlist, sostmt->colTypes)
2052 Oid colType = lfirst_oid(dtlist);
2053 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2058 Assert(!lefttle->resjunk);
2059 colName = pstrdup(lefttle->resname);
2060 expr = (Expr *) makeVar(leftmostRTI,
2065 tle = makeTargetEntry(expr,
2066 (AttrNumber) pstate->p_next_resno++,
2069 qry->targetList = lappend(qry->targetList, tle);
2070 targetvars = lappend(targetvars, expr);
2071 targetnames = lappend(targetnames, makeString(colName));
2072 left_tlist = lnext(left_tlist);
2076 * Handle SELECT INTO/CREATE TABLE AS.
2078 * Any column names from CREATE TABLE AS need to be attached to both the
2079 * top level and the leftmost subquery. We do not do this earlier because
2080 * we do *not* want the targetnames list to be affected.
2085 applyColumnNames(qry->targetList, intoColNames);
2086 applyColumnNames(leftmostQuery->targetList, intoColNames);
2090 * As a first step towards supporting sort clauses that are expressions
2091 * using the output columns, generate a varnamespace entry that makes the
2092 * output columns visible. A Join RTE node is handy for this, since we
2093 * can easily control the Vars generated upon matches.
2095 * Note: we don't yet do anything useful with such cases, but at least
2096 * "ORDER BY upper(foo)" will draw the right error message rather than
2099 jrte = addRangeTableEntryForJoin(NULL,
2106 sv_rtable = pstate->p_rtable;
2107 pstate->p_rtable = list_make1(jrte);
2109 sv_relnamespace = pstate->p_relnamespace;
2110 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2112 sv_varnamespace = pstate->p_varnamespace;
2113 pstate->p_varnamespace = list_make1(jrte);
2116 * For now, we don't support resjunk sort clauses on the output of a
2117 * setOperation tree --- you can only use the SQL92-spec options of
2118 * selecting an output column by name or number. Enforce by checking that
2119 * transformSortClause doesn't add any items to tlist.
2121 tllen = list_length(qry->targetList);
2123 qry->sortClause = transformSortClause(pstate,
2126 false /* no unknowns expected */ );
2128 pstate->p_rtable = sv_rtable;
2129 pstate->p_relnamespace = sv_relnamespace;
2130 pstate->p_varnamespace = sv_varnamespace;
2132 if (tllen != list_length(qry->targetList))
2134 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2135 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2137 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2139 qry->limitCount = transformLimitClause(pstate, limitCount,
2142 qry->rtable = pstate->p_rtable;
2143 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2145 qry->hasSubLinks = pstate->p_hasSubLinks;
2146 qry->hasAggs = pstate->p_hasAggs;
2147 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2148 parseCheckAggregates(pstate, qry);
2150 foreach(l, lockingClause)
2152 transformLockingClause(qry, (LockingClause *) lfirst(l));
2159 * transformSetOperationTree
2160 * Recursively transform leaves and internal nodes of a set-op tree
2163 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2167 Assert(stmt && IsA(stmt, SelectStmt));
2170 * Validity-check both leaf and internal SELECTs for disallowed ops.
2174 (errcode(ERRCODE_SYNTAX_ERROR),
2175 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2176 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2177 if (stmt->lockingClause)
2179 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2180 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2183 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2184 * clauses attached, we need to treat it like a leaf node to generate an
2185 * independent sub-Query tree. Otherwise, it can be represented by a
2186 * SetOperationStmt node underneath the parent Query.
2188 if (stmt->op == SETOP_NONE)
2190 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2195 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2196 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2197 stmt->lockingClause)
2205 /* Process leaf SELECT */
2208 char selectName[32];
2213 * Transform SelectStmt into a Query.
2215 * Note: previously transformed sub-queries don't affect the parsing
2216 * of this sub-query, because they are not in the toplevel pstate's
2219 selectList = parse_sub_analyze((Node *) stmt, pstate);
2221 Assert(list_length(selectList) == 1);
2222 selectQuery = (Query *) linitial(selectList);
2223 Assert(IsA(selectQuery, Query));
2226 * Check for bogus references to Vars on the current query level (but
2227 * upper-level references are okay). Normally this can't happen
2228 * because the namespace will be empty, but it could happen if we are
2231 if (pstate->p_relnamespace || pstate->p_varnamespace)
2233 if (contain_vars_of_level((Node *) selectQuery, 1))
2235 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2236 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2240 * Make the leaf query be a subquery in the top-level rangetable.
2242 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2243 list_length(pstate->p_rtable) + 1);
2244 rte = addRangeTableEntryForSubquery(pstate,
2246 makeAlias(selectName, NIL),
2250 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2252 rtr = makeNode(RangeTblRef);
2253 /* assume new rte is at end */
2254 rtr->rtindex = list_length(pstate->p_rtable);
2255 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2256 return (Node *) rtr;
2260 /* Process an internal node (set operation node) */
2261 SetOperationStmt *op = makeNode(SetOperationStmt);
2266 const char *context;
2268 context = (stmt->op == SETOP_UNION ? "UNION" :
2269 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2273 op->all = stmt->all;
2276 * Recursively transform the child nodes.
2278 op->larg = transformSetOperationTree(pstate, stmt->larg);
2279 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2282 * Verify that the two children have the same number of non-junk
2283 * columns, and determine the types of the merged output columns.
2285 lcoltypes = getSetColTypes(pstate, op->larg);
2286 rcoltypes = getSetColTypes(pstate, op->rarg);
2287 if (list_length(lcoltypes) != list_length(rcoltypes))
2289 (errcode(ERRCODE_SYNTAX_ERROR),
2290 errmsg("each %s query must have the same number of columns",
2294 forboth(l, lcoltypes, r, rcoltypes)
2296 Oid lcoltype = lfirst_oid(l);
2297 Oid rcoltype = lfirst_oid(r);
2300 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2302 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2311 * Get output column types of an (already transformed) set-op node
2314 getSetColTypes(ParseState *pstate, Node *node)
2316 if (IsA(node, RangeTblRef))
2318 RangeTblRef *rtr = (RangeTblRef *) node;
2319 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2320 Query *selectQuery = rte->subquery;
2324 Assert(selectQuery != NULL);
2325 /* Get types of non-junk columns */
2326 foreach(tl, selectQuery->targetList)
2328 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2332 result = lappend_oid(result, exprType((Node *) tle->expr));
2336 else if (IsA(node, SetOperationStmt))
2338 SetOperationStmt *op = (SetOperationStmt *) node;
2340 /* Result already computed during transformation of node */
2341 Assert(op->colTypes != NIL);
2342 return op->colTypes;
2346 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2347 return NIL; /* keep compiler quiet */
2351 /* Attach column names from a ColumnDef list to a TargetEntry list */
2353 applyColumnNames(List *dst, List *src)
2358 if (list_length(src) > list_length(dst))
2360 (errcode(ERRCODE_SYNTAX_ERROR),
2361 errmsg("CREATE TABLE AS specifies too many column names")));
2363 forboth(dst_item, dst, src_item, src)
2365 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2366 ColumnDef *s = (ColumnDef *) lfirst(src_item);
2368 Assert(!d->resjunk);
2369 d->resname = pstrdup(s->colname);
2375 * transformUpdateStmt -
2376 * transforms an update statement
2379 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2381 Query *qry = makeNode(Query);
2383 ListCell *origTargetList;
2386 qry->commandType = CMD_UPDATE;
2387 pstate->p_is_update = true;
2389 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2390 interpretInhOption(stmt->relation->inhOpt),
2395 * the FROM clause is non-standard SQL syntax. We used to be able to do
2396 * this with REPLACE in POSTQUEL so we keep the feature.
2398 transformFromClause(pstate, stmt->fromClause);
2400 qry->targetList = transformTargetList(pstate, stmt->targetList);
2402 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2404 qry->rtable = pstate->p_rtable;
2405 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2407 qry->hasSubLinks = pstate->p_hasSubLinks;
2410 * Top-level aggregates are simply disallowed in UPDATE, per spec.
2411 * (From an implementation point of view, this is forced because the
2412 * implicit ctid reference would otherwise be an ungrouped variable.)
2414 if (pstate->p_hasAggs)
2416 (errcode(ERRCODE_GROUPING_ERROR),
2417 errmsg("cannot use aggregate function in UPDATE")));
2420 * Now we are done with SELECT-like processing, and can get on with
2421 * transforming the target list to match the UPDATE target columns.
2424 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2425 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2426 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2428 /* Prepare non-junk columns for assignment to target table */
2429 origTargetList = list_head(stmt->targetList);
2431 foreach(tl, qry->targetList)
2433 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2434 ResTarget *origTarget;
2440 * Resjunk nodes need no additional processing, but be sure they
2441 * have resnos that do not match any target columns; else rewriter
2442 * or planner might get confused. They don't need a resname
2445 tle->resno = (AttrNumber) pstate->p_next_resno++;
2446 tle->resname = NULL;
2449 if (origTargetList == NULL)
2450 elog(ERROR, "UPDATE target count mismatch --- internal error");
2451 origTarget = (ResTarget *) lfirst(origTargetList);
2452 Assert(IsA(origTarget, ResTarget));
2454 attrno = attnameAttNum(pstate->p_target_relation,
2455 origTarget->name, true);
2456 if (attrno == InvalidAttrNumber)
2458 (errcode(ERRCODE_UNDEFINED_COLUMN),
2459 errmsg("column \"%s\" of relation \"%s\" does not exist",
2461 RelationGetRelationName(pstate->p_target_relation)),
2462 parser_errposition(pstate, origTarget->location)));
2464 updateTargetListEntry(pstate, tle, origTarget->name,
2466 origTarget->indirection,
2467 origTarget->location);
2469 origTargetList = lnext(origTargetList);
2471 if (origTargetList != NULL)
2472 elog(ERROR, "UPDATE target count mismatch --- internal error");
2478 * tranformAlterTableStmt -
2479 * transform an Alter Table Statement
2482 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2483 List **extras_before, List **extras_after)
2485 CreateStmtContext cxt;
2489 List *newcmds = NIL;
2490 bool skipValidation = true;
2491 AlterTableCmd *newcmd;
2493 cxt.stmtType = "ALTER TABLE";
2494 cxt.relation = stmt->relation;
2495 cxt.inhRelations = NIL;
2497 cxt.hasoids = false; /* need not be right */
2499 cxt.ckconstraints = NIL;
2500 cxt.fkconstraints = NIL;
2501 cxt.ixconstraints = NIL;
2507 * The only subtypes that currently require parse transformation handling
2508 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2511 foreach(lcmd, stmt->cmds)
2513 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2515 switch (cmd->subtype)
2519 ColumnDef *def = (ColumnDef *) cmd->def;
2521 Assert(IsA(cmd->def, ColumnDef));
2522 transformColumnDefinition(pstate, &cxt,
2523 (ColumnDef *) cmd->def);
2526 * If the column has a non-null default, we can't skip
2527 * validation of foreign keys.
2529 if (((ColumnDef *) cmd->def)->raw_default != NULL)
2530 skipValidation = false;
2532 newcmds = lappend(newcmds, cmd);
2535 * Convert an ADD COLUMN ... NOT NULL constraint to a
2538 if (def->is_not_null)
2540 /* Remove NOT NULL from AddColumn */
2541 def->is_not_null = false;
2543 /* Add as a separate AlterTableCmd */
2544 newcmd = makeNode(AlterTableCmd);
2545 newcmd->subtype = AT_SetNotNull;
2546 newcmd->name = pstrdup(def->colname);
2547 newcmds = lappend(newcmds, newcmd);
2551 * All constraints are processed in other ways. Remove the
2554 def->constraints = NIL;
2558 case AT_AddConstraint:
2561 * The original AddConstraint cmd node doesn't go to newcmds
2564 if (IsA(cmd->def, Constraint))
2565 transformTableConstraint(pstate, &cxt,
2566 (Constraint *) cmd->def);
2567 else if (IsA(cmd->def, FkConstraint))
2569 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
2570 skipValidation = false;
2573 elog(ERROR, "unrecognized node type: %d",
2574 (int) nodeTag(cmd->def));
2577 case AT_ProcessedConstraint:
2580 * Already-transformed ADD CONSTRAINT, so just make it look
2581 * like the standard case.
2583 cmd->subtype = AT_AddConstraint;
2584 newcmds = lappend(newcmds, cmd);
2588 newcmds = lappend(newcmds, cmd);
2593 /* Postprocess index and FK constraints */
2594 transformIndexConstraints(pstate, &cxt);
2596 transformFKConstraints(pstate, &cxt, skipValidation, true);
2599 * Push any index-creation commands into the ALTER, so that they can be
2600 * scheduled nicely by tablecmds.c.
2602 foreach(l, cxt.alist)
2604 Node *idxstmt = (Node *) lfirst(l);
2606 Assert(IsA(idxstmt, IndexStmt));
2607 newcmd = makeNode(AlterTableCmd);
2608 newcmd->subtype = AT_AddIndex;
2609 newcmd->def = idxstmt;
2610 newcmds = lappend(newcmds, newcmd);
2614 /* Append any CHECK or FK constraints to the commands list */
2615 foreach(l, cxt.ckconstraints)
2617 newcmd = makeNode(AlterTableCmd);
2618 newcmd->subtype = AT_AddConstraint;
2619 newcmd->def = (Node *) lfirst(l);
2620 newcmds = lappend(newcmds, newcmd);
2622 foreach(l, cxt.fkconstraints)
2624 newcmd = makeNode(AlterTableCmd);
2625 newcmd->subtype = AT_AddConstraint;
2626 newcmd->def = (Node *) lfirst(l);
2627 newcmds = lappend(newcmds, newcmd);
2630 /* Update statement's commands list */
2631 stmt->cmds = newcmds;
2633 qry = makeNode(Query);
2634 qry->commandType = CMD_UTILITY;
2635 qry->utilityStmt = (Node *) stmt;
2637 *extras_before = list_concat(*extras_before, cxt.blist);
2638 *extras_after = list_concat(cxt.alist, *extras_after);
2644 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2646 Query *result = makeNode(Query);
2647 List *extras_before = NIL,
2648 *extras_after = NIL;
2650 result->commandType = CMD_UTILITY;
2651 result->utilityStmt = (Node *) stmt;
2654 * Don't allow both SCROLL and NO SCROLL to be specified
2656 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2657 (stmt->options & CURSOR_OPT_NO_SCROLL))
2659 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2660 errmsg("cannot specify both SCROLL and NO SCROLL")));
2662 stmt->query = (Node *) transformStmt(pstate, stmt->query,
2663 &extras_before, &extras_after);
2665 /* Shouldn't get any extras, since grammar only allows SelectStmt */
2666 if (extras_before || extras_after)
2667 elog(ERROR, "unexpected extra stuff in cursor statement");
2674 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2676 Query *result = makeNode(Query);
2677 List *argtype_oids; /* argtype OIDs in a list */
2678 Oid *argtoids = NULL; /* and as an array */
2683 result->commandType = CMD_UTILITY;
2684 result->utilityStmt = (Node *) stmt;
2686 /* Transform list of TypeNames to list (and array) of type OIDs */
2687 nargs = list_length(stmt->argtypes);
2693 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2696 foreach(l, stmt->argtypes)
2698 TypeName *tn = lfirst(l);
2699 Oid toid = typenameTypeId(pstate, tn);
2701 argtoids[i++] = toid;
2706 * Analyze the statement using these parameter types (any
2707 * parameters passed in from above us will not be visible to it),
2708 * allowing information about unknown parameters to be deduced
2711 queries = parse_analyze_varparams((Node *) stmt->query,
2712 pstate->p_sourcetext,
2716 * Shouldn't get any extra statements, since grammar only allows
2719 if (list_length(queries) != 1)
2720 elog(ERROR, "unexpected extra stuff in prepared statement");
2723 * Check that all parameter types were determined, and convert the
2724 * array of OIDs into a list for storage.
2727 for (i = 0; i < nargs; i++)
2729 Oid argtype = argtoids[i];
2731 if (argtype == InvalidOid || argtype == UNKNOWNOID)
2733 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
2734 errmsg("could not determine data type of parameter $%d",
2737 argtype_oids = lappend_oid(argtype_oids, argtype);
2740 stmt->argtype_oids = argtype_oids;
2741 stmt->query = linitial(queries);
2746 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2748 Query *result = makeNode(Query);
2751 result->commandType = CMD_UTILITY;
2752 result->utilityStmt = (Node *) stmt;
2754 paramtypes = FetchPreparedStatementParams(stmt->name);
2756 if (stmt->params || paramtypes)
2758 int nparams = list_length(stmt->params);
2759 int nexpected = list_length(paramtypes);
2764 if (nparams != nexpected)
2766 (errcode(ERRCODE_SYNTAX_ERROR),
2767 errmsg("wrong number of parameters for prepared statement \"%s\"",
2769 errdetail("Expected %d parameters but got %d.",
2770 nexpected, nparams)));
2772 forboth(l, stmt->params, l2, paramtypes)
2774 Node *expr = lfirst(l);
2775 Oid expected_type_id = lfirst_oid(l2);
2778 expr = transformExpr(pstate, expr);
2780 /* Cannot contain subselects or aggregates */
2781 if (pstate->p_hasSubLinks)
2783 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2784 errmsg("cannot use subquery in EXECUTE parameter")));
2785 if (pstate->p_hasAggs)
2787 (errcode(ERRCODE_GROUPING_ERROR),
2788 errmsg("cannot use aggregate function in EXECUTE parameter")));
2790 given_type_id = exprType(expr);
2792 expr = coerce_to_target_type(pstate, expr, given_type_id,
2793 expected_type_id, -1,
2794 COERCION_ASSIGNMENT,
2795 COERCE_IMPLICIT_CAST);
2799 (errcode(ERRCODE_DATATYPE_MISMATCH),
2800 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
2802 format_type_be(given_type_id),
2803 format_type_be(expected_type_id)),
2804 errhint("You will need to rewrite or cast the expression.")));
2814 /* exported so planner can check again after rewriting, query pullup, etc */
2816 CheckSelectLocking(Query *qry)
2818 if (qry->setOperations)
2820 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2821 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2822 if (qry->distinctClause != NIL)
2824 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2825 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
2826 if (qry->groupClause != NIL)
2828 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2829 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
2830 if (qry->havingQual != NULL)
2832 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2833 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
2836 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2837 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
2841 * Transform a FOR UPDATE/SHARE clause
2843 * This basically involves replacing names by integer relids.
2845 * NB: if you need to change this, see also markQueryForLocking()
2846 * in rewriteHandler.c.
2849 transformLockingClause(Query *qry, LockingClause *lc)
2851 List *lockedRels = lc->lockedRels;
2855 LockingClause *allrels;
2857 CheckSelectLocking(qry);
2859 /* make a clause we can pass down to subqueries to select all rels */
2860 allrels = makeNode(LockingClause);
2861 allrels->lockedRels = NIL; /* indicates all rels */
2862 allrels->forUpdate = lc->forUpdate;
2863 allrels->noWait = lc->noWait;
2865 if (lockedRels == NIL)
2867 /* all regular tables used in query */
2869 foreach(rt, qry->rtable)
2871 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2874 switch (rte->rtekind)
2877 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
2878 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2883 * FOR UPDATE/SHARE of subquery is propagated to all of
2886 transformLockingClause(rte->subquery, allrels);
2889 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2896 /* just the named tables */
2897 foreach(l, lockedRels)
2899 char *relname = strVal(lfirst(l));
2902 foreach(rt, qry->rtable)
2904 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2907 if (strcmp(rte->eref->aliasname, relname) == 0)
2909 switch (rte->rtekind)
2912 applyLockingClause(qry, i,
2913 lc->forUpdate, lc->noWait);
2914 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2919 * FOR UPDATE/SHARE of subquery is propagated to
2920 * all of subquery's rels
2922 transformLockingClause(rte->subquery, allrels);
2926 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2927 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
2931 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2932 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
2936 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2937 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
2940 elog(ERROR, "unrecognized RTE type: %d",
2941 (int) rte->rtekind);
2944 break; /* out of foreach loop */
2949 (errcode(ERRCODE_UNDEFINED_TABLE),
2950 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2957 * Record locking info for a single rangetable item
2960 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
2964 /* Check for pre-existing entry for same rtindex */
2965 if ((rc = get_rowmark(qry, rtindex)) != NULL)
2968 * If the same RTE is specified both FOR UPDATE and FOR SHARE,
2969 * treat it as FOR UPDATE. (Reasonable, since you can't take
2970 * both a shared and exclusive lock at the same time; it'll
2971 * end up being exclusive anyway.)
2973 * We also consider that NOWAIT wins if it's specified both ways.
2974 * This is a bit more debatable but raising an error doesn't
2975 * seem helpful. (Consider for instance SELECT FOR UPDATE NOWAIT
2976 * from a view that internally contains a plain FOR UPDATE spec.)
2978 rc->forUpdate |= forUpdate;
2979 rc->noWait |= noWait;
2983 /* Make a new RowMarkClause */
2984 rc = makeNode(RowMarkClause);
2986 rc->forUpdate = forUpdate;
2987 rc->noWait = noWait;
2988 qry->rowMarks = lappend(qry->rowMarks, rc);
2993 * Preprocess a list of column constraint clauses
2994 * to attach constraint attributes to their primary constraint nodes
2995 * and detect inconsistent/misplaced constraint attributes.
2997 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2998 * constraints, but someday they ought to be supported for other constraints.
3001 transformConstraintAttrs(List *constraintList)
3003 Node *lastprimarynode = NULL;
3004 bool saw_deferrability = false;
3005 bool saw_initially = false;
3008 foreach(clist, constraintList)
3010 Node *node = lfirst(clist);
3012 if (!IsA(node, Constraint))
3014 lastprimarynode = node;
3015 /* reset flags for new primary node */
3016 saw_deferrability = false;
3017 saw_initially = false;
3021 Constraint *con = (Constraint *) node;
3023 switch (con->contype)
3025 case CONSTR_ATTR_DEFERRABLE:
3026 if (lastprimarynode == NULL ||
3027 !IsA(lastprimarynode, FkConstraint))
3029 (errcode(ERRCODE_SYNTAX_ERROR),
3030 errmsg("misplaced DEFERRABLE clause")));
3031 if (saw_deferrability)
3033 (errcode(ERRCODE_SYNTAX_ERROR),
3034 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3035 saw_deferrability = true;
3036 ((FkConstraint *) lastprimarynode)->deferrable = true;
3038 case CONSTR_ATTR_NOT_DEFERRABLE:
3039 if (lastprimarynode == NULL ||
3040 !IsA(lastprimarynode, FkConstraint))
3042 (errcode(ERRCODE_SYNTAX_ERROR),
3043 errmsg("misplaced NOT DEFERRABLE clause")));
3044 if (saw_deferrability)
3046 (errcode(ERRCODE_SYNTAX_ERROR),
3047 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3048 saw_deferrability = true;
3049 ((FkConstraint *) lastprimarynode)->deferrable = false;
3050 if (saw_initially &&
3051 ((FkConstraint *) lastprimarynode)->initdeferred)
3053 (errcode(ERRCODE_SYNTAX_ERROR),
3054 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3056 case CONSTR_ATTR_DEFERRED:
3057 if (lastprimarynode == NULL ||
3058 !IsA(lastprimarynode, FkConstraint))
3060 (errcode(ERRCODE_SYNTAX_ERROR),
3061 errmsg("misplaced INITIALLY DEFERRED clause")));
3064 (errcode(ERRCODE_SYNTAX_ERROR),
3065 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3066 saw_initially = true;
3067 ((FkConstraint *) lastprimarynode)->initdeferred = true;
3070 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3072 if (!saw_deferrability)
3073 ((FkConstraint *) lastprimarynode)->deferrable = true;
3074 else if (!((FkConstraint *) lastprimarynode)->deferrable)
3076 (errcode(ERRCODE_SYNTAX_ERROR),
3077 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3079 case CONSTR_ATTR_IMMEDIATE:
3080 if (lastprimarynode == NULL ||
3081 !IsA(lastprimarynode, FkConstraint))
3083 (errcode(ERRCODE_SYNTAX_ERROR),
3084 errmsg("misplaced INITIALLY IMMEDIATE clause")));
3087 (errcode(ERRCODE_SYNTAX_ERROR),
3088 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3089 saw_initially = true;
3090 ((FkConstraint *) lastprimarynode)->initdeferred = false;
3093 /* Otherwise it's not an attribute */
3094 lastprimarynode = node;
3095 /* reset flags for new primary node */
3096 saw_deferrability = false;
3097 saw_initially = false;
3104 /* Build a FromExpr node */
3106 makeFromExpr(List *fromlist, Node *quals)
3108 FromExpr *f = makeNode(FromExpr);
3110 f->fromlist = fromlist;
3116 * Special handling of type definition for a column
3119 transformColumnType(ParseState *pstate, ColumnDef *column)
3122 * All we really need to do here is verify that the type is valid.
3124 Type ctype = typenameType(pstate, column->typename);
3126 ReleaseSysCache(ctype);
3130 setSchemaName(char *context_schema, char **stmt_schema_name)
3132 if (*stmt_schema_name == NULL)
3133 *stmt_schema_name = context_schema;
3134 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3136 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3137 errmsg("CREATE specifies a schema (%s) "
3138 "different from the one being created (%s)",
3139 *stmt_schema_name, context_schema)));
3143 * analyzeCreateSchemaStmt -
3144 * analyzes the "create schema" statement
3146 * Split the schema element list into individual commands and place
3147 * them in the result list in an order such that there are no forward
3148 * references (e.g. GRANT to a table created later in the list). Note
3149 * that the logic we use for determining forward references is
3150 * presently quite incomplete.
3152 * SQL92 also allows constraints to make forward references, so thumb through
3153 * the table columns and move forward references to a posterior alter-table
3156 * The result is a list of parse nodes that still need to be analyzed ---
3157 * but we can't analyze the later commands until we've executed the earlier
3158 * ones, because of possible inter-object references.
3160 * Note: Called from commands/schemacmds.c
3163 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3165 CreateSchemaStmtContext cxt;
3169 cxt.stmtType = "CREATE SCHEMA";
3170 cxt.schemaname = stmt->schemaname;
3171 cxt.authid = stmt->authid;
3172 cxt.sequences = NIL;
3178 cxt.fwconstraints = NIL;
3184 * Run through each schema element in the schema element list. Separate
3185 * statements by type, and do preliminary analysis.
3187 foreach(elements, stmt->schemaElts)
3189 Node *element = lfirst(elements);
3191 switch (nodeTag(element))
3193 case T_CreateSeqStmt:
3195 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3197 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3198 cxt.sequences = lappend(cxt.sequences, element);
3204 CreateStmt *elp = (CreateStmt *) element;
3206 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3209 * XXX todo: deal with constraints
3211 cxt.tables = lappend(cxt.tables, element);
3217 ViewStmt *elp = (ViewStmt *) element;
3219 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3222 * XXX todo: deal with references between views
3224 cxt.views = lappend(cxt.views, element);
3230 IndexStmt *elp = (IndexStmt *) element;
3232 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3233 cxt.indexes = lappend(cxt.indexes, element);
3237 case T_CreateTrigStmt:
3239 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3241 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3242 cxt.triggers = lappend(cxt.triggers, element);
3247 cxt.grants = lappend(cxt.grants, element);
3251 elog(ERROR, "unrecognized node type: %d",
3252 (int) nodeTag(element));
3257 result = list_concat(result, cxt.sequences);
3258 result = list_concat(result, cxt.tables);
3259 result = list_concat(result, cxt.views);
3260 result = list_concat(result, cxt.indexes);
3261 result = list_concat(result, cxt.triggers);
3262 result = list_concat(result, cxt.grants);
3268 * Traverse a fully-analyzed tree to verify that parameter symbols
3269 * match their types. We need this because some Params might still
3270 * be UNKNOWN, if there wasn't anything to force their coercion,
3271 * and yet other instances seen later might have gotten coerced.
3274 check_parameter_resolution_walker(Node *node,
3275 check_parameter_resolution_context *context)
3279 if (IsA(node, Param))
3281 Param *param = (Param *) node;
3283 if (param->paramkind == PARAM_EXTERN)
3285 int paramno = param->paramid;
3287 if (paramno <= 0 || /* shouldn't happen, but... */
3288 paramno > context->numParams)
3290 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3291 errmsg("there is no parameter $%d", paramno)));
3293 if (param->paramtype != context->paramTypes[paramno - 1])
3295 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3296 errmsg("could not determine data type of parameter $%d",
3301 if (IsA(node, Query))
3303 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3304 return query_tree_walker((Query *) node,
3305 check_parameter_resolution_walker,
3306 (void *) context, 0);
3308 return expression_tree_walker(node, check_parameter_resolution_walker,