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 * DECLARE CURSOR and EXPLAIN are exceptions because they contain
14 * optimizable statements.
17 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
18 * Portions Copyright (c) 1994, Regents of the University of California
20 * $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.388 2009/01/22 20:16:04 tgl Exp $
22 *-------------------------------------------------------------------------
27 #include "access/sysattr.h"
28 #include "catalog/pg_type.h"
29 #include "nodes/makefuncs.h"
30 #include "nodes/nodeFuncs.h"
31 #include "optimizer/var.h"
32 #include "parser/analyze.h"
33 #include "parser/parse_agg.h"
34 #include "parser/parse_clause.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_cte.h"
37 #include "parser/parse_oper.h"
38 #include "parser/parse_relation.h"
39 #include "parser/parse_target.h"
40 #include "parser/parsetree.h"
41 #include "rewrite/rewriteManip.h"
42 #include "utils/rel.h"
45 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
46 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
47 static List *transformInsertRow(ParseState *pstate, List *exprlist,
48 List *stmtcols, List *icolumns, List *attrnos);
49 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
50 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
51 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
52 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
54 static void applyColumnNames(List *dst, List *src);
55 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
56 static List *transformReturningList(ParseState *pstate, List *returningList);
57 static Query *transformDeclareCursorStmt(ParseState *pstate,
58 DeclareCursorStmt *stmt);
59 static Query *transformExplainStmt(ParseState *pstate,
61 static void transformLockingClause(ParseState *pstate,
62 Query *qry, LockingClause *lc);
63 static bool check_parameter_resolution_walker(Node *node, ParseState *pstate);
68 * Analyze a raw parse tree and transform it to Query form.
70 * Optionally, information about $n parameter types can be supplied.
71 * References to $n indexes not defined by paramTypes[] are disallowed.
73 * The result is a Query node. Optimizable statements require considerable
74 * transformation, while utility-type statements are simply hung off
75 * a dummy CMD_UTILITY Query node.
78 parse_analyze(Node *parseTree, const char *sourceText,
79 Oid *paramTypes, int numParams)
81 ParseState *pstate = make_parsestate(NULL);
84 Assert(sourceText != NULL); /* required as of 8.4 */
86 pstate->p_sourcetext = sourceText;
87 pstate->p_paramtypes = paramTypes;
88 pstate->p_numparams = numParams;
89 pstate->p_variableparams = false;
91 query = transformStmt(pstate, parseTree);
93 free_parsestate(pstate);
99 * parse_analyze_varparams
101 * This variant is used when it's okay to deduce information about $n
102 * symbol datatypes from context. The passed-in paramTypes[] array can
103 * be modified or enlarged (via repalloc).
106 parse_analyze_varparams(Node *parseTree, const char *sourceText,
107 Oid **paramTypes, int *numParams)
109 ParseState *pstate = make_parsestate(NULL);
112 Assert(sourceText != NULL); /* required as of 8.4 */
114 pstate->p_sourcetext = sourceText;
115 pstate->p_paramtypes = *paramTypes;
116 pstate->p_numparams = *numParams;
117 pstate->p_variableparams = true;
119 query = transformStmt(pstate, parseTree);
121 /* make sure all is well with parameter types */
122 if (pstate->p_numparams > 0)
123 check_parameter_resolution_walker((Node *) query, pstate);
125 *paramTypes = pstate->p_paramtypes;
126 *numParams = pstate->p_numparams;
128 free_parsestate(pstate);
135 * Entry point for recursively analyzing a sub-statement.
138 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
140 ParseState *pstate = make_parsestate(parentParseState);
143 query = transformStmt(pstate, parseTree);
145 free_parsestate(pstate);
152 * transform a Parse tree into a Query tree.
155 transformStmt(ParseState *pstate, Node *parseTree)
159 switch (nodeTag(parseTree))
162 * Optimizable statements
165 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
169 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
173 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
178 SelectStmt *n = (SelectStmt *) parseTree;
181 result = transformValuesClause(pstate, n);
182 else if (n->op == SETOP_NONE)
183 result = transformSelectStmt(pstate, n);
185 result = transformSetOperationStmt(pstate, n);
192 case T_DeclareCursorStmt:
193 result = transformDeclareCursorStmt(pstate,
194 (DeclareCursorStmt *) parseTree);
198 result = transformExplainStmt(pstate,
199 (ExplainStmt *) parseTree);
205 * other statements don't require any transformation; just return
206 * the original parsetree with a Query node plastered on top.
208 result = makeNode(Query);
209 result->commandType = CMD_UTILITY;
210 result->utilityStmt = (Node *) parseTree;
214 /* Mark as original query until we learn differently */
215 result->querySource = QSRC_ORIGINAL;
216 result->canSetTag = true;
222 * analyze_requires_snapshot
223 * Returns true if a snapshot must be set before doing parse analysis
224 * on the given raw parse tree.
226 * Classification here should match transformStmt(); but we also have to
227 * allow a NULL input (for Parse/Bind of an empty query string).
230 analyze_requires_snapshot(Node *parseTree)
234 if (parseTree == NULL)
237 switch (nodeTag(parseTree))
240 * Optimizable statements
252 case T_DeclareCursorStmt:
253 /* yes, because it's analyzed just like SELECT */
259 * We only need a snapshot in varparams case, but it doesn't seem
260 * worth complicating this function's API to distinguish that.
266 /* utility statements don't have any active parse analysis */
275 * transformDeleteStmt -
276 * transforms a Delete Statement
279 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
281 Query *qry = makeNode(Query);
284 qry->commandType = CMD_DELETE;
286 /* set up range table with just the result rel */
287 qry->resultRelation = setTargetTable(pstate, stmt->relation,
288 interpretInhOption(stmt->relation->inhOpt),
292 qry->distinctClause = NIL;
295 * The USING clause is non-standard SQL syntax, and is equivalent in
296 * functionality to the FROM list that can be specified for UPDATE. The
297 * USING keyword is used rather than FROM because FROM is already a
298 * keyword in the DELETE syntax.
300 transformFromClause(pstate, stmt->usingClause);
302 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
304 qry->returningList = transformReturningList(pstate, stmt->returningList);
306 /* done building the range table and jointree */
307 qry->rtable = pstate->p_rtable;
308 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
310 qry->hasSubLinks = pstate->p_hasSubLinks;
311 qry->hasAggs = pstate->p_hasAggs;
312 if (pstate->p_hasAggs)
313 parseCheckAggregates(pstate, qry);
314 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
315 if (pstate->p_hasWindowFuncs)
316 parseCheckWindowFuncs(pstate, qry);
322 * transformInsertStmt -
323 * transform an Insert Statement
326 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
328 Query *qry = makeNode(Query);
329 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
330 List *exprList = NIL;
331 bool isGeneralSelect;
333 List *sub_relnamespace;
334 List *sub_varnamespace;
343 qry->commandType = CMD_INSERT;
344 pstate->p_is_insert = true;
347 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
348 * VALUES list, or general SELECT input. We special-case VALUES, both for
349 * efficiency and so we can handle DEFAULT specifications.
351 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
354 * If a non-nil rangetable/namespace was passed in, and we are doing
355 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
356 * SELECT. This can only happen if we are inside a CREATE RULE, and in
357 * that case we want the rule's OLD and NEW rtable entries to appear as
358 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
359 * The SELECT's joinlist is not affected however. We must do this before
360 * adding the target table to the INSERT's rtable.
364 sub_rtable = pstate->p_rtable;
365 pstate->p_rtable = NIL;
366 sub_relnamespace = pstate->p_relnamespace;
367 pstate->p_relnamespace = NIL;
368 sub_varnamespace = pstate->p_varnamespace;
369 pstate->p_varnamespace = NIL;
370 /* There can't be any outer WITH to worry about */
371 Assert(pstate->p_ctenamespace == NIL);
375 sub_rtable = NIL; /* not used, but keep compiler quiet */
376 sub_relnamespace = NIL;
377 sub_varnamespace = NIL;
381 * Must get write lock on INSERT target table before scanning SELECT, else
382 * we will grab the wrong kind of initial lock if the target table is also
383 * mentioned in the SELECT part. Note that the target table is not added
384 * to the joinlist or namespace.
386 qry->resultRelation = setTargetTable(pstate, stmt->relation,
387 false, false, ACL_INSERT);
389 /* Validate stmt->cols list, or build default list if no list given */
390 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
391 Assert(list_length(icolumns) == list_length(attrnos));
394 * Determine which variant of INSERT we have.
396 if (selectStmt == NULL)
399 * We have INSERT ... DEFAULT VALUES. We can handle this case by
400 * emitting an empty targetlist --- all columns will be defaulted when
401 * the planner expands the targetlist.
405 else if (isGeneralSelect)
408 * We make the sub-pstate a child of the outer pstate so that it can
409 * see any Param definitions supplied from above. Since the outer
410 * pstate's rtable and namespace are presently empty, there are no
411 * side-effects of exposing names the sub-SELECT shouldn't be able to
414 ParseState *sub_pstate = make_parsestate(pstate);
418 * Process the source SELECT.
420 * It is important that this be handled just like a standalone SELECT;
421 * otherwise the behavior of SELECT within INSERT might be different
422 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
423 * bugs of just that nature...)
425 sub_pstate->p_rtable = sub_rtable;
426 sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
427 sub_pstate->p_relnamespace = sub_relnamespace;
428 sub_pstate->p_varnamespace = sub_varnamespace;
430 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
432 free_parsestate(sub_pstate);
434 /* The grammar should have produced a SELECT, but it might have INTO */
435 if (!IsA(selectQuery, Query) ||
436 selectQuery->commandType != CMD_SELECT ||
437 selectQuery->utilityStmt != NULL)
438 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
439 if (selectQuery->intoClause)
441 (errcode(ERRCODE_SYNTAX_ERROR),
442 errmsg("INSERT ... SELECT cannot specify INTO"),
443 parser_errposition(pstate,
444 exprLocation((Node *) selectQuery->intoClause))));
447 * Make the source be a subquery in the INSERT's rangetable, and add
448 * it to the INSERT's joinlist.
450 rte = addRangeTableEntryForSubquery(pstate,
452 makeAlias("*SELECT*", NIL),
454 rtr = makeNode(RangeTblRef);
455 /* assume new rte is at end */
456 rtr->rtindex = list_length(pstate->p_rtable);
457 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
458 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
461 * Generate an expression list for the INSERT that selects all the
462 * non-resjunk columns from the subquery. (INSERT's tlist must be
463 * separate from the subquery's tlist because we may add columns,
464 * insert datatype coercions, etc.)
466 * HACK: unknown-type constants and params in the SELECT's targetlist
467 * are copied up as-is rather than being referenced as subquery
468 * outputs. This is to ensure that when we try to coerce them to
469 * the target column's datatype, the right things happen (see
470 * special cases in coerce_type). Otherwise, this fails:
471 * INSERT INTO foo SELECT 'bar', ... FROM baz
475 foreach(lc, selectQuery->targetList)
477 TargetEntry *tle = (TargetEntry *) lfirst(lc);
483 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
484 exprType((Node *) tle->expr) == UNKNOWNOID)
488 Var *var = makeVar(rtr->rtindex,
490 exprType((Node *) tle->expr),
491 exprTypmod((Node *) tle->expr),
493 var->location = exprLocation((Node *) tle->expr);
496 exprList = lappend(exprList, expr);
499 /* Prepare row for assignment to target table */
500 exprList = transformInsertRow(pstate, exprList,
504 else if (list_length(selectStmt->valuesLists) > 1)
507 * Process INSERT ... VALUES with multiple VALUES sublists. We
508 * generate a VALUES RTE holding the transformed expression lists, and
509 * build up a targetlist containing Vars that reference the VALUES
512 List *exprsLists = NIL;
513 int sublist_length = -1;
515 /* process the WITH clause */
516 if (selectStmt->withClause)
518 qry->hasRecursive = selectStmt->withClause->recursive;
519 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
522 foreach(lc, selectStmt->valuesLists)
524 List *sublist = (List *) lfirst(lc);
526 /* Do basic expression transformation (same as a ROW() expr) */
527 sublist = transformExpressionList(pstate, sublist);
530 * All the sublists must be the same length, *after*
531 * transformation (which might expand '*' into multiple items).
532 * The VALUES RTE can't handle anything different.
534 if (sublist_length < 0)
536 /* Remember post-transformation length of first sublist */
537 sublist_length = list_length(sublist);
539 else if (sublist_length != list_length(sublist))
542 (errcode(ERRCODE_SYNTAX_ERROR),
543 errmsg("VALUES lists must all be the same length"),
544 parser_errposition(pstate,
545 exprLocation((Node *) sublist))));
548 /* Prepare row for assignment to target table */
549 sublist = transformInsertRow(pstate, sublist,
553 exprsLists = lappend(exprsLists, sublist);
557 * There mustn't have been any table references in the expressions,
558 * else strange things would happen, like Cartesian products of those
559 * tables with the VALUES list ...
561 if (pstate->p_joinlist != NIL)
563 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
564 errmsg("VALUES must not contain table references"),
565 parser_errposition(pstate,
566 locate_var_of_level((Node *) exprsLists, 0))));
569 * Another thing we can't currently support is NEW/OLD references in
570 * rules --- seems we'd need something like SQL99's LATERAL construct
571 * to ensure that the values would be available while evaluating the
572 * VALUES RTE. This is a shame. FIXME
574 if (list_length(pstate->p_rtable) != 1 &&
575 contain_vars_of_level((Node *) exprsLists, 0))
577 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
578 errmsg("VALUES must not contain OLD or NEW references"),
579 errhint("Use SELECT ... UNION ALL ... instead."),
580 parser_errposition(pstate,
581 locate_var_of_level((Node *) exprsLists, 0))));
584 * Generate the VALUES RTE
586 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
587 rtr = makeNode(RangeTblRef);
588 /* assume new rte is at end */
589 rtr->rtindex = list_length(pstate->p_rtable);
590 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
591 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
594 * Generate list of Vars referencing the RTE
596 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
601 * Process INSERT ... VALUES with a single VALUES sublist.
602 * We treat this separately for efficiency and for historical
603 * compatibility --- specifically, allowing table references,
605 * INSERT INTO foo VALUES(bar.*)
607 * The sublist is just computed directly as the Query's targetlist,
608 * with no VALUES RTE. So it works just like SELECT without FROM.
611 List *valuesLists = selectStmt->valuesLists;
613 Assert(list_length(valuesLists) == 1);
615 /* process the WITH clause */
616 if (selectStmt->withClause)
618 qry->hasRecursive = selectStmt->withClause->recursive;
619 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
622 /* Do basic expression transformation (same as a ROW() expr) */
623 exprList = transformExpressionList(pstate,
624 (List *) linitial(valuesLists));
626 /* Prepare row for assignment to target table */
627 exprList = transformInsertRow(pstate, exprList,
633 * Generate query's target list using the computed list of expressions.
634 * Also, mark all the target columns as needing insert permissions.
636 rte = pstate->p_target_rangetblentry;
637 qry->targetList = NIL;
638 icols = list_head(icolumns);
639 attnos = list_head(attrnos);
640 foreach(lc, exprList)
642 Expr *expr = (Expr *) lfirst(lc);
647 col = (ResTarget *) lfirst(icols);
648 Assert(IsA(col, ResTarget));
649 attr_num = (AttrNumber) lfirst_int(attnos);
651 tle = makeTargetEntry(expr,
655 qry->targetList = lappend(qry->targetList, tle);
657 rte->modifiedCols = bms_add_member(rte->modifiedCols,
658 attr_num - FirstLowInvalidHeapAttributeNumber);
660 icols = lnext(icols);
661 attnos = lnext(attnos);
665 * If we have a RETURNING clause, we need to add the target relation to
666 * the query namespace before processing it, so that Var references in
667 * RETURNING will work. Also, remove any namespace entries added in a
668 * sub-SELECT or VALUES list.
670 if (stmt->returningList)
672 pstate->p_relnamespace = NIL;
673 pstate->p_varnamespace = NIL;
674 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
676 qry->returningList = transformReturningList(pstate,
677 stmt->returningList);
680 /* done building the range table and jointree */
681 qry->rtable = pstate->p_rtable;
682 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
684 qry->hasSubLinks = pstate->p_hasSubLinks;
685 /* aggregates not allowed (but subselects are okay) */
686 if (pstate->p_hasAggs)
688 (errcode(ERRCODE_GROUPING_ERROR),
689 errmsg("cannot use aggregate function in VALUES"),
690 parser_errposition(pstate,
691 locate_agg_of_level((Node *) qry, 0))));
692 if (pstate->p_hasWindowFuncs)
694 (errcode(ERRCODE_WINDOWING_ERROR),
695 errmsg("cannot use window function in VALUES"),
696 parser_errposition(pstate,
697 locate_windowfunc((Node *) qry))));
703 * Prepare an INSERT row for assignment to the target table.
705 * The row might be either a VALUES row, or variables referencing a
709 transformInsertRow(ParseState *pstate, List *exprlist,
710 List *stmtcols, List *icolumns, List *attrnos)
718 * Check length of expr list. It must not have more expressions than
719 * there are target columns. We allow fewer, but only if no explicit
720 * columns list was given (the remaining columns are implicitly
721 * defaulted). Note we must check this *after* transformation because
722 * that could expand '*' into multiple items.
724 if (list_length(exprlist) > list_length(icolumns))
726 (errcode(ERRCODE_SYNTAX_ERROR),
727 errmsg("INSERT has more expressions than target columns"),
728 parser_errposition(pstate,
729 exprLocation(list_nth(exprlist,
730 list_length(icolumns))))));
731 if (stmtcols != NIL &&
732 list_length(exprlist) < list_length(icolumns))
734 (errcode(ERRCODE_SYNTAX_ERROR),
735 errmsg("INSERT has more target columns than expressions"),
736 parser_errposition(pstate,
737 exprLocation(list_nth(icolumns,
738 list_length(exprlist))))));
741 * Prepare columns for assignment to target table.
744 icols = list_head(icolumns);
745 attnos = list_head(attrnos);
746 foreach(lc, exprlist)
748 Expr *expr = (Expr *) lfirst(lc);
751 col = (ResTarget *) lfirst(icols);
752 Assert(IsA(col, ResTarget));
754 expr = transformAssignedExpr(pstate, expr,
760 result = lappend(result, expr);
762 icols = lnext(icols);
763 attnos = lnext(attnos);
771 * transformSelectStmt -
772 * transforms a Select Statement
774 * Note: this covers only cases with no set operations and no VALUES lists;
775 * see below for the other cases.
778 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
780 Query *qry = makeNode(Query);
784 qry->commandType = CMD_SELECT;
786 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
787 pstate->p_locking_clause = stmt->lockingClause;
789 /* make WINDOW info available for window functions, too */
790 pstate->p_windowdefs = stmt->windowClause;
792 /* process the WITH clause */
793 if (stmt->withClause)
795 qry->hasRecursive = stmt->withClause->recursive;
796 qry->cteList = transformWithClause(pstate, stmt->withClause);
799 /* process the FROM clause */
800 transformFromClause(pstate, stmt->fromClause);
802 /* transform targetlist */
803 qry->targetList = transformTargetList(pstate, stmt->targetList);
805 /* mark column origins */
806 markTargetListOrigins(pstate, qry->targetList);
808 /* transform WHERE */
809 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
812 * Initial processing of HAVING clause is just like WHERE clause.
814 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
818 * Transform sorting/grouping stuff. Do ORDER BY first because both
819 * transformGroupClause and transformDistinctClause need the results.
820 * Note that these functions can also change the targetList, so it's
821 * passed to them by reference.
823 qry->sortClause = transformSortClause(pstate,
826 true /* fix unknowns */ );
828 qry->groupClause = transformGroupClause(pstate,
834 if (stmt->distinctClause == NIL)
836 qry->distinctClause = NIL;
837 qry->hasDistinctOn = false;
839 else if (linitial(stmt->distinctClause) == NULL)
841 /* We had SELECT DISTINCT */
842 qry->distinctClause = transformDistinctClause(pstate,
845 qry->hasDistinctOn = false;
849 /* We had SELECT DISTINCT ON */
850 qry->distinctClause = transformDistinctOnClause(pstate,
851 stmt->distinctClause,
854 qry->hasDistinctOn = true;
857 /* transform LIMIT */
858 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
860 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
863 /* transform window clauses after we have seen all window functions */
864 qry->windowClause = transformWindowDefinitions(pstate,
865 pstate->p_windowdefs,
868 /* handle any SELECT INTO/CREATE TABLE AS spec */
869 if (stmt->intoClause)
871 qry->intoClause = stmt->intoClause;
872 if (stmt->intoClause->colNames)
873 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
876 qry->rtable = pstate->p_rtable;
877 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
879 qry->hasSubLinks = pstate->p_hasSubLinks;
880 qry->hasAggs = pstate->p_hasAggs;
881 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
882 parseCheckAggregates(pstate, qry);
883 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
884 if (pstate->p_hasWindowFuncs)
885 parseCheckWindowFuncs(pstate, qry);
887 foreach(l, stmt->lockingClause)
889 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
896 * transformValuesClause -
897 * transforms a VALUES clause that's being used as a standalone SELECT
899 * We build a Query containing a VALUES RTE, rather as if one had written
900 * SELECT * FROM (VALUES ...)
903 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
905 Query *qry = makeNode(Query);
906 List *exprsLists = NIL;
907 List **colexprs = NULL;
908 Oid *coltypes = NULL;
909 int sublist_length = -1;
917 qry->commandType = CMD_SELECT;
919 /* Most SELECT stuff doesn't apply in a VALUES clause */
920 Assert(stmt->distinctClause == NIL);
921 Assert(stmt->targetList == NIL);
922 Assert(stmt->fromClause == NIL);
923 Assert(stmt->whereClause == NULL);
924 Assert(stmt->groupClause == NIL);
925 Assert(stmt->havingClause == NULL);
926 Assert(stmt->windowClause == NIL);
927 Assert(stmt->op == SETOP_NONE);
929 /* process the WITH clause */
930 if (stmt->withClause)
932 qry->hasRecursive = stmt->withClause->recursive;
933 qry->cteList = transformWithClause(pstate, stmt->withClause);
937 * For each row of VALUES, transform the raw expressions and gather type
938 * information. This is also a handy place to reject DEFAULT nodes, which
939 * the grammar allows for simplicity.
941 foreach(lc, stmt->valuesLists)
943 List *sublist = (List *) lfirst(lc);
945 /* Do basic expression transformation (same as a ROW() expr) */
946 sublist = transformExpressionList(pstate, sublist);
949 * All the sublists must be the same length, *after* transformation
950 * (which might expand '*' into multiple items). The VALUES RTE can't
951 * handle anything different.
953 if (sublist_length < 0)
955 /* Remember post-transformation length of first sublist */
956 sublist_length = list_length(sublist);
957 /* and allocate arrays for per-column info */
958 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
959 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
961 else if (sublist_length != list_length(sublist))
964 (errcode(ERRCODE_SYNTAX_ERROR),
965 errmsg("VALUES lists must all be the same length"),
966 parser_errposition(pstate,
967 exprLocation((Node *) sublist))));
970 exprsLists = lappend(exprsLists, sublist);
972 /* Check for DEFAULT and build per-column expression lists */
974 foreach(lc2, sublist)
976 Node *col = (Node *) lfirst(lc2);
978 if (IsA(col, SetToDefault))
980 (errcode(ERRCODE_SYNTAX_ERROR),
981 errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
982 parser_errposition(pstate, exprLocation(col))));
983 colexprs[i] = lappend(colexprs[i], col);
989 * Now resolve the common types of the columns, and coerce everything to
992 for (i = 0; i < sublist_length; i++)
994 coltypes[i] = select_common_type(pstate, colexprs[i], "VALUES", NULL);
998 foreach(lc, exprsLists)
1000 List *sublist = (List *) lfirst(lc);
1001 List *newsublist = NIL;
1004 foreach(lc2, sublist)
1006 Node *col = (Node *) lfirst(lc2);
1008 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
1009 newsublist = lappend(newsublist, col);
1013 newExprsLists = lappend(newExprsLists, newsublist);
1017 * Generate the VALUES RTE
1019 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
1020 rtr = makeNode(RangeTblRef);
1021 /* assume new rte is at end */
1022 rtr->rtindex = list_length(pstate->p_rtable);
1023 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1024 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1025 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1028 * Generate a targetlist as though expanding "*"
1030 Assert(pstate->p_next_resno == 1);
1031 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
1034 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1037 qry->sortClause = transformSortClause(pstate,
1040 true /* fix unknowns */ );
1042 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1044 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1047 if (stmt->lockingClause)
1049 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1050 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1052 /* handle any CREATE TABLE AS spec */
1053 if (stmt->intoClause)
1055 qry->intoClause = stmt->intoClause;
1056 if (stmt->intoClause->colNames)
1057 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
1061 * There mustn't have been any table references in the expressions, else
1062 * strange things would happen, like Cartesian products of those tables
1063 * with the VALUES list. We have to check this after parsing ORDER BY et
1064 * al since those could insert more junk.
1066 if (list_length(pstate->p_joinlist) != 1)
1068 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1069 errmsg("VALUES must not contain table references"),
1070 parser_errposition(pstate,
1071 locate_var_of_level((Node *) newExprsLists, 0))));
1074 * Another thing we can't currently support is NEW/OLD references in rules
1075 * --- seems we'd need something like SQL99's LATERAL construct to ensure
1076 * that the values would be available while evaluating the VALUES RTE.
1077 * This is a shame. FIXME
1079 if (list_length(pstate->p_rtable) != 1 &&
1080 contain_vars_of_level((Node *) newExprsLists, 0))
1082 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1083 errmsg("VALUES must not contain OLD or NEW references"),
1084 errhint("Use SELECT ... UNION ALL ... instead."),
1085 parser_errposition(pstate,
1086 locate_var_of_level((Node *) newExprsLists, 0))));
1088 qry->rtable = pstate->p_rtable;
1089 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1091 qry->hasSubLinks = pstate->p_hasSubLinks;
1092 /* aggregates not allowed (but subselects are okay) */
1093 if (pstate->p_hasAggs)
1095 (errcode(ERRCODE_GROUPING_ERROR),
1096 errmsg("cannot use aggregate function in VALUES"),
1097 parser_errposition(pstate,
1098 locate_agg_of_level((Node *) newExprsLists, 0))));
1099 if (pstate->p_hasWindowFuncs)
1101 (errcode(ERRCODE_WINDOWING_ERROR),
1102 errmsg("cannot use window function in VALUES"),
1103 parser_errposition(pstate,
1104 locate_windowfunc((Node *) newExprsLists))));
1110 * transformSetOperationStmt -
1111 * transforms a set-operations tree
1113 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1114 * structure to it. We must transform each leaf SELECT and build up a top-
1115 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1116 * The tree of set operations is converted into the setOperations field of
1117 * the top-level Query.
1120 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1122 Query *qry = makeNode(Query);
1123 SelectStmt *leftmostSelect;
1125 Query *leftmostQuery;
1126 SetOperationStmt *sostmt;
1128 List *intoColNames = NIL;
1132 List *lockingClause;
1134 ListCell *left_tlist,
1142 int sv_rtable_length;
1143 RangeTblEntry *jrte;
1146 qry->commandType = CMD_SELECT;
1149 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1150 * and from the top-level node.
1152 leftmostSelect = stmt->larg;
1153 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1154 leftmostSelect = leftmostSelect->larg;
1155 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1156 leftmostSelect->larg == NULL);
1157 if (leftmostSelect->intoClause)
1159 qry->intoClause = leftmostSelect->intoClause;
1160 intoColNames = leftmostSelect->intoClause->colNames;
1163 /* clear this to prevent complaints in transformSetOperationTree() */
1164 leftmostSelect->intoClause = NULL;
1167 * These are not one-time, exactly, but we want to process them here and
1168 * not let transformSetOperationTree() see them --- else it'll just
1169 * recurse right back here!
1171 sortClause = stmt->sortClause;
1172 limitOffset = stmt->limitOffset;
1173 limitCount = stmt->limitCount;
1174 lockingClause = stmt->lockingClause;
1176 stmt->sortClause = NIL;
1177 stmt->limitOffset = NULL;
1178 stmt->limitCount = NULL;
1179 stmt->lockingClause = NIL;
1181 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1185 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1187 /* process the WITH clause */
1188 if (stmt->withClause)
1190 qry->hasRecursive = stmt->withClause->recursive;
1191 qry->cteList = transformWithClause(pstate, stmt->withClause);
1195 * Recursively transform the components of the tree.
1197 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1199 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1200 qry->setOperations = (Node *) sostmt;
1203 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1205 node = sostmt->larg;
1206 while (node && IsA(node, SetOperationStmt))
1207 node = ((SetOperationStmt *) node)->larg;
1208 Assert(node && IsA(node, RangeTblRef));
1209 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1210 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1211 Assert(leftmostQuery != NULL);
1214 * Generate dummy targetlist for outer query using column names of
1215 * leftmost select and common datatypes of topmost set operation. Also
1216 * make lists of the dummy vars and their names for use in parsing ORDER
1219 * Note: we use leftmostRTI as the varno of the dummy variables. It
1220 * shouldn't matter too much which RT index they have, as long as they
1221 * have one that corresponds to a real RT entry; else funny things may
1222 * happen when the tree is mashed by rule rewriting.
1224 qry->targetList = NIL;
1227 left_tlist = list_head(leftmostQuery->targetList);
1229 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1231 Oid colType = lfirst_oid(lct);
1232 int32 colTypmod = lfirst_int(lcm);
1233 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1238 Assert(!lefttle->resjunk);
1239 colName = pstrdup(lefttle->resname);
1240 var = makeVar(leftmostRTI,
1245 var->location = exprLocation((Node *) lefttle->expr);
1246 tle = makeTargetEntry((Expr *) var,
1247 (AttrNumber) pstate->p_next_resno++,
1250 qry->targetList = lappend(qry->targetList, tle);
1251 targetvars = lappend(targetvars, var);
1252 targetnames = lappend(targetnames, makeString(colName));
1253 left_tlist = lnext(left_tlist);
1257 * As a first step towards supporting sort clauses that are expressions
1258 * using the output columns, generate a varnamespace entry that makes the
1259 * output columns visible. A Join RTE node is handy for this, since we
1260 * can easily control the Vars generated upon matches.
1262 * Note: we don't yet do anything useful with such cases, but at least
1263 * "ORDER BY upper(foo)" will draw the right error message rather than
1266 sv_rtable_length = list_length(pstate->p_rtable);
1268 jrte = addRangeTableEntryForJoin(pstate,
1275 sv_relnamespace = pstate->p_relnamespace;
1276 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1278 sv_varnamespace = pstate->p_varnamespace;
1279 pstate->p_varnamespace = list_make1(jrte);
1282 * For now, we don't support resjunk sort clauses on the output of a
1283 * setOperation tree --- you can only use the SQL92-spec options of
1284 * selecting an output column by name or number. Enforce by checking that
1285 * transformSortClause doesn't add any items to tlist.
1287 tllen = list_length(qry->targetList);
1289 qry->sortClause = transformSortClause(pstate,
1292 false /* no unknowns expected */ );
1294 pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1295 pstate->p_relnamespace = sv_relnamespace;
1296 pstate->p_varnamespace = sv_varnamespace;
1298 if (tllen != list_length(qry->targetList))
1300 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1301 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1302 errdetail("Only result column names can be used, not expressions or functions."),
1303 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1304 parser_errposition(pstate,
1305 exprLocation(list_nth(qry->targetList, tllen)))));
1307 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1309 qry->limitCount = transformLimitClause(pstate, limitCount,
1313 * Handle SELECT INTO/CREATE TABLE AS.
1315 * Any column names from CREATE TABLE AS need to be attached to both the
1316 * top level and the leftmost subquery. We do not do this earlier because
1317 * we do *not* want sortClause processing to be affected.
1321 applyColumnNames(qry->targetList, intoColNames);
1322 applyColumnNames(leftmostQuery->targetList, intoColNames);
1325 qry->rtable = pstate->p_rtable;
1326 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1328 qry->hasSubLinks = pstate->p_hasSubLinks;
1329 qry->hasAggs = pstate->p_hasAggs;
1330 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1331 parseCheckAggregates(pstate, qry);
1332 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1333 if (pstate->p_hasWindowFuncs)
1334 parseCheckWindowFuncs(pstate, qry);
1336 foreach(l, lockingClause)
1338 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
1345 * transformSetOperationTree
1346 * Recursively transform leaves and internal nodes of a set-op tree
1348 * In addition to returning the transformed node, we return a list of
1349 * expression nodes showing the type, typmod, and location (for error messages)
1350 * of each output column of the set-op node. This is used only during the
1351 * internal recursion of this function. At the upper levels we use
1352 * SetToDefault nodes for this purpose, since they carry exactly the fields
1353 * needed, but any other expression node type would do as well.
1356 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1361 Assert(stmt && IsA(stmt, SelectStmt));
1364 * Validity-check both leaf and internal SELECTs for disallowed ops.
1366 if (stmt->intoClause)
1368 (errcode(ERRCODE_SYNTAX_ERROR),
1369 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1370 parser_errposition(pstate,
1371 exprLocation((Node *) stmt->intoClause))));
1373 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1374 if (stmt->lockingClause)
1376 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1377 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1380 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1381 * clauses attached, we need to treat it like a leaf node to generate an
1382 * independent sub-Query tree. Otherwise, it can be represented by a
1383 * SetOperationStmt node underneath the parent Query.
1385 if (stmt->op == SETOP_NONE)
1387 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1392 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1393 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1394 stmt->lockingClause)
1402 /* Process leaf SELECT */
1404 char selectName[32];
1410 * Transform SelectStmt into a Query.
1412 * Note: previously transformed sub-queries don't affect the parsing
1413 * of this sub-query, because they are not in the toplevel pstate's
1416 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1419 * Check for bogus references to Vars on the current query level (but
1420 * upper-level references are okay). Normally this can't happen
1421 * because the namespace will be empty, but it could happen if we are
1424 if (pstate->p_relnamespace || pstate->p_varnamespace)
1426 if (contain_vars_of_level((Node *) selectQuery, 1))
1428 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1429 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1430 parser_errposition(pstate,
1431 locate_var_of_level((Node *) selectQuery, 1))));
1435 * Extract a list of the result expressions for upper-level checking.
1438 foreach(tl, selectQuery->targetList)
1440 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1443 *colInfo = lappend(*colInfo, tle->expr);
1447 * Make the leaf query be a subquery in the top-level rangetable.
1449 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1450 list_length(pstate->p_rtable) + 1);
1451 rte = addRangeTableEntryForSubquery(pstate,
1453 makeAlias(selectName, NIL),
1457 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1459 rtr = makeNode(RangeTblRef);
1460 /* assume new rte is at end */
1461 rtr->rtindex = list_length(pstate->p_rtable);
1462 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1463 return (Node *) rtr;
1467 /* Process an internal node (set operation node) */
1468 SetOperationStmt *op = makeNode(SetOperationStmt);
1473 const char *context;
1475 context = (stmt->op == SETOP_UNION ? "UNION" :
1476 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1480 op->all = stmt->all;
1483 * Recursively transform the child nodes.
1485 op->larg = transformSetOperationTree(pstate, stmt->larg,
1487 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1491 * Verify that the two children have the same number of non-junk
1492 * columns, and determine the types of the merged output columns.
1494 if (list_length(lcolinfo) != list_length(rcolinfo))
1496 (errcode(ERRCODE_SYNTAX_ERROR),
1497 errmsg("each %s query must have the same number of columns",
1499 parser_errposition(pstate,
1500 exprLocation((Node *) rcolinfo))));
1504 op->colTypmods = NIL;
1505 op->groupClauses = NIL;
1506 forboth(lci, lcolinfo, rci, rcolinfo)
1508 Node *lcolinfo = (Node *) lfirst(lci);
1509 Node *rcolinfo = (Node *) lfirst(rci);
1510 Oid lcoltype = exprType(lcolinfo);
1511 Oid rcoltype = exprType(rcolinfo);
1512 int32 lcoltypmod = exprTypmod(lcolinfo);
1513 int32 rcoltypmod = exprTypmod(rcolinfo);
1515 SetToDefault *rescolinfo;
1519 /* select common type, same as CASE et al */
1520 rescoltype = select_common_type(pstate,
1521 list_make2(lcolinfo, rcolinfo),
1524 /* if same type and same typmod, use typmod; else default */
1525 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1526 rescoltypmod = lcoltypmod;
1530 /* verify the coercions are actually possible */
1531 (void) coerce_to_common_type(pstate, lcolinfo,
1532 rescoltype, context);
1533 (void) coerce_to_common_type(pstate, rcolinfo,
1534 rescoltype, context);
1537 rescolinfo = makeNode(SetToDefault);
1538 rescolinfo->typeId = rescoltype;
1539 rescolinfo->typeMod = rescoltypmod;
1540 rescolinfo->location = exprLocation(bestexpr);
1541 *colInfo = lappend(*colInfo, rescolinfo);
1543 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1544 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1547 * For all cases except UNION ALL, identify the grouping operators
1548 * (and, if available, sorting operators) that will be used to
1549 * eliminate duplicates.
1551 if (op->op != SETOP_UNION || !op->all)
1553 SortGroupClause *grpcl = makeNode(SortGroupClause);
1556 ParseCallbackState pcbstate;
1558 setup_parser_errposition_callback(&pcbstate, pstate,
1559 rescolinfo->location);
1561 /* determine the eqop and optional sortop */
1562 get_sort_group_operators(rescoltype,
1564 &sortop, &eqop, NULL);
1566 cancel_parser_errposition_callback(&pcbstate);
1568 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1569 grpcl->tleSortGroupRef = 0;
1571 grpcl->sortop = sortop;
1572 grpcl->nulls_first = false; /* OK with or without sortop */
1574 op->groupClauses = lappend(op->groupClauses, grpcl);
1583 * Attach column names from a ColumnDef list to a TargetEntry list
1584 * (for CREATE TABLE AS)
1587 applyColumnNames(List *dst, List *src)
1592 src_item = list_head(src);
1594 foreach(dst_item, dst)
1596 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1599 /* junk targets don't count */
1603 /* fewer ColumnDefs than target entries is OK */
1604 if (src_item == NULL)
1607 s = (ColumnDef *) lfirst(src_item);
1608 src_item = lnext(src_item);
1610 d->resname = pstrdup(s->colname);
1613 /* more ColumnDefs than target entries is not OK */
1614 if (src_item != NULL)
1616 (errcode(ERRCODE_SYNTAX_ERROR),
1617 errmsg("CREATE TABLE AS specifies too many column names")));
1622 * transformUpdateStmt -
1623 * transforms an update statement
1626 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1628 Query *qry = makeNode(Query);
1629 RangeTblEntry *target_rte;
1631 ListCell *origTargetList;
1634 qry->commandType = CMD_UPDATE;
1635 pstate->p_is_update = true;
1637 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1638 interpretInhOption(stmt->relation->inhOpt),
1643 * the FROM clause is non-standard SQL syntax. We used to be able to do
1644 * this with REPLACE in POSTQUEL so we keep the feature.
1646 transformFromClause(pstate, stmt->fromClause);
1648 qry->targetList = transformTargetList(pstate, stmt->targetList);
1650 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1652 qry->returningList = transformReturningList(pstate, stmt->returningList);
1654 qry->rtable = pstate->p_rtable;
1655 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1657 qry->hasSubLinks = pstate->p_hasSubLinks;
1660 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1661 * an implementation point of view, this is forced because the implicit
1662 * ctid reference would otherwise be an ungrouped variable.)
1664 if (pstate->p_hasAggs)
1666 (errcode(ERRCODE_GROUPING_ERROR),
1667 errmsg("cannot use aggregate function in UPDATE"),
1668 parser_errposition(pstate,
1669 locate_agg_of_level((Node *) qry, 0))));
1670 if (pstate->p_hasWindowFuncs)
1672 (errcode(ERRCODE_WINDOWING_ERROR),
1673 errmsg("cannot use window function in UPDATE"),
1674 parser_errposition(pstate,
1675 locate_windowfunc((Node *) qry))));
1678 * Now we are done with SELECT-like processing, and can get on with
1679 * transforming the target list to match the UPDATE target columns.
1682 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1683 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1684 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1686 /* Prepare non-junk columns for assignment to target table */
1687 target_rte = pstate->p_target_rangetblentry;
1688 origTargetList = list_head(stmt->targetList);
1690 foreach(tl, qry->targetList)
1692 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1693 ResTarget *origTarget;
1699 * Resjunk nodes need no additional processing, but be sure they
1700 * have resnos that do not match any target columns; else rewriter
1701 * or planner might get confused. They don't need a resname
1704 tle->resno = (AttrNumber) pstate->p_next_resno++;
1705 tle->resname = NULL;
1708 if (origTargetList == NULL)
1709 elog(ERROR, "UPDATE target count mismatch --- internal error");
1710 origTarget = (ResTarget *) lfirst(origTargetList);
1711 Assert(IsA(origTarget, ResTarget));
1713 attrno = attnameAttNum(pstate->p_target_relation,
1714 origTarget->name, true);
1715 if (attrno == InvalidAttrNumber)
1717 (errcode(ERRCODE_UNDEFINED_COLUMN),
1718 errmsg("column \"%s\" of relation \"%s\" does not exist",
1720 RelationGetRelationName(pstate->p_target_relation)),
1721 parser_errposition(pstate, origTarget->location)));
1723 updateTargetListEntry(pstate, tle, origTarget->name,
1725 origTarget->indirection,
1726 origTarget->location);
1728 /* Mark the target column as requiring update permissions */
1729 target_rte->modifiedCols = bms_add_member(target_rte->modifiedCols,
1730 attrno - FirstLowInvalidHeapAttributeNumber);
1732 origTargetList = lnext(origTargetList);
1734 if (origTargetList != NULL)
1735 elog(ERROR, "UPDATE target count mismatch --- internal error");
1741 * transformReturningList -
1742 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1745 transformReturningList(ParseState *pstate, List *returningList)
1748 int save_next_resno;
1750 bool save_hasWindowFuncs;
1753 if (returningList == NIL)
1754 return NIL; /* nothing to do */
1757 * We need to assign resnos starting at one in the RETURNING list. Save
1758 * and restore the main tlist's value of p_next_resno, just in case
1759 * someone looks at it later (probably won't happen).
1761 save_next_resno = pstate->p_next_resno;
1762 pstate->p_next_resno = 1;
1764 /* save other state so that we can detect disallowed stuff */
1765 save_hasAggs = pstate->p_hasAggs;
1766 pstate->p_hasAggs = false;
1767 save_hasWindowFuncs = pstate->p_hasWindowFuncs;
1768 pstate->p_hasWindowFuncs = false;
1769 length_rtable = list_length(pstate->p_rtable);
1771 /* transform RETURNING identically to a SELECT targetlist */
1772 rlist = transformTargetList(pstate, returningList);
1774 /* check for disallowed stuff */
1776 /* aggregates not allowed (but subselects are okay) */
1777 if (pstate->p_hasAggs)
1779 (errcode(ERRCODE_GROUPING_ERROR),
1780 errmsg("cannot use aggregate function in RETURNING"),
1781 parser_errposition(pstate,
1782 locate_agg_of_level((Node *) rlist, 0))));
1783 if (pstate->p_hasWindowFuncs)
1785 (errcode(ERRCODE_WINDOWING_ERROR),
1786 errmsg("cannot use window function in RETURNING"),
1787 parser_errposition(pstate,
1788 locate_windowfunc((Node *) rlist))));
1790 /* no new relation references please */
1791 if (list_length(pstate->p_rtable) != length_rtable)
1796 /* try to locate such a reference to point to */
1797 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
1799 vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
1804 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1805 errmsg("RETURNING cannot contain references to other relations"),
1806 parser_errposition(pstate, vlocation)));
1809 /* mark column origins */
1810 markTargetListOrigins(pstate, rlist);
1813 pstate->p_next_resno = save_next_resno;
1814 pstate->p_hasAggs = save_hasAggs;
1815 pstate->p_hasWindowFuncs = save_hasWindowFuncs;
1822 * transformDeclareCursorStmt -
1823 * transform a DECLARE CURSOR Statement
1825 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1826 * significantly different from a SELECT) as far as parsing/rewriting/planning
1827 * are concerned, but it's not passed to the executor and so in that sense is
1828 * a utility statement. We transform it into a Query exactly as if it were
1829 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1830 * field to carry the cursor name and options.
1833 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1838 * Don't allow both SCROLL and NO SCROLL to be specified
1840 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1841 (stmt->options & CURSOR_OPT_NO_SCROLL))
1843 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1844 errmsg("cannot specify both SCROLL and NO SCROLL")));
1846 result = transformStmt(pstate, stmt->query);
1848 /* Grammar should not have allowed anything but SELECT */
1849 if (!IsA(result, Query) ||
1850 result->commandType != CMD_SELECT ||
1851 result->utilityStmt != NULL)
1852 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
1854 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1855 if (result->intoClause)
1857 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1858 errmsg("DECLARE CURSOR cannot specify INTO"),
1859 parser_errposition(pstate,
1860 exprLocation((Node *) result->intoClause))));
1862 /* FOR UPDATE and WITH HOLD are not compatible */
1863 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1865 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1866 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1867 errdetail("Holdable cursors must be READ ONLY.")));
1869 /* FOR UPDATE and SCROLL are not compatible */
1870 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1872 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1873 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1874 errdetail("Scrollable cursors must be READ ONLY.")));
1876 /* FOR UPDATE and INSENSITIVE are not compatible */
1877 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1879 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1880 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1881 errdetail("Insensitive cursors must be READ ONLY.")));
1883 /* We won't need the raw querytree any more */
1886 result->utilityStmt = (Node *) stmt;
1893 * transformExplainStmt -
1894 * transform an EXPLAIN Statement
1896 * EXPLAIN is just like other utility statements in that we emit it as a
1897 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1898 * However, if p_variableparams is set, it could be that the client is
1899 * expecting us to resolve parameter types in something like
1900 * EXPLAIN SELECT * FROM tab WHERE col = $1
1901 * To deal with such cases, we run parse analysis and throw away the result;
1902 * this is a bit grotty but not worth contorting the rest of the system for.
1903 * (The approach we use for DECLARE CURSOR won't work because the statement
1904 * being explained isn't necessarily a SELECT, and in particular might rewrite
1905 * to multiple parsetrees.)
1908 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1912 if (pstate->p_variableparams)
1914 /* Since parse analysis scribbles on its input, copy the tree first! */
1915 (void) transformStmt(pstate, copyObject(stmt->query));
1918 /* Now return the untransformed command as a utility Query */
1919 result = makeNode(Query);
1920 result->commandType = CMD_UTILITY;
1921 result->utilityStmt = (Node *) stmt;
1927 /* exported so planner can check again after rewriting, query pullup, etc */
1929 CheckSelectLocking(Query *qry)
1931 if (qry->setOperations)
1933 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1934 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1935 if (qry->distinctClause != NIL)
1937 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1938 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1939 if (qry->groupClause != NIL)
1941 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1942 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1943 if (qry->havingQual != NULL)
1945 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1946 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1949 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1950 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1951 if (qry->hasWindowFuncs)
1953 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1954 errmsg("SELECT FOR UPDATE/SHARE is not allowed with window functions")));
1958 * Transform a FOR UPDATE/SHARE clause
1960 * This basically involves replacing names by integer relids.
1962 * NB: if you need to change this, see also markQueryForLocking()
1963 * in rewriteHandler.c, and isLockedRel() in parse_relation.c.
1966 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc)
1968 List *lockedRels = lc->lockedRels;
1972 LockingClause *allrels;
1974 CheckSelectLocking(qry);
1976 /* make a clause we can pass down to subqueries to select all rels */
1977 allrels = makeNode(LockingClause);
1978 allrels->lockedRels = NIL; /* indicates all rels */
1979 allrels->forUpdate = lc->forUpdate;
1980 allrels->noWait = lc->noWait;
1982 if (lockedRels == NIL)
1984 /* all regular tables used in query */
1986 foreach(rt, qry->rtable)
1988 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1991 switch (rte->rtekind)
1994 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1995 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2000 * FOR UPDATE/SHARE of subquery is propagated to all of
2003 transformLockingClause(pstate, rte->subquery, allrels);
2008 * We allow FOR UPDATE/SHARE of a WITH query to be
2009 * propagated into the WITH, but it doesn't seem
2010 * very sane to allow this for a reference to an
2011 * outer-level WITH. And it definitely wouldn't
2012 * work for a self-reference, since we're not done
2013 * analyzing the CTE anyway.
2015 CommonTableExpr *cte;
2017 if (rte->ctelevelsup > 0 || rte->self_reference)
2019 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2020 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query")));
2021 cte = GetCTEForRTE(pstate, rte, -1);
2022 /* should be analyzed by now */
2023 Assert(IsA(cte->ctequery, Query));
2024 transformLockingClause(pstate,
2025 (Query *) cte->ctequery,
2030 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2037 /* just the named tables */
2038 foreach(l, lockedRels)
2040 RangeVar *thisrel = (RangeVar *) lfirst(l);
2042 /* For simplicity we insist on unqualified alias names here */
2043 if (thisrel->catalogname || thisrel->schemaname)
2045 (errcode(ERRCODE_SYNTAX_ERROR),
2046 errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
2047 parser_errposition(pstate, thisrel->location)));
2050 foreach(rt, qry->rtable)
2052 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2055 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2057 switch (rte->rtekind)
2060 applyLockingClause(qry, i,
2061 lc->forUpdate, lc->noWait);
2062 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2067 * FOR UPDATE/SHARE of subquery is propagated to
2068 * all of subquery's rels
2070 transformLockingClause(pstate, rte->subquery, allrels);
2074 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2075 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2076 parser_errposition(pstate, thisrel->location)));
2080 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2081 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD"),
2082 parser_errposition(pstate, thisrel->location)));
2086 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2087 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2088 parser_errposition(pstate, thisrel->location)));
2092 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2093 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2094 parser_errposition(pstate, thisrel->location)));
2099 * We allow FOR UPDATE/SHARE of a WITH query
2100 * to be propagated into the WITH, but it
2101 * doesn't seem very sane to allow this for a
2102 * reference to an outer-level WITH. And it
2103 * definitely wouldn't work for a
2104 * self-reference, since we're not done
2105 * analyzing the CTE anyway.
2107 CommonTableExpr *cte;
2109 if (rte->ctelevelsup > 0 || rte->self_reference)
2111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2112 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query"),
2113 parser_errposition(pstate, thisrel->location)));
2114 cte = GetCTEForRTE(pstate, rte, -1);
2115 /* should be analyzed by now */
2116 Assert(IsA(cte->ctequery, Query));
2117 transformLockingClause(pstate,
2118 (Query *) cte->ctequery,
2123 elog(ERROR, "unrecognized RTE type: %d",
2124 (int) rte->rtekind);
2127 break; /* out of foreach loop */
2132 (errcode(ERRCODE_UNDEFINED_TABLE),
2133 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2135 parser_errposition(pstate, thisrel->location)));
2141 * Record locking info for a single rangetable item
2144 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
2148 /* Check for pre-existing entry for same rtindex */
2149 if ((rc = get_rowmark(qry, rtindex)) != NULL)
2152 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2153 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
2154 * and exclusive lock at the same time; it'll end up being exclusive
2157 * We also consider that NOWAIT wins if it's specified both ways. This
2158 * is a bit more debatable but raising an error doesn't seem helpful.
2159 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2160 * internally contains a plain FOR UPDATE spec.)
2162 rc->forUpdate |= forUpdate;
2163 rc->noWait |= noWait;
2167 /* Make a new RowMarkClause */
2168 rc = makeNode(RowMarkClause);
2171 rc->forUpdate = forUpdate;
2172 rc->noWait = noWait;
2173 rc->isParent = false;
2174 qry->rowMarks = lappend(qry->rowMarks, rc);
2179 * Traverse a fully-analyzed tree to verify that parameter symbols
2180 * match their types. We need this because some Params might still
2181 * be UNKNOWN, if there wasn't anything to force their coercion,
2182 * and yet other instances seen later might have gotten coerced.
2185 check_parameter_resolution_walker(Node *node, ParseState *pstate)
2189 if (IsA(node, Param))
2191 Param *param = (Param *) node;
2193 if (param->paramkind == PARAM_EXTERN)
2195 int paramno = param->paramid;
2197 if (paramno <= 0 || /* shouldn't happen, but... */
2198 paramno > pstate->p_numparams)
2200 (errcode(ERRCODE_UNDEFINED_PARAMETER),
2201 errmsg("there is no parameter $%d", paramno),
2202 parser_errposition(pstate, param->location)));
2204 if (param->paramtype != pstate->p_paramtypes[paramno - 1])
2206 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
2207 errmsg("could not determine data type of parameter $%d",
2209 parser_errposition(pstate, param->location)));
2213 if (IsA(node, Query))
2215 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2216 return query_tree_walker((Query *) node,
2217 check_parameter_resolution_walker,
2218 (void *) pstate, 0);
2220 return expression_tree_walker(node, check_parameter_resolution_walker,