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.365 2007/06/19 21:24:48 neilc 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_relation.h"
49 #include "parser/parse_target.h"
50 #include "parser/parse_type.h"
51 #include "parser/parsetree.h"
52 #include "rewrite/rewriteManip.h"
53 #include "utils/acl.h"
54 #include "utils/builtins.h"
55 #include "utils/lsyscache.h"
56 #include "utils/syscache.h"
59 /* State shared by transformCreateSchemaStmt and its subroutines */
62 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
63 char *schemaname; /* name of schema */
64 char *authid; /* owner of schema */
65 List *sequences; /* CREATE SEQUENCE items */
66 List *tables; /* CREATE TABLE items */
67 List *views; /* CREATE VIEW items */
68 List *indexes; /* CREATE INDEX items */
69 List *triggers; /* CREATE TRIGGER items */
70 List *grants; /* GRANT items */
71 List *fwconstraints; /* Forward referencing FOREIGN KEY constraints */
72 List *alters; /* Generated ALTER items (from the above) */
73 List *ixconstraints; /* index-creating constraints */
74 List *blist; /* "before list" of things to do before
75 * creating the schema */
76 List *alist; /* "after list" of things to do after creating
78 } CreateSchemaStmtContext;
80 /* State shared by transformCreateStmt and its subroutines */
83 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
84 RangeVar *relation; /* relation to create */
85 List *inhRelations; /* relations to inherit from */
86 bool hasoids; /* does relation have an OID column? */
87 bool isalter; /* true if altering existing table */
88 List *columns; /* ColumnDef items */
89 List *ckconstraints; /* CHECK constraints */
90 List *fkconstraints; /* FOREIGN KEY constraints */
91 List *ixconstraints; /* index-creating constraints */
92 List *blist; /* "before list" of things to do before
93 * creating the table */
94 List *alist; /* "after list" of things to do after creating
96 IndexStmt *pkey; /* PRIMARY KEY index, if any */
103 } check_parameter_resolution_context;
106 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
107 static Query *transformStmt(ParseState *pstate, Node *stmt,
108 List **extras_before, List **extras_after);
109 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
110 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
111 List **extras_before, List **extras_after);
112 static List *transformInsertRow(ParseState *pstate, List *exprlist,
113 List *stmtcols, List *icolumns, List *attrnos);
114 static List *transformReturningList(ParseState *pstate, List *returningList);
115 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
116 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
117 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
118 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
119 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
120 static Query *transformDeclareCursorStmt(ParseState *pstate,
121 DeclareCursorStmt *stmt);
122 static Query *transformExplainStmt(ParseState *pstate,
124 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
125 List **extras_before, List **extras_after);
126 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
127 List **extras_before, List **extras_after);
128 static void transformColumnDefinition(ParseState *pstate,
129 CreateStmtContext *cxt,
131 static void transformTableConstraint(ParseState *pstate,
132 CreateStmtContext *cxt,
133 Constraint *constraint);
134 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
135 InhRelation *inhrelation);
136 static void transformIndexConstraints(ParseState *pstate,
137 CreateStmtContext *cxt);
138 static void transformFKConstraints(ParseState *pstate,
139 CreateStmtContext *cxt,
141 bool isAddConstraint);
142 static void applyColumnNames(List *dst, List *src);
143 static void getSetColTypes(ParseState *pstate, Node *node,
144 List **colTypes, List **colTypmods);
145 static void transformLockingClause(Query *qry, LockingClause *lc);
146 static void transformConstraintAttrs(List *constraintList);
147 static void transformColumnType(ParseState *pstate, ColumnDef *column);
148 static void release_pstate_resources(ParseState *pstate);
149 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
150 static bool check_parameter_resolution_walker(Node *node,
151 check_parameter_resolution_context *context);
156 * Analyze a raw parse tree and transform it to Query form.
158 * If available, pass the source text from which the raw parse tree was
159 * generated; it's OK to pass NULL if this is not available.
161 * Optionally, information about $n parameter types can be supplied.
162 * References to $n indexes not defined by paramTypes[] are disallowed.
164 * The result is a List of Query nodes (we need a list since some commands
165 * produce multiple Queries). Optimizable statements require considerable
166 * transformation, while most utility-type statements are simply hung off
167 * a dummy CMD_UTILITY Query node.
170 parse_analyze(Node *parseTree, const char *sourceText,
171 Oid *paramTypes, int numParams)
173 ParseState *pstate = make_parsestate(NULL);
176 pstate->p_sourcetext = sourceText;
177 pstate->p_paramtypes = paramTypes;
178 pstate->p_numparams = numParams;
179 pstate->p_variableparams = false;
181 result = do_parse_analyze(parseTree, pstate);
189 * parse_analyze_varparams
191 * This variant is used when it's okay to deduce information about $n
192 * symbol datatypes from context. The passed-in paramTypes[] array can
193 * be modified or enlarged (via repalloc).
196 parse_analyze_varparams(Node *parseTree, const char *sourceText,
197 Oid **paramTypes, int *numParams)
199 ParseState *pstate = make_parsestate(NULL);
202 pstate->p_sourcetext = sourceText;
203 pstate->p_paramtypes = *paramTypes;
204 pstate->p_numparams = *numParams;
205 pstate->p_variableparams = true;
207 result = do_parse_analyze(parseTree, pstate);
209 *paramTypes = pstate->p_paramtypes;
210 *numParams = pstate->p_numparams;
214 /* make sure all is well with parameter types */
217 check_parameter_resolution_context context;
219 context.paramTypes = *paramTypes;
220 context.numParams = *numParams;
221 check_parameter_resolution_walker((Node *) result, &context);
229 * Entry point for recursively analyzing a sub-statement.
232 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
234 ParseState *pstate = make_parsestate(parentParseState);
237 result = do_parse_analyze(parseTree, pstate);
246 * Workhorse code shared by the above variants of parse_analyze.
249 do_parse_analyze(Node *parseTree, ParseState *pstate)
253 /* Lists to return extra commands from transformation */
254 List *extras_before = NIL;
255 List *extras_after = NIL;
259 query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
261 /* don't need to access result relation any more */
262 release_pstate_resources(pstate);
264 foreach(l, extras_before)
265 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
267 result = lappend(result, query);
269 foreach(l, extras_after)
270 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
273 * Make sure that only the original query is marked original. We have to
274 * do this explicitly since recursive calls of do_parse_analyze will have
275 * marked some of the added-on queries as "original". Also mark only the
276 * original query as allowed to set the command-result tag.
280 Query *q = lfirst(l);
284 q->querySource = QSRC_ORIGINAL;
289 q->querySource = QSRC_PARSER;
290 q->canSetTag = false;
298 release_pstate_resources(ParseState *pstate)
300 if (pstate->p_target_relation != NULL)
301 heap_close(pstate->p_target_relation, NoLock);
302 pstate->p_target_relation = NULL;
303 pstate->p_target_rangetblentry = NULL;
308 * transform a Parse tree into a Query tree.
311 transformStmt(ParseState *pstate, Node *parseTree,
312 List **extras_before, List **extras_after)
314 Query *result = NULL;
316 switch (nodeTag(parseTree))
319 * Optimizable statements
322 result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
323 extras_before, extras_after);
327 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
331 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
336 SelectStmt *n = (SelectStmt *) parseTree;
339 result = transformValuesClause(pstate, n);
340 else if (n->op == SETOP_NONE)
341 result = transformSelectStmt(pstate, n);
343 result = transformSetOperationStmt(pstate, n);
348 * Non-optimizable statements
351 result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
352 extras_before, extras_after);
355 case T_AlterTableStmt:
356 result = transformAlterTableStmt(pstate,
357 (AlterTableStmt *) parseTree,
358 extras_before, extras_after);
364 case T_DeclareCursorStmt:
365 result = transformDeclareCursorStmt(pstate,
366 (DeclareCursorStmt *) parseTree);
370 result = transformExplainStmt(pstate,
371 (ExplainStmt *) parseTree);
377 * other statements don't require any transformation; just return
378 * the original parsetree with a Query node plastered on top.
380 result = makeNode(Query);
381 result->commandType = CMD_UTILITY;
382 result->utilityStmt = (Node *) parseTree;
386 /* Mark as original query until we learn differently */
387 result->querySource = QSRC_ORIGINAL;
388 result->canSetTag = true;
391 * Check that we did not produce too many resnos; at the very least we
392 * cannot allow more than 2^16, since that would exceed the range of a
393 * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
395 if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
397 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
398 errmsg("target lists can have at most %d entries",
399 MaxTupleAttributeNumber)));
405 * transformDeleteStmt -
406 * transforms a Delete Statement
409 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
411 Query *qry = makeNode(Query);
414 qry->commandType = CMD_DELETE;
416 /* set up range table with just the result rel */
417 qry->resultRelation = setTargetTable(pstate, stmt->relation,
418 interpretInhOption(stmt->relation->inhOpt),
422 qry->distinctClause = NIL;
425 * The USING clause is non-standard SQL syntax, and is equivalent in
426 * functionality to the FROM list that can be specified for UPDATE. The
427 * USING keyword is used rather than FROM because FROM is already a
428 * keyword in the DELETE syntax.
430 transformFromClause(pstate, stmt->usingClause);
432 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
434 qry->returningList = transformReturningList(pstate, stmt->returningList);
436 /* done building the range table and jointree */
437 qry->rtable = pstate->p_rtable;
438 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
440 qry->hasSubLinks = pstate->p_hasSubLinks;
441 qry->hasAggs = pstate->p_hasAggs;
442 if (pstate->p_hasAggs)
443 parseCheckAggregates(pstate, qry);
449 * transformInsertStmt -
450 * transform an Insert Statement
453 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
454 List **extras_before, List **extras_after)
456 Query *qry = makeNode(Query);
457 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
458 List *exprList = NIL;
459 bool isGeneralSelect;
461 List *sub_relnamespace;
462 List *sub_varnamespace;
471 qry->commandType = CMD_INSERT;
472 pstate->p_is_insert = true;
475 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
476 * VALUES list, or general SELECT input. We special-case VALUES, both for
477 * efficiency and so we can handle DEFAULT specifications.
479 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
482 * If a non-nil rangetable/namespace was passed in, and we are doing
483 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
484 * SELECT. This can only happen if we are inside a CREATE RULE, and in
485 * that case we want the rule's OLD and NEW rtable entries to appear as
486 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
487 * The SELECT's joinlist is not affected however. We must do this before
488 * adding the target table to the INSERT's rtable.
492 sub_rtable = pstate->p_rtable;
493 pstate->p_rtable = NIL;
494 sub_relnamespace = pstate->p_relnamespace;
495 pstate->p_relnamespace = NIL;
496 sub_varnamespace = pstate->p_varnamespace;
497 pstate->p_varnamespace = NIL;
501 sub_rtable = NIL; /* not used, but keep compiler quiet */
502 sub_relnamespace = NIL;
503 sub_varnamespace = NIL;
507 * Must get write lock on INSERT target table before scanning SELECT, else
508 * we will grab the wrong kind of initial lock if the target table is also
509 * mentioned in the SELECT part. Note that the target table is not added
510 * to the joinlist or namespace.
512 qry->resultRelation = setTargetTable(pstate, stmt->relation,
513 false, false, ACL_INSERT);
515 /* Validate stmt->cols list, or build default list if no list given */
516 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
517 Assert(list_length(icolumns) == list_length(attrnos));
520 * Determine which variant of INSERT we have.
522 if (selectStmt == NULL)
525 * We have INSERT ... DEFAULT VALUES. We can handle this case by
526 * emitting an empty targetlist --- all columns will be defaulted when
527 * the planner expands the targetlist.
531 else if (isGeneralSelect)
534 * We make the sub-pstate a child of the outer pstate so that it can
535 * see any Param definitions supplied from above. Since the outer
536 * pstate's rtable and namespace are presently empty, there are no
537 * side-effects of exposing names the sub-SELECT shouldn't be able to
540 ParseState *sub_pstate = make_parsestate(pstate);
544 * Process the source SELECT.
546 * It is important that this be handled just like a standalone SELECT;
547 * otherwise the behavior of SELECT within INSERT might be different
548 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
549 * bugs of just that nature...)
551 sub_pstate->p_rtable = sub_rtable;
552 sub_pstate->p_relnamespace = sub_relnamespace;
553 sub_pstate->p_varnamespace = sub_varnamespace;
556 * Note: we are not expecting that extras_before and extras_after are
557 * going to be used by the transformation of the SELECT statement.
559 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
560 extras_before, extras_after);
562 release_pstate_resources(sub_pstate);
565 /* The grammar should have produced a SELECT, but it might have INTO */
566 Assert(IsA(selectQuery, Query));
567 Assert(selectQuery->commandType == CMD_SELECT);
568 Assert(selectQuery->utilityStmt == NULL);
569 if (selectQuery->intoClause)
571 (errcode(ERRCODE_SYNTAX_ERROR),
572 errmsg("INSERT ... SELECT cannot specify INTO")));
575 * Make the source be a subquery in the INSERT's rangetable, and add
576 * it to the INSERT's joinlist.
578 rte = addRangeTableEntryForSubquery(pstate,
580 makeAlias("*SELECT*", NIL),
582 rtr = makeNode(RangeTblRef);
583 /* assume new rte is at end */
584 rtr->rtindex = list_length(pstate->p_rtable);
585 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
586 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
589 * Generate an expression list for the INSERT that selects all the
590 * non-resjunk columns from the subquery. (INSERT's tlist must be
591 * separate from the subquery's tlist because we may add columns,
592 * insert datatype coercions, etc.)
594 * HACK: unknown-type constants and params in the SELECT's targetlist
595 * are copied up as-is rather than being referenced as subquery
596 * outputs. This is to ensure that when we try to coerce them to
597 * the target column's datatype, the right things happen (see
598 * special cases in coerce_type). Otherwise, this fails:
599 * INSERT INTO foo SELECT 'bar', ... FROM baz
603 foreach(lc, selectQuery->targetList)
605 TargetEntry *tle = (TargetEntry *) lfirst(lc);
611 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
612 exprType((Node *) tle->expr) == UNKNOWNOID)
615 expr = (Expr *) makeVar(rtr->rtindex,
617 exprType((Node *) tle->expr),
618 exprTypmod((Node *) tle->expr),
620 exprList = lappend(exprList, expr);
623 /* Prepare row for assignment to target table */
624 exprList = transformInsertRow(pstate, exprList,
628 else if (list_length(selectStmt->valuesLists) > 1)
631 * Process INSERT ... VALUES with multiple VALUES sublists. We
632 * generate a VALUES RTE holding the transformed expression lists, and
633 * build up a targetlist containing Vars that reference the VALUES
636 List *exprsLists = NIL;
637 int sublist_length = -1;
639 foreach(lc, selectStmt->valuesLists)
641 List *sublist = (List *) lfirst(lc);
643 /* Do basic expression transformation (same as a ROW() expr) */
644 sublist = transformExpressionList(pstate, sublist);
647 * All the sublists must be the same length, *after*
648 * transformation (which might expand '*' into multiple items).
649 * The VALUES RTE can't handle anything different.
651 if (sublist_length < 0)
653 /* Remember post-transformation length of first sublist */
654 sublist_length = list_length(sublist);
656 else if (sublist_length != list_length(sublist))
659 (errcode(ERRCODE_SYNTAX_ERROR),
660 errmsg("VALUES lists must all be the same length")));
663 /* Prepare row for assignment to target table */
664 sublist = transformInsertRow(pstate, sublist,
668 exprsLists = lappend(exprsLists, sublist);
672 * There mustn't have been any table references in the expressions,
673 * else strange things would happen, like Cartesian products of those
674 * tables with the VALUES list ...
676 if (pstate->p_joinlist != NIL)
678 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
679 errmsg("VALUES must not contain table references")));
682 * Another thing we can't currently support is NEW/OLD references in
683 * rules --- seems we'd need something like SQL99's LATERAL construct
684 * to ensure that the values would be available while evaluating the
685 * VALUES RTE. This is a shame. FIXME
687 if (list_length(pstate->p_rtable) != 1 &&
688 contain_vars_of_level((Node *) exprsLists, 0))
690 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
691 errmsg("VALUES must not contain OLD or NEW references"),
692 errhint("Use SELECT ... UNION ALL ... instead.")));
695 * Generate the VALUES RTE
697 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
698 rtr = makeNode(RangeTblRef);
699 /* assume new rte is at end */
700 rtr->rtindex = list_length(pstate->p_rtable);
701 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
702 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
705 * Generate list of Vars referencing the RTE
707 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
712 * Process INSERT ... VALUES with a single VALUES sublist.
713 * We treat this separately for efficiency and for historical
714 * compatibility --- specifically, allowing table references,
716 * INSERT INTO foo VALUES(bar.*)
718 * The sublist is just computed directly as the Query's targetlist,
719 * with no VALUES RTE. So it works just like SELECT without FROM.
722 List *valuesLists = selectStmt->valuesLists;
724 Assert(list_length(valuesLists) == 1);
726 /* Do basic expression transformation (same as a ROW() expr) */
727 exprList = transformExpressionList(pstate,
728 (List *) linitial(valuesLists));
730 /* Prepare row for assignment to target table */
731 exprList = transformInsertRow(pstate, exprList,
737 * Generate query's target list using the computed list of expressions.
739 qry->targetList = NIL;
740 icols = list_head(icolumns);
741 attnos = list_head(attrnos);
742 foreach(lc, exprList)
744 Expr *expr = (Expr *) lfirst(lc);
748 col = (ResTarget *) lfirst(icols);
749 Assert(IsA(col, ResTarget));
751 tle = makeTargetEntry(expr,
752 (AttrNumber) lfirst_int(attnos),
755 qry->targetList = lappend(qry->targetList, tle);
757 icols = lnext(icols);
758 attnos = lnext(attnos);
762 * If we have a RETURNING clause, we need to add the target relation to
763 * the query namespace before processing it, so that Var references in
764 * RETURNING will work. Also, remove any namespace entries added in a
765 * sub-SELECT or VALUES list.
767 if (stmt->returningList)
769 pstate->p_relnamespace = NIL;
770 pstate->p_varnamespace = NIL;
771 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
773 qry->returningList = transformReturningList(pstate,
774 stmt->returningList);
777 /* done building the range table and jointree */
778 qry->rtable = pstate->p_rtable;
779 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
781 qry->hasSubLinks = pstate->p_hasSubLinks;
782 /* aggregates not allowed (but subselects are okay) */
783 if (pstate->p_hasAggs)
785 (errcode(ERRCODE_GROUPING_ERROR),
786 errmsg("cannot use aggregate function in VALUES")));
792 * Prepare an INSERT row for assignment to the target table.
794 * The row might be either a VALUES row, or variables referencing a
798 transformInsertRow(ParseState *pstate, List *exprlist,
799 List *stmtcols, List *icolumns, List *attrnos)
807 * Check length of expr list. It must not have more expressions than
808 * there are target columns. We allow fewer, but only if no explicit
809 * columns list was given (the remaining columns are implicitly
810 * defaulted). Note we must check this *after* transformation because
811 * that could expand '*' into multiple items.
813 if (list_length(exprlist) > list_length(icolumns))
815 (errcode(ERRCODE_SYNTAX_ERROR),
816 errmsg("INSERT has more expressions than target columns")));
817 if (stmtcols != NIL &&
818 list_length(exprlist) < list_length(icolumns))
820 (errcode(ERRCODE_SYNTAX_ERROR),
821 errmsg("INSERT has more target columns than expressions")));
824 * Prepare columns for assignment to target table.
827 icols = list_head(icolumns);
828 attnos = list_head(attrnos);
829 foreach(lc, exprlist)
831 Expr *expr = (Expr *) lfirst(lc);
834 col = (ResTarget *) lfirst(icols);
835 Assert(IsA(col, ResTarget));
837 expr = transformAssignedExpr(pstate, expr,
843 result = lappend(result, expr);
845 icols = lnext(icols);
846 attnos = lnext(attnos);
853 * transformCreateStmt -
854 * transforms the "create table" statement
855 * SQL92 allows constraints to be scattered all over, so thumb through
856 * the columns and collect all constraints into one place.
857 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
858 * then expand those into multiple IndexStmt blocks.
859 * - thomas 1997-12-02
862 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
863 List **extras_before, List **extras_after)
865 CreateStmtContext cxt;
869 cxt.stmtType = "CREATE TABLE";
870 cxt.relation = stmt->relation;
871 cxt.inhRelations = stmt->inhRelations;
874 cxt.ckconstraints = NIL;
875 cxt.fkconstraints = NIL;
876 cxt.ixconstraints = NIL;
880 cxt.hasoids = interpretOidsOption(stmt->options);
883 * Run through each primary element in the table creation clause. Separate
884 * column defs from constraints, and do preliminary analysis.
886 foreach(elements, stmt->tableElts)
888 Node *element = lfirst(elements);
890 switch (nodeTag(element))
893 transformColumnDefinition(pstate, &cxt,
894 (ColumnDef *) element);
898 transformTableConstraint(pstate, &cxt,
899 (Constraint *) element);
903 /* No pre-transformation needed */
904 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
908 transformInhRelation(pstate, &cxt,
909 (InhRelation *) element);
913 elog(ERROR, "unrecognized node type: %d",
914 (int) nodeTag(element));
920 * transformIndexConstraints wants cxt.alist to contain only index
921 * statements, so transfer anything we already have into extras_after
924 *extras_after = list_concat(cxt.alist, *extras_after);
927 Assert(stmt->constraints == NIL);
930 * Postprocess constraints that give rise to index definitions.
932 transformIndexConstraints(pstate, &cxt);
935 * Postprocess foreign-key constraints.
937 transformFKConstraints(pstate, &cxt, true, false);
943 q->commandType = CMD_UTILITY;
944 q->utilityStmt = (Node *) stmt;
945 stmt->tableElts = cxt.columns;
946 stmt->constraints = cxt.ckconstraints;
947 *extras_before = list_concat(*extras_before, cxt.blist);
948 *extras_after = list_concat(cxt.alist, *extras_after);
954 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
959 Constraint *constraint;
962 cxt->columns = lappend(cxt->columns, column);
964 /* Check for SERIAL pseudo-types */
966 if (list_length(column->typename->names) == 1)
968 char *typname = strVal(linitial(column->typename->names));
970 if (strcmp(typname, "serial") == 0 ||
971 strcmp(typname, "serial4") == 0)
974 column->typename->names = NIL;
975 column->typename->typeid = INT4OID;
977 else if (strcmp(typname, "bigserial") == 0 ||
978 strcmp(typname, "serial8") == 0)
981 column->typename->names = NIL;
982 column->typename->typeid = INT8OID;
986 /* Do necessary work on the column type declaration */
987 transformColumnType(pstate, column);
989 /* Special actions for SERIAL pseudo-types */
997 FuncCall *funccallnode;
998 CreateSeqStmt *seqstmt;
999 AlterSeqStmt *altseqstmt;
1003 * Determine namespace and name to use for the sequence.
1005 * Although we use ChooseRelationName, it's not guaranteed that the
1006 * selected sequence name won't conflict; given sufficiently long
1007 * field names, two different serial columns in the same table could
1008 * be assigned the same sequence name, and we'd not notice since we
1009 * aren't creating the sequence quite yet. In practice this seems
1010 * quite unlikely to be a problem, especially since few people would
1011 * need two serial columns in one table.
1013 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
1014 snamespace = get_namespace_name(snamespaceid);
1015 sname = ChooseRelationName(cxt->relation->relname,
1021 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
1022 cxt->stmtType, sname,
1023 cxt->relation->relname, column->colname)));
1026 * Build a CREATE SEQUENCE command to create the sequence object, and
1027 * add it to the list of things to be done before this CREATE/ALTER
1030 seqstmt = makeNode(CreateSeqStmt);
1031 seqstmt->sequence = makeRangeVar(snamespace, sname);
1032 seqstmt->options = NIL;
1034 cxt->blist = lappend(cxt->blist, seqstmt);
1037 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
1038 * as owned by this column, and add it to the list of things to be
1039 * done after this CREATE/ALTER TABLE.
1041 altseqstmt = makeNode(AlterSeqStmt);
1042 altseqstmt->sequence = makeRangeVar(snamespace, sname);
1043 attnamelist = list_make3(makeString(snamespace),
1044 makeString(cxt->relation->relname),
1045 makeString(column->colname));
1046 altseqstmt->options = list_make1(makeDefElem("owned_by",
1047 (Node *) attnamelist));
1049 cxt->alist = lappend(cxt->alist, altseqstmt);
1052 * Create appropriate constraints for SERIAL. We do this in full,
1053 * rather than shortcutting, so that we will detect any conflicting
1054 * constraints the user wrote (like a different DEFAULT).
1056 * Create an expression tree representing the function call
1057 * nextval('sequencename'). We cannot reduce the raw tree to cooked
1058 * form until after the sequence is created, but there's no need to do
1061 qstring = quote_qualified_identifier(snamespace, sname);
1062 snamenode = makeNode(A_Const);
1063 snamenode->val.type = T_String;
1064 snamenode->val.val.str = qstring;
1065 snamenode->typename = SystemTypeName("regclass");
1066 funccallnode = makeNode(FuncCall);
1067 funccallnode->funcname = SystemFuncName("nextval");
1068 funccallnode->args = list_make1(snamenode);
1069 funccallnode->agg_star = false;
1070 funccallnode->agg_distinct = false;
1071 funccallnode->location = -1;
1073 constraint = makeNode(Constraint);
1074 constraint->contype = CONSTR_DEFAULT;
1075 constraint->raw_expr = (Node *) funccallnode;
1076 constraint->cooked_expr = NULL;
1077 constraint->keys = NIL;
1078 column->constraints = lappend(column->constraints, constraint);
1080 constraint = makeNode(Constraint);
1081 constraint->contype = CONSTR_NOTNULL;
1082 column->constraints = lappend(column->constraints, constraint);
1085 /* Process column constraints, if any... */
1086 transformConstraintAttrs(column->constraints);
1088 saw_nullable = false;
1090 foreach(clist, column->constraints)
1092 constraint = lfirst(clist);
1095 * If this column constraint is a FOREIGN KEY constraint, then we fill
1096 * in the current attribute's name and throw it into the list of FK
1097 * constraints to be processed later.
1099 if (IsA(constraint, FkConstraint))
1101 FkConstraint *fkconstraint = (FkConstraint *) constraint;
1103 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
1104 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
1108 Assert(IsA(constraint, Constraint));
1110 switch (constraint->contype)
1113 if (saw_nullable && column->is_not_null)
1115 (errcode(ERRCODE_SYNTAX_ERROR),
1116 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1117 column->colname, cxt->relation->relname)));
1118 column->is_not_null = FALSE;
1119 saw_nullable = true;
1122 case CONSTR_NOTNULL:
1123 if (saw_nullable && !column->is_not_null)
1125 (errcode(ERRCODE_SYNTAX_ERROR),
1126 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1127 column->colname, cxt->relation->relname)));
1128 column->is_not_null = TRUE;
1129 saw_nullable = true;
1132 case CONSTR_DEFAULT:
1133 if (column->raw_default != NULL)
1135 (errcode(ERRCODE_SYNTAX_ERROR),
1136 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
1137 column->colname, cxt->relation->relname)));
1138 column->raw_default = constraint->raw_expr;
1139 Assert(constraint->cooked_expr == NULL);
1142 case CONSTR_PRIMARY:
1144 if (constraint->keys == NIL)
1145 constraint->keys = list_make1(makeString(column->colname));
1146 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1150 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1153 case CONSTR_ATTR_DEFERRABLE:
1154 case CONSTR_ATTR_NOT_DEFERRABLE:
1155 case CONSTR_ATTR_DEFERRED:
1156 case CONSTR_ATTR_IMMEDIATE:
1157 /* transformConstraintAttrs took care of these */
1161 elog(ERROR, "unrecognized constraint type: %d",
1162 constraint->contype);
1169 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1170 Constraint *constraint)
1172 switch (constraint->contype)
1174 case CONSTR_PRIMARY:
1176 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1180 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1184 case CONSTR_NOTNULL:
1185 case CONSTR_DEFAULT:
1186 case CONSTR_ATTR_DEFERRABLE:
1187 case CONSTR_ATTR_NOT_DEFERRABLE:
1188 case CONSTR_ATTR_DEFERRED:
1189 case CONSTR_ATTR_IMMEDIATE:
1190 elog(ERROR, "invalid context for constraint type %d",
1191 constraint->contype);
1195 elog(ERROR, "unrecognized constraint type: %d",
1196 constraint->contype);
1202 * transformInhRelation
1204 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
1205 * column definitions which recreate the user defined column portions of
1208 * Note: because we do this at parse analysis time, any change in the
1209 * referenced table between parse analysis and execution won't be reflected
1210 * into the new table. Is this OK?
1213 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1214 InhRelation *inhRelation)
1216 AttrNumber parent_attno;
1218 TupleDesc tupleDesc;
1219 TupleConstr *constr;
1220 AclResult aclresult;
1221 bool including_defaults = false;
1222 bool including_constraints = false;
1223 bool including_indexes = false;
1226 relation = heap_openrv(inhRelation->relation, AccessShareLock);
1228 if (relation->rd_rel->relkind != RELKIND_RELATION)
1230 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1231 errmsg("inherited relation \"%s\" is not a table",
1232 inhRelation->relation->relname)));
1235 * Check for SELECT privilages
1237 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1239 if (aclresult != ACLCHECK_OK)
1240 aclcheck_error(aclresult, ACL_KIND_CLASS,
1241 RelationGetRelationName(relation));
1243 tupleDesc = RelationGetDescr(relation);
1244 constr = tupleDesc->constr;
1246 foreach(elem, inhRelation->options)
1248 int option = lfirst_int(elem);
1252 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
1253 including_defaults = true;
1255 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
1256 including_defaults = false;
1258 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
1259 including_constraints = true;
1261 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
1262 including_constraints = false;
1264 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
1265 including_indexes = true;
1267 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
1268 including_indexes = false;
1271 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
1276 if (including_indexes)
1278 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1279 errmsg("LIKE INCLUDING INDEXES is not implemented")));
1282 * Insert the copied attributes into the cxt for the new table
1285 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1288 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1289 char *attributeName = NameStr(attribute->attname);
1293 * Ignore dropped columns in the parent.
1295 if (attribute->attisdropped)
1299 * Create a new column, which is marked as NOT inherited.
1301 * For constraints, ONLY the NOT NULL constraint is inherited by the
1302 * new column definition per SQL99.
1304 def = makeNode(ColumnDef);
1305 def->colname = pstrdup(attributeName);
1306 def->typename = makeTypeNameFromOid(attribute->atttypid,
1307 attribute->atttypmod);
1309 def->is_local = true;
1310 def->is_not_null = attribute->attnotnull;
1311 def->raw_default = NULL;
1312 def->cooked_default = NULL;
1313 def->constraints = NIL;
1316 * Add to column list
1318 cxt->columns = lappend(cxt->columns, def);
1321 * Copy default, if present and the default has been requested
1323 if (attribute->atthasdef && including_defaults)
1325 char *this_default = NULL;
1326 AttrDefault *attrdef;
1329 /* Find default in constraint structure */
1330 Assert(constr != NULL);
1331 attrdef = constr->defval;
1332 for (i = 0; i < constr->num_defval; i++)
1334 if (attrdef[i].adnum == parent_attno)
1336 this_default = attrdef[i].adbin;
1340 Assert(this_default != NULL);
1343 * If default expr could contain any vars, we'd need to fix 'em,
1344 * but it can't; so default is ready to apply to child.
1347 def->cooked_default = pstrdup(this_default);
1352 * Copy CHECK constraints if requested, being careful to adjust
1355 if (including_constraints && tupleDesc->constr)
1357 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
1360 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
1362 char *ccname = tupleDesc->constr->check[ccnum].ccname;
1363 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1364 Node *ccbin_node = stringToNode(ccbin);
1365 Constraint *n = makeNode(Constraint);
1367 change_varattnos_of_a_node(ccbin_node, attmap);
1369 n->contype = CONSTR_CHECK;
1370 n->name = pstrdup(ccname);
1372 n->cooked_expr = nodeToString(ccbin_node);
1373 n->indexspace = NULL;
1374 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
1379 * Close the parent rel, but keep our AccessShareLock on it until xact
1380 * commit. That will prevent someone else from deleting or ALTERing the
1381 * parent before the child is committed.
1383 heap_close(relation, NoLock);
1387 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1390 List *indexlist = NIL;
1395 * Run through the constraints that need to generate an index. For PRIMARY
1396 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1397 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1399 foreach(listptr, cxt->ixconstraints)
1401 Constraint *constraint = lfirst(listptr);
1405 Assert(IsA(constraint, Constraint));
1406 Assert((constraint->contype == CONSTR_PRIMARY)
1407 || (constraint->contype == CONSTR_UNIQUE));
1409 index = makeNode(IndexStmt);
1411 index->unique = true;
1412 index->primary = (constraint->contype == CONSTR_PRIMARY);
1415 if (cxt->pkey != NULL)
1417 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1418 errmsg("multiple primary keys for table \"%s\" are not allowed",
1419 cxt->relation->relname)));
1423 * In ALTER TABLE case, a primary index might already exist, but
1424 * DefineIndex will check for it.
1427 index->isconstraint = true;
1429 if (constraint->name != NULL)
1430 index->idxname = pstrdup(constraint->name);
1432 index->idxname = NULL; /* DefineIndex will choose name */
1434 index->relation = cxt->relation;
1435 index->accessMethod = DEFAULT_INDEX_TYPE;
1436 index->options = constraint->options;
1437 index->tableSpace = constraint->indexspace;
1438 index->indexParams = NIL;
1439 index->whereClause = NULL;
1440 index->concurrent = false;
1443 * Make sure referenced keys exist. If we are making a PRIMARY KEY
1444 * index, also make sure they are NOT NULL, if possible. (Although we
1445 * could leave it to DefineIndex to mark the columns NOT NULL, it's
1446 * more efficient to get it right the first time.)
1448 foreach(keys, constraint->keys)
1450 char *key = strVal(lfirst(keys));
1452 ColumnDef *column = NULL;
1455 foreach(columns, cxt->columns)
1457 column = (ColumnDef *) lfirst(columns);
1458 Assert(IsA(column, ColumnDef));
1459 if (strcmp(column->colname, key) == 0)
1467 /* found column in the new table; force it to be NOT NULL */
1468 if (constraint->contype == CONSTR_PRIMARY)
1469 column->is_not_null = TRUE;
1471 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1474 * column will be a system column in the new table, so accept
1475 * it. System columns can't ever be null, so no need to worry
1476 * about PRIMARY/NOT NULL constraint.
1480 else if (cxt->inhRelations)
1482 /* try inherited tables */
1485 foreach(inher, cxt->inhRelations)
1487 RangeVar *inh = (RangeVar *) lfirst(inher);
1491 Assert(IsA(inh, RangeVar));
1492 rel = heap_openrv(inh, AccessShareLock);
1493 if (rel->rd_rel->relkind != RELKIND_RELATION)
1495 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1496 errmsg("inherited relation \"%s\" is not a table",
1498 for (count = 0; count < rel->rd_att->natts; count++)
1500 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1501 char *inhname = NameStr(inhattr->attname);
1503 if (inhattr->attisdropped)
1505 if (strcmp(key, inhname) == 0)
1510 * We currently have no easy way to force an
1511 * inherited column to be NOT NULL at creation, if
1512 * its parent wasn't so already. We leave it to
1513 * DefineIndex to fix things up in this case.
1518 heap_close(rel, NoLock);
1525 * In the ALTER TABLE case, don't complain about index keys not
1526 * created in the command; they may well exist already.
1527 * DefineIndex will complain about them if not, and will also take
1528 * care of marking them NOT NULL.
1530 if (!found && !cxt->isalter)
1532 (errcode(ERRCODE_UNDEFINED_COLUMN),
1533 errmsg("column \"%s\" named in key does not exist",
1536 /* Check for PRIMARY KEY(foo, foo) */
1537 foreach(columns, index->indexParams)
1539 iparam = (IndexElem *) lfirst(columns);
1540 if (iparam->name && strcmp(key, iparam->name) == 0)
1544 (errcode(ERRCODE_DUPLICATE_COLUMN),
1545 errmsg("column \"%s\" appears twice in primary key constraint",
1549 (errcode(ERRCODE_DUPLICATE_COLUMN),
1550 errmsg("column \"%s\" appears twice in unique constraint",
1555 /* OK, add it to the index definition */
1556 iparam = makeNode(IndexElem);
1557 iparam->name = pstrdup(key);
1558 iparam->expr = NULL;
1559 iparam->opclass = NIL;
1560 iparam->ordering = SORTBY_DEFAULT;
1561 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1562 index->indexParams = lappend(index->indexParams, iparam);
1565 indexlist = lappend(indexlist, index);
1569 * Scan the index list and remove any redundant index specifications. This
1570 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1571 * strict reading of SQL92 would suggest raising an error instead, but
1572 * that strikes me as too anal-retentive. - tgl 2001-02-14
1574 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1575 * pre-existing indexes, too. However, that seems to risk race
1576 * conditions since we can't be sure the command will be executed
1579 Assert(cxt->alist == NIL);
1580 if (cxt->pkey != NULL)
1582 /* Make sure we keep the PKEY index in preference to others... */
1583 cxt->alist = list_make1(cxt->pkey);
1586 foreach(l, indexlist)
1593 /* if it's pkey, it's already in cxt->alist */
1594 if (index == cxt->pkey)
1597 foreach(k, cxt->alist)
1599 IndexStmt *priorindex = lfirst(k);
1601 if (equal(index->indexParams, priorindex->indexParams))
1604 * If the prior index is as yet unnamed, and this one is
1605 * named, then transfer the name to the prior index. This
1606 * ensures that if we have named and unnamed constraints,
1607 * we'll use (at least one of) the names for the index.
1609 if (priorindex->idxname == NULL)
1610 priorindex->idxname = index->idxname;
1617 cxt->alist = lappend(cxt->alist, index);
1622 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1623 bool skipValidation, bool isAddConstraint)
1627 if (cxt->fkconstraints == NIL)
1631 * If CREATE TABLE or adding a column with NULL default, we can safely
1632 * skip validation of the constraint.
1636 foreach(fkclist, cxt->fkconstraints)
1638 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1640 fkconstraint->skip_validation = true;
1645 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1646 * CONSTRAINT command to execute after the basic command is complete. (If
1647 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1648 * its own subcommand list.)
1650 * Note: the ADD CONSTRAINT command must also execute after any index
1651 * creation commands. Thus, this should run after
1652 * transformIndexConstraints, so that the CREATE INDEX commands are
1653 * already in cxt->alist.
1655 if (!isAddConstraint)
1657 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1659 alterstmt->relation = cxt->relation;
1660 alterstmt->cmds = NIL;
1661 alterstmt->relkind = OBJECT_TABLE;
1663 foreach(fkclist, cxt->fkconstraints)
1665 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1666 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1668 altercmd->subtype = AT_ProcessedConstraint;
1669 altercmd->name = NULL;
1670 altercmd->def = (Node *) fkconstraint;
1671 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1674 cxt->alist = lappend(cxt->alist, alterstmt);
1679 * analyzeIndexStmt - perform parse analysis for CREATE INDEX
1681 * Note that this has to be performed during execution not parse analysis, so
1682 * it's called by ProcessUtility. (Most other callers don't need to bother,
1683 * because this is a no-op for an index not using either index expressions or
1684 * a predicate expression.)
1687 analyzeIndexStmt(IndexStmt *stmt, const char *queryString)
1695 * We must not scribble on the passed-in IndexStmt, so copy it. (This
1696 * is overkill, but easy.)
1698 stmt = (IndexStmt *) copyObject(stmt);
1701 * Open the parent table with appropriate locking. We must do this
1702 * because addRangeTableEntry() would acquire only AccessShareLock,
1703 * leaving DefineIndex() needing to do a lock upgrade with consequent
1704 * risk of deadlock. Make sure this stays in sync with the type of
1705 * lock DefineIndex() wants.
1707 rel = heap_openrv(stmt->relation,
1708 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1711 pstate = make_parsestate(NULL);
1712 pstate->p_sourcetext = queryString;
1715 * Put the parent table into the rtable so that the expressions can
1716 * refer to its fields without qualification.
1718 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1720 /* no to join list, yes to namespaces */
1721 addRTEtoQuery(pstate, rte, false, true, true);
1723 /* take care of the where clause */
1724 if (stmt->whereClause)
1725 stmt->whereClause = transformWhereClause(pstate,
1729 /* take care of any index expressions */
1730 foreach(l, stmt->indexParams)
1732 IndexElem *ielem = (IndexElem *) lfirst(l);
1736 ielem->expr = transformExpr(pstate, ielem->expr);
1739 * We check only that the result type is legitimate; this is for
1740 * consistency with what transformWhereClause() checks for the
1741 * predicate. DefineIndex() will make more checks.
1743 if (expression_returns_set(ielem->expr))
1745 (errcode(ERRCODE_DATATYPE_MISMATCH),
1746 errmsg("index expression cannot return a set")));
1751 * Check that only the base rel is mentioned.
1753 if (list_length(pstate->p_rtable) != 1)
1755 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1756 errmsg("index expressions and predicates can refer only to the table being indexed")));
1758 release_pstate_resources(pstate);
1761 /* Close relation, but keep the lock */
1762 heap_close(rel, NoLock);
1770 * transform a Create Rule Statement. The action is a list of parse
1771 * trees which is transformed into a list of query trees, and we also
1772 * transform the WHERE clause if any.
1774 * Note that this has to be performed during execution not parse analysis,
1775 * so it's called by DefineRule. Also note that we must not scribble on
1776 * the passed-in RuleStmt, so we do copyObject() on the actions and WHERE
1780 analyzeRuleStmt(RuleStmt *stmt, const char *queryString,
1781 List **actions, Node **whereClause)
1785 RangeTblEntry *oldrte;
1786 RangeTblEntry *newrte;
1789 * To avoid deadlock, make sure the first thing we do is grab
1790 * AccessExclusiveLock on the target relation. This will be needed by
1791 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1794 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1797 pstate = make_parsestate(NULL);
1798 pstate->p_sourcetext = queryString;
1801 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1802 * Set up their RTEs in the main pstate for use in parsing the rule
1805 oldrte = addRangeTableEntryForRelation(pstate, rel,
1806 makeAlias("*OLD*", NIL),
1808 newrte = addRangeTableEntryForRelation(pstate, rel,
1809 makeAlias("*NEW*", NIL),
1811 /* Must override addRangeTableEntry's default access-check flags */
1812 oldrte->requiredPerms = 0;
1813 newrte->requiredPerms = 0;
1816 * They must be in the namespace too for lookup purposes, but only add the
1817 * one(s) that are relevant for the current kind of rule. In an UPDATE
1818 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1819 * there's no need to be so picky for INSERT & DELETE. We do not add them
1822 switch (stmt->event)
1825 addRTEtoQuery(pstate, oldrte, false, true, true);
1828 addRTEtoQuery(pstate, oldrte, false, true, true);
1829 addRTEtoQuery(pstate, newrte, false, true, true);
1832 addRTEtoQuery(pstate, newrte, false, true, true);
1835 addRTEtoQuery(pstate, oldrte, false, true, true);
1838 elog(ERROR, "unrecognized event type: %d",
1843 /* take care of the where clause */
1844 *whereClause = transformWhereClause(pstate,
1845 (Node *) copyObject(stmt->whereClause),
1848 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1850 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1851 errmsg("rule WHERE condition cannot contain references to other relations")));
1853 /* aggregates not allowed (but subselects are okay) */
1854 if (pstate->p_hasAggs)
1856 (errcode(ERRCODE_GROUPING_ERROR),
1857 errmsg("cannot use aggregate function in rule WHERE condition")));
1860 * 'instead nothing' rules with a qualification need a query rangetable so
1861 * the rewrite handler can add the negated rule qualification to the
1862 * original query. We create a query with the new command type CMD_NOTHING
1863 * here that is treated specially by the rewrite system.
1865 if (stmt->actions == NIL)
1867 Query *nothing_qry = makeNode(Query);
1869 nothing_qry->commandType = CMD_NOTHING;
1870 nothing_qry->rtable = pstate->p_rtable;
1871 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1873 *actions = list_make1(nothing_qry);
1878 List *newactions = NIL;
1881 * transform each statement, like parse_sub_analyze()
1883 foreach(l, stmt->actions)
1885 Node *action = (Node *) lfirst(l);
1886 ParseState *sub_pstate = make_parsestate(NULL);
1889 List *extras_before = NIL;
1890 List *extras_after = NIL;
1895 * Since outer ParseState isn't parent of inner, have to pass
1896 * down the query text by hand.
1898 sub_pstate->p_sourcetext = queryString;
1901 * Set up OLD/NEW in the rtable for this statement. The entries
1902 * are added only to relnamespace, not varnamespace, because we
1903 * don't want them to be referred to by unqualified field names
1904 * nor "*" in the rule actions. We decide later whether to put
1905 * them in the joinlist.
1907 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1908 makeAlias("*OLD*", NIL),
1910 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1911 makeAlias("*NEW*", NIL),
1913 oldrte->requiredPerms = 0;
1914 newrte->requiredPerms = 0;
1915 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1916 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1918 /* Transform the rule action statement */
1919 top_subqry = transformStmt(sub_pstate,
1920 (Node *) copyObject(action),
1921 &extras_before, &extras_after);
1924 * We cannot support utility-statement actions (eg NOTIFY) with
1925 * nonempty rule WHERE conditions, because there's no way to make
1926 * the utility action execute conditionally.
1928 if (top_subqry->commandType == CMD_UTILITY &&
1929 *whereClause != NULL)
1931 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1932 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1935 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1936 * into the SELECT, and that's what we need to look at. (Ugly
1937 * kluge ... try to fix this when we redesign querytrees.)
1939 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1942 * If the sub_qry is a setop, we cannot attach any qualifications
1943 * to it, because the planner won't notice them. This could
1944 * perhaps be relaxed someday, but for now, we may as well reject
1945 * such a rule immediately.
1947 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1949 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1950 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1953 * Validate action's use of OLD/NEW, qual too
1956 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1957 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1959 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1960 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1962 switch (stmt->event)
1967 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1968 errmsg("ON SELECT rule cannot use OLD")));
1971 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1972 errmsg("ON SELECT rule cannot use NEW")));
1980 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1981 errmsg("ON INSERT rule cannot use OLD")));
1986 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1987 errmsg("ON DELETE rule cannot use NEW")));
1990 elog(ERROR, "unrecognized event type: %d",
1996 * For efficiency's sake, add OLD to the rule action's jointree
1997 * only if it was actually referenced in the statement or qual.
1999 * For INSERT, NEW is not really a relation (only a reference to
2000 * the to-be-inserted tuple) and should never be added to the
2003 * For UPDATE, we treat NEW as being another kind of reference to
2004 * OLD, because it represents references to *transformed* tuples
2005 * of the existing relation. It would be wrong to enter NEW
2006 * separately in the jointree, since that would cause a double
2007 * join of the updated relation. It's also wrong to fail to make
2008 * a jointree entry if only NEW and not OLD is mentioned.
2010 if (has_old || (has_new && stmt->event == CMD_UPDATE))
2013 * If sub_qry is a setop, manipulating its jointree will do no
2014 * good at all, because the jointree is dummy. (This should be
2015 * a can't-happen case because of prior tests.)
2017 if (sub_qry->setOperations != NULL)
2019 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2020 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2021 /* hack so we can use addRTEtoQuery() */
2022 sub_pstate->p_rtable = sub_qry->rtable;
2023 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2024 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2025 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2028 newactions = list_concat(newactions, extras_before);
2029 newactions = lappend(newactions, top_subqry);
2030 newactions = list_concat(newactions, extras_after);
2032 release_pstate_resources(sub_pstate);
2036 *actions = newactions;
2039 release_pstate_resources(pstate);
2042 /* Close relation, but keep the exclusive lock */
2043 heap_close(rel, NoLock);
2048 * transformSelectStmt -
2049 * transforms a Select Statement
2051 * Note: this is also used for DECLARE CURSOR statements.
2054 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
2056 Query *qry = makeNode(Query);
2060 qry->commandType = CMD_SELECT;
2062 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2063 pstate->p_locking_clause = stmt->lockingClause;
2065 /* process the FROM clause */
2066 transformFromClause(pstate, stmt->fromClause);
2068 /* transform targetlist */
2069 qry->targetList = transformTargetList(pstate, stmt->targetList);
2071 /* mark column origins */
2072 markTargetListOrigins(pstate, qry->targetList);
2074 /* transform WHERE */
2075 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2078 * Initial processing of HAVING clause is just like WHERE clause.
2080 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
2084 * Transform sorting/grouping stuff. Do ORDER BY first because both
2085 * transformGroupClause and transformDistinctClause need the results.
2087 qry->sortClause = transformSortClause(pstate,
2090 true /* fix unknowns */ );
2092 qry->groupClause = transformGroupClause(pstate,
2097 qry->distinctClause = transformDistinctClause(pstate,
2098 stmt->distinctClause,
2102 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2104 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2107 /* handle any SELECT INTO/CREATE TABLE AS spec */
2108 if (stmt->intoClause)
2110 qry->intoClause = stmt->intoClause;
2111 if (stmt->intoClause->colNames)
2112 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
2115 qry->rtable = pstate->p_rtable;
2116 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2118 qry->hasSubLinks = pstate->p_hasSubLinks;
2119 qry->hasAggs = pstate->p_hasAggs;
2120 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2121 parseCheckAggregates(pstate, qry);
2123 foreach(l, stmt->lockingClause)
2125 transformLockingClause(qry, (LockingClause *) lfirst(l));
2132 * transformValuesClause -
2133 * transforms a VALUES clause that's being used as a standalone SELECT
2135 * We build a Query containing a VALUES RTE, rather as if one had written
2136 * SELECT * FROM (VALUES ...)
2139 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
2141 Query *qry = makeNode(Query);
2142 List *exprsLists = NIL;
2143 List **coltype_lists = NULL;
2144 Oid *coltypes = NULL;
2145 int sublist_length = -1;
2146 List *newExprsLists;
2153 qry->commandType = CMD_SELECT;
2155 /* Most SELECT stuff doesn't apply in a VALUES clause */
2156 Assert(stmt->distinctClause == NIL);
2157 Assert(stmt->targetList == NIL);
2158 Assert(stmt->fromClause == NIL);
2159 Assert(stmt->whereClause == NULL);
2160 Assert(stmt->groupClause == NIL);
2161 Assert(stmt->havingClause == NULL);
2162 Assert(stmt->op == SETOP_NONE);
2165 * For each row of VALUES, transform the raw expressions and gather type
2166 * information. This is also a handy place to reject DEFAULT nodes, which
2167 * the grammar allows for simplicity.
2169 foreach(lc, stmt->valuesLists)
2171 List *sublist = (List *) lfirst(lc);
2173 /* Do basic expression transformation (same as a ROW() expr) */
2174 sublist = transformExpressionList(pstate, sublist);
2177 * All the sublists must be the same length, *after* transformation
2178 * (which might expand '*' into multiple items). The VALUES RTE can't
2179 * handle anything different.
2181 if (sublist_length < 0)
2183 /* Remember post-transformation length of first sublist */
2184 sublist_length = list_length(sublist);
2185 /* and allocate arrays for column-type info */
2186 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
2187 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
2189 else if (sublist_length != list_length(sublist))
2192 (errcode(ERRCODE_SYNTAX_ERROR),
2193 errmsg("VALUES lists must all be the same length")));
2196 exprsLists = lappend(exprsLists, sublist);
2199 foreach(lc2, sublist)
2201 Node *col = (Node *) lfirst(lc2);
2203 if (IsA(col, SetToDefault))
2205 (errcode(ERRCODE_SYNTAX_ERROR),
2206 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
2207 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
2213 * Now resolve the common types of the columns, and coerce everything to
2216 for (i = 0; i < sublist_length; i++)
2218 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
2221 newExprsLists = NIL;
2222 foreach(lc, exprsLists)
2224 List *sublist = (List *) lfirst(lc);
2225 List *newsublist = NIL;
2228 foreach(lc2, sublist)
2230 Node *col = (Node *) lfirst(lc2);
2232 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
2233 newsublist = lappend(newsublist, col);
2237 newExprsLists = lappend(newExprsLists, newsublist);
2241 * Generate the VALUES RTE
2243 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
2244 rtr = makeNode(RangeTblRef);
2245 /* assume new rte is at end */
2246 rtr->rtindex = list_length(pstate->p_rtable);
2247 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2248 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2249 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
2252 * Generate a targetlist as though expanding "*"
2254 Assert(pstate->p_next_resno == 1);
2255 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
2258 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2261 qry->sortClause = transformSortClause(pstate,
2264 true /* fix unknowns */ );
2266 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2268 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2271 if (stmt->lockingClause)
2273 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2274 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
2276 /* handle any CREATE TABLE AS spec */
2277 if (stmt->intoClause)
2279 qry->intoClause = stmt->intoClause;
2280 if (stmt->intoClause->colNames)
2281 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
2285 * There mustn't have been any table references in the expressions, else
2286 * strange things would happen, like Cartesian products of those tables
2287 * with the VALUES list. We have to check this after parsing ORDER BY et
2288 * al since those could insert more junk.
2290 if (list_length(pstate->p_joinlist) != 1)
2292 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2293 errmsg("VALUES must not contain table references")));
2296 * Another thing we can't currently support is NEW/OLD references in rules
2297 * --- seems we'd need something like SQL99's LATERAL construct to ensure
2298 * that the values would be available while evaluating the VALUES RTE.
2299 * This is a shame. FIXME
2301 if (list_length(pstate->p_rtable) != 1 &&
2302 contain_vars_of_level((Node *) newExprsLists, 0))
2304 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2305 errmsg("VALUES must not contain OLD or NEW references"),
2306 errhint("Use SELECT ... UNION ALL ... instead.")));
2308 qry->rtable = pstate->p_rtable;
2309 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2311 qry->hasSubLinks = pstate->p_hasSubLinks;
2312 /* aggregates not allowed (but subselects are okay) */
2313 if (pstate->p_hasAggs)
2315 (errcode(ERRCODE_GROUPING_ERROR),
2316 errmsg("cannot use aggregate function in VALUES")));
2322 * transformSetOperationsStmt -
2323 * transforms a set-operations tree
2325 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
2326 * structure to it. We must transform each leaf SELECT and build up a top-
2327 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
2328 * The tree of set operations is converted into the setOperations field of
2329 * the top-level Query.
2332 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
2334 Query *qry = makeNode(Query);
2335 SelectStmt *leftmostSelect;
2337 Query *leftmostQuery;
2338 SetOperationStmt *sostmt;
2339 List *intoColNames = NIL;
2343 List *lockingClause;
2345 ListCell *left_tlist,
2354 RangeTblEntry *jrte;
2357 qry->commandType = CMD_SELECT;
2360 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
2361 * and from the top-level node.
2363 leftmostSelect = stmt->larg;
2364 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2365 leftmostSelect = leftmostSelect->larg;
2366 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
2367 leftmostSelect->larg == NULL);
2368 if (leftmostSelect->intoClause)
2370 qry->intoClause = leftmostSelect->intoClause;
2371 intoColNames = leftmostSelect->intoClause->colNames;
2374 /* clear this to prevent complaints in transformSetOperationTree() */
2375 leftmostSelect->intoClause = NULL;
2378 * These are not one-time, exactly, but we want to process them here and
2379 * not let transformSetOperationTree() see them --- else it'll just
2380 * recurse right back here!
2382 sortClause = stmt->sortClause;
2383 limitOffset = stmt->limitOffset;
2384 limitCount = stmt->limitCount;
2385 lockingClause = stmt->lockingClause;
2387 stmt->sortClause = NIL;
2388 stmt->limitOffset = NULL;
2389 stmt->limitCount = NULL;
2390 stmt->lockingClause = NIL;
2392 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2395 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2396 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2399 * Recursively transform the components of the tree.
2401 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
2402 Assert(sostmt && IsA(sostmt, SetOperationStmt));
2403 qry->setOperations = (Node *) sostmt;
2406 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2408 node = sostmt->larg;
2409 while (node && IsA(node, SetOperationStmt))
2410 node = ((SetOperationStmt *) node)->larg;
2411 Assert(node && IsA(node, RangeTblRef));
2412 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2413 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2414 Assert(leftmostQuery != NULL);
2417 * Generate dummy targetlist for outer query using column names of
2418 * leftmost select and common datatypes of topmost set operation. Also
2419 * make lists of the dummy vars and their names for use in parsing ORDER
2422 * Note: we use leftmostRTI as the varno of the dummy variables. It
2423 * shouldn't matter too much which RT index they have, as long as they
2424 * have one that corresponds to a real RT entry; else funny things may
2425 * happen when the tree is mashed by rule rewriting.
2427 qry->targetList = NIL;
2430 left_tlist = list_head(leftmostQuery->targetList);
2432 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
2434 Oid colType = lfirst_oid(lct);
2435 int32 colTypmod = lfirst_int(lcm);
2436 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2441 Assert(!lefttle->resjunk);
2442 colName = pstrdup(lefttle->resname);
2443 expr = (Expr *) makeVar(leftmostRTI,
2448 tle = makeTargetEntry(expr,
2449 (AttrNumber) pstate->p_next_resno++,
2452 qry->targetList = lappend(qry->targetList, tle);
2453 targetvars = lappend(targetvars, expr);
2454 targetnames = lappend(targetnames, makeString(colName));
2455 left_tlist = lnext(left_tlist);
2459 * As a first step towards supporting sort clauses that are expressions
2460 * using the output columns, generate a varnamespace entry that makes the
2461 * output columns visible. A Join RTE node is handy for this, since we
2462 * can easily control the Vars generated upon matches.
2464 * Note: we don't yet do anything useful with such cases, but at least
2465 * "ORDER BY upper(foo)" will draw the right error message rather than
2468 jrte = addRangeTableEntryForJoin(NULL,
2475 sv_rtable = pstate->p_rtable;
2476 pstate->p_rtable = list_make1(jrte);
2478 sv_relnamespace = pstate->p_relnamespace;
2479 pstate->p_relnamespace = NIL; /* no qualified names allowed */
2481 sv_varnamespace = pstate->p_varnamespace;
2482 pstate->p_varnamespace = list_make1(jrte);
2485 * For now, we don't support resjunk sort clauses on the output of a
2486 * setOperation tree --- you can only use the SQL92-spec options of
2487 * selecting an output column by name or number. Enforce by checking that
2488 * transformSortClause doesn't add any items to tlist.
2490 tllen = list_length(qry->targetList);
2492 qry->sortClause = transformSortClause(pstate,
2495 false /* no unknowns expected */ );
2497 pstate->p_rtable = sv_rtable;
2498 pstate->p_relnamespace = sv_relnamespace;
2499 pstate->p_varnamespace = sv_varnamespace;
2501 if (tllen != list_length(qry->targetList))
2503 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2504 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2505 errdetail("Only result column names can be used, not expressions or functions."),
2506 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
2508 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2510 qry->limitCount = transformLimitClause(pstate, limitCount,
2514 * Handle SELECT INTO/CREATE TABLE AS.
2516 * Any column names from CREATE TABLE AS need to be attached to both the
2517 * top level and the leftmost subquery. We do not do this earlier because
2518 * we do *not* want sortClause processing to be affected.
2522 applyColumnNames(qry->targetList, intoColNames);
2523 applyColumnNames(leftmostQuery->targetList, intoColNames);
2526 qry->rtable = pstate->p_rtable;
2527 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2529 qry->hasSubLinks = pstate->p_hasSubLinks;
2530 qry->hasAggs = pstate->p_hasAggs;
2531 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2532 parseCheckAggregates(pstate, qry);
2534 foreach(l, lockingClause)
2536 transformLockingClause(qry, (LockingClause *) lfirst(l));
2543 * transformSetOperationTree
2544 * Recursively transform leaves and internal nodes of a set-op tree
2547 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2551 Assert(stmt && IsA(stmt, SelectStmt));
2554 * Validity-check both leaf and internal SELECTs for disallowed ops.
2556 if (stmt->intoClause)
2558 (errcode(ERRCODE_SYNTAX_ERROR),
2559 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2560 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2561 if (stmt->lockingClause)
2563 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2564 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2567 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2568 * clauses attached, we need to treat it like a leaf node to generate an
2569 * independent sub-Query tree. Otherwise, it can be represented by a
2570 * SetOperationStmt node underneath the parent Query.
2572 if (stmt->op == SETOP_NONE)
2574 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2579 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2580 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2581 stmt->lockingClause)
2589 /* Process leaf SELECT */
2592 char selectName[32];
2597 * Transform SelectStmt into a Query.
2599 * Note: previously transformed sub-queries don't affect the parsing
2600 * of this sub-query, because they are not in the toplevel pstate's
2603 selectList = parse_sub_analyze((Node *) stmt, pstate);
2605 Assert(list_length(selectList) == 1);
2606 selectQuery = (Query *) linitial(selectList);
2607 Assert(IsA(selectQuery, Query));
2610 * Check for bogus references to Vars on the current query level (but
2611 * upper-level references are okay). Normally this can't happen
2612 * because the namespace will be empty, but it could happen if we are
2615 if (pstate->p_relnamespace || pstate->p_varnamespace)
2617 if (contain_vars_of_level((Node *) selectQuery, 1))
2619 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2620 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
2624 * Make the leaf query be a subquery in the top-level rangetable.
2626 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2627 list_length(pstate->p_rtable) + 1);
2628 rte = addRangeTableEntryForSubquery(pstate,
2630 makeAlias(selectName, NIL),
2634 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2636 rtr = makeNode(RangeTblRef);
2637 /* assume new rte is at end */
2638 rtr->rtindex = list_length(pstate->p_rtable);
2639 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2640 return (Node *) rtr;
2644 /* Process an internal node (set operation node) */
2645 SetOperationStmt *op = makeNode(SetOperationStmt);
2654 const char *context;
2656 context = (stmt->op == SETOP_UNION ? "UNION" :
2657 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2661 op->all = stmt->all;
2664 * Recursively transform the child nodes.
2666 op->larg = transformSetOperationTree(pstate, stmt->larg);
2667 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2670 * Verify that the two children have the same number of non-junk
2671 * columns, and determine the types of the merged output columns.
2673 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
2674 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
2675 if (list_length(lcoltypes) != list_length(rcoltypes))
2677 (errcode(ERRCODE_SYNTAX_ERROR),
2678 errmsg("each %s query must have the same number of columns",
2680 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
2681 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
2684 op->colTypmods = NIL;
2685 /* don't have a "foreach4", so chase two of the lists by hand */
2686 lcm = list_head(lcoltypmods);
2687 rcm = list_head(rcoltypmods);
2688 forboth(lct, lcoltypes, rct, rcoltypes)
2690 Oid lcoltype = lfirst_oid(lct);
2691 Oid rcoltype = lfirst_oid(rct);
2692 int32 lcoltypmod = lfirst_int(lcm);
2693 int32 rcoltypmod = lfirst_int(rcm);
2697 /* select common type, same as CASE et al */
2698 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2700 /* if same type and same typmod, use typmod; else default */
2701 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
2702 rescoltypmod = lcoltypmod;
2705 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2706 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2718 * Get output column types/typmods of an (already transformed) set-op node
2721 getSetColTypes(ParseState *pstate, Node *node,
2722 List **colTypes, List **colTypmods)
2726 if (IsA(node, RangeTblRef))
2728 RangeTblRef *rtr = (RangeTblRef *) node;
2729 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2730 Query *selectQuery = rte->subquery;
2733 Assert(selectQuery != NULL);
2734 /* Get types of non-junk columns */
2735 foreach(tl, selectQuery->targetList)
2737 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2741 *colTypes = lappend_oid(*colTypes,
2742 exprType((Node *) tle->expr));
2743 *colTypmods = lappend_int(*colTypmods,
2744 exprTypmod((Node *) tle->expr));
2747 else if (IsA(node, SetOperationStmt))
2749 SetOperationStmt *op = (SetOperationStmt *) node;
2751 /* Result already computed during transformation of node */
2752 Assert(op->colTypes != NIL);
2753 *colTypes = op->colTypes;
2754 *colTypmods = op->colTypmods;
2757 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2760 /* Attach column names from a ColumnDef list to a TargetEntry list */
2762 applyColumnNames(List *dst, List *src)
2767 src_item = list_head(src);
2769 foreach(dst_item, dst)
2771 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2774 /* junk targets don't count */
2778 /* fewer ColumnDefs than target entries is OK */
2779 if (src_item == NULL)
2782 s = (ColumnDef *) lfirst(src_item);
2783 src_item = lnext(src_item);
2785 d->resname = pstrdup(s->colname);
2788 /* more ColumnDefs than target entries is not OK */
2789 if (src_item != NULL)
2791 (errcode(ERRCODE_SYNTAX_ERROR),
2792 errmsg("CREATE TABLE AS specifies too many column names")));
2797 * transformUpdateStmt -
2798 * transforms an update statement
2801 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2803 Query *qry = makeNode(Query);
2805 ListCell *origTargetList;
2808 qry->commandType = CMD_UPDATE;
2809 pstate->p_is_update = true;
2811 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2812 interpretInhOption(stmt->relation->inhOpt),
2817 * the FROM clause is non-standard SQL syntax. We used to be able to do
2818 * this with REPLACE in POSTQUEL so we keep the feature.
2820 transformFromClause(pstate, stmt->fromClause);
2822 qry->targetList = transformTargetList(pstate, stmt->targetList);
2824 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2826 qry->returningList = transformReturningList(pstate, stmt->returningList);
2828 qry->rtable = pstate->p_rtable;
2829 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2831 qry->hasSubLinks = pstate->p_hasSubLinks;
2834 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
2835 * an implementation point of view, this is forced because the implicit
2836 * ctid reference would otherwise be an ungrouped variable.)
2838 if (pstate->p_hasAggs)
2840 (errcode(ERRCODE_GROUPING_ERROR),
2841 errmsg("cannot use aggregate function in UPDATE")));
2844 * Now we are done with SELECT-like processing, and can get on with
2845 * transforming the target list to match the UPDATE target columns.
2848 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2849 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2850 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2852 /* Prepare non-junk columns for assignment to target table */
2853 origTargetList = list_head(stmt->targetList);
2855 foreach(tl, qry->targetList)
2857 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2858 ResTarget *origTarget;
2864 * Resjunk nodes need no additional processing, but be sure they
2865 * have resnos that do not match any target columns; else rewriter
2866 * or planner might get confused. They don't need a resname
2869 tle->resno = (AttrNumber) pstate->p_next_resno++;
2870 tle->resname = NULL;
2873 if (origTargetList == NULL)
2874 elog(ERROR, "UPDATE target count mismatch --- internal error");
2875 origTarget = (ResTarget *) lfirst(origTargetList);
2876 Assert(IsA(origTarget, ResTarget));
2878 attrno = attnameAttNum(pstate->p_target_relation,
2879 origTarget->name, true);
2880 if (attrno == InvalidAttrNumber)
2882 (errcode(ERRCODE_UNDEFINED_COLUMN),
2883 errmsg("column \"%s\" of relation \"%s\" does not exist",
2885 RelationGetRelationName(pstate->p_target_relation)),
2886 parser_errposition(pstate, origTarget->location)));
2888 updateTargetListEntry(pstate, tle, origTarget->name,
2890 origTarget->indirection,
2891 origTarget->location);
2893 origTargetList = lnext(origTargetList);
2895 if (origTargetList != NULL)
2896 elog(ERROR, "UPDATE target count mismatch --- internal error");
2902 * transformReturningList -
2903 * handle a RETURNING clause in INSERT/UPDATE/DELETE
2906 transformReturningList(ParseState *pstate, List *returningList)
2909 int save_next_resno;
2913 if (returningList == NIL)
2914 return NIL; /* nothing to do */
2917 * We need to assign resnos starting at one in the RETURNING list. Save
2918 * and restore the main tlist's value of p_next_resno, just in case
2919 * someone looks at it later (probably won't happen).
2921 save_next_resno = pstate->p_next_resno;
2922 pstate->p_next_resno = 1;
2924 /* save other state so that we can detect disallowed stuff */
2925 save_hasAggs = pstate->p_hasAggs;
2926 pstate->p_hasAggs = false;
2927 length_rtable = list_length(pstate->p_rtable);
2929 /* transform RETURNING identically to a SELECT targetlist */
2930 rlist = transformTargetList(pstate, returningList);
2932 /* check for disallowed stuff */
2934 /* aggregates not allowed (but subselects are okay) */
2935 if (pstate->p_hasAggs)
2937 (errcode(ERRCODE_GROUPING_ERROR),
2938 errmsg("cannot use aggregate function in RETURNING")));
2940 /* no new relation references please */
2941 if (list_length(pstate->p_rtable) != length_rtable)
2943 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2944 errmsg("RETURNING cannot contain references to other relations")));
2946 /* mark column origins */
2947 markTargetListOrigins(pstate, rlist);
2950 pstate->p_next_resno = save_next_resno;
2951 pstate->p_hasAggs = save_hasAggs;
2957 * transformAlterTableStmt -
2958 * transform an Alter Table Statement
2960 * CAUTION: resist the temptation to do any work here that depends on the
2961 * current state of the table. Actual execution of the command might not
2962 * occur till some future transaction. Hence, we do only purely syntactic
2963 * transformations here, comparable to the processing of CREATE TABLE.
2966 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2967 List **extras_before, List **extras_after)
2969 CreateStmtContext cxt;
2973 List *newcmds = NIL;
2974 bool skipValidation = true;
2975 AlterTableCmd *newcmd;
2977 cxt.stmtType = "ALTER TABLE";
2978 cxt.relation = stmt->relation;
2979 cxt.inhRelations = NIL;
2981 cxt.hasoids = false; /* need not be right */
2983 cxt.ckconstraints = NIL;
2984 cxt.fkconstraints = NIL;
2985 cxt.ixconstraints = NIL;
2991 * The only subtypes that currently require parse transformation handling
2992 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
2995 foreach(lcmd, stmt->cmds)
2997 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2999 switch (cmd->subtype)
3003 ColumnDef *def = (ColumnDef *) cmd->def;
3005 Assert(IsA(cmd->def, ColumnDef));
3006 transformColumnDefinition(pstate, &cxt,
3007 (ColumnDef *) cmd->def);
3010 * If the column has a non-null default, we can't skip
3011 * validation of foreign keys.
3013 if (((ColumnDef *) cmd->def)->raw_default != NULL)
3014 skipValidation = false;
3016 newcmds = lappend(newcmds, cmd);
3019 * Convert an ADD COLUMN ... NOT NULL constraint to a
3022 if (def->is_not_null)
3024 /* Remove NOT NULL from AddColumn */
3025 def->is_not_null = false;
3027 /* Add as a separate AlterTableCmd */
3028 newcmd = makeNode(AlterTableCmd);
3029 newcmd->subtype = AT_SetNotNull;
3030 newcmd->name = pstrdup(def->colname);
3031 newcmds = lappend(newcmds, newcmd);
3035 * All constraints are processed in other ways. Remove the
3038 def->constraints = NIL;
3042 case AT_AddConstraint:
3045 * The original AddConstraint cmd node doesn't go to newcmds
3048 if (IsA(cmd->def, Constraint))
3049 transformTableConstraint(pstate, &cxt,
3050 (Constraint *) cmd->def);
3051 else if (IsA(cmd->def, FkConstraint))
3053 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
3054 skipValidation = false;
3057 elog(ERROR, "unrecognized node type: %d",
3058 (int) nodeTag(cmd->def));
3061 case AT_ProcessedConstraint:
3064 * Already-transformed ADD CONSTRAINT, so just make it look
3065 * like the standard case.
3067 cmd->subtype = AT_AddConstraint;
3068 newcmds = lappend(newcmds, cmd);
3072 newcmds = lappend(newcmds, cmd);
3078 * transformIndexConstraints wants cxt.alist to contain only index
3079 * statements, so transfer anything we already have into extras_after
3082 *extras_after = list_concat(cxt.alist, *extras_after);
3085 /* Postprocess index and FK constraints */
3086 transformIndexConstraints(pstate, &cxt);
3088 transformFKConstraints(pstate, &cxt, skipValidation, true);
3091 * Push any index-creation commands into the ALTER, so that they can be
3092 * scheduled nicely by tablecmds.c.
3094 foreach(l, cxt.alist)
3096 Node *idxstmt = (Node *) lfirst(l);
3098 Assert(IsA(idxstmt, IndexStmt));
3099 newcmd = makeNode(AlterTableCmd);
3100 newcmd->subtype = AT_AddIndex;
3101 newcmd->def = idxstmt;
3102 newcmds = lappend(newcmds, newcmd);
3106 /* Append any CHECK or FK constraints to the commands list */
3107 foreach(l, cxt.ckconstraints)
3109 newcmd = makeNode(AlterTableCmd);
3110 newcmd->subtype = AT_AddConstraint;
3111 newcmd->def = (Node *) lfirst(l);
3112 newcmds = lappend(newcmds, newcmd);
3114 foreach(l, cxt.fkconstraints)
3116 newcmd = makeNode(AlterTableCmd);
3117 newcmd->subtype = AT_AddConstraint;
3118 newcmd->def = (Node *) lfirst(l);
3119 newcmds = lappend(newcmds, newcmd);
3122 /* Update statement's commands list */
3123 stmt->cmds = newcmds;
3125 qry = makeNode(Query);
3126 qry->commandType = CMD_UTILITY;
3127 qry->utilityStmt = (Node *) stmt;
3129 *extras_before = list_concat(*extras_before, cxt.blist);
3130 *extras_after = list_concat(cxt.alist, *extras_after);
3137 * transformDeclareCursorStmt -
3138 * transform a DECLARE CURSOR Statement
3140 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
3141 * significantly different from a SELECT) as far as parsing/rewriting/planning
3142 * are concerned, but it's not passed to the executor and so in that sense is
3143 * a utility statement. We transform it into a Query exactly as if it were
3144 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
3145 * field to carry the cursor name and options.
3148 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
3151 List *extras_before = NIL,
3152 *extras_after = NIL;
3155 * Don't allow both SCROLL and NO SCROLL to be specified
3157 if ((stmt->options & CURSOR_OPT_SCROLL) &&
3158 (stmt->options & CURSOR_OPT_NO_SCROLL))
3160 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3161 errmsg("cannot specify both SCROLL and NO SCROLL")));
3163 result = transformStmt(pstate, stmt->query,
3164 &extras_before, &extras_after);
3166 /* Shouldn't get any extras, since grammar only allows SelectStmt */
3167 if (extras_before || extras_after)
3168 elog(ERROR, "unexpected extra stuff in cursor statement");
3169 if (!IsA(result, Query) ||
3170 result->commandType != CMD_SELECT ||
3171 result->utilityStmt != NULL)
3172 elog(ERROR, "unexpected non-SELECT command in cursor statement");
3174 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
3175 if (result->intoClause)
3177 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3178 errmsg("DECLARE CURSOR cannot specify INTO")));
3180 /* FOR UPDATE and WITH HOLD are not compatible */
3181 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
3183 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3184 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
3185 errdetail("Holdable cursors must be READ ONLY.")));
3187 /* We won't need the raw querytree any more */
3190 result->utilityStmt = (Node *) stmt;
3197 * transformExplainStmt -
3198 * transform an EXPLAIN Statement
3200 * EXPLAIN is just like other utility statements in that we emit it as a
3201 * CMD_UTILITY Query node with no transformation of the raw parse tree.
3202 * However, if p_variableparams is set, it could be that the client is
3203 * expecting us to resolve parameter types in something like
3204 * EXPLAIN SELECT * FROM tab WHERE col = $1
3205 * To deal with such cases, we run parse analysis and throw away the result;
3206 * this is a bit grotty but not worth contorting the rest of the system for.
3207 * (The approach we use for DECLARE CURSOR won't work because the statement
3208 * being explained isn't necessarily a SELECT, and in particular might rewrite
3209 * to multiple parsetrees.)
3212 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
3216 if (pstate->p_variableparams)
3218 List *extras_before = NIL,
3219 *extras_after = NIL;
3221 /* Since parse analysis scribbles on its input, copy the tree first! */
3222 (void) transformStmt(pstate, copyObject(stmt->query),
3223 &extras_before, &extras_after);
3226 /* Now return the untransformed command as a utility Query */
3227 result = makeNode(Query);
3228 result->commandType = CMD_UTILITY;
3229 result->utilityStmt = (Node *) stmt;
3235 /* exported so planner can check again after rewriting, query pullup, etc */
3237 CheckSelectLocking(Query *qry)
3239 if (qry->setOperations)
3241 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3242 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
3243 if (qry->distinctClause != NIL)
3245 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3246 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
3247 if (qry->groupClause != NIL)
3249 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3250 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
3251 if (qry->havingQual != NULL)
3253 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3254 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
3257 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3258 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
3262 * Transform a FOR UPDATE/SHARE clause
3264 * This basically involves replacing names by integer relids.
3266 * NB: if you need to change this, see also markQueryForLocking()
3267 * in rewriteHandler.c.
3270 transformLockingClause(Query *qry, LockingClause *lc)
3272 List *lockedRels = lc->lockedRels;
3276 LockingClause *allrels;
3278 CheckSelectLocking(qry);
3280 /* make a clause we can pass down to subqueries to select all rels */
3281 allrels = makeNode(LockingClause);
3282 allrels->lockedRels = NIL; /* indicates all rels */
3283 allrels->forUpdate = lc->forUpdate;
3284 allrels->noWait = lc->noWait;
3286 if (lockedRels == NIL)
3288 /* all regular tables used in query */
3290 foreach(rt, qry->rtable)
3292 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3295 switch (rte->rtekind)
3298 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
3299 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3304 * FOR UPDATE/SHARE of subquery is propagated to all of
3307 transformLockingClause(rte->subquery, allrels);
3310 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
3317 /* just the named tables */
3318 foreach(l, lockedRels)
3320 char *relname = strVal(lfirst(l));
3323 foreach(rt, qry->rtable)
3325 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3328 if (strcmp(rte->eref->aliasname, relname) == 0)
3330 switch (rte->rtekind)
3333 applyLockingClause(qry, i,
3334 lc->forUpdate, lc->noWait);
3335 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3340 * FOR UPDATE/SHARE of subquery is propagated to
3341 * all of subquery's rels
3343 transformLockingClause(rte->subquery, allrels);
3347 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3348 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
3352 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3353 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
3357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3358 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
3362 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3363 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
3366 elog(ERROR, "unrecognized RTE type: %d",
3367 (int) rte->rtekind);
3370 break; /* out of foreach loop */
3375 (errcode(ERRCODE_UNDEFINED_TABLE),
3376 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
3383 * Record locking info for a single rangetable item
3386 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
3390 /* Check for pre-existing entry for same rtindex */
3391 if ((rc = get_rowmark(qry, rtindex)) != NULL)
3394 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
3395 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
3396 * and exclusive lock at the same time; it'll end up being exclusive
3399 * We also consider that NOWAIT wins if it's specified both ways. This
3400 * is a bit more debatable but raising an error doesn't seem helpful.
3401 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
3402 * internally contains a plain FOR UPDATE spec.)
3404 rc->forUpdate |= forUpdate;
3405 rc->noWait |= noWait;
3409 /* Make a new RowMarkClause */
3410 rc = makeNode(RowMarkClause);
3412 rc->forUpdate = forUpdate;
3413 rc->noWait = noWait;
3414 qry->rowMarks = lappend(qry->rowMarks, rc);
3419 * Preprocess a list of column constraint clauses
3420 * to attach constraint attributes to their primary constraint nodes
3421 * and detect inconsistent/misplaced constraint attributes.
3423 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
3424 * constraints, but someday they ought to be supported for other constraints.
3427 transformConstraintAttrs(List *constraintList)
3429 Node *lastprimarynode = NULL;
3430 bool saw_deferrability = false;
3431 bool saw_initially = false;
3434 foreach(clist, constraintList)
3436 Node *node = lfirst(clist);
3438 if (!IsA(node, Constraint))
3440 lastprimarynode = node;
3441 /* reset flags for new primary node */
3442 saw_deferrability = false;
3443 saw_initially = false;
3447 Constraint *con = (Constraint *) node;
3449 switch (con->contype)
3451 case CONSTR_ATTR_DEFERRABLE:
3452 if (lastprimarynode == NULL ||
3453 !IsA(lastprimarynode, FkConstraint))
3455 (errcode(ERRCODE_SYNTAX_ERROR),
3456 errmsg("misplaced DEFERRABLE clause")));
3457 if (saw_deferrability)
3459 (errcode(ERRCODE_SYNTAX_ERROR),
3460 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3461 saw_deferrability = true;
3462 ((FkConstraint *) lastprimarynode)->deferrable = true;
3464 case CONSTR_ATTR_NOT_DEFERRABLE:
3465 if (lastprimarynode == NULL ||
3466 !IsA(lastprimarynode, FkConstraint))
3468 (errcode(ERRCODE_SYNTAX_ERROR),
3469 errmsg("misplaced NOT DEFERRABLE clause")));
3470 if (saw_deferrability)
3472 (errcode(ERRCODE_SYNTAX_ERROR),
3473 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3474 saw_deferrability = true;
3475 ((FkConstraint *) lastprimarynode)->deferrable = false;
3476 if (saw_initially &&
3477 ((FkConstraint *) lastprimarynode)->initdeferred)
3479 (errcode(ERRCODE_SYNTAX_ERROR),
3480 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3482 case CONSTR_ATTR_DEFERRED:
3483 if (lastprimarynode == NULL ||
3484 !IsA(lastprimarynode, FkConstraint))
3486 (errcode(ERRCODE_SYNTAX_ERROR),
3487 errmsg("misplaced INITIALLY DEFERRED clause")));
3490 (errcode(ERRCODE_SYNTAX_ERROR),
3491 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3492 saw_initially = true;
3493 ((FkConstraint *) lastprimarynode)->initdeferred = true;
3496 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3498 if (!saw_deferrability)
3499 ((FkConstraint *) lastprimarynode)->deferrable = true;
3500 else if (!((FkConstraint *) lastprimarynode)->deferrable)
3502 (errcode(ERRCODE_SYNTAX_ERROR),
3503 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3505 case CONSTR_ATTR_IMMEDIATE:
3506 if (lastprimarynode == NULL ||
3507 !IsA(lastprimarynode, FkConstraint))
3509 (errcode(ERRCODE_SYNTAX_ERROR),
3510 errmsg("misplaced INITIALLY IMMEDIATE clause")));
3513 (errcode(ERRCODE_SYNTAX_ERROR),
3514 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3515 saw_initially = true;
3516 ((FkConstraint *) lastprimarynode)->initdeferred = false;
3519 /* Otherwise it's not an attribute */
3520 lastprimarynode = node;
3521 /* reset flags for new primary node */
3522 saw_deferrability = false;
3523 saw_initially = false;
3530 /* Build a FromExpr node */
3532 makeFromExpr(List *fromlist, Node *quals)
3534 FromExpr *f = makeNode(FromExpr);
3536 f->fromlist = fromlist;
3542 * Special handling of type definition for a column
3545 transformColumnType(ParseState *pstate, ColumnDef *column)
3548 * All we really need to do here is verify that the type is valid.
3550 Type ctype = typenameType(pstate, column->typename);
3552 ReleaseSysCache(ctype);
3556 setSchemaName(char *context_schema, char **stmt_schema_name)
3558 if (*stmt_schema_name == NULL)
3559 *stmt_schema_name = context_schema;
3560 else if (strcmp(context_schema, *stmt_schema_name) != 0)
3562 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3563 errmsg("CREATE specifies a schema (%s) "
3564 "different from the one being created (%s)",
3565 *stmt_schema_name, context_schema)));
3569 * analyzeCreateSchemaStmt -
3570 * analyzes the "create schema" statement
3572 * Split the schema element list into individual commands and place
3573 * them in the result list in an order such that there are no forward
3574 * references (e.g. GRANT to a table created later in the list). Note
3575 * that the logic we use for determining forward references is
3576 * presently quite incomplete.
3578 * SQL92 also allows constraints to make forward references, so thumb through
3579 * the table columns and move forward references to a posterior alter-table
3582 * The result is a list of parse nodes that still need to be analyzed ---
3583 * but we can't analyze the later commands until we've executed the earlier
3584 * ones, because of possible inter-object references.
3586 * Note: Called from commands/schemacmds.c
3589 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3591 CreateSchemaStmtContext cxt;
3595 cxt.stmtType = "CREATE SCHEMA";
3596 cxt.schemaname = stmt->schemaname;
3597 cxt.authid = stmt->authid;
3598 cxt.sequences = NIL;
3604 cxt.fwconstraints = NIL;
3610 * Run through each schema element in the schema element list. Separate
3611 * statements by type, and do preliminary analysis.
3613 foreach(elements, stmt->schemaElts)
3615 Node *element = lfirst(elements);
3617 switch (nodeTag(element))
3619 case T_CreateSeqStmt:
3621 CreateSeqStmt *elp = (CreateSeqStmt *) element;
3623 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3624 cxt.sequences = lappend(cxt.sequences, element);
3630 CreateStmt *elp = (CreateStmt *) element;
3632 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3635 * XXX todo: deal with constraints
3637 cxt.tables = lappend(cxt.tables, element);
3643 ViewStmt *elp = (ViewStmt *) element;
3645 setSchemaName(cxt.schemaname, &elp->view->schemaname);
3648 * XXX todo: deal with references between views
3650 cxt.views = lappend(cxt.views, element);
3656 IndexStmt *elp = (IndexStmt *) element;
3658 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3659 cxt.indexes = lappend(cxt.indexes, element);
3663 case T_CreateTrigStmt:
3665 CreateTrigStmt *elp = (CreateTrigStmt *) element;
3667 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3668 cxt.triggers = lappend(cxt.triggers, element);
3673 cxt.grants = lappend(cxt.grants, element);
3677 elog(ERROR, "unrecognized node type: %d",
3678 (int) nodeTag(element));
3683 result = list_concat(result, cxt.sequences);
3684 result = list_concat(result, cxt.tables);
3685 result = list_concat(result, cxt.views);
3686 result = list_concat(result, cxt.indexes);
3687 result = list_concat(result, cxt.triggers);
3688 result = list_concat(result, cxt.grants);
3694 * Traverse a fully-analyzed tree to verify that parameter symbols
3695 * match their types. We need this because some Params might still
3696 * be UNKNOWN, if there wasn't anything to force their coercion,
3697 * and yet other instances seen later might have gotten coerced.
3700 check_parameter_resolution_walker(Node *node,
3701 check_parameter_resolution_context *context)
3705 if (IsA(node, Param))
3707 Param *param = (Param *) node;
3709 if (param->paramkind == PARAM_EXTERN)
3711 int paramno = param->paramid;
3713 if (paramno <= 0 || /* shouldn't happen, but... */
3714 paramno > context->numParams)
3716 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3717 errmsg("there is no parameter $%d", paramno)));
3719 if (param->paramtype != context->paramTypes[paramno - 1])
3721 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3722 errmsg("could not determine data type of parameter $%d",
3727 if (IsA(node, Query))
3729 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3730 return query_tree_walker((Query *) node,
3731 check_parameter_resolution_walker,
3732 (void *) context, 0);
3734 return expression_tree_walker(node, check_parameter_resolution_walker,