1 /*-------------------------------------------------------------------------
4 * transform the raw parse tree into a query tree
6 * For optimizable statements, we are careful to obtain a suitable lock on
7 * each referenced table, and other modules of the backend preserve or
8 * re-obtain these locks before depending on the results. It is therefore
9 * okay to do significant semantic analysis of these statements. For
10 * utility commands, no locks are obtained here (and if they were, we could
11 * not be sure we'd still have them at execution). Hence the general rule
12 * for utility commands is to just dump them into a Query node untransformed.
13 * parse_analyze does do some purely syntactic transformations on CREATE TABLE
14 * and ALTER TABLE, but that's about it. In cases where this module contains
15 * mechanisms that are useful for utility statements, we provide separate
16 * subroutines that should be called at the beginning of utility execution;
17 * an example is analyzeIndexStmt.
20 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
21 * Portions Copyright (c) 1994, Regents of the University of California
23 * $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.363 2007/04/27 22:05:48 tgl Exp $
25 *-------------------------------------------------------------------------
30 #include "access/heapam.h"
31 #include "catalog/heap.h"
32 #include "catalog/index.h"
33 #include "catalog/namespace.h"
34 #include "catalog/pg_type.h"
35 #include "commands/defrem.h"
36 #include "commands/prepare.h"
37 #include "commands/tablecmds.h"
38 #include "miscadmin.h"
39 #include "nodes/makefuncs.h"
40 #include "optimizer/clauses.h"
41 #include "optimizer/var.h"
42 #include "parser/analyze.h"
43 #include "parser/gramparse.h"
44 #include "parser/parse_agg.h"
45 #include "parser/parse_clause.h"
46 #include "parser/parse_coerce.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_expr.h"
49 #include "parser/parse_relation.h"
50 #include "parser/parse_target.h"
51 #include "parser/parse_type.h"
52 #include "parser/parsetree.h"
53 #include "rewrite/rewriteManip.h"
54 #include "utils/acl.h"
55 #include "utils/builtins.h"
56 #include "utils/lsyscache.h"
57 #include "utils/syscache.h"
60 /* State shared by transformCreateSchemaStmt and its subroutines */
63 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
64 char *schemaname; /* name of schema */
65 char *authid; /* owner of schema */
66 List *sequences; /* CREATE SEQUENCE items */
67 List *tables; /* CREATE TABLE items */
68 List *views; /* CREATE VIEW items */
69 List *indexes; /* CREATE INDEX items */
70 List *triggers; /* CREATE TRIGGER items */
71 List *grants; /* GRANT items */
72 List *fwconstraints; /* Forward referencing FOREIGN KEY constraints */
73 List *alters; /* Generated ALTER items (from the above) */
74 List *ixconstraints; /* index-creating constraints */
75 List *blist; /* "before list" of things to do before
76 * creating the schema */
77 List *alist; /* "after list" of things to do after creating
79 } CreateSchemaStmtContext;
81 /* State shared by transformCreateStmt and its subroutines */
84 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
85 RangeVar *relation; /* relation to create */
86 List *inhRelations; /* relations to inherit from */
87 bool hasoids; /* does relation have an OID column? */
88 bool isalter; /* true if altering existing table */
89 List *columns; /* ColumnDef items */
90 List *ckconstraints; /* CHECK constraints */
91 List *fkconstraints; /* FOREIGN KEY constraints */
92 List *ixconstraints; /* index-creating constraints */
93 List *blist; /* "before list" of things to do before
94 * creating the table */
95 List *alist; /* "after list" of things to do after creating
97 IndexStmt *pkey; /* PRIMARY KEY index, if any */
104 } check_parameter_resolution_context;
107 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
108 static Query *transformStmt(ParseState *pstate, Node *stmt,
109 List **extras_before, List **extras_after);
110 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
111 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
112 List **extras_before, List **extras_after);
113 static List *transformInsertRow(ParseState *pstate, List *exprlist,
114 List *stmtcols, List *icolumns, List *attrnos);
115 static List *transformReturningList(ParseState *pstate, List *returningList);
116 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
117 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
118 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
119 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
120 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
121 static Query *transformDeclareCursorStmt(ParseState *pstate,
122 DeclareCursorStmt *stmt);
123 static Query *transformExplainStmt(ParseState *pstate,
125 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
126 List **extras_before, List **extras_after);
127 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
128 List **extras_before, List **extras_after);
129 static void transformColumnDefinition(ParseState *pstate,
130 CreateStmtContext *cxt,
132 static void transformTableConstraint(ParseState *pstate,
133 CreateStmtContext *cxt,
134 Constraint *constraint);
135 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
136 InhRelation *inhrelation);
137 static void transformIndexConstraints(ParseState *pstate,
138 CreateStmtContext *cxt);
139 static void transformFKConstraints(ParseState *pstate,
140 CreateStmtContext *cxt,
142 bool isAddConstraint);
143 static void applyColumnNames(List *dst, List *src);
144 static void getSetColTypes(ParseState *pstate, Node *node,
145 List **colTypes, List **colTypmods);
146 static void transformLockingClause(Query *qry, LockingClause *lc);
147 static void transformConstraintAttrs(List *constraintList);
148 static void transformColumnType(ParseState *pstate, ColumnDef *column);
149 static void release_pstate_resources(ParseState *pstate);
150 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
151 static bool check_parameter_resolution_walker(Node *node,
152 check_parameter_resolution_context *context);
157 * Analyze a raw parse tree and transform it to Query form.
159 * If available, pass the source text from which the raw parse tree was
160 * generated; it's OK to pass NULL if this is not available.
162 * Optionally, information about $n parameter types can be supplied.
163 * References to $n indexes not defined by paramTypes[] are disallowed.
165 * The result is a List of Query nodes (we need a list since some commands
166 * produce multiple Queries). Optimizable statements require considerable
167 * transformation, while most utility-type statements are simply hung off
168 * a dummy CMD_UTILITY Query node.
171 parse_analyze(Node *parseTree, const char *sourceText,
172 Oid *paramTypes, int numParams)
174 ParseState *pstate = make_parsestate(NULL);
177 pstate->p_sourcetext = sourceText;
178 pstate->p_paramtypes = paramTypes;
179 pstate->p_numparams = numParams;
180 pstate->p_variableparams = false;
182 result = do_parse_analyze(parseTree, pstate);
190 * parse_analyze_varparams
192 * This variant is used when it's okay to deduce information about $n
193 * symbol datatypes from context. The passed-in paramTypes[] array can
194 * be modified or enlarged (via repalloc).
197 parse_analyze_varparams(Node *parseTree, const char *sourceText,
198 Oid **paramTypes, int *numParams)
200 ParseState *pstate = make_parsestate(NULL);
203 pstate->p_sourcetext = sourceText;
204 pstate->p_paramtypes = *paramTypes;
205 pstate->p_numparams = *numParams;
206 pstate->p_variableparams = true;
208 result = do_parse_analyze(parseTree, pstate);
210 *paramTypes = pstate->p_paramtypes;
211 *numParams = pstate->p_numparams;
215 /* make sure all is well with parameter types */
218 check_parameter_resolution_context context;
220 context.paramTypes = *paramTypes;
221 context.numParams = *numParams;
222 check_parameter_resolution_walker((Node *) result, &context);
230 * Entry point for recursively analyzing a sub-statement.
233 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
235 ParseState *pstate = make_parsestate(parentParseState);
238 result = do_parse_analyze(parseTree, pstate);
247 * Workhorse code shared by the above variants of parse_analyze.
250 do_parse_analyze(Node *parseTree, ParseState *pstate)
254 /* Lists to return extra commands from transformation */
255 List *extras_before = NIL;
256 List *extras_after = NIL;
260 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
262 /* don't need to access result relation any more */
263 release_pstate_resources(pstate);
265 foreach(l, extras_before)
266 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
268 result = lappend(result, query);
270 foreach(l, extras_after)
271 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
274 * Make sure that only the original query is marked original. We have to
275 * do this explicitly since recursive calls of do_parse_analyze will have
276 * marked some of the added-on queries as "original". Also mark only the
277 * original query as allowed to set the command-result tag.
281 Query *q = lfirst(l);
285 q->querySource = QSRC_ORIGINAL;
290 q->querySource = QSRC_PARSER;
291 q->canSetTag = false;
299 release_pstate_resources(ParseState *pstate)
301 if (pstate->p_target_relation != NULL)
302 heap_close(pstate->p_target_relation, NoLock);
303 pstate->p_target_relation = NULL;
304 pstate->p_target_rangetblentry = NULL;
309 * transform a Parse tree into a Query tree.
312 transformStmt(ParseState *pstate, Node *parseTree,
313 List **extras_before, List **extras_after)
315 Query *result = NULL;
317 switch (nodeTag(parseTree))
320 * Optimizable statements
323 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
324 extras_before, extras_after);
328 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
332 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
337 SelectStmt *n = (SelectStmt *) parseTree;
340 result = transformValuesClause(pstate, n);
341 else if (n->op == SETOP_NONE)
342 result = transformSelectStmt(pstate, n);
344 result = transformSetOperationStmt(pstate, n);
349 * Non-optimizable statements
352 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
353 extras_before, extras_after);
356 case T_AlterTableStmt:
357 result = transformAlterTableStmt(pstate,
358 (AlterTableStmt *) parseTree,
359 extras_before, extras_after);
365 case T_DeclareCursorStmt:
366 result = transformDeclareCursorStmt(pstate,
367 (DeclareCursorStmt *) parseTree);
371 result = transformExplainStmt(pstate,
372 (ExplainStmt *) parseTree);
378 * other statements don't require any transformation; just return
379 * the original parsetree with a Query node plastered on top.
381 result = makeNode(Query);
382 result->commandType = CMD_UTILITY;
383 result->utilityStmt = (Node *) parseTree;
387 /* Mark as original query until we learn differently */
388 result->querySource = QSRC_ORIGINAL;
389 result->canSetTag = true;
392 * Check that we did not produce too many resnos; at the very least we
393 * cannot allow more than 2^16, since that would exceed the range of a
394 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
396 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
398 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
399 errmsg("target lists can have at most %d entries",
400 MaxTupleAttributeNumber)));
406 * transformDeleteStmt -
407 * transforms a Delete Statement
410 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
412 Query *qry = makeNode(Query);
415 qry->commandType = CMD_DELETE;
417 /* set up range table with just the result rel */
418 qry->resultRelation = setTargetTable(pstate, stmt->relation,
419 interpretInhOption(stmt->relation->inhOpt),
423 qry->distinctClause = NIL;
426 * The USING clause is non-standard SQL syntax, and is equivalent in
427 * functionality to the FROM list that can be specified for UPDATE. The
428 * USING keyword is used rather than FROM because FROM is already a
429 * keyword in the DELETE syntax.
431 transformFromClause(pstate, stmt->usingClause);
433 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
435 qry->returningList = transformReturningList(pstate, stmt->returningList);
437 /* done building the range table and jointree */
438 qry->rtable = pstate->p_rtable;
439 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
441 qry->hasSubLinks = pstate->p_hasSubLinks;
442 qry->hasAggs = pstate->p_hasAggs;
443 if (pstate->p_hasAggs)
444 parseCheckAggregates(pstate, qry);
450 * transformInsertStmt -
451 * transform an Insert Statement
454 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
455 List **extras_before, List **extras_after)
457 Query *qry = makeNode(Query);
458 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
459 List *exprList = NIL;
460 bool isGeneralSelect;
462 List *sub_relnamespace;
463 List *sub_varnamespace;
472 qry->commandType = CMD_INSERT;
473 pstate->p_is_insert = true;
476 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
477 * VALUES list, or general SELECT input. We special-case VALUES, both for
478 * efficiency and so we can handle DEFAULT specifications.
480 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
483 * If a non-nil rangetable/namespace was passed in, and we are doing
484 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
485 * SELECT. This can only happen if we are inside a CREATE RULE, and in
486 * that case we want the rule's OLD and NEW rtable entries to appear as
487 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
488 * The SELECT's joinlist is not affected however. We must do this before
489 * adding the target table to the INSERT's rtable.
493 sub_rtable = pstate->p_rtable;
494 pstate->p_rtable = NIL;
495 sub_relnamespace = pstate->p_relnamespace;
496 pstate->p_relnamespace = NIL;
497 sub_varnamespace = pstate->p_varnamespace;
498 pstate->p_varnamespace = NIL;
502 sub_rtable = NIL; /* not used, but keep compiler quiet */
503 sub_relnamespace = NIL;
504 sub_varnamespace = NIL;
508 * Must get write lock on INSERT target table before scanning SELECT, else
509 * we will grab the wrong kind of initial lock if the target table is also
510 * mentioned in the SELECT part. Note that the target table is not added
511 * to the joinlist or namespace.
513 qry->resultRelation = setTargetTable(pstate, stmt->relation,
514 false, false, ACL_INSERT);
516 /* Validate stmt->cols list, or build default list if no list given */
517 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
518 Assert(list_length(icolumns) == list_length(attrnos));
521 * Determine which variant of INSERT we have.
523 if (selectStmt == NULL)
526 * We have INSERT ... DEFAULT VALUES. We can handle this case by
527 * emitting an empty targetlist --- all columns will be defaulted when
528 * the planner expands the targetlist.
532 else if (isGeneralSelect)
535 * We make the sub-pstate a child of the outer pstate so that it can
536 * see any Param definitions supplied from above. Since the outer
537 * pstate's rtable and namespace are presently empty, there are no
538 * side-effects of exposing names the sub-SELECT shouldn't be able to
541 ParseState *sub_pstate = make_parsestate(pstate);
545 * Process the source SELECT.
547 * It is important that this be handled just like a standalone SELECT;
548 * otherwise the behavior of SELECT within INSERT might be different
549 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
550 * bugs of just that nature...)
552 sub_pstate->p_rtable = sub_rtable;
553 sub_pstate->p_relnamespace = sub_relnamespace;
554 sub_pstate->p_varnamespace = sub_varnamespace;
557 * Note: we are not expecting that extras_before and extras_after are
558 * going to be used by the transformation of the SELECT statement.
560 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
561 extras_before, extras_after);
563 release_pstate_resources(sub_pstate);
566 /* The grammar should have produced a SELECT, but it might have INTO */
567 Assert(IsA(selectQuery, Query));
568 Assert(selectQuery->commandType == CMD_SELECT);
569 Assert(selectQuery->utilityStmt == NULL);
570 if (selectQuery->intoClause)
572 (errcode(ERRCODE_SYNTAX_ERROR),
573 errmsg("INSERT ... SELECT cannot specify INTO")));
576 * Make the source be a subquery in the INSERT's rangetable, and add
577 * it to the INSERT's joinlist.
579 rte = addRangeTableEntryForSubquery(pstate,
581 makeAlias("*SELECT*", NIL),
583 rtr = makeNode(RangeTblRef);
584 /* assume new rte is at end */
585 rtr->rtindex = list_length(pstate->p_rtable);
586 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
587 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
590 * Generate an expression list for the INSERT that selects all the
591 * non-resjunk columns from the subquery. (INSERT's tlist must be
592 * separate from the subquery's tlist because we may add columns,
593 * insert datatype coercions, etc.)
595 * HACK: unknown-type constants and params in the SELECT's targetlist
596 * are copied up as-is rather than being referenced as subquery
597 * outputs. This is to ensure that when we try to coerce them to
598 * the target column's datatype, the right things happen (see
599 * special cases in coerce_type). Otherwise, this fails:
600 * INSERT INTO foo SELECT 'bar', ... FROM baz
604 foreach(lc, selectQuery->targetList)
606 TargetEntry *tle = (TargetEntry *) lfirst(lc);
612 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
613 exprType((Node *) tle->expr) == UNKNOWNOID)
616 expr = (Expr *) makeVar(rtr->rtindex,
618 exprType((Node *) tle->expr),
619 exprTypmod((Node *) tle->expr),
621 exprList = lappend(exprList, expr);
624 /* Prepare row for assignment to target table */
625 exprList = transformInsertRow(pstate, exprList,
629 else if (list_length(selectStmt->valuesLists) > 1)
632 * Process INSERT ... VALUES with multiple VALUES sublists. We
633 * generate a VALUES RTE holding the transformed expression lists, and
634 * build up a targetlist containing Vars that reference the VALUES
637 List *exprsLists = NIL;
638 int sublist_length = -1;
640 foreach(lc, selectStmt->valuesLists)
642 List *sublist = (List *) lfirst(lc);
644 /* Do basic expression transformation (same as a ROW() expr) */
645 sublist = transformExpressionList(pstate, sublist);
648 * All the sublists must be the same length, *after*
649 * transformation (which might expand '*' into multiple items).
650 * The VALUES RTE can't handle anything different.
652 if (sublist_length < 0)
654 /* Remember post-transformation length of first sublist */
655 sublist_length = list_length(sublist);
657 else if (sublist_length != list_length(sublist))
660 (errcode(ERRCODE_SYNTAX_ERROR),
661 errmsg("VALUES lists must all be the same length")));
664 /* Prepare row for assignment to target table */
665 sublist = transformInsertRow(pstate, sublist,
669 exprsLists = lappend(exprsLists, sublist);
673 * There mustn't have been any table references in the expressions,
674 * else strange things would happen, like Cartesian products of those
675 * tables with the VALUES list ...
677 if (pstate->p_joinlist != NIL)
679 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
680 errmsg("VALUES must not contain table references")));
683 * Another thing we can't currently support is NEW/OLD references in
684 * rules --- seems we'd need something like SQL99's LATERAL construct
685 * to ensure that the values would be available while evaluating the
686 * VALUES RTE. This is a shame. FIXME
688 if (list_length(pstate->p_rtable) != 1 &&
689 contain_vars_of_level((Node *) exprsLists, 0))
691 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
692 errmsg("VALUES must not contain OLD or NEW references"),
693 errhint("Use SELECT ... UNION ALL ... instead.")));
696 * Generate the VALUES RTE
698 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
699 rtr = makeNode(RangeTblRef);
700 /* assume new rte is at end */
701 rtr->rtindex = list_length(pstate->p_rtable);
702 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
703 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
706 * Generate list of Vars referencing the RTE
708 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
713 * Process INSERT ... VALUES with a single VALUES sublist.
714 * We treat this separately for efficiency and for historical
715 * compatibility --- specifically, allowing table references,
717 * INSERT INTO foo VALUES(bar.*)
719 * The sublist is just computed directly as the Query's targetlist,
720 * with no VALUES RTE. So it works just like SELECT without FROM.
723 List *valuesLists = selectStmt->valuesLists;
725 Assert(list_length(valuesLists) == 1);
727 /* Do basic expression transformation (same as a ROW() expr) */
728 exprList = transformExpressionList(pstate,
729 (List *) linitial(valuesLists));
731 /* Prepare row for assignment to target table */
732 exprList = transformInsertRow(pstate, exprList,
738 * Generate query's target list using the computed list of expressions.
740 qry->targetList = NIL;
741 icols = list_head(icolumns);
742 attnos = list_head(attrnos);
743 foreach(lc, exprList)
745 Expr *expr = (Expr *) lfirst(lc);
749 col = (ResTarget *) lfirst(icols);
750 Assert(IsA(col, ResTarget));
752 tle = makeTargetEntry(expr,
753 (AttrNumber) lfirst_int(attnos),
756 qry->targetList = lappend(qry->targetList, tle);
758 icols = lnext(icols);
759 attnos = lnext(attnos);
763 * If we have a RETURNING clause, we need to add the target relation to
764 * the query namespace before processing it, so that Var references in
765 * RETURNING will work. Also, remove any namespace entries added in a
766 * sub-SELECT or VALUES list.
768 if (stmt->returningList)
770 pstate->p_relnamespace = NIL;
771 pstate->p_varnamespace = NIL;
772 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
774 qry->returningList = transformReturningList(pstate,
775 stmt->returningList);
778 /* done building the range table and jointree */
779 qry->rtable = pstate->p_rtable;
780 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
782 qry->hasSubLinks = pstate->p_hasSubLinks;
783 /* aggregates not allowed (but subselects are okay) */
784 if (pstate->p_hasAggs)
786 (errcode(ERRCODE_GROUPING_ERROR),
787 errmsg("cannot use aggregate function in VALUES")));
793 * Prepare an INSERT row for assignment to the target table.
795 * The row might be either a VALUES row, or variables referencing a
799 transformInsertRow(ParseState *pstate, List *exprlist,
800 List *stmtcols, List *icolumns, List *attrnos)
808 * Check length of expr list. It must not have more expressions than
809 * there are target columns. We allow fewer, but only if no explicit
810 * columns list was given (the remaining columns are implicitly
811 * defaulted). Note we must check this *after* transformation because
812 * that could expand '*' into multiple items.
814 if (list_length(exprlist) > list_length(icolumns))
816 (errcode(ERRCODE_SYNTAX_ERROR),
817 errmsg("INSERT has more expressions than target columns")));
818 if (stmtcols != NIL &&
819 list_length(exprlist) < list_length(icolumns))
821 (errcode(ERRCODE_SYNTAX_ERROR),
822 errmsg("INSERT has more target columns than expressions")));
825 * Prepare columns for assignment to target table.
828 icols = list_head(icolumns);
829 attnos = list_head(attrnos);
830 foreach(lc, exprlist)
832 Expr *expr = (Expr *) lfirst(lc);
835 col = (ResTarget *) lfirst(icols);
836 Assert(IsA(col, ResTarget));
838 expr = transformAssignedExpr(pstate, expr,
844 result = lappend(result, expr);
846 icols = lnext(icols);
847 attnos = lnext(attnos);
854 * transformCreateStmt -
855 * transforms the "create table" statement
856 * SQL92 allows constraints to be scattered all over, so thumb through
857 * the columns and collect all constraints into one place.
858 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
859 * then expand those into multiple IndexStmt blocks.
860 * - thomas 1997-12-02
863 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
864 List **extras_before, List **extras_after)
866 CreateStmtContext cxt;
870 cxt.stmtType = "CREATE TABLE";
871 cxt.relation = stmt->relation;
872 cxt.inhRelations = stmt->inhRelations;
875 cxt.ckconstraints = NIL;
876 cxt.fkconstraints = NIL;
877 cxt.ixconstraints = NIL;
881 cxt.hasoids = interpretOidsOption(stmt->options);
884 * Run through each primary element in the table creation clause. Separate
885 * column defs from constraints, and do preliminary analysis.
887 foreach(elements, stmt->tableElts)
889 Node *element = lfirst(elements);
891 switch (nodeTag(element))
894 transformColumnDefinition(pstate, &cxt,
895 (ColumnDef *) element);
899 transformTableConstraint(pstate, &cxt,
900 (Constraint *) element);
904 /* No pre-transformation needed */
905 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
909 transformInhRelation(pstate, &cxt,
910 (InhRelation *) element);
914 elog(ERROR, "unrecognized node type: %d",
915 (int) nodeTag(element));
921 * transformIndexConstraints wants cxt.alist to contain only index
922 * statements, so transfer anything we already have into extras_after
925 *extras_after = list_concat(cxt.alist, *extras_after);
928 Assert(stmt->constraints == NIL);
931 * Postprocess constraints that give rise to index definitions.
933 transformIndexConstraints(pstate, &cxt);
936 * Postprocess foreign-key constraints.
938 transformFKConstraints(pstate, &cxt, true, false);
944 q->commandType = CMD_UTILITY;
945 q->utilityStmt = (Node *) stmt;
946 stmt->tableElts = cxt.columns;
947 stmt->constraints = cxt.ckconstraints;
948 *extras_before = list_concat(*extras_before, cxt.blist);
949 *extras_after = list_concat(cxt.alist, *extras_after);
955 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
960 Constraint *constraint;
963 cxt->columns = lappend(cxt->columns, column);
965 /* Check for SERIAL pseudo-types */
967 if (list_length(column->typename->names) == 1)
969 char *typname = strVal(linitial(column->typename->names));
971 if (strcmp(typname, "serial") == 0 ||
972 strcmp(typname, "serial4") == 0)
975 column->typename->names = NIL;
976 column->typename->typeid = INT4OID;
978 else if (strcmp(typname, "bigserial") == 0 ||
979 strcmp(typname, "serial8") == 0)
982 column->typename->names = NIL;
983 column->typename->typeid = INT8OID;
987 /* Do necessary work on the column type declaration */
988 transformColumnType(pstate, column);
990 /* Special actions for SERIAL pseudo-types */
998 FuncCall *funccallnode;
999 CreateSeqStmt *seqstmt;
1000 AlterSeqStmt *altseqstmt;
1004 * Determine namespace and name to use for the sequence.
1006 * Although we use ChooseRelationName, it's not guaranteed that the
1007 * selected sequence name won't conflict; given sufficiently long
1008 * field names, two different serial columns in the same table could
1009 * be assigned the same sequence name, and we'd not notice since we
1010 * aren't creating the sequence quite yet. In practice this seems
1011 * quite unlikely to be a problem, especially since few people would
1012 * need two serial columns in one table.
1014 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
1015 snamespace = get_namespace_name(snamespaceid);
1016 sname = ChooseRelationName(cxt->relation->relname,
1022 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
1023 cxt->stmtType, sname,
1024 cxt->relation->relname, column->colname)));
1027 * Build a CREATE SEQUENCE command to create the sequence object, and
1028 * add it to the list of things to be done before this CREATE/ALTER
1031 seqstmt = makeNode(CreateSeqStmt);
1032 seqstmt->sequence = makeRangeVar(snamespace, sname);
1033 seqstmt->options = NIL;
1035 cxt->blist = lappend(cxt->blist, seqstmt);
1038 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
1039 * as owned by this column, and add it to the list of things to be
1040 * done after this CREATE/ALTER TABLE.
1042 altseqstmt = makeNode(AlterSeqStmt);
1043 altseqstmt->sequence = makeRangeVar(snamespace, sname);
1044 attnamelist = list_make3(makeString(snamespace),
1045 makeString(cxt->relation->relname),
1046 makeString(column->colname));
1047 altseqstmt->options = list_make1(makeDefElem("owned_by",
1048 (Node *) attnamelist));
1050 cxt->alist = lappend(cxt->alist, altseqstmt);
1053 * Create appropriate constraints for SERIAL. We do this in full,
1054 * rather than shortcutting, so that we will detect any conflicting
1055 * constraints the user wrote (like a different DEFAULT).
1057 * Create an expression tree representing the function call
1058 * nextval('sequencename'). We cannot reduce the raw tree to cooked
1059 * form until after the sequence is created, but there's no need to do
1062 qstring = quote_qualified_identifier(snamespace, sname);
1063 snamenode = makeNode(A_Const);
1064 snamenode->val.type = T_String;
1065 snamenode->val.val.str = qstring;
1066 snamenode->typename = SystemTypeName("regclass");
1067 funccallnode = makeNode(FuncCall);
1068 funccallnode->funcname = SystemFuncName("nextval");
1069 funccallnode->args = list_make1(snamenode);
1070 funccallnode->agg_star = false;
1071 funccallnode->agg_distinct = false;
1072 funccallnode->location = -1;
1074 constraint = makeNode(Constraint);
1075 constraint->contype = CONSTR_DEFAULT;
1076 constraint->raw_expr = (Node *) funccallnode;
1077 constraint->cooked_expr = NULL;
1078 constraint->keys = NIL;
1079 column->constraints = lappend(column->constraints, constraint);
1081 constraint = makeNode(Constraint);
1082 constraint->contype = CONSTR_NOTNULL;
1083 column->constraints = lappend(column->constraints, constraint);
1086 /* Process column constraints, if any... */
1087 transformConstraintAttrs(column->constraints);
1089 saw_nullable = false;
1091 foreach(clist, column->constraints)
1093 constraint = lfirst(clist);
1096 * If this column constraint is a FOREIGN KEY constraint, then we fill
1097 * in the current attribute's name and throw it into the list of FK
1098 * constraints to be processed later.
1100 if (IsA(constraint, FkConstraint))
1102 FkConstraint *fkconstraint = (FkConstraint *) constraint;
1104 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
1105 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
1109 Assert(IsA(constraint, Constraint));
1111 switch (constraint->contype)
1114 if (saw_nullable && column->is_not_null)
1116 (errcode(ERRCODE_SYNTAX_ERROR),
1117 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1118 column->colname, cxt->relation->relname)));
1119 column->is_not_null = FALSE;
1120 saw_nullable = true;
1123 case CONSTR_NOTNULL:
1124 if (saw_nullable && !column->is_not_null)
1126 (errcode(ERRCODE_SYNTAX_ERROR),
1127 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1128 column->colname, cxt->relation->relname)));
1129 column->is_not_null = TRUE;
1130 saw_nullable = true;
1133 case CONSTR_DEFAULT:
1134 if (column->raw_default != NULL)
1136 (errcode(ERRCODE_SYNTAX_ERROR),
1137 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
1138 column->colname, cxt->relation->relname)));
1139 column->raw_default = constraint->raw_expr;
1140 Assert(constraint->cooked_expr == NULL);
1143 case CONSTR_PRIMARY:
1145 if (constraint->keys == NIL)
1146 constraint->keys = list_make1(makeString(column->colname));
1147 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1151 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1154 case CONSTR_ATTR_DEFERRABLE:
1155 case CONSTR_ATTR_NOT_DEFERRABLE:
1156 case CONSTR_ATTR_DEFERRED:
1157 case CONSTR_ATTR_IMMEDIATE:
1158 /* transformConstraintAttrs took care of these */
1162 elog(ERROR, "unrecognized constraint type: %d",
1163 constraint->contype);
1170 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1171 Constraint *constraint)
1173 switch (constraint->contype)
1175 case CONSTR_PRIMARY:
1177 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1181 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1185 case CONSTR_NOTNULL:
1186 case CONSTR_DEFAULT:
1187 case CONSTR_ATTR_DEFERRABLE:
1188 case CONSTR_ATTR_NOT_DEFERRABLE:
1189 case CONSTR_ATTR_DEFERRED:
1190 case CONSTR_ATTR_IMMEDIATE:
1191 elog(ERROR, "invalid context for constraint type %d",
1192 constraint->contype);
1196 elog(ERROR, "unrecognized constraint type: %d",
1197 constraint->contype);
1203 * transformInhRelation
1205 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
1206 * column definitions which recreate the user defined column portions of
1209 * Note: because we do this at parse analysis time, any change in the
1210 * referenced table between parse analysis and execution won't be reflected
1211 * into the new table. Is this OK?
1214 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1215 InhRelation *inhRelation)
1217 AttrNumber parent_attno;
1219 TupleDesc tupleDesc;
1220 TupleConstr *constr;
1221 AclResult aclresult;
1222 bool including_defaults = false;
1223 bool including_constraints = false;
1224 bool including_indexes = false;
1227 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1229 if (relation->rd_rel->relkind != RELKIND_RELATION)
1231 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1232 errmsg("inherited relation \"%s\" is not a table",
1233 inhRelation->relation->relname)));
1236 * Check for SELECT privilages
1238 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1240 if (aclresult != ACLCHECK_OK)
1241 aclcheck_error(aclresult, ACL_KIND_CLASS,
1242 RelationGetRelationName(relation));
1244 tupleDesc = RelationGetDescr(relation);
1245 constr = tupleDesc->constr;
1247 foreach(elem, inhRelation->options)
1249 int option = lfirst_int(elem);
1253 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
1254 including_defaults = true;
1256 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
1257 including_defaults = false;
1259 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
1260 including_constraints = true;
1262 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
1263 including_constraints = false;
1265 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
1266 including_indexes = true;
1268 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
1269 including_indexes = false;
1272 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
1277 if (including_indexes)
1279 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1280 errmsg("LIKE INCLUDING INDEXES is not implemented")));
1283 * Insert the copied attributes into the cxt for the new table
1286 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1289 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1290 char *attributeName = NameStr(attribute->attname);
1294 * Ignore dropped columns in the parent.
1296 if (attribute->attisdropped)
1300 * Create a new column, which is marked as NOT inherited.
1302 * For constraints, ONLY the NOT NULL constraint is inherited by the
1303 * new column definition per SQL99.
1305 def = makeNode(ColumnDef);
1306 def->colname = pstrdup(attributeName);
1307 def->typename = makeTypeNameFromOid(attribute->atttypid,
1308 attribute->atttypmod);
1310 def->is_local = true;
1311 def->is_not_null = attribute->attnotnull;
1312 def->raw_default = NULL;
1313 def->cooked_default = NULL;
1314 def->constraints = NIL;
1317 * Add to column list
1319 cxt->columns = lappend(cxt->columns, def);
1322 * Copy default, if present and the default has been requested
1324 if (attribute->atthasdef && including_defaults)
1326 char *this_default = NULL;
1327 AttrDefault *attrdef;
1330 /* Find default in constraint structure */
1331 Assert(constr != NULL);
1332 attrdef = constr->defval;
1333 for (i = 0; i < constr->num_defval; i++)
1335 if (attrdef[i].adnum == parent_attno)
1337 this_default = attrdef[i].adbin;
1341 Assert(this_default != NULL);
1344 * If default expr could contain any vars, we'd need to fix 'em,
1345 * but it can't; so default is ready to apply to child.
1348 def->cooked_default = pstrdup(this_default);
1353 * Copy CHECK constraints if requested, being careful to adjust
1356 if (including_constraints && tupleDesc->constr)
1358 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
1361 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
1363 char *ccname = tupleDesc->constr->check[ccnum].ccname;
1364 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1365 Node *ccbin_node = stringToNode(ccbin);
1366 Constraint *n = makeNode(Constraint);
1368 change_varattnos_of_a_node(ccbin_node, attmap);
1370 n->contype = CONSTR_CHECK;
1371 n->name = pstrdup(ccname);
1373 n->cooked_expr = nodeToString(ccbin_node);
1374 n->indexspace = NULL;
1375 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
1380 * Close the parent rel, but keep our AccessShareLock on it until xact
1381 * commit. That will prevent someone else from deleting or ALTERing the
1382 * parent before the child is committed.
1384 heap_close(relation, NoLock);
1388 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1391 List *indexlist = NIL;
1396 * Run through the constraints that need to generate an index. For PRIMARY
1397 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1398 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1400 foreach(listptr, cxt->ixconstraints)
1402 Constraint *constraint = lfirst(listptr);
1406 Assert(IsA(constraint, Constraint));
1407 Assert((constraint->contype == CONSTR_PRIMARY)
1408 || (constraint->contype == CONSTR_UNIQUE));
1410 index = makeNode(IndexStmt);
1412 index->unique = true;
1413 index->primary = (constraint->contype == CONSTR_PRIMARY);
1416 if (cxt->pkey != NULL)
1418 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1419 errmsg("multiple primary keys for table \"%s\" are not allowed",
1420 cxt->relation->relname)));
1424 * In ALTER TABLE case, a primary index might already exist, but
1425 * DefineIndex will check for it.
1428 index->isconstraint = true;
1430 if (constraint->name != NULL)
1431 index->idxname = pstrdup(constraint->name);
1433 index->idxname = NULL; /* DefineIndex will choose name */
1435 index->relation = cxt->relation;
1436 index->accessMethod = DEFAULT_INDEX_TYPE;
1437 index->options = constraint->options;
1438 index->tableSpace = constraint->indexspace;
1439 index->indexParams = NIL;
1440 index->whereClause = NULL;
1441 index->concurrent = false;
1444 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1445 * index, also make sure they are NOT NULL, if possible. (Although we
1446 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1447 * more efficient to get it right the first time.)
1449 foreach(keys, constraint->keys)
1451 char *key = strVal(lfirst(keys));
1453 ColumnDef *column = NULL;
1456 foreach(columns, cxt->columns)
1458 column = (ColumnDef *) lfirst(columns);
1459 Assert(IsA(column, ColumnDef));
1460 if (strcmp(column->colname, key) == 0)
1468 /* found column in the new table; force it to be NOT NULL */
1469 if (constraint->contype == CONSTR_PRIMARY)
1470 column->is_not_null = TRUE;
1472 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1475 * column will be a system column in the new table, so accept
1476 * it. System columns can't ever be null, so no need to worry
1477 * about PRIMARY/NOT NULL constraint.
1481 else if (cxt->inhRelations)
1483 /* try inherited tables */
1486 foreach(inher, cxt->inhRelations)
1488 RangeVar *inh = (RangeVar *) lfirst(inher);
1492 Assert(IsA(inh, RangeVar));
1493 rel = heap_openrv(inh, AccessShareLock);
1494 if (rel->rd_rel->relkind != RELKIND_RELATION)
1496 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1497 errmsg("inherited relation \"%s\" is not a table",
1499 for (count = 0; count < rel->rd_att->natts; count++)
1501 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1502 char *inhname = NameStr(inhattr->attname);
1504 if (inhattr->attisdropped)
1506 if (strcmp(key, inhname) == 0)
1511 * We currently have no easy way to force an
1512 * inherited column to be NOT NULL at creation, if
1513 * its parent wasn't so already. We leave it to
1514 * DefineIndex to fix things up in this case.
1519 heap_close(rel, NoLock);
1526 * In the ALTER TABLE case, don't complain about index keys not
1527 * created in the command; they may well exist already.
1528 * DefineIndex will complain about them if not, and will also take
1529 * care of marking them NOT NULL.
1531 if (!found && !cxt->isalter)
1533 (errcode(ERRCODE_UNDEFINED_COLUMN),
1534 errmsg("column \"%s\" named in key does not exist",
1537 /* Check for PRIMARY KEY(foo, foo) */
1538 foreach(columns, index->indexParams)
1540 iparam = (IndexElem *) lfirst(columns);
1541 if (iparam->name && strcmp(key, iparam->name) == 0)
1545 (errcode(ERRCODE_DUPLICATE_COLUMN),
1546 errmsg("column \"%s\" appears twice in primary key constraint",
1550 (errcode(ERRCODE_DUPLICATE_COLUMN),
1551 errmsg("column \"%s\" appears twice in unique constraint",
1556 /* OK, add it to the index definition */
1557 iparam = makeNode(IndexElem);
1558 iparam->name = pstrdup(key);
1559 iparam->expr = NULL;
1560 iparam->opclass = NIL;
1561 iparam->ordering = SORTBY_DEFAULT;
1562 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1563 index->indexParams = lappend(index->indexParams, iparam);
1566 indexlist = lappend(indexlist, index);
1570 * Scan the index list and remove any redundant index specifications. This
1571 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1572 * strict reading of SQL92 would suggest raising an error instead, but
1573 * that strikes me as too anal-retentive. - tgl 2001-02-14
1575 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1576 * pre-existing indexes, too. However, that seems to risk race
1577 * conditions since we can't be sure the command will be executed
1580 Assert(cxt->alist == NIL);
1581 if (cxt->pkey != NULL)
1583 /* Make sure we keep the PKEY index in preference to others... */
1584 cxt->alist = list_make1(cxt->pkey);
1587 foreach(l, indexlist)
1594 /* if it's pkey, it's already in cxt->alist */
1595 if (index == cxt->pkey)
1598 foreach(k, cxt->alist)
1600 IndexStmt *priorindex = lfirst(k);
1602 if (equal(index->indexParams, priorindex->indexParams))
1605 * If the prior index is as yet unnamed, and this one is
1606 * named, then transfer the name to the prior index. This
1607 * ensures that if we have named and unnamed constraints,
1608 * we'll use (at least one of) the names for the index.
1610 if (priorindex->idxname == NULL)
1611 priorindex->idxname = index->idxname;
1618 cxt->alist = lappend(cxt->alist, index);
1623 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1624 bool skipValidation, bool isAddConstraint)
1628 if (cxt->fkconstraints == NIL)
1632 * If CREATE TABLE or adding a column with NULL default, we can safely
1633 * skip validation of the constraint.
1637 foreach(fkclist, cxt->fkconstraints)
1639 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1641 fkconstraint->skip_validation = true;
1646 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1647 * CONSTRAINT command to execute after the basic command is complete. (If
1648 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1649 * its own subcommand list.)
1651 * Note: the ADD CONSTRAINT command must also execute after any index
1652 * creation commands. Thus, this should run after
1653 * transformIndexConstraints, so that the CREATE INDEX commands are
1654 * already in cxt->alist.
1656 if (!isAddConstraint)
1658 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1660 alterstmt->relation = cxt->relation;
1661 alterstmt->cmds = NIL;
1662 alterstmt->relkind = OBJECT_TABLE;
1664 foreach(fkclist, cxt->fkconstraints)
1666 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1667 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1669 altercmd->subtype = AT_ProcessedConstraint;
1670 altercmd->name = NULL;
1671 altercmd->def = (Node *) fkconstraint;
1672 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1675 cxt->alist = lappend(cxt->alist, alterstmt);
1680 * analyzeIndexStmt - perform parse analysis for CREATE INDEX
1682 * Note that this has to be performed during execution not parse analysis, so
1683 * it's called by ProcessUtility. (Most other callers don't need to bother,
1684 * because this is a no-op for an index not using either index expressions or
1685 * a predicate expression.)
1688 analyzeIndexStmt(IndexStmt *stmt, const char *queryString)
1696 * We must not scribble on the passed-in IndexStmt, so copy it. (This
1697 * is overkill, but easy.)
1699 stmt = (IndexStmt *) copyObject(stmt);
1702 * Open the parent table with appropriate locking. We must do this
1703 * because addRangeTableEntry() would acquire only AccessShareLock,
1704 * leaving DefineIndex() needing to do a lock upgrade with consequent
1705 * risk of deadlock. Make sure this stays in sync with the type of
1706 * lock DefineIndex() wants.
1708 rel = heap_openrv(stmt->relation,
1709 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1712 pstate = make_parsestate(NULL);
1713 pstate->p_sourcetext = queryString;
1716 * Put the parent table into the rtable so that the expressions can
1717 * refer to its fields without qualification.
1719 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1721 /* no to join list, yes to namespaces */
1722 addRTEtoQuery(pstate, rte, false, true, true);
1724 /* take care of the where clause */
1725 if (stmt->whereClause)
1726 stmt->whereClause = transformWhereClause(pstate,
1730 /* take care of any index expressions */
1731 foreach(l, stmt->indexParams)
1733 IndexElem *ielem = (IndexElem *) lfirst(l);
1737 ielem->expr = transformExpr(pstate, ielem->expr);
1740 * We check only that the result type is legitimate; this is for
1741 * consistency with what transformWhereClause() checks for the
1742 * predicate. DefineIndex() will make more checks.
1744 if (expression_returns_set(ielem->expr))
1746 (errcode(ERRCODE_DATATYPE_MISMATCH),
1747 errmsg("index expression cannot return a set")));
1752 * Check that only the base rel is mentioned.
1754 if (list_length(pstate->p_rtable) != 1)
1756 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1757 errmsg("index expressions and predicates can refer only to the table being indexed")));
1759 release_pstate_resources(pstate);
1762 /* Close relation, but keep the lock */
1763 heap_close(rel, NoLock);
1771 * transform a Create Rule Statement. The action is a list of parse
1772 * trees which is transformed into a list of query trees, and we also
1773 * transform the WHERE clause if any.
1775 * Note that this has to be performed during execution not parse analysis,
1776 * so it's called by DefineRule. Also note that we must not scribble on
1777 * the passed-in RuleStmt, so we do copyObject() on the actions and WHERE
1781 analyzeRuleStmt(RuleStmt *stmt, const char *queryString,
1782 List **actions, Node **whereClause)
1786 RangeTblEntry *oldrte;
1787 RangeTblEntry *newrte;
1790 * To avoid deadlock, make sure the first thing we do is grab
1791 * AccessExclusiveLock on the target relation. This will be needed by
1792 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1795 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1798 pstate = make_parsestate(NULL);
1799 pstate->p_sourcetext = queryString;
1802 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1803 * Set up their RTEs in the main pstate for use in parsing the rule
1806 oldrte = addRangeTableEntryForRelation(pstate, rel,
1807 makeAlias("*OLD*", NIL),
1809 newrte = addRangeTableEntryForRelation(pstate, rel,
1810 makeAlias("*NEW*", NIL),
1812 /* Must override addRangeTableEntry's default access-check flags */
1813 oldrte->requiredPerms = 0;
1814 newrte->requiredPerms = 0;
1817 * They must be in the namespace too for lookup purposes, but only add the
1818 * one(s) that are relevant for the current kind of rule. In an UPDATE
1819 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1820 * there's no need to be so picky for INSERT & DELETE. We do not add them
1823 switch (stmt->event)
1826 addRTEtoQuery(pstate, oldrte, false, true, true);
1829 addRTEtoQuery(pstate, oldrte, false, true, true);
1830 addRTEtoQuery(pstate, newrte, false, true, true);
1833 addRTEtoQuery(pstate, newrte, false, true, true);
1836 addRTEtoQuery(pstate, oldrte, false, true, true);
1839 elog(ERROR, "unrecognized event type: %d",
1844 /* take care of the where clause */
1845 *whereClause = transformWhereClause(pstate,
1846 (Node *) copyObject(stmt->whereClause),
1849 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1851 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1852 errmsg("rule WHERE condition cannot contain references to other relations")));
1854 /* aggregates not allowed (but subselects are okay) */
1855 if (pstate->p_hasAggs)
1857 (errcode(ERRCODE_GROUPING_ERROR),
1858 errmsg("cannot use aggregate function in rule WHERE condition")));
1861 * 'instead nothing' rules with a qualification need a query rangetable so
1862 * the rewrite handler can add the negated rule qualification to the
1863 * original query. We create a query with the new command type CMD_NOTHING
1864 * here that is treated specially by the rewrite system.
1866 if (stmt->actions == NIL)
1868 Query *nothing_qry = makeNode(Query);
1870 nothing_qry->commandType = CMD_NOTHING;
1871 nothing_qry->rtable = pstate->p_rtable;
1872 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1874 *actions = list_make1(nothing_qry);
1879 List *newactions = NIL;
1882 * transform each statement, like parse_sub_analyze()
1884 foreach(l, stmt->actions)
1886 Node *action = (Node *) lfirst(l);
1887 ParseState *sub_pstate = make_parsestate(NULL);
1890 List *extras_before = NIL;
1891 List *extras_after = NIL;
1896 * Since outer ParseState isn't parent of inner, have to pass
1897 * down the query text by hand.
1899 sub_pstate->p_sourcetext = queryString;
1902 * Set up OLD/NEW in the rtable for this statement. The entries
1903 * are added only to relnamespace, not varnamespace, because we
1904 * don't want them to be referred to by unqualified field names
1905 * nor "*" in the rule actions. We decide later whether to put
1906 * them in the joinlist.
1908 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1909 makeAlias("*OLD*", NIL),
1911 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1912 makeAlias("*NEW*", NIL),
1914 oldrte->requiredPerms = 0;
1915 newrte->requiredPerms = 0;
1916 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1917 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1919 /* Transform the rule action statement */
1920 top_subqry = transformStmt(sub_pstate,
1921 (Node *) copyObject(action),
1922 &extras_before, &extras_after);
1925 * We cannot support utility-statement actions (eg NOTIFY) with
1926 * nonempty rule WHERE conditions, because there's no way to make
1927 * the utility action execute conditionally.
1929 if (top_subqry->commandType == CMD_UTILITY &&
1930 *whereClause != NULL)
1932 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1933 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1936 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1937 * into the SELECT, and that's what we need to look at. (Ugly
1938 * kluge ... try to fix this when we redesign querytrees.)
1940 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1943 * If the sub_qry is a setop, we cannot attach any qualifications
1944 * to it, because the planner won't notice them. This could
1945 * perhaps be relaxed someday, but for now, we may as well reject
1946 * such a rule immediately.
1948 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1950 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1951 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1954 * Validate action's use of OLD/NEW, qual too
1957 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1958 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1960 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1961 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1963 switch (stmt->event)
1968 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1969 errmsg("ON SELECT rule cannot use OLD")));
1972 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1973 errmsg("ON SELECT rule cannot use NEW")));
1981 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1982 errmsg("ON INSERT rule cannot use OLD")));
1987 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1988 errmsg("ON DELETE rule cannot use NEW")));
1991 elog(ERROR, "unrecognized event type: %d",
1997 * For efficiency's sake, add OLD to the rule action's jointree
1998 * only if it was actually referenced in the statement or qual.
2000 * For INSERT, NEW is not really a relation (only a reference to
2001 * the to-be-inserted tuple) and should never be added to the
2004 * For UPDATE, we treat NEW as being another kind of reference to
2005 * OLD, because it represents references to *transformed* tuples
2006 * of the existing relation. It would be wrong to enter NEW
2007 * separately in the jointree, since that would cause a double
2008 * join of the updated relation. It's also wrong to fail to make
2009 * a jointree entry if only NEW and not OLD is mentioned.
2011 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2014 * If sub_qry is a setop, manipulating its jointree will do no
2015 * good at all, because the jointree is dummy. (This should be
2016 * a can't-happen case because of prior tests.)
2018 if (sub_qry->setOperations != NULL)
2020 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2021 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2022 /* hack so we can use addRTEtoQuery() */
2023 sub_pstate->p_rtable = sub_qry->rtable;
2024 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2025 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2026 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2029 newactions = list_concat(newactions, extras_before);
2030 newactions = lappend(newactions, top_subqry);
2031 newactions = list_concat(newactions, extras_after);
2033 release_pstate_resources(sub_pstate);
2037 *actions = newactions;
2040 release_pstate_resources(pstate);
2043 /* Close relation, but keep the exclusive lock */
2044 heap_close(rel, NoLock);
2049 * transformSelectStmt -
2050 * transforms a Select Statement
2052 * Note: this is also used for DECLARE CURSOR statements.
2055 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
2057 Query *qry = makeNode(Query);
2061 qry->commandType = CMD_SELECT;
2063 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2064 pstate->p_locking_clause = stmt->lockingClause;
2066 /* process the FROM clause */
2067 transformFromClause(pstate, stmt->fromClause);
2069 /* transform targetlist */
2070 qry->targetList = transformTargetList(pstate, stmt->targetList);
2072 /* mark column origins */
2073 markTargetListOrigins(pstate, qry->targetList);
2075 /* transform WHERE */
2076 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2079 * Initial processing of HAVING clause is just like WHERE clause.
2081 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
2085 * Transform sorting/grouping stuff. Do ORDER BY first because both
2086 * transformGroupClause and transformDistinctClause need the results.
2088 qry->sortClause = transformSortClause(pstate,
2091 true /* fix unknowns */ );
2093 qry->groupClause = transformGroupClause(pstate,
2098 qry->distinctClause = transformDistinctClause(pstate,
2099 stmt->distinctClause,
2103 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2105 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2108 /* handle any SELECT INTO/CREATE TABLE AS spec */
2109 if (stmt->intoClause)
2111 qry->intoClause = stmt->intoClause;
2112 if (stmt->intoClause->colNames)
2113 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
2116 qry->rtable = pstate->p_rtable;
2117 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2119 qry->hasSubLinks = pstate->p_hasSubLinks;
2120 qry->hasAggs = pstate->p_hasAggs;
2121 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2122 parseCheckAggregates(pstate, qry);
2124 foreach(l, stmt->lockingClause)
2126 transformLockingClause(qry, (LockingClause *) lfirst(l));
2133 * transformValuesClause -
2134 * transforms a VALUES clause that's being used as a standalone SELECT
2136 * We build a Query containing a VALUES RTE, rather as if one had written
2137 * SELECT * FROM (VALUES ...)
2140 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
2142 Query *qry = makeNode(Query);
2143 List *exprsLists = NIL;
2144 List **coltype_lists = NULL;
2145 Oid *coltypes = NULL;
2146 int sublist_length = -1;
2147 List *newExprsLists;
2154 qry->commandType = CMD_SELECT;
2156 /* Most SELECT stuff doesn't apply in a VALUES clause */
2157 Assert(stmt->distinctClause == NIL);
2158 Assert(stmt->targetList == NIL);
2159 Assert(stmt->fromClause == NIL);
2160 Assert(stmt->whereClause == NULL);
2161 Assert(stmt->groupClause == NIL);
2162 Assert(stmt->havingClause == NULL);
2163 Assert(stmt->op == SETOP_NONE);
2166 * For each row of VALUES, transform the raw expressions and gather type
2167 * information. This is also a handy place to reject DEFAULT nodes, which
2168 * the grammar allows for simplicity.
2170 foreach(lc, stmt->valuesLists)
2172 List *sublist = (List *) lfirst(lc);
2174 /* Do basic expression transformation (same as a ROW() expr) */
2175 sublist = transformExpressionList(pstate, sublist);
2178 * All the sublists must be the same length, *after* transformation
2179 * (which might expand '*' into multiple items). The VALUES RTE can't
2180 * handle anything different.
2182 if (sublist_length < 0)
2184 /* Remember post-transformation length of first sublist */
2185 sublist_length = list_length(sublist);
2186 /* and allocate arrays for column-type info */
2187 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
2188 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
2190 else if (sublist_length != list_length(sublist))
2193 (errcode(ERRCODE_SYNTAX_ERROR),
2194 errmsg("VALUES lists must all be the same length")));
2197 exprsLists = lappend(exprsLists, sublist);
2200 foreach(lc2, sublist)
2202 Node *col = (Node *) lfirst(lc2);
2204 if (IsA(col, SetToDefault))
2206 (errcode(ERRCODE_SYNTAX_ERROR),
2207 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
2208 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
2214 * Now resolve the common types of the columns, and coerce everything to
2217 for (i = 0; i < sublist_length; i++)
2219 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
2222 newExprsLists = NIL;
2223 foreach(lc, exprsLists)
2225 List *sublist = (List *) lfirst(lc);
2226 List *newsublist = NIL;
2229 foreach(lc2, sublist)
2231 Node *col = (Node *) lfirst(lc2);
2233 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
2234 newsublist = lappend(newsublist, col);
2238 newExprsLists = lappend(newExprsLists, newsublist);
2242 * Generate the VALUES RTE
2244 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
2245 rtr = makeNode(RangeTblRef);
2246 /* assume new rte is at end */
2247 rtr->rtindex = list_length(pstate->p_rtable);
2248 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2249 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2250 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
2253 * Generate a targetlist as though expanding "*"
2255 Assert(pstate->p_next_resno == 1);
2256 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
2259 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2262 qry->sortClause = transformSortClause(pstate,
2265 true /* fix unknowns */ );
2267 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2269 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2272 if (stmt->lockingClause)
2274 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2275 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
2277 /* handle any CREATE TABLE AS spec */
2278 if (stmt->intoClause)
2280 qry->intoClause = stmt->intoClause;
2281 if (stmt->intoClause->colNames)
2282 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
2286 * There mustn't have been any table references in the expressions, else
2287 * strange things would happen, like Cartesian products of those tables
2288 * with the VALUES list. We have to check this after parsing ORDER BY et
2289 * al since those could insert more junk.
2291 if (list_length(pstate->p_joinlist) != 1)
2293 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2294 errmsg("VALUES must not contain table references")));
2297 * Another thing we can't currently support is NEW/OLD references in rules
2298 * --- seems we'd need something like SQL99's LATERAL construct to ensure
2299 * that the values would be available while evaluating the VALUES RTE.
2300 * This is a shame. FIXME
2302 if (list_length(pstate->p_rtable) != 1 &&
2303 contain_vars_of_level((Node *) newExprsLists, 0))
2305 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2306 errmsg("VALUES must not contain OLD or NEW references"),
2307 errhint("Use SELECT ... UNION ALL ... instead.")));
2309 qry->rtable = pstate->p_rtable;
2310 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2312 qry->hasSubLinks = pstate->p_hasSubLinks;
2313 /* aggregates not allowed (but subselects are okay) */
2314 if (pstate->p_hasAggs)
2316 (errcode(ERRCODE_GROUPING_ERROR),
2317 errmsg("cannot use aggregate function in VALUES")));
2323 * transformSetOperationsStmt -
2324 * transforms a set-operations tree
2326 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
2327 * structure to it. We must transform each leaf SELECT and build up a top-
2328 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
2329 * The tree of set operations is converted into the setOperations field of
2330 * the top-level Query.
2333 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
2335 Query *qry = makeNode(Query);
2336 SelectStmt *leftmostSelect;
2338 Query *leftmostQuery;
2339 SetOperationStmt *sostmt;
2340 List *intoColNames = NIL;
2344 List *lockingClause;
2346 ListCell *left_tlist,
2355 RangeTblEntry *jrte;
2358 qry->commandType = CMD_SELECT;
2361 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
2362 * and from the top-level node.
2364 leftmostSelect = stmt->larg;
2365 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2366 leftmostSelect = leftmostSelect->larg;
2367 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
2368 leftmostSelect->larg == NULL);
2369 if (leftmostSelect->intoClause)
2371 qry->intoClause = leftmostSelect->intoClause;
2372 intoColNames = leftmostSelect->intoClause->colNames;
2375 /* clear this to prevent complaints in transformSetOperationTree() */
2376 leftmostSelect->intoClause = NULL;
2379 * These are not one-time, exactly, but we want to process them here and
2380 * not let transformSetOperationTree() see them --- else it'll just
2381 * recurse right back here!
2383 sortClause = stmt->sortClause;
2384 limitOffset = stmt->limitOffset;
2385 limitCount = stmt->limitCount;
2386 lockingClause = stmt->lockingClause;
2388 stmt->sortClause = NIL;
2389 stmt->limitOffset = NULL;
2390 stmt->limitCount = NULL;
2391 stmt->lockingClause = NIL;
2393 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2396 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2397 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2400 * Recursively transform the components of the tree.
2402 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
2403 Assert(sostmt && IsA(sostmt, SetOperationStmt));
2404 qry->setOperations = (Node *) sostmt;
2407 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2409 node = sostmt->larg;
2410 while (node && IsA(node, SetOperationStmt))
2411 node = ((SetOperationStmt *) node)->larg;
2412 Assert(node && IsA(node, RangeTblRef));
2413 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2414 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2415 Assert(leftmostQuery != NULL);
2418 * Generate dummy targetlist for outer query using column names of
2419 * leftmost select and common datatypes of topmost set operation. Also
2420 * make lists of the dummy vars and their names for use in parsing ORDER
2423 * Note: we use leftmostRTI as the varno of the dummy variables. It
2424 * shouldn't matter too much which RT index they have, as long as they
2425 * have one that corresponds to a real RT entry; else funny things may
2426 * happen when the tree is mashed by rule rewriting.
2428 qry->targetList = NIL;
2431 left_tlist = list_head(leftmostQuery->targetList);
2433 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
2435 Oid colType = lfirst_oid(lct);
2436 int32 colTypmod = lfirst_int(lcm);
2437 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2442 Assert(!lefttle->resjunk);
2443 colName = pstrdup(lefttle->resname);
2444 expr = (Expr *) makeVar(leftmostRTI,
2449 tle = makeTargetEntry(expr,
2450 (AttrNumber) pstate->p_next_resno++,
2453 qry->targetList = lappend(qry->targetList, tle);
2454 targetvars = lappend(targetvars, expr);
2455 targetnames = lappend(targetnames, makeString(colName));
2456 left_tlist = lnext(left_tlist);
2460 * As a first step towards supporting sort clauses that are expressions
2461 * using the output columns, generate a varnamespace entry that makes the
2462 * output columns visible. A Join RTE node is handy for this, since we
2463 * can easily control the Vars generated upon matches.
2465 * Note: we don't yet do anything useful with such cases, but at least
2466 * "ORDER BY upper(foo)" will draw the right error message rather than
2469 jrte = addRangeTableEntryForJoin(NULL,
2476 sv_rtable = pstate->p_rtable;
2477 pstate->p_rtable = list_make1(jrte);
2479 sv_relnamespace = pstate->p_relnamespace;
2480 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2482 sv_varnamespace = pstate->p_varnamespace;
2483 pstate->p_varnamespace = list_make1(jrte);
2486 * For now, we don't support resjunk sort clauses on the output of a
2487 * setOperation tree --- you can only use the SQL92-spec options of
2488 * selecting an output column by name or number. Enforce by checking that
2489 * transformSortClause doesn't add any items to tlist.
2491 tllen = list_length(qry->targetList);
2493 qry->sortClause = transformSortClause(pstate,
2496 false /* no unknowns expected */ );
2498 pstate->p_rtable = sv_rtable;
2499 pstate->p_relnamespace = sv_relnamespace;
2500 pstate->p_varnamespace = sv_varnamespace;
2502 if (tllen != list_length(qry->targetList))
2504 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2505 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2506 errdetail("Only result column names can be used, not expressions or functions."),
2507 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
2509 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2511 qry->limitCount = transformLimitClause(pstate, limitCount,
2515 * Handle SELECT INTO/CREATE TABLE AS.
2517 * Any column names from CREATE TABLE AS need to be attached to both the
2518 * top level and the leftmost subquery. We do not do this earlier because
2519 * we do *not* want sortClause processing to be affected.
2523 applyColumnNames(qry->targetList, intoColNames);
2524 applyColumnNames(leftmostQuery->targetList, intoColNames);
2527 qry->rtable = pstate->p_rtable;
2528 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2530 qry->hasSubLinks = pstate->p_hasSubLinks;
2531 qry->hasAggs = pstate->p_hasAggs;
2532 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2533 parseCheckAggregates(pstate, qry);
2535 foreach(l, lockingClause)
2537 transformLockingClause(qry, (LockingClause *) lfirst(l));
2544 * transformSetOperationTree
2545 * Recursively transform leaves and internal nodes of a set-op tree
2548 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2552 Assert(stmt && IsA(stmt, SelectStmt));
2555 * Validity-check both leaf and internal SELECTs for disallowed ops.
2557 if (stmt->intoClause)
2559 (errcode(ERRCODE_SYNTAX_ERROR),
2560 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2561 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2562 if (stmt->lockingClause)
2564 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2565 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2568 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2569 * clauses attached, we need to treat it like a leaf node to generate an
2570 * independent sub-Query tree. Otherwise, it can be represented by a
2571 * SetOperationStmt node underneath the parent Query.
2573 if (stmt->op == SETOP_NONE)
2575 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2580 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2581 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2582 stmt->lockingClause)
2590 /* Process leaf SELECT */
2593 char selectName[32];
2598 * Transform SelectStmt into a Query.
2600 * Note: previously transformed sub-queries don't affect the parsing
2601 * of this sub-query, because they are not in the toplevel pstate's
2604 selectList = parse_sub_analyze((Node *) stmt, pstate);
2606 Assert(list_length(selectList) == 1);
2607 selectQuery = (Query *) linitial(selectList);
2608 Assert(IsA(selectQuery, Query));
2611 * Check for bogus references to Vars on the current query level (but
2612 * upper-level references are okay). Normally this can't happen
2613 * because the namespace will be empty, but it could happen if we are
2616 if (pstate->p_relnamespace || pstate->p_varnamespace)
2618 if (contain_vars_of_level((Node *) selectQuery, 1))
2620 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2621 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
2625 * Make the leaf query be a subquery in the top-level rangetable.
2627 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2628 list_length(pstate->p_rtable) + 1);
2629 rte = addRangeTableEntryForSubquery(pstate,
2631 makeAlias(selectName, NIL),
2635 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2637 rtr = makeNode(RangeTblRef);
2638 /* assume new rte is at end */
2639 rtr->rtindex = list_length(pstate->p_rtable);
2640 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2641 return (Node *) rtr;
2645 /* Process an internal node (set operation node) */
2646 SetOperationStmt *op = makeNode(SetOperationStmt);
2655 const char *context;
2657 context = (stmt->op == SETOP_UNION ? "UNION" :
2658 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2662 op->all = stmt->all;
2665 * Recursively transform the child nodes.
2667 op->larg = transformSetOperationTree(pstate, stmt->larg);
2668 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2671 * Verify that the two children have the same number of non-junk
2672 * columns, and determine the types of the merged output columns.
2674 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
2675 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
2676 if (list_length(lcoltypes) != list_length(rcoltypes))
2678 (errcode(ERRCODE_SYNTAX_ERROR),
2679 errmsg("each %s query must have the same number of columns",
2681 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
2682 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
2685 op->colTypmods = NIL;
2686 /* don't have a "foreach4", so chase two of the lists by hand */
2687 lcm = list_head(lcoltypmods);
2688 rcm = list_head(rcoltypmods);
2689 forboth(lct, lcoltypes, rct, rcoltypes)
2691 Oid lcoltype = lfirst_oid(lct);
2692 Oid rcoltype = lfirst_oid(rct);
2693 int32 lcoltypmod = lfirst_int(lcm);
2694 int32 rcoltypmod = lfirst_int(rcm);
2698 /* select common type, same as CASE et al */
2699 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2701 /* if same type and same typmod, use typmod; else default */
2702 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
2703 rescoltypmod = lcoltypmod;
2706 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2707 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2719 * Get output column types/typmods of an (already transformed) set-op node
2722 getSetColTypes(ParseState *pstate, Node *node,
2723 List **colTypes, List **colTypmods)
2727 if (IsA(node, RangeTblRef))
2729 RangeTblRef *rtr = (RangeTblRef *) node;
2730 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2731 Query *selectQuery = rte->subquery;
2734 Assert(selectQuery != NULL);
2735 /* Get types of non-junk columns */
2736 foreach(tl, selectQuery->targetList)
2738 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2742 *colTypes = lappend_oid(*colTypes,
2743 exprType((Node *) tle->expr));
2744 *colTypmods = lappend_int(*colTypmods,
2745 exprTypmod((Node *) tle->expr));
2748 else if (IsA(node, SetOperationStmt))
2750 SetOperationStmt *op = (SetOperationStmt *) node;
2752 /* Result already computed during transformation of node */
2753 Assert(op->colTypes != NIL);
2754 *colTypes = op->colTypes;
2755 *colTypmods = op->colTypmods;
2758 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2761 /* Attach column names from a ColumnDef list to a TargetEntry list */
2763 applyColumnNames(List *dst, List *src)
2768 src_item = list_head(src);
2770 foreach(dst_item, dst)
2772 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2775 /* junk targets don't count */
2779 /* fewer ColumnDefs than target entries is OK */
2780 if (src_item == NULL)
2783 s = (ColumnDef *) lfirst(src_item);
2784 src_item = lnext(src_item);
2786 d->resname = pstrdup(s->colname);
2789 /* more ColumnDefs than target entries is not OK */
2790 if (src_item != NULL)
2792 (errcode(ERRCODE_SYNTAX_ERROR),
2793 errmsg("CREATE TABLE AS specifies too many column names")));
2798 * transformUpdateStmt -
2799 * transforms an update statement
2802 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2804 Query *qry = makeNode(Query);
2806 ListCell *origTargetList;
2809 qry->commandType = CMD_UPDATE;
2810 pstate->p_is_update = true;
2812 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2813 interpretInhOption(stmt->relation->inhOpt),
2818 * the FROM clause is non-standard SQL syntax. We used to be able to do
2819 * this with REPLACE in POSTQUEL so we keep the feature.
2821 transformFromClause(pstate, stmt->fromClause);
2823 qry->targetList = transformTargetList(pstate, stmt->targetList);
2825 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2827 qry->returningList = transformReturningList(pstate, stmt->returningList);
2829 qry->rtable = pstate->p_rtable;
2830 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2832 qry->hasSubLinks = pstate->p_hasSubLinks;
2835 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
2836 * an implementation point of view, this is forced because the implicit
2837 * ctid reference would otherwise be an ungrouped variable.)
2839 if (pstate->p_hasAggs)
2841 (errcode(ERRCODE_GROUPING_ERROR),
2842 errmsg("cannot use aggregate function in UPDATE")));
2845 * Now we are done with SELECT-like processing, and can get on with
2846 * transforming the target list to match the UPDATE target columns.
2849 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2850 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2851 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2853 /* Prepare non-junk columns for assignment to target table */
2854 origTargetList = list_head(stmt->targetList);
2856 foreach(tl, qry->targetList)
2858 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2859 ResTarget *origTarget;
2865 * Resjunk nodes need no additional processing, but be sure they
2866 * have resnos that do not match any target columns; else rewriter
2867 * or planner might get confused. They don't need a resname
2870 tle->resno = (AttrNumber) pstate->p_next_resno++;
2871 tle->resname = NULL;
2874 if (origTargetList == NULL)
2875 elog(ERROR, "UPDATE target count mismatch --- internal error");
2876 origTarget = (ResTarget *) lfirst(origTargetList);
2877 Assert(IsA(origTarget, ResTarget));
2879 attrno = attnameAttNum(pstate->p_target_relation,
2880 origTarget->name, true);
2881 if (attrno == InvalidAttrNumber)
2883 (errcode(ERRCODE_UNDEFINED_COLUMN),
2884 errmsg("column \"%s\" of relation \"%s\" does not exist",
2886 RelationGetRelationName(pstate->p_target_relation)),
2887 parser_errposition(pstate, origTarget->location)));
2889 updateTargetListEntry(pstate, tle, origTarget->name,
2891 origTarget->indirection,
2892 origTarget->location);
2894 origTargetList = lnext(origTargetList);
2896 if (origTargetList != NULL)
2897 elog(ERROR, "UPDATE target count mismatch --- internal error");
2903 * transformReturningList -
2904 * handle a RETURNING clause in INSERT/UPDATE/DELETE
2907 transformReturningList(ParseState *pstate, List *returningList)
2910 int save_next_resno;
2914 if (returningList == NIL)
2915 return NIL; /* nothing to do */
2918 * We need to assign resnos starting at one in the RETURNING list. Save
2919 * and restore the main tlist's value of p_next_resno, just in case
2920 * someone looks at it later (probably won't happen).
2922 save_next_resno = pstate->p_next_resno;
2923 pstate->p_next_resno = 1;
2925 /* save other state so that we can detect disallowed stuff */
2926 save_hasAggs = pstate->p_hasAggs;
2927 pstate->p_hasAggs = false;
2928 length_rtable = list_length(pstate->p_rtable);
2930 /* transform RETURNING identically to a SELECT targetlist */
2931 rlist = transformTargetList(pstate, returningList);
2933 /* check for disallowed stuff */
2935 /* aggregates not allowed (but subselects are okay) */
2936 if (pstate->p_hasAggs)
2938 (errcode(ERRCODE_GROUPING_ERROR),
2939 errmsg("cannot use aggregate function in RETURNING")));
2941 /* no new relation references please */
2942 if (list_length(pstate->p_rtable) != length_rtable)
2944 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2945 errmsg("RETURNING cannot contain references to other relations")));
2947 /* mark column origins */
2948 markTargetListOrigins(pstate, rlist);
2951 pstate->p_next_resno = save_next_resno;
2952 pstate->p_hasAggs = save_hasAggs;
2958 * transformAlterTableStmt -
2959 * transform an Alter Table Statement
2961 * CAUTION: resist the temptation to do any work here that depends on the
2962 * current state of the table. Actual execution of the command might not
2963 * occur till some future transaction. Hence, we do only purely syntactic
2964 * transformations here, comparable to the processing of CREATE TABLE.
2967 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2968 List **extras_before, List **extras_after)
2970 CreateStmtContext cxt;
2974 List *newcmds = NIL;
2975 bool skipValidation = true;
2976 AlterTableCmd *newcmd;
2978 cxt.stmtType = "ALTER TABLE";
2979 cxt.relation = stmt->relation;
2980 cxt.inhRelations = NIL;
2982 cxt.hasoids = false; /* need not be right */
2984 cxt.ckconstraints = NIL;
2985 cxt.fkconstraints = NIL;
2986 cxt.ixconstraints = NIL;
2992 * The only subtypes that currently require parse transformation handling
2993 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2996 foreach(lcmd, stmt->cmds)
2998 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3000 switch (cmd->subtype)
3004 ColumnDef *def = (ColumnDef *) cmd->def;
3006 Assert(IsA(cmd->def, ColumnDef));
3007 transformColumnDefinition(pstate, &cxt,
3008 (ColumnDef *) cmd->def);
3011 * If the column has a non-null default, we can't skip
3012 * validation of foreign keys.
3014 if (((ColumnDef *) cmd->def)->raw_default != NULL)
3015 skipValidation = false;
3017 newcmds = lappend(newcmds, cmd);
3020 * Convert an ADD COLUMN ... NOT NULL constraint to a
3023 if (def->is_not_null)
3025 /* Remove NOT NULL from AddColumn */
3026 def->is_not_null = false;
3028 /* Add as a separate AlterTableCmd */
3029 newcmd = makeNode(AlterTableCmd);
3030 newcmd->subtype = AT_SetNotNull;
3031 newcmd->name = pstrdup(def->colname);
3032 newcmds = lappend(newcmds, newcmd);
3036 * All constraints are processed in other ways. Remove the
3039 def->constraints = NIL;
3043 case AT_AddConstraint:
3046 * The original AddConstraint cmd node doesn't go to newcmds
3049 if (IsA(cmd->def, Constraint))
3050 transformTableConstraint(pstate, &cxt,
3051 (Constraint *) cmd->def);
3052 else if (IsA(cmd->def, FkConstraint))
3054 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
3055 skipValidation = false;
3058 elog(ERROR, "unrecognized node type: %d",
3059 (int) nodeTag(cmd->def));
3062 case AT_ProcessedConstraint:
3065 * Already-transformed ADD CONSTRAINT, so just make it look
3066 * like the standard case.
3068 cmd->subtype = AT_AddConstraint;
3069 newcmds = lappend(newcmds, cmd);
3073 newcmds = lappend(newcmds, cmd);
3079 * transformIndexConstraints wants cxt.alist to contain only index
3080 * statements, so transfer anything we already have into extras_after
3083 *extras_after = list_concat(cxt.alist, *extras_after);
3086 /* Postprocess index and FK constraints */
3087 transformIndexConstraints(pstate, &cxt);
3089 transformFKConstraints(pstate, &cxt, skipValidation, true);
3092 * Push any index-creation commands into the ALTER, so that they can be
3093 * scheduled nicely by tablecmds.c.
3095 foreach(l, cxt.alist)
3097 Node *idxstmt = (Node *) lfirst(l);
3099 Assert(IsA(idxstmt, IndexStmt));
3100 newcmd = makeNode(AlterTableCmd);
3101 newcmd->subtype = AT_AddIndex;
3102 newcmd->def = idxstmt;
3103 newcmds = lappend(newcmds, newcmd);
3107 /* Append any CHECK or FK constraints to the commands list */
3108 foreach(l, cxt.ckconstraints)
3110 newcmd = makeNode(AlterTableCmd);
3111 newcmd->subtype = AT_AddConstraint;
3112 newcmd->def = (Node *) lfirst(l);
3113 newcmds = lappend(newcmds, newcmd);
3115 foreach(l, cxt.fkconstraints)
3117 newcmd = makeNode(AlterTableCmd);
3118 newcmd->subtype = AT_AddConstraint;
3119 newcmd->def = (Node *) lfirst(l);
3120 newcmds = lappend(newcmds, newcmd);
3123 /* Update statement's commands list */
3124 stmt->cmds = newcmds;
3126 qry = makeNode(Query);
3127 qry->commandType = CMD_UTILITY;
3128 qry->utilityStmt = (Node *) stmt;
3130 *extras_before = list_concat(*extras_before, cxt.blist);
3131 *extras_after = list_concat(cxt.alist, *extras_after);
3138 * transformDeclareCursorStmt -
3139 * transform a DECLARE CURSOR Statement
3141 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
3142 * significantly different from a SELECT) as far as parsing/rewriting/planning
3143 * are concerned, but it's not passed to the executor and so in that sense is
3144 * a utility statement. We transform it into a Query exactly as if it were
3145 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
3146 * field to carry the cursor name and options.
3149 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
3152 List *extras_before = NIL,
3153 *extras_after = NIL;
3156 * Don't allow both SCROLL and NO SCROLL to be specified
3158 if ((stmt->options & CURSOR_OPT_SCROLL) &&
3159 (stmt->options & CURSOR_OPT_NO_SCROLL))
3161 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3162 errmsg("cannot specify both SCROLL and NO SCROLL")));
3164 result = transformStmt(pstate, stmt->query,
3165 &extras_before, &extras_after);
3167 /* Shouldn't get any extras, since grammar only allows SelectStmt */
3168 if (extras_before || extras_after)
3169 elog(ERROR, "unexpected extra stuff in cursor statement");
3170 if (!IsA(result, Query) ||
3171 result->commandType != CMD_SELECT ||
3172 result->utilityStmt != NULL)
3173 elog(ERROR, "unexpected non-SELECT command in cursor statement");
3175 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
3176 if (result->intoClause)
3178 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3179 errmsg("DECLARE CURSOR cannot specify INTO")));
3181 /* Implementation restriction (might go away someday) */
3182 if (result->rowMarks != NIL)
3184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3185 errmsg("DECLARE CURSOR ... FOR UPDATE/SHARE is not supported"),
3186 errdetail("Cursors must be READ ONLY.")));
3188 /* We won't need the raw querytree any more */
3191 result->utilityStmt = (Node *) stmt;
3198 * transformExplainStmt -
3199 * transform an EXPLAIN Statement
3201 * EXPLAIN is just like other utility statements in that we emit it as a
3202 * CMD_UTILITY Query node with no transformation of the raw parse tree.
3203 * However, if p_variableparams is set, it could be that the client is
3204 * expecting us to resolve parameter types in something like
3205 * EXPLAIN SELECT * FROM tab WHERE col = $1
3206 * To deal with such cases, we run parse analysis and throw away the result;
3207 * this is a bit grotty but not worth contorting the rest of the system for.
3208 * (The approach we use for DECLARE CURSOR won't work because the statement
3209 * being explained isn't necessarily a SELECT, and in particular might rewrite
3210 * to multiple parsetrees.)
3213 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
3217 if (pstate->p_variableparams)
3219 List *extras_before = NIL,
3220 *extras_after = NIL;
3222 /* Since parse analysis scribbles on its input, copy the tree first! */
3223 (void) transformStmt(pstate, copyObject(stmt->query),
3224 &extras_before, &extras_after);
3227 /* Now return the untransformed command as a utility Query */
3228 result = makeNode(Query);
3229 result->commandType = CMD_UTILITY;
3230 result->utilityStmt = (Node *) stmt;
3236 /* exported so planner can check again after rewriting, query pullup, etc */
3238 CheckSelectLocking(Query *qry)
3240 if (qry->setOperations)
3242 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3243 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
3244 if (qry->distinctClause != NIL)
3246 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3247 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
3248 if (qry->groupClause != NIL)
3250 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3251 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
3252 if (qry->havingQual != NULL)
3254 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3255 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
3258 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3259 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
3263 * Transform a FOR UPDATE/SHARE clause
3265 * This basically involves replacing names by integer relids.
3267 * NB: if you need to change this, see also markQueryForLocking()
3268 * in rewriteHandler.c.
3271 transformLockingClause(Query *qry, LockingClause *lc)
3273 List *lockedRels = lc->lockedRels;
3277 LockingClause *allrels;
3279 CheckSelectLocking(qry);
3281 /* make a clause we can pass down to subqueries to select all rels */
3282 allrels = makeNode(LockingClause);
3283 allrels->lockedRels = NIL; /* indicates all rels */
3284 allrels->forUpdate = lc->forUpdate;
3285 allrels->noWait = lc->noWait;
3287 if (lockedRels == NIL)
3289 /* all regular tables used in query */
3291 foreach(rt, qry->rtable)
3293 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3296 switch (rte->rtekind)
3299 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
3300 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3305 * FOR UPDATE/SHARE of subquery is propagated to all of
3308 transformLockingClause(rte->subquery, allrels);
3311 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
3318 /* just the named tables */
3319 foreach(l, lockedRels)
3321 char *relname = strVal(lfirst(l));
3324 foreach(rt, qry->rtable)
3326 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3329 if (strcmp(rte->eref->aliasname, relname) == 0)
3331 switch (rte->rtekind)
3334 applyLockingClause(qry, i,
3335 lc->forUpdate, lc->noWait);
3336 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3341 * FOR UPDATE/SHARE of subquery is propagated to
3342 * all of subquery's rels
3344 transformLockingClause(rte->subquery, allrels);
3348 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3349 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
3353 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3354 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
3358 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3359 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
3363 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
3367 elog(ERROR, "unrecognized RTE type: %d",
3368 (int) rte->rtekind);
3371 break; /* out of foreach loop */
3376 (errcode(ERRCODE_UNDEFINED_TABLE),
3377 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
3384 * Record locking info for a single rangetable item
3387 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
3391 /* Check for pre-existing entry for same rtindex */
3392 if ((rc = get_rowmark(qry, rtindex)) != NULL)
3395 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
3396 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
3397 * and exclusive lock at the same time; it'll end up being exclusive
3400 * We also consider that NOWAIT wins if it's specified both ways. This
3401 * is a bit more debatable but raising an error doesn't seem helpful.
3402 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
3403 * internally contains a plain FOR UPDATE spec.)
3405 rc->forUpdate |= forUpdate;
3406 rc->noWait |= noWait;
3410 /* Make a new RowMarkClause */
3411 rc = makeNode(RowMarkClause);
3413 rc->forUpdate = forUpdate;
3414 rc->noWait = noWait;
3415 qry->rowMarks = lappend(qry->rowMarks, rc);
3420 * Preprocess a list of column constraint clauses
3421 * to attach constraint attributes to their primary constraint nodes
3422 * and detect inconsistent/misplaced constraint attributes.
3424 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
3425 * constraints, but someday they ought to be supported for other constraints.
3428 transformConstraintAttrs(List *constraintList)
3430 Node *lastprimarynode = NULL;
3431 bool saw_deferrability = false;
3432 bool saw_initially = false;
3435 foreach(clist, constraintList)
3437 Node *node = lfirst(clist);
3439 if (!IsA(node, Constraint))
3441 lastprimarynode = node;
3442 /* reset flags for new primary node */
3443 saw_deferrability = false;
3444 saw_initially = false;
3448 Constraint *con = (Constraint *) node;
3450 switch (con->contype)
3452 case CONSTR_ATTR_DEFERRABLE:
3453 if (lastprimarynode == NULL ||
3454 !IsA(lastprimarynode, FkConstraint))
3456 (errcode(ERRCODE_SYNTAX_ERROR),
3457 errmsg("misplaced DEFERRABLE clause")));
3458 if (saw_deferrability)
3460 (errcode(ERRCODE_SYNTAX_ERROR),
3461 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3462 saw_deferrability = true;
3463 ((FkConstraint *) lastprimarynode)->deferrable = true;
3465 case CONSTR_ATTR_NOT_DEFERRABLE:
3466 if (lastprimarynode == NULL ||
3467 !IsA(lastprimarynode, FkConstraint))
3469 (errcode(ERRCODE_SYNTAX_ERROR),
3470 errmsg("misplaced NOT DEFERRABLE clause")));
3471 if (saw_deferrability)
3473 (errcode(ERRCODE_SYNTAX_ERROR),
3474 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3475 saw_deferrability = true;
3476 ((FkConstraint *) lastprimarynode)->deferrable = false;
3477 if (saw_initially &&
3478 ((FkConstraint *) lastprimarynode)->initdeferred)
3480 (errcode(ERRCODE_SYNTAX_ERROR),
3481 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3483 case CONSTR_ATTR_DEFERRED:
3484 if (lastprimarynode == NULL ||
3485 !IsA(lastprimarynode, FkConstraint))
3487 (errcode(ERRCODE_SYNTAX_ERROR),
3488 errmsg("misplaced INITIALLY DEFERRED clause")));
3491 (errcode(ERRCODE_SYNTAX_ERROR),
3492 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3493 saw_initially = true;
3494 ((FkConstraint *) lastprimarynode)->initdeferred = true;
3497 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3499 if (!saw_deferrability)
3500 ((FkConstraint *) lastprimarynode)->deferrable = true;
3501 else if (!((FkConstraint *) lastprimarynode)->deferrable)
3503 (errcode(ERRCODE_SYNTAX_ERROR),
3504 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3506 case CONSTR_ATTR_IMMEDIATE:
3507 if (lastprimarynode == NULL ||
3508 !IsA(lastprimarynode, FkConstraint))
3510 (errcode(ERRCODE_SYNTAX_ERROR),
3511 errmsg("misplaced INITIALLY IMMEDIATE clause")));
3514 (errcode(ERRCODE_SYNTAX_ERROR),
3515 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3516 saw_initially = true;
3517 ((FkConstraint *) lastprimarynode)->initdeferred = false;
3520 /* Otherwise it's not an attribute */
3521 lastprimarynode = node;
3522 /* reset flags for new primary node */
3523 saw_deferrability = false;
3524 saw_initially = false;
3531 /* Build a FromExpr node */
3533 makeFromExpr(List *fromlist, Node *quals)
3535 FromExpr *f = makeNode(FromExpr);
3537 f->fromlist = fromlist;
3543 * Special handling of type definition for a column
3546 transformColumnType(ParseState *pstate, ColumnDef *column)
3549 * All we really need to do here is verify that the type is valid.
3551 Type ctype = typenameType(pstate, column->typename);
3553 ReleaseSysCache(ctype);
3557 setSchemaName(char *context_schema, char **stmt_schema_name)
3559 if (*stmt_schema_name == NULL)
3560 *stmt_schema_name = context_schema;
3561 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3563 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3564 errmsg("CREATE specifies a schema (%s) "
3565 "different from the one being created (%s)",
3566 *stmt_schema_name, context_schema)));
3570 * analyzeCreateSchemaStmt -
3571 * analyzes the "create schema" statement
3573 * Split the schema element list into individual commands and place
3574 * them in the result list in an order such that there are no forward
3575 * references (e.g. GRANT to a table created later in the list). Note
3576 * that the logic we use for determining forward references is
3577 * presently quite incomplete.
3579 * SQL92 also allows constraints to make forward references, so thumb through
3580 * the table columns and move forward references to a posterior alter-table
3583 * The result is a list of parse nodes that still need to be analyzed ---
3584 * but we can't analyze the later commands until we've executed the earlier
3585 * ones, because of possible inter-object references.
3587 * Note: Called from commands/schemacmds.c
3590 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3592 CreateSchemaStmtContext cxt;
3596 cxt.stmtType = "CREATE SCHEMA";
3597 cxt.schemaname = stmt->schemaname;
3598 cxt.authid = stmt->authid;
3599 cxt.sequences = NIL;
3605 cxt.fwconstraints = NIL;
3611 * Run through each schema element in the schema element list. Separate
3612 * statements by type, and do preliminary analysis.
3614 foreach(elements, stmt->schemaElts)
3616 Node *element = lfirst(elements);
3618 switch (nodeTag(element))
3620 case T_CreateSeqStmt:
3622 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3624 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3625 cxt.sequences = lappend(cxt.sequences, element);
3631 CreateStmt *elp = (CreateStmt *) element;
3633 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3636 * XXX todo: deal with constraints
3638 cxt.tables = lappend(cxt.tables, element);
3644 ViewStmt *elp = (ViewStmt *) element;
3646 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3649 * XXX todo: deal with references between views
3651 cxt.views = lappend(cxt.views, element);
3657 IndexStmt *elp = (IndexStmt *) element;
3659 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3660 cxt.indexes = lappend(cxt.indexes, element);
3664 case T_CreateTrigStmt:
3666 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3668 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3669 cxt.triggers = lappend(cxt.triggers, element);
3674 cxt.grants = lappend(cxt.grants, element);
3678 elog(ERROR, "unrecognized node type: %d",
3679 (int) nodeTag(element));
3684 result = list_concat(result, cxt.sequences);
3685 result = list_concat(result, cxt.tables);
3686 result = list_concat(result, cxt.views);
3687 result = list_concat(result, cxt.indexes);
3688 result = list_concat(result, cxt.triggers);
3689 result = list_concat(result, cxt.grants);
3695 * Traverse a fully-analyzed tree to verify that parameter symbols
3696 * match their types. We need this because some Params might still
3697 * be UNKNOWN, if there wasn't anything to force their coercion,
3698 * and yet other instances seen later might have gotten coerced.
3701 check_parameter_resolution_walker(Node *node,
3702 check_parameter_resolution_context *context)
3706 if (IsA(node, Param))
3708 Param *param = (Param *) node;
3710 if (param->paramkind == PARAM_EXTERN)
3712 int paramno = param->paramid;
3714 if (paramno <= 0 || /* shouldn't happen, but... */
3715 paramno > context->numParams)
3717 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3718 errmsg("there is no parameter $%d", paramno)));
3720 if (param->paramtype != context->paramTypes[paramno - 1])
3722 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3723 errmsg("could not determine data type of parameter $%d",
3728 if (IsA(node, Query))
3730 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3731 return query_tree_walker((Query *) node,
3732 check_parameter_resolution_walker,
3733 (void *) context, 0);
3735 return expression_tree_walker(node, check_parameter_resolution_walker,