1 /*-------------------------------------------------------------------------
4 * transform the parse tree into a query tree
6 * Portions Copyright (c) 1996-2007, 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.354 2007/01/05 22:19:33 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_type.h"
21 #include "commands/defrem.h"
22 #include "commands/prepare.h"
23 #include "commands/tablecmds.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/var.h"
28 #include "parser/analyze.h"
29 #include "parser/gramparse.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_expr.h"
35 #include "parser/parse_relation.h"
36 #include "parser/parse_target.h"
37 #include "parser/parse_type.h"
38 #include "parser/parsetree.h"
39 #include "rewrite/rewriteManip.h"
40 #include "utils/acl.h"
41 #include "utils/builtins.h"
42 #include "utils/lsyscache.h"
43 #include "utils/syscache.h"
46 /* State shared by transformCreateSchemaStmt and its subroutines */
49 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
50 char *schemaname; /* name of schema */
51 char *authid; /* owner of schema */
52 List *sequences; /* CREATE SEQUENCE items */
53 List *tables; /* CREATE TABLE items */
54 List *views; /* CREATE VIEW items */
55 List *indexes; /* CREATE INDEX items */
56 List *triggers; /* CREATE TRIGGER items */
57 List *grants; /* GRANT items */
58 List *fwconstraints; /* Forward referencing FOREIGN KEY constraints */
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 creating
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 bool isalter; /* true if altering existing table */
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 creating
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 *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
97 List **extras_before, List **extras_after);
98 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
99 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
100 List **extras_before, List **extras_after);
101 static List *transformInsertRow(ParseState *pstate, List *exprlist,
102 List *stmtcols, List *icolumns, List *attrnos);
103 static List *transformReturningList(ParseState *pstate, List *returningList);
104 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
105 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
106 List **extras_before, List **extras_after);
107 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
108 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
109 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
110 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
111 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
112 static Query *transformDeclareCursorStmt(ParseState *pstate,
113 DeclareCursorStmt *stmt);
114 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
115 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
116 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
117 List **extras_before, List **extras_after);
118 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
119 List **extras_before, List **extras_after);
120 static void transformColumnDefinition(ParseState *pstate,
121 CreateStmtContext *cxt,
123 static void transformTableConstraint(ParseState *pstate,
124 CreateStmtContext *cxt,
125 Constraint *constraint);
126 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
127 InhRelation *inhrelation);
128 static void transformIndexConstraints(ParseState *pstate,
129 CreateStmtContext *cxt);
130 static void transformFKConstraints(ParseState *pstate,
131 CreateStmtContext *cxt,
133 bool isAddConstraint);
134 static void applyColumnNames(List *dst, List *src);
135 static void getSetColTypes(ParseState *pstate, Node *node,
136 List **colTypes, List **colTypmods);
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;
346 CopyStmt *n = (CopyStmt *) parseTree;
348 result = makeNode(Query);
349 result->commandType = CMD_UTILITY;
351 n->query = transformStmt(pstate, (Node *) n->query,
352 extras_before, extras_after);
353 result->utilityStmt = (Node *) parseTree;
357 case T_AlterTableStmt:
358 result = transformAlterTableStmt(pstate,
359 (AlterTableStmt *) parseTree,
360 extras_before, extras_after);
364 result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
368 result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
372 * Optimizable statements
375 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
376 extras_before, extras_after);
380 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
384 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
389 SelectStmt *n = (SelectStmt *) parseTree;
392 result = transformValuesClause(pstate, n);
393 else if (n->op == SETOP_NONE)
394 result = transformSelectStmt(pstate, n);
396 result = transformSetOperationStmt(pstate, n);
400 case T_DeclareCursorStmt:
401 result = transformDeclareCursorStmt(pstate,
402 (DeclareCursorStmt *) parseTree);
408 * other statements don't require any transformation-- just return
409 * the original parsetree, yea!
411 result = makeNode(Query);
412 result->commandType = CMD_UTILITY;
413 result->utilityStmt = (Node *) parseTree;
417 /* Mark as original query until we learn differently */
418 result->querySource = QSRC_ORIGINAL;
419 result->canSetTag = true;
422 * Check that we did not produce too many resnos; at the very least we
423 * cannot allow more than 2^16, since that would exceed the range of a
424 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
426 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
428 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
429 errmsg("target lists can have at most %d entries",
430 MaxTupleAttributeNumber)));
436 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
437 List **extras_before, List **extras_after)
439 Query *result = makeNode(Query);
441 result->commandType = CMD_UTILITY;
442 result->utilityStmt = (Node *) stmt;
444 stmt->query = transformStmt(pstate, (Node *) stmt->query,
445 extras_before, extras_after);
448 * If a list of column names was given, run through and insert these into
449 * the actual query tree. - thomas 2000-03-08
451 * Outer loop is over targetlist to make it easier to skip junk targetlist
454 if (stmt->aliases != NIL)
456 ListCell *alist_item = list_head(stmt->aliases);
457 ListCell *targetList;
459 foreach(targetList, stmt->query->targetList)
461 TargetEntry *te = (TargetEntry *) lfirst(targetList);
463 Assert(IsA(te, TargetEntry));
464 /* junk columns don't get aliases */
467 te->resname = pstrdup(strVal(lfirst(alist_item)));
468 alist_item = lnext(alist_item);
469 if (alist_item == NULL)
470 break; /* done assigning aliases */
473 if (alist_item != NULL)
475 (errcode(ERRCODE_SYNTAX_ERROR),
476 errmsg("CREATE VIEW specifies more column "
477 "names than columns")));
484 * transformDeleteStmt -
485 * transforms a Delete Statement
488 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
490 Query *qry = makeNode(Query);
493 qry->commandType = CMD_DELETE;
495 /* set up range table with just the result rel */
496 qry->resultRelation = setTargetTable(pstate, stmt->relation,
497 interpretInhOption(stmt->relation->inhOpt),
501 qry->distinctClause = NIL;
504 * The USING clause is non-standard SQL syntax, and is equivalent in
505 * functionality to the FROM list that can be specified for UPDATE. The
506 * USING keyword is used rather than FROM because FROM is already a
507 * keyword in the DELETE syntax.
509 transformFromClause(pstate, stmt->usingClause);
511 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
513 qry->returningList = transformReturningList(pstate, stmt->returningList);
515 /* done building the range table and jointree */
516 qry->rtable = pstate->p_rtable;
517 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
519 qry->hasSubLinks = pstate->p_hasSubLinks;
520 qry->hasAggs = pstate->p_hasAggs;
521 if (pstate->p_hasAggs)
522 parseCheckAggregates(pstate, qry);
528 * transformInsertStmt -
529 * transform an Insert Statement
532 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
533 List **extras_before, List **extras_after)
535 Query *qry = makeNode(Query);
536 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
537 List *exprList = NIL;
538 bool isGeneralSelect;
540 List *sub_relnamespace;
541 List *sub_varnamespace;
550 qry->commandType = CMD_INSERT;
551 pstate->p_is_insert = true;
554 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
555 * VALUES list, or general SELECT input. We special-case VALUES, both for
556 * efficiency and so we can handle DEFAULT specifications.
558 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
561 * If a non-nil rangetable/namespace was passed in, and we are doing
562 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
563 * SELECT. This can only happen if we are inside a CREATE RULE, and in
564 * that case we want the rule's OLD and NEW rtable entries to appear as
565 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
566 * The SELECT's joinlist is not affected however. We must do this before
567 * adding the target table to the INSERT's rtable.
571 sub_rtable = pstate->p_rtable;
572 pstate->p_rtable = NIL;
573 sub_relnamespace = pstate->p_relnamespace;
574 pstate->p_relnamespace = NIL;
575 sub_varnamespace = pstate->p_varnamespace;
576 pstate->p_varnamespace = NIL;
580 sub_rtable = NIL; /* not used, but keep compiler quiet */
581 sub_relnamespace = NIL;
582 sub_varnamespace = NIL;
586 * Must get write lock on INSERT target table before scanning SELECT, else
587 * we will grab the wrong kind of initial lock if the target table is also
588 * mentioned in the SELECT part. Note that the target table is not added
589 * to the joinlist or namespace.
591 qry->resultRelation = setTargetTable(pstate, stmt->relation,
592 false, false, ACL_INSERT);
594 /* Validate stmt->cols list, or build default list if no list given */
595 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
596 Assert(list_length(icolumns) == list_length(attrnos));
599 * Determine which variant of INSERT we have.
601 if (selectStmt == NULL)
604 * We have INSERT ... DEFAULT VALUES. We can handle this case by
605 * emitting an empty targetlist --- all columns will be defaulted when
606 * the planner expands the targetlist.
610 else if (isGeneralSelect)
613 * We make the sub-pstate a child of the outer pstate so that it can
614 * see any Param definitions supplied from above. Since the outer
615 * pstate's rtable and namespace are presently empty, there are no
616 * side-effects of exposing names the sub-SELECT shouldn't be able to
619 ParseState *sub_pstate = make_parsestate(pstate);
623 * Process the source SELECT.
625 * It is important that this be handled just like a standalone SELECT;
626 * otherwise the behavior of SELECT within INSERT might be different
627 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
628 * bugs of just that nature...)
630 sub_pstate->p_rtable = sub_rtable;
631 sub_pstate->p_relnamespace = sub_relnamespace;
632 sub_pstate->p_varnamespace = sub_varnamespace;
635 * Note: we are not expecting that extras_before and extras_after are
636 * going to be used by the transformation of the SELECT statement.
638 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
639 extras_before, extras_after);
641 release_pstate_resources(sub_pstate);
644 Assert(IsA(selectQuery, Query));
645 Assert(selectQuery->commandType == CMD_SELECT);
646 if (selectQuery->into)
648 (errcode(ERRCODE_SYNTAX_ERROR),
649 errmsg("INSERT ... SELECT may not specify INTO")));
652 * Make the source be a subquery in the INSERT's rangetable, and add
653 * it to the INSERT's joinlist.
655 rte = addRangeTableEntryForSubquery(pstate,
657 makeAlias("*SELECT*", NIL),
659 rtr = makeNode(RangeTblRef);
660 /* assume new rte is at end */
661 rtr->rtindex = list_length(pstate->p_rtable);
662 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
663 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
666 * Generate an expression list for the INSERT that selects all the
667 * non-resjunk columns from the subquery. (INSERT's tlist must be
668 * separate from the subquery's tlist because we may add columns,
669 * insert datatype coercions, etc.)
671 * HACK: unknown-type constants and params in the SELECT's targetlist
672 * are copied up as-is rather than being referenced as subquery
673 * outputs. This is to ensure that when we try to coerce them to
674 * the target column's datatype, the right things happen (see
675 * special cases in coerce_type). Otherwise, this fails:
676 * INSERT INTO foo SELECT 'bar', ... FROM baz
680 foreach(lc, selectQuery->targetList)
682 TargetEntry *tle = (TargetEntry *) lfirst(lc);
688 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
689 exprType((Node *) tle->expr) == UNKNOWNOID)
692 expr = (Expr *) makeVar(rtr->rtindex,
694 exprType((Node *) tle->expr),
695 exprTypmod((Node *) tle->expr),
697 exprList = lappend(exprList, expr);
700 /* Prepare row for assignment to target table */
701 exprList = transformInsertRow(pstate, exprList,
705 else if (list_length(selectStmt->valuesLists) > 1)
708 * Process INSERT ... VALUES with multiple VALUES sublists. We
709 * generate a VALUES RTE holding the transformed expression lists, and
710 * build up a targetlist containing Vars that reference the VALUES
713 List *exprsLists = NIL;
714 int sublist_length = -1;
716 foreach(lc, selectStmt->valuesLists)
718 List *sublist = (List *) lfirst(lc);
720 /* Do basic expression transformation (same as a ROW() expr) */
721 sublist = transformExpressionList(pstate, sublist);
724 * All the sublists must be the same length, *after*
725 * transformation (which might expand '*' into multiple items).
726 * The VALUES RTE can't handle anything different.
728 if (sublist_length < 0)
730 /* Remember post-transformation length of first sublist */
731 sublist_length = list_length(sublist);
733 else if (sublist_length != list_length(sublist))
736 (errcode(ERRCODE_SYNTAX_ERROR),
737 errmsg("VALUES lists must all be the same length")));
740 /* Prepare row for assignment to target table */
741 sublist = transformInsertRow(pstate, sublist,
745 exprsLists = lappend(exprsLists, sublist);
749 * There mustn't have been any table references in the expressions,
750 * else strange things would happen, like Cartesian products of those
751 * tables with the VALUES list ...
753 if (pstate->p_joinlist != NIL)
755 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
756 errmsg("VALUES must not contain table references")));
759 * Another thing we can't currently support is NEW/OLD references in
760 * rules --- seems we'd need something like SQL99's LATERAL construct
761 * to ensure that the values would be available while evaluating the
762 * VALUES RTE. This is a shame. FIXME
764 if (list_length(pstate->p_rtable) != 1 &&
765 contain_vars_of_level((Node *) exprsLists, 0))
767 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768 errmsg("VALUES must not contain OLD or NEW references"),
769 errhint("Use SELECT ... UNION ALL ... instead.")));
772 * Generate the VALUES RTE
774 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
775 rtr = makeNode(RangeTblRef);
776 /* assume new rte is at end */
777 rtr->rtindex = list_length(pstate->p_rtable);
778 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
779 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
782 * Generate list of Vars referencing the RTE
784 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
789 * Process INSERT ... VALUES with a single VALUES sublist.
790 * We treat this separately for efficiency and for historical
791 * compatibility --- specifically, allowing table references,
793 * INSERT INTO foo VALUES(bar.*)
795 * The sublist is just computed directly as the Query's targetlist,
796 * with no VALUES RTE. So it works just like SELECT without FROM.
799 List *valuesLists = selectStmt->valuesLists;
801 Assert(list_length(valuesLists) == 1);
803 /* Do basic expression transformation (same as a ROW() expr) */
804 exprList = transformExpressionList(pstate,
805 (List *) linitial(valuesLists));
807 /* Prepare row for assignment to target table */
808 exprList = transformInsertRow(pstate, exprList,
814 * Generate query's target list using the computed list of expressions.
816 qry->targetList = NIL;
817 icols = list_head(icolumns);
818 attnos = list_head(attrnos);
819 foreach(lc, exprList)
821 Expr *expr = (Expr *) lfirst(lc);
825 col = (ResTarget *) lfirst(icols);
826 Assert(IsA(col, ResTarget));
828 tle = makeTargetEntry(expr,
829 (AttrNumber) lfirst_int(attnos),
832 qry->targetList = lappend(qry->targetList, tle);
834 icols = lnext(icols);
835 attnos = lnext(attnos);
839 * If we have a RETURNING clause, we need to add the target relation to
840 * the query namespace before processing it, so that Var references in
841 * RETURNING will work. Also, remove any namespace entries added in a
842 * sub-SELECT or VALUES list.
844 if (stmt->returningList)
846 pstate->p_relnamespace = NIL;
847 pstate->p_varnamespace = NIL;
848 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
850 qry->returningList = transformReturningList(pstate,
851 stmt->returningList);
854 /* done building the range table and jointree */
855 qry->rtable = pstate->p_rtable;
856 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
858 qry->hasSubLinks = pstate->p_hasSubLinks;
859 /* aggregates not allowed (but subselects are okay) */
860 if (pstate->p_hasAggs)
862 (errcode(ERRCODE_GROUPING_ERROR),
863 errmsg("cannot use aggregate function in VALUES")));
869 * Prepare an INSERT row for assignment to the target table.
871 * The row might be either a VALUES row, or variables referencing a
875 transformInsertRow(ParseState *pstate, List *exprlist,
876 List *stmtcols, List *icolumns, List *attrnos)
884 * Check length of expr list. It must not have more expressions than
885 * there are target columns. We allow fewer, but only if no explicit
886 * columns list was given (the remaining columns are implicitly
887 * defaulted). Note we must check this *after* transformation because
888 * that could expand '*' into multiple items.
890 if (list_length(exprlist) > list_length(icolumns))
892 (errcode(ERRCODE_SYNTAX_ERROR),
893 errmsg("INSERT has more expressions than target columns")));
894 if (stmtcols != NIL &&
895 list_length(exprlist) < list_length(icolumns))
897 (errcode(ERRCODE_SYNTAX_ERROR),
898 errmsg("INSERT has more target columns than expressions")));
901 * Prepare columns for assignment to target table.
904 icols = list_head(icolumns);
905 attnos = list_head(attrnos);
906 foreach(lc, exprlist)
908 Expr *expr = (Expr *) lfirst(lc);
911 col = (ResTarget *) lfirst(icols);
912 Assert(IsA(col, ResTarget));
914 expr = transformAssignedExpr(pstate, expr,
920 result = lappend(result, expr);
922 icols = lnext(icols);
923 attnos = lnext(attnos);
930 * transformCreateStmt -
931 * transforms the "create table" statement
932 * SQL92 allows constraints to be scattered all over, so thumb through
933 * the columns and collect all constraints into one place.
934 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
935 * then expand those into multiple IndexStmt blocks.
936 * - thomas 1997-12-02
939 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
940 List **extras_before, List **extras_after)
942 CreateStmtContext cxt;
946 cxt.stmtType = "CREATE TABLE";
947 cxt.relation = stmt->relation;
948 cxt.inhRelations = stmt->inhRelations;
951 cxt.ckconstraints = NIL;
952 cxt.fkconstraints = NIL;
953 cxt.ixconstraints = NIL;
957 cxt.hasoids = interpretOidsOption(stmt->options);
960 * Run through each primary element in the table creation clause. Separate
961 * column defs from constraints, and do preliminary analysis.
963 foreach(elements, stmt->tableElts)
965 Node *element = lfirst(elements);
967 switch (nodeTag(element))
970 transformColumnDefinition(pstate, &cxt,
971 (ColumnDef *) element);
975 transformTableConstraint(pstate, &cxt,
976 (Constraint *) element);
980 /* No pre-transformation needed */
981 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
985 transformInhRelation(pstate, &cxt,
986 (InhRelation *) element);
990 elog(ERROR, "unrecognized node type: %d",
991 (int) nodeTag(element));
997 * transformIndexConstraints wants cxt.alist to contain only index
998 * statements, so transfer anything we already have into extras_after
1001 *extras_after = list_concat(cxt.alist, *extras_after);
1004 Assert(stmt->constraints == NIL);
1007 * Postprocess constraints that give rise to index definitions.
1009 transformIndexConstraints(pstate, &cxt);
1012 * Postprocess foreign-key constraints.
1014 transformFKConstraints(pstate, &cxt, true, false);
1019 q = makeNode(Query);
1020 q->commandType = CMD_UTILITY;
1021 q->utilityStmt = (Node *) stmt;
1022 stmt->tableElts = cxt.columns;
1023 stmt->constraints = cxt.ckconstraints;
1024 *extras_before = list_concat(*extras_before, cxt.blist);
1025 *extras_after = list_concat(cxt.alist, *extras_after);
1031 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
1036 Constraint *constraint;
1039 cxt->columns = lappend(cxt->columns, column);
1041 /* Check for SERIAL pseudo-types */
1043 if (list_length(column->typename->names) == 1)
1045 char *typname = strVal(linitial(column->typename->names));
1047 if (strcmp(typname, "serial") == 0 ||
1048 strcmp(typname, "serial4") == 0)
1051 column->typename->names = NIL;
1052 column->typename->typeid = INT4OID;
1054 else if (strcmp(typname, "bigserial") == 0 ||
1055 strcmp(typname, "serial8") == 0)
1058 column->typename->names = NIL;
1059 column->typename->typeid = INT8OID;
1063 /* Do necessary work on the column type declaration */
1064 transformColumnType(pstate, column);
1066 /* Special actions for SERIAL pseudo-types */
1074 FuncCall *funccallnode;
1075 CreateSeqStmt *seqstmt;
1076 AlterSeqStmt *altseqstmt;
1080 * Determine namespace and name to use for the sequence.
1082 * Although we use ChooseRelationName, it's not guaranteed that the
1083 * selected sequence name won't conflict; given sufficiently long
1084 * field names, two different serial columns in the same table could
1085 * be assigned the same sequence name, and we'd not notice since we
1086 * aren't creating the sequence quite yet. In practice this seems
1087 * quite unlikely to be a problem, especially since few people would
1088 * need two serial columns in one table.
1090 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
1091 snamespace = get_namespace_name(snamespaceid);
1092 sname = ChooseRelationName(cxt->relation->relname,
1098 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
1099 cxt->stmtType, sname,
1100 cxt->relation->relname, column->colname)));
1103 * Build a CREATE SEQUENCE command to create the sequence object, and
1104 * add it to the list of things to be done before this CREATE/ALTER
1107 seqstmt = makeNode(CreateSeqStmt);
1108 seqstmt->sequence = makeRangeVar(snamespace, sname);
1109 seqstmt->options = NIL;
1111 cxt->blist = lappend(cxt->blist, seqstmt);
1114 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
1115 * as owned by this column, and add it to the list of things to be
1116 * done after this CREATE/ALTER TABLE.
1118 altseqstmt = makeNode(AlterSeqStmt);
1119 altseqstmt->sequence = makeRangeVar(snamespace, sname);
1120 attnamelist = list_make3(makeString(snamespace),
1121 makeString(cxt->relation->relname),
1122 makeString(column->colname));
1123 altseqstmt->options = list_make1(makeDefElem("owned_by",
1124 (Node *) attnamelist));
1126 cxt->alist = lappend(cxt->alist, altseqstmt);
1129 * Create appropriate constraints for SERIAL. We do this in full,
1130 * rather than shortcutting, so that we will detect any conflicting
1131 * constraints the user wrote (like a different DEFAULT).
1133 * Create an expression tree representing the function call
1134 * nextval('sequencename'). We cannot reduce the raw tree to cooked
1135 * form until after the sequence is created, but there's no need to do
1138 qstring = quote_qualified_identifier(snamespace, sname);
1139 snamenode = makeNode(A_Const);
1140 snamenode->val.type = T_String;
1141 snamenode->val.val.str = qstring;
1142 snamenode->typename = SystemTypeName("regclass");
1143 funccallnode = makeNode(FuncCall);
1144 funccallnode->funcname = SystemFuncName("nextval");
1145 funccallnode->args = list_make1(snamenode);
1146 funccallnode->agg_star = false;
1147 funccallnode->agg_distinct = false;
1148 funccallnode->location = -1;
1150 constraint = makeNode(Constraint);
1151 constraint->contype = CONSTR_DEFAULT;
1152 constraint->raw_expr = (Node *) funccallnode;
1153 constraint->cooked_expr = NULL;
1154 constraint->keys = NIL;
1155 column->constraints = lappend(column->constraints, constraint);
1157 constraint = makeNode(Constraint);
1158 constraint->contype = CONSTR_NOTNULL;
1159 column->constraints = lappend(column->constraints, constraint);
1162 /* Process column constraints, if any... */
1163 transformConstraintAttrs(column->constraints);
1165 saw_nullable = false;
1167 foreach(clist, column->constraints)
1169 constraint = lfirst(clist);
1172 * If this column constraint is a FOREIGN KEY constraint, then we fill
1173 * in the current attribute's name and throw it into the list of FK
1174 * constraints to be processed later.
1176 if (IsA(constraint, FkConstraint))
1178 FkConstraint *fkconstraint = (FkConstraint *) constraint;
1180 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
1181 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
1185 Assert(IsA(constraint, Constraint));
1187 switch (constraint->contype)
1190 if (saw_nullable && column->is_not_null)
1192 (errcode(ERRCODE_SYNTAX_ERROR),
1193 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1194 column->colname, cxt->relation->relname)));
1195 column->is_not_null = FALSE;
1196 saw_nullable = true;
1199 case CONSTR_NOTNULL:
1200 if (saw_nullable && !column->is_not_null)
1202 (errcode(ERRCODE_SYNTAX_ERROR),
1203 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1204 column->colname, cxt->relation->relname)));
1205 column->is_not_null = TRUE;
1206 saw_nullable = true;
1209 case CONSTR_DEFAULT:
1210 if (column->raw_default != NULL)
1212 (errcode(ERRCODE_SYNTAX_ERROR),
1213 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
1214 column->colname, cxt->relation->relname)));
1215 column->raw_default = constraint->raw_expr;
1216 Assert(constraint->cooked_expr == NULL);
1219 case CONSTR_PRIMARY:
1221 if (constraint->keys == NIL)
1222 constraint->keys = list_make1(makeString(column->colname));
1223 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1227 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1230 case CONSTR_ATTR_DEFERRABLE:
1231 case CONSTR_ATTR_NOT_DEFERRABLE:
1232 case CONSTR_ATTR_DEFERRED:
1233 case CONSTR_ATTR_IMMEDIATE:
1234 /* transformConstraintAttrs took care of these */
1238 elog(ERROR, "unrecognized constraint type: %d",
1239 constraint->contype);
1246 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1247 Constraint *constraint)
1249 switch (constraint->contype)
1251 case CONSTR_PRIMARY:
1253 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1257 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1261 case CONSTR_NOTNULL:
1262 case CONSTR_DEFAULT:
1263 case CONSTR_ATTR_DEFERRABLE:
1264 case CONSTR_ATTR_NOT_DEFERRABLE:
1265 case CONSTR_ATTR_DEFERRED:
1266 case CONSTR_ATTR_IMMEDIATE:
1267 elog(ERROR, "invalid context for constraint type %d",
1268 constraint->contype);
1272 elog(ERROR, "unrecognized constraint type: %d",
1273 constraint->contype);
1279 * transformInhRelation
1281 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1282 * column definitions which recreate the user defined column portions of <subtable>.
1285 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1286 InhRelation *inhRelation)
1288 AttrNumber parent_attno;
1290 TupleDesc tupleDesc;
1291 TupleConstr *constr;
1292 AclResult aclresult;
1293 bool including_defaults = false;
1294 bool including_constraints = false;
1295 bool including_indexes = false;
1298 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1300 if (relation->rd_rel->relkind != RELKIND_RELATION)
1302 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1303 errmsg("inherited relation \"%s\" is not a table",
1304 inhRelation->relation->relname)));
1307 * Check for SELECT privilages
1309 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1311 if (aclresult != ACLCHECK_OK)
1312 aclcheck_error(aclresult, ACL_KIND_CLASS,
1313 RelationGetRelationName(relation));
1315 tupleDesc = RelationGetDescr(relation);
1316 constr = tupleDesc->constr;
1318 foreach(elem, inhRelation->options)
1320 int option = lfirst_int(elem);
1324 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
1325 including_defaults = true;
1327 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
1328 including_defaults = false;
1330 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
1331 including_constraints = true;
1333 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
1334 including_constraints = false;
1336 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
1337 including_indexes = true;
1339 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
1340 including_indexes = false;
1343 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
1348 if (including_indexes)
1350 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1351 errmsg("LIKE INCLUDING INDEXES is not implemented")));
1354 * Insert the copied attributes into the cxt for the new table
1357 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1360 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1361 char *attributeName = NameStr(attribute->attname);
1365 * Ignore dropped columns in the parent.
1367 if (attribute->attisdropped)
1371 * Create a new column, which is marked as NOT inherited.
1373 * For constraints, ONLY the NOT NULL constraint is inherited by the
1374 * new column definition per SQL99.
1376 def = makeNode(ColumnDef);
1377 def->colname = pstrdup(attributeName);
1378 def->typename = makeTypeNameFromOid(attribute->atttypid,
1379 attribute->atttypmod);
1381 def->is_local = true;
1382 def->is_not_null = attribute->attnotnull;
1383 def->raw_default = NULL;
1384 def->cooked_default = NULL;
1385 def->constraints = NIL;
1388 * Add to column list
1390 cxt->columns = lappend(cxt->columns, def);
1393 * Copy default, if present and the default has been requested
1395 if (attribute->atthasdef && including_defaults)
1397 char *this_default = NULL;
1398 AttrDefault *attrdef;
1401 /* Find default in constraint structure */
1402 Assert(constr != NULL);
1403 attrdef = constr->defval;
1404 for (i = 0; i < constr->num_defval; i++)
1406 if (attrdef[i].adnum == parent_attno)
1408 this_default = attrdef[i].adbin;
1412 Assert(this_default != NULL);
1415 * If default expr could contain any vars, we'd need to fix 'em,
1416 * but it can't; so default is ready to apply to child.
1419 def->cooked_default = pstrdup(this_default);
1424 * Copy CHECK constraints if requested, being careful to adjust
1427 if (including_constraints && tupleDesc->constr)
1429 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
1432 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
1434 char *ccname = tupleDesc->constr->check[ccnum].ccname;
1435 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1436 Node *ccbin_node = stringToNode(ccbin);
1437 Constraint *n = makeNode(Constraint);
1439 change_varattnos_of_a_node(ccbin_node, attmap);
1441 n->contype = CONSTR_CHECK;
1442 n->name = pstrdup(ccname);
1444 n->cooked_expr = nodeToString(ccbin_node);
1445 n->indexspace = NULL;
1446 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
1451 * Close the parent rel, but keep our AccessShareLock on it until xact
1452 * commit. That will prevent someone else from deleting or ALTERing the
1453 * parent before the child is committed.
1455 heap_close(relation, NoLock);
1459 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1462 List *indexlist = NIL;
1467 * Run through the constraints that need to generate an index. For PRIMARY
1468 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1469 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1471 foreach(listptr, cxt->ixconstraints)
1473 Constraint *constraint = lfirst(listptr);
1477 Assert(IsA(constraint, Constraint));
1478 Assert((constraint->contype == CONSTR_PRIMARY)
1479 || (constraint->contype == CONSTR_UNIQUE));
1481 index = makeNode(IndexStmt);
1483 index->unique = true;
1484 index->primary = (constraint->contype == CONSTR_PRIMARY);
1487 if (cxt->pkey != NULL)
1489 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1490 errmsg("multiple primary keys for table \"%s\" are not allowed",
1491 cxt->relation->relname)));
1495 * In ALTER TABLE case, a primary index might already exist, but
1496 * DefineIndex will check for it.
1499 index->isconstraint = true;
1501 if (constraint->name != NULL)
1502 index->idxname = pstrdup(constraint->name);
1504 index->idxname = NULL; /* DefineIndex will choose name */
1506 index->relation = cxt->relation;
1507 index->accessMethod = DEFAULT_INDEX_TYPE;
1508 index->options = constraint->options;
1509 index->tableSpace = constraint->indexspace;
1510 index->indexParams = NIL;
1511 index->whereClause = NULL;
1512 index->concurrent = false;
1515 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1516 * index, also make sure they are NOT NULL, if possible. (Although we
1517 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1518 * more efficient to get it right the first time.)
1520 foreach(keys, constraint->keys)
1522 char *key = strVal(lfirst(keys));
1524 ColumnDef *column = NULL;
1527 foreach(columns, cxt->columns)
1529 column = (ColumnDef *) lfirst(columns);
1530 Assert(IsA(column, ColumnDef));
1531 if (strcmp(column->colname, key) == 0)
1539 /* found column in the new table; force it to be NOT NULL */
1540 if (constraint->contype == CONSTR_PRIMARY)
1541 column->is_not_null = TRUE;
1543 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1546 * column will be a system column in the new table, so accept
1547 * it. System columns can't ever be null, so no need to worry
1548 * about PRIMARY/NOT NULL constraint.
1552 else if (cxt->inhRelations)
1554 /* try inherited tables */
1557 foreach(inher, cxt->inhRelations)
1559 RangeVar *inh = (RangeVar *) lfirst(inher);
1563 Assert(IsA(inh, RangeVar));
1564 rel = heap_openrv(inh, AccessShareLock);
1565 if (rel->rd_rel->relkind != RELKIND_RELATION)
1567 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1568 errmsg("inherited relation \"%s\" is not a table",
1570 for (count = 0; count < rel->rd_att->natts; count++)
1572 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1573 char *inhname = NameStr(inhattr->attname);
1575 if (inhattr->attisdropped)
1577 if (strcmp(key, inhname) == 0)
1582 * We currently have no easy way to force an
1583 * inherited column to be NOT NULL at creation, if
1584 * its parent wasn't so already. We leave it to
1585 * DefineIndex to fix things up in this case.
1590 heap_close(rel, NoLock);
1597 * In the ALTER TABLE case, don't complain about index keys not
1598 * created in the command; they may well exist already.
1599 * DefineIndex will complain about them if not, and will also take
1600 * care of marking them NOT NULL.
1602 if (!found && !cxt->isalter)
1604 (errcode(ERRCODE_UNDEFINED_COLUMN),
1605 errmsg("column \"%s\" named in key does not exist",
1608 /* Check for PRIMARY KEY(foo, foo) */
1609 foreach(columns, index->indexParams)
1611 iparam = (IndexElem *) lfirst(columns);
1612 if (iparam->name && strcmp(key, iparam->name) == 0)
1616 (errcode(ERRCODE_DUPLICATE_COLUMN),
1617 errmsg("column \"%s\" appears twice in primary key constraint",
1621 (errcode(ERRCODE_DUPLICATE_COLUMN),
1622 errmsg("column \"%s\" appears twice in unique constraint",
1627 /* OK, add it to the index definition */
1628 iparam = makeNode(IndexElem);
1629 iparam->name = pstrdup(key);
1630 iparam->expr = NULL;
1631 iparam->opclass = NIL;
1632 index->indexParams = lappend(index->indexParams, iparam);
1635 indexlist = lappend(indexlist, index);
1639 * Scan the index list and remove any redundant index specifications. This
1640 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1641 * strict reading of SQL92 would suggest raising an error instead, but
1642 * that strikes me as too anal-retentive. - tgl 2001-02-14
1644 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1645 * pre-existing indexes, too.
1647 Assert(cxt->alist == NIL);
1648 if (cxt->pkey != NULL)
1650 /* Make sure we keep the PKEY index in preference to others... */
1651 cxt->alist = list_make1(cxt->pkey);
1654 foreach(l, indexlist)
1661 /* if it's pkey, it's already in cxt->alist */
1662 if (index == cxt->pkey)
1665 foreach(k, cxt->alist)
1667 IndexStmt *priorindex = lfirst(k);
1669 if (equal(index->indexParams, priorindex->indexParams))
1672 * If the prior index is as yet unnamed, and this one is
1673 * named, then transfer the name to the prior index. This
1674 * ensures that if we have named and unnamed constraints,
1675 * we'll use (at least one of) the names for the index.
1677 if (priorindex->idxname == NULL)
1678 priorindex->idxname = index->idxname;
1685 cxt->alist = lappend(cxt->alist, index);
1690 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1691 bool skipValidation, bool isAddConstraint)
1695 if (cxt->fkconstraints == NIL)
1699 * If CREATE TABLE or adding a column with NULL default, we can safely
1700 * skip validation of the constraint.
1704 foreach(fkclist, cxt->fkconstraints)
1706 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1708 fkconstraint->skip_validation = true;
1713 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1714 * CONSTRAINT command to execute after the basic command is complete. (If
1715 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1716 * its own subcommand list.)
1718 * Note: the ADD CONSTRAINT command must also execute after any index
1719 * creation commands. Thus, this should run after
1720 * transformIndexConstraints, so that the CREATE INDEX commands are
1721 * already in cxt->alist.
1723 if (!isAddConstraint)
1725 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1727 alterstmt->relation = cxt->relation;
1728 alterstmt->cmds = NIL;
1729 alterstmt->relkind = OBJECT_TABLE;
1731 foreach(fkclist, cxt->fkconstraints)
1733 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1734 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1736 altercmd->subtype = AT_ProcessedConstraint;
1737 altercmd->name = NULL;
1738 altercmd->def = (Node *) fkconstraint;
1739 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1742 cxt->alist = lappend(cxt->alist, alterstmt);
1747 * transformIndexStmt -
1748 * transforms the qualification of the index statement
1751 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1754 RangeTblEntry *rte = NULL;
1757 qry = makeNode(Query);
1758 qry->commandType = CMD_UTILITY;
1760 /* take care of the where clause */
1761 if (stmt->whereClause)
1764 * Put the parent table into the rtable so that the WHERE clause can
1765 * refer to its fields without qualification. Note that this only
1766 * works if the parent table already exists --- so we can't easily
1767 * support predicates on indexes created implicitly by CREATE TABLE.
1768 * Fortunately, that's not necessary.
1770 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1772 /* no to join list, yes to namespaces */
1773 addRTEtoQuery(pstate, rte, false, true, true);
1775 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1779 /* take care of any index expressions */
1780 foreach(l, stmt->indexParams)
1782 IndexElem *ielem = (IndexElem *) lfirst(l);
1786 /* Set up rtable as for predicate, see notes above */
1789 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1791 /* no to join list, yes to namespaces */
1792 addRTEtoQuery(pstate, rte, false, true, true);
1794 ielem->expr = transformExpr(pstate, ielem->expr);
1797 * We check only that the result type is legitimate; this is for
1798 * consistency with what transformWhereClause() checks for the
1799 * predicate. DefineIndex() will make more checks.
1801 if (expression_returns_set(ielem->expr))
1803 (errcode(ERRCODE_DATATYPE_MISMATCH),
1804 errmsg("index expression may not return a set")));
1808 qry->hasSubLinks = pstate->p_hasSubLinks;
1809 stmt->rangetable = pstate->p_rtable;
1811 qry->utilityStmt = (Node *) stmt;
1817 * transformRuleStmt -
1818 * transform a Create Rule Statement. The actions is a list of parse
1819 * trees which is transformed into a list of query trees.
1822 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1823 List **extras_before, List **extras_after)
1827 RangeTblEntry *oldrte;
1828 RangeTblEntry *newrte;
1830 qry = makeNode(Query);
1831 qry->commandType = CMD_UTILITY;
1832 qry->utilityStmt = (Node *) stmt;
1835 * To avoid deadlock, make sure the first thing we do is grab
1836 * AccessExclusiveLock on the target relation. This will be needed by
1837 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1840 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1843 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1844 * Set up their RTEs in the main pstate for use in parsing the rule
1847 Assert(pstate->p_rtable == NIL);
1848 oldrte = addRangeTableEntryForRelation(pstate, rel,
1849 makeAlias("*OLD*", NIL),
1851 newrte = addRangeTableEntryForRelation(pstate, rel,
1852 makeAlias("*NEW*", NIL),
1854 /* Must override addRangeTableEntry's default access-check flags */
1855 oldrte->requiredPerms = 0;
1856 newrte->requiredPerms = 0;
1859 * They must be in the namespace too for lookup purposes, but only add the
1860 * one(s) that are relevant for the current kind of rule. In an UPDATE
1861 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1862 * there's no need to be so picky for INSERT & DELETE. We do not add them
1865 switch (stmt->event)
1868 addRTEtoQuery(pstate, oldrte, false, true, true);
1871 addRTEtoQuery(pstate, oldrte, false, true, true);
1872 addRTEtoQuery(pstate, newrte, false, true, true);
1875 addRTEtoQuery(pstate, newrte, false, true, true);
1878 addRTEtoQuery(pstate, oldrte, false, true, true);
1881 elog(ERROR, "unrecognized event type: %d",
1886 /* take care of the where clause */
1887 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1890 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1892 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1893 errmsg("rule WHERE condition may not contain references to other relations")));
1895 /* aggregates not allowed (but subselects are okay) */
1896 if (pstate->p_hasAggs)
1898 (errcode(ERRCODE_GROUPING_ERROR),
1899 errmsg("cannot use aggregate function in rule WHERE condition")));
1901 /* save info about sublinks in where clause */
1902 qry->hasSubLinks = pstate->p_hasSubLinks;
1905 * 'instead nothing' rules with a qualification need a query rangetable so
1906 * the rewrite handler can add the negated rule qualification to the
1907 * original query. We create a query with the new command type CMD_NOTHING
1908 * here that is treated specially by the rewrite system.
1910 if (stmt->actions == NIL)
1912 Query *nothing_qry = makeNode(Query);
1914 nothing_qry->commandType = CMD_NOTHING;
1915 nothing_qry->rtable = pstate->p_rtable;
1916 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1918 stmt->actions = list_make1(nothing_qry);
1923 List *newactions = NIL;
1926 * transform each statement, like parse_sub_analyze()
1928 foreach(l, stmt->actions)
1930 Node *action = (Node *) lfirst(l);
1931 ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1938 * Set up OLD/NEW in the rtable for this statement. The entries
1939 * are added only to relnamespace, not varnamespace, because we
1940 * don't want them to be referred to by unqualified field names
1941 * nor "*" in the rule actions. We decide later whether to put
1942 * them in the joinlist.
1944 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1945 makeAlias("*OLD*", NIL),
1947 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1948 makeAlias("*NEW*", NIL),
1950 oldrte->requiredPerms = 0;
1951 newrte->requiredPerms = 0;
1952 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1953 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1955 /* Transform the rule action statement */
1956 top_subqry = transformStmt(sub_pstate, action,
1957 extras_before, extras_after);
1960 * We cannot support utility-statement actions (eg NOTIFY) with
1961 * nonempty rule WHERE conditions, because there's no way to make
1962 * the utility action execute conditionally.
1964 if (top_subqry->commandType == CMD_UTILITY &&
1965 stmt->whereClause != NULL)
1967 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1968 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1971 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1972 * into the SELECT, and that's what we need to look at. (Ugly
1973 * kluge ... try to fix this when we redesign querytrees.)
1975 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1978 * If the sub_qry is a setop, we cannot attach any qualifications
1979 * to it, because the planner won't notice them. This could
1980 * perhaps be relaxed someday, but for now, we may as well reject
1981 * such a rule immediately.
1983 if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1985 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1986 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1989 * Validate action's use of OLD/NEW, qual too
1992 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1993 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1995 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1996 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1998 switch (stmt->event)
2003 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2004 errmsg("ON SELECT rule may not use OLD")));
2007 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2008 errmsg("ON SELECT rule may not use NEW")));
2016 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2017 errmsg("ON INSERT rule may not use OLD")));
2022 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2023 errmsg("ON DELETE rule may not use NEW")));
2026 elog(ERROR, "unrecognized event type: %d",
2032 * For efficiency's sake, add OLD to the rule action's jointree
2033 * only if it was actually referenced in the statement or qual.
2035 * For INSERT, NEW is not really a relation (only a reference to
2036 * the to-be-inserted tuple) and should never be added to the
2039 * For UPDATE, we treat NEW as being another kind of reference to
2040 * OLD, because it represents references to *transformed* tuples
2041 * of the existing relation. It would be wrong to enter NEW
2042 * separately in the jointree, since that would cause a double
2043 * join of the updated relation. It's also wrong to fail to make
2044 * a jointree entry if only NEW and not OLD is mentioned.
2046 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2049 * If sub_qry is a setop, manipulating its jointree will do no
2050 * good at all, because the jointree is dummy. (This should be
2051 * a can't-happen case because of prior tests.)
2053 if (sub_qry->setOperations != NULL)
2055 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2056 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2057 /* hack so we can use addRTEtoQuery() */
2058 sub_pstate->p_rtable = sub_qry->rtable;
2059 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2060 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2061 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2064 newactions = lappend(newactions, top_subqry);
2066 release_pstate_resources(sub_pstate);
2070 stmt->actions = newactions;
2073 /* Close relation, but keep the exclusive lock */
2074 heap_close(rel, NoLock);
2081 * transformSelectStmt -
2082 * transforms a Select Statement
2084 * Note: this is also used for DECLARE CURSOR statements.
2087 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
2089 Query *qry = makeNode(Query);
2093 qry->commandType = CMD_SELECT;
2095 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2096 pstate->p_locking_clause = stmt->lockingClause;
2098 /* process the FROM clause */
2099 transformFromClause(pstate, stmt->fromClause);
2101 /* transform targetlist */
2102 qry->targetList = transformTargetList(pstate, stmt->targetList);
2104 /* mark column origins */
2105 markTargetListOrigins(pstate, qry->targetList);
2107 /* transform WHERE */
2108 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2111 * Initial processing of HAVING clause is just like WHERE clause.
2113 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
2117 * Transform sorting/grouping stuff. Do ORDER BY first because both
2118 * transformGroupClause and transformDistinctClause need the results.
2120 qry->sortClause = transformSortClause(pstate,
2123 true /* fix unknowns */ );
2125 qry->groupClause = transformGroupClause(pstate,
2130 qry->distinctClause = transformDistinctClause(pstate,
2131 stmt->distinctClause,
2135 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2137 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2140 /* handle any SELECT INTO/CREATE TABLE AS spec */
2143 qry->into = stmt->into;
2144 if (stmt->intoColNames)
2145 applyColumnNames(qry->targetList, stmt->intoColNames);
2146 qry->intoOptions = copyObject(stmt->intoOptions);
2147 qry->intoOnCommit = stmt->intoOnCommit;
2148 qry->intoTableSpaceName = stmt->intoTableSpaceName;
2151 qry->rtable = pstate->p_rtable;
2152 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2154 qry->hasSubLinks = pstate->p_hasSubLinks;
2155 qry->hasAggs = pstate->p_hasAggs;
2156 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2157 parseCheckAggregates(pstate, qry);
2159 foreach(l, stmt->lockingClause)
2161 transformLockingClause(qry, (LockingClause *) lfirst(l));
2168 * transformValuesClause -
2169 * transforms a VALUES clause that's being used as a standalone SELECT
2171 * We build a Query containing a VALUES RTE, rather as if one had written
2172 * SELECT * FROM (VALUES ...)
2175 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
2177 Query *qry = makeNode(Query);
2178 List *exprsLists = NIL;
2179 List **coltype_lists = NULL;
2180 Oid *coltypes = NULL;
2181 int sublist_length = -1;
2182 List *newExprsLists;
2189 qry->commandType = CMD_SELECT;
2191 /* Most SELECT stuff doesn't apply in a VALUES clause */
2192 Assert(stmt->distinctClause == NIL);
2193 Assert(stmt->targetList == NIL);
2194 Assert(stmt->fromClause == NIL);
2195 Assert(stmt->whereClause == NULL);
2196 Assert(stmt->groupClause == NIL);
2197 Assert(stmt->havingClause == NULL);
2198 Assert(stmt->op == SETOP_NONE);
2201 * For each row of VALUES, transform the raw expressions and gather type
2202 * information. This is also a handy place to reject DEFAULT nodes, which
2203 * the grammar allows for simplicity.
2205 foreach(lc, stmt->valuesLists)
2207 List *sublist = (List *) lfirst(lc);
2209 /* Do basic expression transformation (same as a ROW() expr) */
2210 sublist = transformExpressionList(pstate, sublist);
2213 * All the sublists must be the same length, *after* transformation
2214 * (which might expand '*' into multiple items). The VALUES RTE can't
2215 * handle anything different.
2217 if (sublist_length < 0)
2219 /* Remember post-transformation length of first sublist */
2220 sublist_length = list_length(sublist);
2221 /* and allocate arrays for column-type info */
2222 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
2223 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
2225 else if (sublist_length != list_length(sublist))
2228 (errcode(ERRCODE_SYNTAX_ERROR),
2229 errmsg("VALUES lists must all be the same length")));
2232 exprsLists = lappend(exprsLists, sublist);
2235 foreach(lc2, sublist)
2237 Node *col = (Node *) lfirst(lc2);
2239 if (IsA(col, SetToDefault))
2241 (errcode(ERRCODE_SYNTAX_ERROR),
2242 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
2243 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
2249 * Now resolve the common types of the columns, and coerce everything to
2252 for (i = 0; i < sublist_length; i++)
2254 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
2257 newExprsLists = NIL;
2258 foreach(lc, exprsLists)
2260 List *sublist = (List *) lfirst(lc);
2261 List *newsublist = NIL;
2264 foreach(lc2, sublist)
2266 Node *col = (Node *) lfirst(lc2);
2268 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
2269 newsublist = lappend(newsublist, col);
2273 newExprsLists = lappend(newExprsLists, newsublist);
2277 * Generate the VALUES RTE
2279 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
2280 rtr = makeNode(RangeTblRef);
2281 /* assume new rte is at end */
2282 rtr->rtindex = list_length(pstate->p_rtable);
2283 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2284 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2285 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
2288 * Generate a targetlist as though expanding "*"
2290 Assert(pstate->p_next_resno == 1);
2291 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
2294 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2297 qry->sortClause = transformSortClause(pstate,
2300 true /* fix unknowns */ );
2302 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2304 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2307 if (stmt->lockingClause)
2309 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2310 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
2312 /* handle any CREATE TABLE AS spec */
2315 qry->into = stmt->into;
2316 if (stmt->intoColNames)
2317 applyColumnNames(qry->targetList, stmt->intoColNames);
2318 qry->intoOptions = copyObject(stmt->intoOptions);
2319 qry->intoOnCommit = stmt->intoOnCommit;
2320 qry->intoTableSpaceName = stmt->intoTableSpaceName;
2324 * There mustn't have been any table references in the expressions, else
2325 * strange things would happen, like Cartesian products of those tables
2326 * with the VALUES list. We have to check this after parsing ORDER BY et
2327 * al since those could insert more junk.
2329 if (list_length(pstate->p_joinlist) != 1)
2331 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2332 errmsg("VALUES must not contain table references")));
2335 * Another thing we can't currently support is NEW/OLD references in rules
2336 * --- seems we'd need something like SQL99's LATERAL construct to ensure
2337 * that the values would be available while evaluating the VALUES RTE.
2338 * This is a shame. FIXME
2340 if (list_length(pstate->p_rtable) != 1 &&
2341 contain_vars_of_level((Node *) newExprsLists, 0))
2343 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2344 errmsg("VALUES must not contain OLD or NEW references"),
2345 errhint("Use SELECT ... UNION ALL ... instead.")));
2347 qry->rtable = pstate->p_rtable;
2348 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2350 qry->hasSubLinks = pstate->p_hasSubLinks;
2351 /* aggregates not allowed (but subselects are okay) */
2352 if (pstate->p_hasAggs)
2354 (errcode(ERRCODE_GROUPING_ERROR),
2355 errmsg("cannot use aggregate function in VALUES")));
2361 * transformSetOperationsStmt -
2362 * transforms a set-operations tree
2364 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
2365 * structure to it. We must transform each leaf SELECT and build up a top-
2366 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
2367 * The tree of set operations is converted into the setOperations field of
2368 * the top-level Query.
2371 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
2373 Query *qry = makeNode(Query);
2374 SelectStmt *leftmostSelect;
2376 Query *leftmostQuery;
2377 SetOperationStmt *sostmt;
2378 List *intoColNames = NIL;
2382 List *lockingClause;
2384 ListCell *left_tlist,
2393 RangeTblEntry *jrte;
2396 qry->commandType = CMD_SELECT;
2399 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
2400 * and from the top-level node. (Most of the INTO options can be
2401 * transferred to the Query immediately, but intoColNames has to be saved
2404 leftmostSelect = stmt->larg;
2405 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2406 leftmostSelect = leftmostSelect->larg;
2407 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
2408 leftmostSelect->larg == NULL);
2409 if (leftmostSelect->into)
2411 qry->into = leftmostSelect->into;
2412 intoColNames = leftmostSelect->intoColNames;
2413 qry->intoOptions = copyObject(leftmostSelect->intoOptions);
2414 qry->intoOnCommit = leftmostSelect->intoOnCommit;
2415 qry->intoTableSpaceName = leftmostSelect->intoTableSpaceName;
2418 /* clear this to prevent complaints in transformSetOperationTree() */
2419 leftmostSelect->into = NULL;
2422 * These are not one-time, exactly, but we want to process them here and
2423 * not let transformSetOperationTree() see them --- else it'll just
2424 * recurse right back here!
2426 sortClause = stmt->sortClause;
2427 limitOffset = stmt->limitOffset;
2428 limitCount = stmt->limitCount;
2429 lockingClause = stmt->lockingClause;
2431 stmt->sortClause = NIL;
2432 stmt->limitOffset = NULL;
2433 stmt->limitCount = NULL;
2434 stmt->lockingClause = NIL;
2436 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2439 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2440 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2443 * Recursively transform the components of the tree.
2445 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
2446 Assert(sostmt && IsA(sostmt, SetOperationStmt));
2447 qry->setOperations = (Node *) sostmt;
2450 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2452 node = sostmt->larg;
2453 while (node && IsA(node, SetOperationStmt))
2454 node = ((SetOperationStmt *) node)->larg;
2455 Assert(node && IsA(node, RangeTblRef));
2456 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2457 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2458 Assert(leftmostQuery != NULL);
2461 * Generate dummy targetlist for outer query using column names of
2462 * leftmost select and common datatypes of topmost set operation. Also
2463 * make lists of the dummy vars and their names for use in parsing ORDER
2466 * Note: we use leftmostRTI as the varno of the dummy variables. It
2467 * shouldn't matter too much which RT index they have, as long as they
2468 * have one that corresponds to a real RT entry; else funny things may
2469 * happen when the tree is mashed by rule rewriting.
2471 qry->targetList = NIL;
2474 left_tlist = list_head(leftmostQuery->targetList);
2476 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
2478 Oid colType = lfirst_oid(lct);
2479 int32 colTypmod = lfirst_int(lcm);
2480 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2485 Assert(!lefttle->resjunk);
2486 colName = pstrdup(lefttle->resname);
2487 expr = (Expr *) makeVar(leftmostRTI,
2492 tle = makeTargetEntry(expr,
2493 (AttrNumber) pstate->p_next_resno++,
2496 qry->targetList = lappend(qry->targetList, tle);
2497 targetvars = lappend(targetvars, expr);
2498 targetnames = lappend(targetnames, makeString(colName));
2499 left_tlist = lnext(left_tlist);
2503 * As a first step towards supporting sort clauses that are expressions
2504 * using the output columns, generate a varnamespace entry that makes the
2505 * output columns visible. A Join RTE node is handy for this, since we
2506 * can easily control the Vars generated upon matches.
2508 * Note: we don't yet do anything useful with such cases, but at least
2509 * "ORDER BY upper(foo)" will draw the right error message rather than
2512 jrte = addRangeTableEntryForJoin(NULL,
2519 sv_rtable = pstate->p_rtable;
2520 pstate->p_rtable = list_make1(jrte);
2522 sv_relnamespace = pstate->p_relnamespace;
2523 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2525 sv_varnamespace = pstate->p_varnamespace;
2526 pstate->p_varnamespace = list_make1(jrte);
2529 * For now, we don't support resjunk sort clauses on the output of a
2530 * setOperation tree --- you can only use the SQL92-spec options of
2531 * selecting an output column by name or number. Enforce by checking that
2532 * transformSortClause doesn't add any items to tlist.
2534 tllen = list_length(qry->targetList);
2536 qry->sortClause = transformSortClause(pstate,
2539 false /* no unknowns expected */ );
2541 pstate->p_rtable = sv_rtable;
2542 pstate->p_relnamespace = sv_relnamespace;
2543 pstate->p_varnamespace = sv_varnamespace;
2545 if (tllen != list_length(qry->targetList))
2547 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2548 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2550 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2552 qry->limitCount = transformLimitClause(pstate, limitCount,
2556 * Handle SELECT INTO/CREATE TABLE AS.
2558 * Any column names from CREATE TABLE AS need to be attached to both the
2559 * top level and the leftmost subquery. We do not do this earlier because
2560 * we do *not* want sortClause processing to be affected.
2564 applyColumnNames(qry->targetList, intoColNames);
2565 applyColumnNames(leftmostQuery->targetList, intoColNames);
2568 qry->rtable = pstate->p_rtable;
2569 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2571 qry->hasSubLinks = pstate->p_hasSubLinks;
2572 qry->hasAggs = pstate->p_hasAggs;
2573 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2574 parseCheckAggregates(pstate, qry);
2576 foreach(l, lockingClause)
2578 transformLockingClause(qry, (LockingClause *) lfirst(l));
2585 * transformSetOperationTree
2586 * Recursively transform leaves and internal nodes of a set-op tree
2589 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2593 Assert(stmt && IsA(stmt, SelectStmt));
2596 * Validity-check both leaf and internal SELECTs for disallowed ops.
2600 (errcode(ERRCODE_SYNTAX_ERROR),
2601 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2602 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2603 if (stmt->lockingClause)
2605 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2606 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2609 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2610 * clauses attached, we need to treat it like a leaf node to generate an
2611 * independent sub-Query tree. Otherwise, it can be represented by a
2612 * SetOperationStmt node underneath the parent Query.
2614 if (stmt->op == SETOP_NONE)
2616 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2621 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2622 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2623 stmt->lockingClause)
2631 /* Process leaf SELECT */
2634 char selectName[32];
2639 * Transform SelectStmt into a Query.
2641 * Note: previously transformed sub-queries don't affect the parsing
2642 * of this sub-query, because they are not in the toplevel pstate's
2645 selectList = parse_sub_analyze((Node *) stmt, pstate);
2647 Assert(list_length(selectList) == 1);
2648 selectQuery = (Query *) linitial(selectList);
2649 Assert(IsA(selectQuery, Query));
2652 * Check for bogus references to Vars on the current query level (but
2653 * upper-level references are okay). Normally this can't happen
2654 * because the namespace will be empty, but it could happen if we are
2657 if (pstate->p_relnamespace || pstate->p_varnamespace)
2659 if (contain_vars_of_level((Node *) selectQuery, 1))
2661 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2662 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2666 * Make the leaf query be a subquery in the top-level rangetable.
2668 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2669 list_length(pstate->p_rtable) + 1);
2670 rte = addRangeTableEntryForSubquery(pstate,
2672 makeAlias(selectName, NIL),
2676 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2678 rtr = makeNode(RangeTblRef);
2679 /* assume new rte is at end */
2680 rtr->rtindex = list_length(pstate->p_rtable);
2681 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2682 return (Node *) rtr;
2686 /* Process an internal node (set operation node) */
2687 SetOperationStmt *op = makeNode(SetOperationStmt);
2696 const char *context;
2698 context = (stmt->op == SETOP_UNION ? "UNION" :
2699 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2703 op->all = stmt->all;
2706 * Recursively transform the child nodes.
2708 op->larg = transformSetOperationTree(pstate, stmt->larg);
2709 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2712 * Verify that the two children have the same number of non-junk
2713 * columns, and determine the types of the merged output columns.
2715 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
2716 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
2717 if (list_length(lcoltypes) != list_length(rcoltypes))
2719 (errcode(ERRCODE_SYNTAX_ERROR),
2720 errmsg("each %s query must have the same number of columns",
2722 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
2723 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
2726 op->colTypmods = NIL;
2727 /* don't have a "foreach4", so chase two of the lists by hand */
2728 lcm = list_head(lcoltypmods);
2729 rcm = list_head(rcoltypmods);
2730 forboth(lct, lcoltypes, rct, rcoltypes)
2732 Oid lcoltype = lfirst_oid(lct);
2733 Oid rcoltype = lfirst_oid(rct);
2734 int32 lcoltypmod = lfirst_int(lcm);
2735 int32 rcoltypmod = lfirst_int(rcm);
2739 /* select common type, same as CASE et al */
2740 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2742 /* if same type and same typmod, use typmod; else default */
2743 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
2744 rescoltypmod = lcoltypmod;
2747 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2748 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2760 * Get output column types/typmods of an (already transformed) set-op node
2763 getSetColTypes(ParseState *pstate, Node *node,
2764 List **colTypes, List **colTypmods)
2768 if (IsA(node, RangeTblRef))
2770 RangeTblRef *rtr = (RangeTblRef *) node;
2771 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2772 Query *selectQuery = rte->subquery;
2775 Assert(selectQuery != NULL);
2776 /* Get types of non-junk columns */
2777 foreach(tl, selectQuery->targetList)
2779 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2783 *colTypes = lappend_oid(*colTypes,
2784 exprType((Node *) tle->expr));
2785 *colTypmods = lappend_int(*colTypmods,
2786 exprTypmod((Node *) tle->expr));
2789 else if (IsA(node, SetOperationStmt))
2791 SetOperationStmt *op = (SetOperationStmt *) node;
2793 /* Result already computed during transformation of node */
2794 Assert(op->colTypes != NIL);
2795 *colTypes = op->colTypes;
2796 *colTypmods = op->colTypmods;
2799 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2802 /* Attach column names from a ColumnDef list to a TargetEntry list */
2804 applyColumnNames(List *dst, List *src)
2809 src_item = list_head(src);
2811 foreach(dst_item, dst)
2813 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2816 /* junk targets don't count */
2820 /* fewer ColumnDefs than target entries is OK */
2821 if (src_item == NULL)
2824 s = (ColumnDef *) lfirst(src_item);
2825 src_item = lnext(src_item);
2827 d->resname = pstrdup(s->colname);
2830 /* more ColumnDefs than target entries is not OK */
2831 if (src_item != NULL)
2833 (errcode(ERRCODE_SYNTAX_ERROR),
2834 errmsg("CREATE TABLE AS specifies too many column names")));
2839 * transformUpdateStmt -
2840 * transforms an update statement
2843 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2845 Query *qry = makeNode(Query);
2847 ListCell *origTargetList;
2850 qry->commandType = CMD_UPDATE;
2851 pstate->p_is_update = true;
2853 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2854 interpretInhOption(stmt->relation->inhOpt),
2859 * the FROM clause is non-standard SQL syntax. We used to be able to do
2860 * this with REPLACE in POSTQUEL so we keep the feature.
2862 transformFromClause(pstate, stmt->fromClause);
2864 qry->targetList = transformTargetList(pstate, stmt->targetList);
2866 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2868 qry->returningList = transformReturningList(pstate, stmt->returningList);
2870 qry->rtable = pstate->p_rtable;
2871 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2873 qry->hasSubLinks = pstate->p_hasSubLinks;
2876 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
2877 * an implementation point of view, this is forced because the implicit
2878 * ctid reference would otherwise be an ungrouped variable.)
2880 if (pstate->p_hasAggs)
2882 (errcode(ERRCODE_GROUPING_ERROR),
2883 errmsg("cannot use aggregate function in UPDATE")));
2886 * Now we are done with SELECT-like processing, and can get on with
2887 * transforming the target list to match the UPDATE target columns.
2890 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2891 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2892 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2894 /* Prepare non-junk columns for assignment to target table */
2895 origTargetList = list_head(stmt->targetList);
2897 foreach(tl, qry->targetList)
2899 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2900 ResTarget *origTarget;
2906 * Resjunk nodes need no additional processing, but be sure they
2907 * have resnos that do not match any target columns; else rewriter
2908 * or planner might get confused. They don't need a resname
2911 tle->resno = (AttrNumber) pstate->p_next_resno++;
2912 tle->resname = NULL;
2915 if (origTargetList == NULL)
2916 elog(ERROR, "UPDATE target count mismatch --- internal error");
2917 origTarget = (ResTarget *) lfirst(origTargetList);
2918 Assert(IsA(origTarget, ResTarget));
2920 attrno = attnameAttNum(pstate->p_target_relation,
2921 origTarget->name, true);
2922 if (attrno == InvalidAttrNumber)
2924 (errcode(ERRCODE_UNDEFINED_COLUMN),
2925 errmsg("column \"%s\" of relation \"%s\" does not exist",
2927 RelationGetRelationName(pstate->p_target_relation)),
2928 parser_errposition(pstate, origTarget->location)));
2930 updateTargetListEntry(pstate, tle, origTarget->name,
2932 origTarget->indirection,
2933 origTarget->location);
2935 origTargetList = lnext(origTargetList);
2937 if (origTargetList != NULL)
2938 elog(ERROR, "UPDATE target count mismatch --- internal error");
2944 * transformReturningList -
2945 * handle a RETURNING clause in INSERT/UPDATE/DELETE
2948 transformReturningList(ParseState *pstate, List *returningList)
2951 int save_next_resno;
2955 if (returningList == NIL)
2956 return NIL; /* nothing to do */
2959 * We need to assign resnos starting at one in the RETURNING list. Save
2960 * and restore the main tlist's value of p_next_resno, just in case
2961 * someone looks at it later (probably won't happen).
2963 save_next_resno = pstate->p_next_resno;
2964 pstate->p_next_resno = 1;
2966 /* save other state so that we can detect disallowed stuff */
2967 save_hasAggs = pstate->p_hasAggs;
2968 pstate->p_hasAggs = false;
2969 length_rtable = list_length(pstate->p_rtable);
2971 /* transform RETURNING identically to a SELECT targetlist */
2972 rlist = transformTargetList(pstate, returningList);
2974 /* check for disallowed stuff */
2976 /* aggregates not allowed (but subselects are okay) */
2977 if (pstate->p_hasAggs)
2979 (errcode(ERRCODE_GROUPING_ERROR),
2980 errmsg("cannot use aggregate function in RETURNING")));
2982 /* no new relation references please */
2983 if (list_length(pstate->p_rtable) != length_rtable)
2985 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2986 errmsg("RETURNING may not contain references to other relations")));
2988 /* mark column origins */
2989 markTargetListOrigins(pstate, rlist);
2992 pstate->p_next_resno = save_next_resno;
2993 pstate->p_hasAggs = save_hasAggs;
2999 * transformAlterTableStmt -
3000 * transform an Alter Table Statement
3003 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
3004 List **extras_before, List **extras_after)
3006 CreateStmtContext cxt;
3010 List *newcmds = NIL;
3011 bool skipValidation = true;
3012 AlterTableCmd *newcmd;
3014 cxt.stmtType = "ALTER TABLE";
3015 cxt.relation = stmt->relation;
3016 cxt.inhRelations = NIL;
3018 cxt.hasoids = false; /* need not be right */
3020 cxt.ckconstraints = NIL;
3021 cxt.fkconstraints = NIL;
3022 cxt.ixconstraints = NIL;
3028 * The only subtypes that currently require parse transformation handling
3029 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
3032 foreach(lcmd, stmt->cmds)
3034 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3036 switch (cmd->subtype)
3040 ColumnDef *def = (ColumnDef *) cmd->def;
3042 Assert(IsA(cmd->def, ColumnDef));
3043 transformColumnDefinition(pstate, &cxt,
3044 (ColumnDef *) cmd->def);
3047 * If the column has a non-null default, we can't skip
3048 * validation of foreign keys.
3050 if (((ColumnDef *) cmd->def)->raw_default != NULL)
3051 skipValidation = false;
3053 newcmds = lappend(newcmds, cmd);
3056 * Convert an ADD COLUMN ... NOT NULL constraint to a
3059 if (def->is_not_null)
3061 /* Remove NOT NULL from AddColumn */
3062 def->is_not_null = false;
3064 /* Add as a separate AlterTableCmd */
3065 newcmd = makeNode(AlterTableCmd);
3066 newcmd->subtype = AT_SetNotNull;
3067 newcmd->name = pstrdup(def->colname);
3068 newcmds = lappend(newcmds, newcmd);
3072 * All constraints are processed in other ways. Remove the
3075 def->constraints = NIL;
3079 case AT_AddConstraint:
3082 * The original AddConstraint cmd node doesn't go to newcmds
3085 if (IsA(cmd->def, Constraint))
3086 transformTableConstraint(pstate, &cxt,
3087 (Constraint *) cmd->def);
3088 else if (IsA(cmd->def, FkConstraint))
3090 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
3091 skipValidation = false;
3094 elog(ERROR, "unrecognized node type: %d",
3095 (int) nodeTag(cmd->def));
3098 case AT_ProcessedConstraint:
3101 * Already-transformed ADD CONSTRAINT, so just make it look
3102 * like the standard case.
3104 cmd->subtype = AT_AddConstraint;
3105 newcmds = lappend(newcmds, cmd);
3109 newcmds = lappend(newcmds, cmd);
3115 * transformIndexConstraints wants cxt.alist to contain only index
3116 * statements, so transfer anything we already have into extras_after
3119 *extras_after = list_concat(cxt.alist, *extras_after);
3122 /* Postprocess index and FK constraints */
3123 transformIndexConstraints(pstate, &cxt);
3125 transformFKConstraints(pstate, &cxt, skipValidation, true);
3128 * Push any index-creation commands into the ALTER, so that they can be
3129 * scheduled nicely by tablecmds.c.
3131 foreach(l, cxt.alist)
3133 Node *idxstmt = (Node *) lfirst(l);
3135 Assert(IsA(idxstmt, IndexStmt));
3136 newcmd = makeNode(AlterTableCmd);
3137 newcmd->subtype = AT_AddIndex;
3138 newcmd->def = idxstmt;
3139 newcmds = lappend(newcmds, newcmd);
3143 /* Append any CHECK or FK constraints to the commands list */
3144 foreach(l, cxt.ckconstraints)
3146 newcmd = makeNode(AlterTableCmd);
3147 newcmd->subtype = AT_AddConstraint;
3148 newcmd->def = (Node *) lfirst(l);
3149 newcmds = lappend(newcmds, newcmd);
3151 foreach(l, cxt.fkconstraints)
3153 newcmd = makeNode(AlterTableCmd);
3154 newcmd->subtype = AT_AddConstraint;
3155 newcmd->def = (Node *) lfirst(l);
3156 newcmds = lappend(newcmds, newcmd);
3159 /* Update statement's commands list */
3160 stmt->cmds = newcmds;
3162 qry = makeNode(Query);
3163 qry->commandType = CMD_UTILITY;
3164 qry->utilityStmt = (Node *) stmt;
3166 *extras_before = list_concat(*extras_before, cxt.blist);
3167 *extras_after = list_concat(cxt.alist, *extras_after);
3173 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
3175 Query *result = makeNode(Query);
3176 List *extras_before = NIL,
3177 *extras_after = NIL;
3179 result->commandType = CMD_UTILITY;
3180 result->utilityStmt = (Node *) stmt;
3183 * Don't allow both SCROLL and NO SCROLL to be specified
3185 if ((stmt->options & CURSOR_OPT_SCROLL) &&
3186 (stmt->options & CURSOR_OPT_NO_SCROLL))
3188 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3189 errmsg("cannot specify both SCROLL and NO SCROLL")));
3191 stmt->query = (Node *) transformStmt(pstate, stmt->query,
3192 &extras_before, &extras_after);
3194 /* Shouldn't get any extras, since grammar only allows SelectStmt */
3195 if (extras_before || extras_after)
3196 elog(ERROR, "unexpected extra stuff in cursor statement");
3197 if (!IsA(stmt->query, Query) ||
3198 ((Query *) stmt->query)->commandType != CMD_SELECT)
3199 elog(ERROR, "unexpected non-SELECT command in cursor statement");
3201 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
3202 if (((Query *) stmt->query)->into)
3204 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3205 errmsg("DECLARE CURSOR may not specify INTO")));
3212 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
3214 Query *result = makeNode(Query);
3215 List *argtype_oids; /* argtype OIDs in a list */
3216 Oid *argtoids = NULL; /* and as an array */
3221 result->commandType = CMD_UTILITY;
3222 result->utilityStmt = (Node *) stmt;
3224 /* Transform list of TypeNames to list (and array) of type OIDs */
3225 nargs = list_length(stmt->argtypes);
3231 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
3234 foreach(l, stmt->argtypes)
3236 TypeName *tn = lfirst(l);
3237 Oid toid = typenameTypeId(pstate, tn);
3239 argtoids[i++] = toid;
3244 * Analyze the statement using these parameter types (any parameters
3245 * passed in from above us will not be visible to it), allowing
3246 * information about unknown parameters to be deduced from context.
3248 queries = parse_analyze_varparams((Node *) stmt->query,
3249 pstate->p_sourcetext,
3253 * Shouldn't get any extra statements, since grammar only allows
3256 if (list_length(queries) != 1)
3257 elog(ERROR, "unexpected extra stuff in prepared statement");
3260 * Check that all parameter types were determined, and convert the array
3261 * of OIDs into a list for storage.
3264 for (i = 0; i < nargs; i++)
3266 Oid argtype = argtoids[i];
3268 if (argtype == InvalidOid || argtype == UNKNOWNOID)
3270 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
3271 errmsg("could not determine data type of parameter $%d",
3274 argtype_oids = lappend_oid(argtype_oids, argtype);
3277 stmt->argtype_oids = argtype_oids;
3278 stmt->query = linitial(queries);
3283 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
3285 Query *result = makeNode(Query);
3288 result->commandType = CMD_UTILITY;
3289 result->utilityStmt = (Node *) stmt;
3291 paramtypes = FetchPreparedStatementParams(stmt->name);
3293 if (stmt->params || paramtypes)
3295 int nparams = list_length(stmt->params);
3296 int nexpected = list_length(paramtypes);
3301 if (nparams != nexpected)
3303 (errcode(ERRCODE_SYNTAX_ERROR),
3304 errmsg("wrong number of parameters for prepared statement \"%s\"",
3306 errdetail("Expected %d parameters but got %d.",
3307 nexpected, nparams)));
3309 forboth(l, stmt->params, l2, paramtypes)
3311 Node *expr = lfirst(l);
3312 Oid expected_type_id = lfirst_oid(l2);
3315 expr = transformExpr(pstate, expr);
3317 /* Cannot contain subselects or aggregates */
3318 if (pstate->p_hasSubLinks)
3320 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3321 errmsg("cannot use subquery in EXECUTE parameter")));
3322 if (pstate->p_hasAggs)
3324 (errcode(ERRCODE_GROUPING_ERROR),
3325 errmsg("cannot use aggregate function in EXECUTE parameter")));
3327 given_type_id = exprType(expr);
3329 expr = coerce_to_target_type(pstate, expr, given_type_id,
3330 expected_type_id, -1,
3331 COERCION_ASSIGNMENT,
3332 COERCE_IMPLICIT_CAST);
3336 (errcode(ERRCODE_DATATYPE_MISMATCH),
3337 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
3339 format_type_be(given_type_id),
3340 format_type_be(expected_type_id)),
3341 errhint("You will need to rewrite or cast the expression.")));
3351 /* exported so planner can check again after rewriting, query pullup, etc */
3353 CheckSelectLocking(Query *qry)
3355 if (qry->setOperations)
3357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3358 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
3359 if (qry->distinctClause != NIL)
3361 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3362 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
3363 if (qry->groupClause != NIL)
3365 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3366 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
3367 if (qry->havingQual != NULL)
3369 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3370 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
3373 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3374 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
3378 * Transform a FOR UPDATE/SHARE clause
3380 * This basically involves replacing names by integer relids.
3382 * NB: if you need to change this, see also markQueryForLocking()
3383 * in rewriteHandler.c.
3386 transformLockingClause(Query *qry, LockingClause *lc)
3388 List *lockedRels = lc->lockedRels;
3392 LockingClause *allrels;
3394 CheckSelectLocking(qry);
3396 /* make a clause we can pass down to subqueries to select all rels */
3397 allrels = makeNode(LockingClause);
3398 allrels->lockedRels = NIL; /* indicates all rels */
3399 allrels->forUpdate = lc->forUpdate;
3400 allrels->noWait = lc->noWait;
3402 if (lockedRels == NIL)
3404 /* all regular tables used in query */
3406 foreach(rt, qry->rtable)
3408 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3411 switch (rte->rtekind)
3414 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
3415 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3420 * FOR UPDATE/SHARE of subquery is propagated to all of
3423 transformLockingClause(rte->subquery, allrels);
3426 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
3433 /* just the named tables */
3434 foreach(l, lockedRels)
3436 char *relname = strVal(lfirst(l));
3439 foreach(rt, qry->rtable)
3441 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3444 if (strcmp(rte->eref->aliasname, relname) == 0)
3446 switch (rte->rtekind)
3449 applyLockingClause(qry, i,
3450 lc->forUpdate, lc->noWait);
3451 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3456 * FOR UPDATE/SHARE of subquery is propagated to
3457 * all of subquery's rels
3459 transformLockingClause(rte->subquery, allrels);
3463 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3464 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
3468 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3469 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
3473 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3474 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
3478 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3479 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
3482 elog(ERROR, "unrecognized RTE type: %d",
3483 (int) rte->rtekind);
3486 break; /* out of foreach loop */
3491 (errcode(ERRCODE_UNDEFINED_TABLE),
3492 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
3499 * Record locking info for a single rangetable item
3502 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
3506 /* Check for pre-existing entry for same rtindex */
3507 if ((rc = get_rowmark(qry, rtindex)) != NULL)
3510 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
3511 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
3512 * and exclusive lock at the same time; it'll end up being exclusive
3515 * We also consider that NOWAIT wins if it's specified both ways. This
3516 * is a bit more debatable but raising an error doesn't seem helpful.
3517 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
3518 * internally contains a plain FOR UPDATE spec.)
3520 rc->forUpdate |= forUpdate;
3521 rc->noWait |= noWait;
3525 /* Make a new RowMarkClause */
3526 rc = makeNode(RowMarkClause);
3528 rc->forUpdate = forUpdate;
3529 rc->noWait = noWait;
3530 qry->rowMarks = lappend(qry->rowMarks, rc);
3535 * Preprocess a list of column constraint clauses
3536 * to attach constraint attributes to their primary constraint nodes
3537 * and detect inconsistent/misplaced constraint attributes.
3539 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
3540 * constraints, but someday they ought to be supported for other constraints.
3543 transformConstraintAttrs(List *constraintList)
3545 Node *lastprimarynode = NULL;
3546 bool saw_deferrability = false;
3547 bool saw_initially = false;
3550 foreach(clist, constraintList)
3552 Node *node = lfirst(clist);
3554 if (!IsA(node, Constraint))
3556 lastprimarynode = node;
3557 /* reset flags for new primary node */
3558 saw_deferrability = false;
3559 saw_initially = false;
3563 Constraint *con = (Constraint *) node;
3565 switch (con->contype)
3567 case CONSTR_ATTR_DEFERRABLE:
3568 if (lastprimarynode == NULL ||
3569 !IsA(lastprimarynode, FkConstraint))
3571 (errcode(ERRCODE_SYNTAX_ERROR),
3572 errmsg("misplaced DEFERRABLE clause")));
3573 if (saw_deferrability)
3575 (errcode(ERRCODE_SYNTAX_ERROR),
3576 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3577 saw_deferrability = true;
3578 ((FkConstraint *) lastprimarynode)->deferrable = true;
3580 case CONSTR_ATTR_NOT_DEFERRABLE:
3581 if (lastprimarynode == NULL ||
3582 !IsA(lastprimarynode, FkConstraint))
3584 (errcode(ERRCODE_SYNTAX_ERROR),
3585 errmsg("misplaced NOT DEFERRABLE clause")));
3586 if (saw_deferrability)
3588 (errcode(ERRCODE_SYNTAX_ERROR),
3589 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3590 saw_deferrability = true;
3591 ((FkConstraint *) lastprimarynode)->deferrable = false;
3592 if (saw_initially &&
3593 ((FkConstraint *) lastprimarynode)->initdeferred)
3595 (errcode(ERRCODE_SYNTAX_ERROR),
3596 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3598 case CONSTR_ATTR_DEFERRED:
3599 if (lastprimarynode == NULL ||
3600 !IsA(lastprimarynode, FkConstraint))
3602 (errcode(ERRCODE_SYNTAX_ERROR),
3603 errmsg("misplaced INITIALLY DEFERRED clause")));
3606 (errcode(ERRCODE_SYNTAX_ERROR),
3607 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3608 saw_initially = true;
3609 ((FkConstraint *) lastprimarynode)->initdeferred = true;
3612 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3614 if (!saw_deferrability)
3615 ((FkConstraint *) lastprimarynode)->deferrable = true;
3616 else if (!((FkConstraint *) lastprimarynode)->deferrable)
3618 (errcode(ERRCODE_SYNTAX_ERROR),
3619 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3621 case CONSTR_ATTR_IMMEDIATE:
3622 if (lastprimarynode == NULL ||
3623 !IsA(lastprimarynode, FkConstraint))
3625 (errcode(ERRCODE_SYNTAX_ERROR),
3626 errmsg("misplaced INITIALLY IMMEDIATE clause")));
3629 (errcode(ERRCODE_SYNTAX_ERROR),
3630 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3631 saw_initially = true;
3632 ((FkConstraint *) lastprimarynode)->initdeferred = false;
3635 /* Otherwise it's not an attribute */
3636 lastprimarynode = node;
3637 /* reset flags for new primary node */
3638 saw_deferrability = false;
3639 saw_initially = false;
3646 /* Build a FromExpr node */
3648 makeFromExpr(List *fromlist, Node *quals)
3650 FromExpr *f = makeNode(FromExpr);
3652 f->fromlist = fromlist;
3658 * Special handling of type definition for a column
3661 transformColumnType(ParseState *pstate, ColumnDef *column)
3664 * All we really need to do here is verify that the type is valid.
3666 Type ctype = typenameType(pstate, column->typename);
3668 ReleaseSysCache(ctype);
3672 setSchemaName(char *context_schema, char **stmt_schema_name)
3674 if (*stmt_schema_name == NULL)
3675 *stmt_schema_name = context_schema;
3676 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3678 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3679 errmsg("CREATE specifies a schema (%s) "
3680 "different from the one being created (%s)",
3681 *stmt_schema_name, context_schema)));
3685 * analyzeCreateSchemaStmt -
3686 * analyzes the "create schema" statement
3688 * Split the schema element list into individual commands and place
3689 * them in the result list in an order such that there are no forward
3690 * references (e.g. GRANT to a table created later in the list). Note
3691 * that the logic we use for determining forward references is
3692 * presently quite incomplete.
3694 * SQL92 also allows constraints to make forward references, so thumb through
3695 * the table columns and move forward references to a posterior alter-table
3698 * The result is a list of parse nodes that still need to be analyzed ---
3699 * but we can't analyze the later commands until we've executed the earlier
3700 * ones, because of possible inter-object references.
3702 * Note: Called from commands/schemacmds.c
3705 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3707 CreateSchemaStmtContext cxt;
3711 cxt.stmtType = "CREATE SCHEMA";
3712 cxt.schemaname = stmt->schemaname;
3713 cxt.authid = stmt->authid;
3714 cxt.sequences = NIL;
3720 cxt.fwconstraints = NIL;
3726 * Run through each schema element in the schema element list. Separate
3727 * statements by type, and do preliminary analysis.
3729 foreach(elements, stmt->schemaElts)
3731 Node *element = lfirst(elements);
3733 switch (nodeTag(element))
3735 case T_CreateSeqStmt:
3737 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3739 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3740 cxt.sequences = lappend(cxt.sequences, element);
3746 CreateStmt *elp = (CreateStmt *) element;
3748 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3751 * XXX todo: deal with constraints
3753 cxt.tables = lappend(cxt.tables, element);
3759 ViewStmt *elp = (ViewStmt *) element;
3761 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3764 * XXX todo: deal with references between views
3766 cxt.views = lappend(cxt.views, element);
3772 IndexStmt *elp = (IndexStmt *) element;
3774 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3775 cxt.indexes = lappend(cxt.indexes, element);
3779 case T_CreateTrigStmt:
3781 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3783 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3784 cxt.triggers = lappend(cxt.triggers, element);
3789 cxt.grants = lappend(cxt.grants, element);
3793 elog(ERROR, "unrecognized node type: %d",
3794 (int) nodeTag(element));
3799 result = list_concat(result, cxt.sequences);
3800 result = list_concat(result, cxt.tables);
3801 result = list_concat(result, cxt.views);
3802 result = list_concat(result, cxt.indexes);
3803 result = list_concat(result, cxt.triggers);
3804 result = list_concat(result, cxt.grants);
3810 * Traverse a fully-analyzed tree to verify that parameter symbols
3811 * match their types. We need this because some Params might still
3812 * be UNKNOWN, if there wasn't anything to force their coercion,
3813 * and yet other instances seen later might have gotten coerced.
3816 check_parameter_resolution_walker(Node *node,
3817 check_parameter_resolution_context *context)
3821 if (IsA(node, Param))
3823 Param *param = (Param *) node;
3825 if (param->paramkind == PARAM_EXTERN)
3827 int paramno = param->paramid;
3829 if (paramno <= 0 || /* shouldn't happen, but... */
3830 paramno > context->numParams)
3832 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3833 errmsg("there is no parameter $%d", paramno)));
3835 if (param->paramtype != context->paramTypes[paramno - 1])
3837 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3838 errmsg("could not determine data type of parameter $%d",
3843 if (IsA(node, Query))
3845 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3846 return query_tree_walker((Query *) node,
3847 check_parameter_resolution_walker,
3848 (void *) context, 0);
3850 return expression_tree_walker(node, check_parameter_resolution_walker,