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, EXPLAIN, and CREATE TABLE AS are exceptions because they
14 * contain optimizable statements, which we should transform.
17 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
18 * Portions Copyright (c) 1994, Regents of the University of California
20 * src/backend/parser/analyze.c
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_collate.h"
37 #include "parser/parse_cte.h"
38 #include "parser/parse_oper.h"
39 #include "parser/parse_param.h"
40 #include "parser/parse_relation.h"
41 #include "parser/parse_target.h"
42 #include "parser/parsetree.h"
43 #include "rewrite/rewriteManip.h"
44 #include "utils/rel.h"
47 /* Hook for plugins to get control at end of parse analysis */
48 post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
50 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
51 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
52 static List *transformInsertRow(ParseState *pstate, List *exprlist,
53 List *stmtcols, List *icolumns, List *attrnos);
54 static int count_rowexpr_columns(ParseState *pstate, Node *expr);
55 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
56 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
57 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
58 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
59 bool isTopLevel, List **targetlist);
60 static void determineRecursiveColTypes(ParseState *pstate,
61 Node *larg, List *nrtargetlist);
62 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
63 static List *transformReturningList(ParseState *pstate, List *returningList);
64 static Query *transformDeclareCursorStmt(ParseState *pstate,
65 DeclareCursorStmt *stmt);
66 static Query *transformExplainStmt(ParseState *pstate,
68 static Query *transformCreateTableAsStmt(ParseState *pstate,
69 CreateTableAsStmt *stmt);
70 static void transformLockingClause(ParseState *pstate, Query *qry,
71 LockingClause *lc, bool pushedDown);
76 * Analyze a raw parse tree and transform it to Query form.
78 * Optionally, information about $n parameter types can be supplied.
79 * References to $n indexes not defined by paramTypes[] are disallowed.
81 * The result is a Query node. Optimizable statements require considerable
82 * transformation, while utility-type statements are simply hung off
83 * a dummy CMD_UTILITY Query node.
86 parse_analyze(Node *parseTree, const char *sourceText,
87 Oid *paramTypes, int numParams)
89 ParseState *pstate = make_parsestate(NULL);
92 Assert(sourceText != NULL); /* required as of 8.4 */
94 pstate->p_sourcetext = sourceText;
97 parse_fixed_parameters(pstate, paramTypes, numParams);
99 query = transformTopLevelStmt(pstate, parseTree);
101 if (post_parse_analyze_hook)
102 (*post_parse_analyze_hook) (pstate, query);
104 free_parsestate(pstate);
110 * parse_analyze_varparams
112 * This variant is used when it's okay to deduce information about $n
113 * symbol datatypes from context. The passed-in paramTypes[] array can
114 * be modified or enlarged (via repalloc).
117 parse_analyze_varparams(Node *parseTree, const char *sourceText,
118 Oid **paramTypes, int *numParams)
120 ParseState *pstate = make_parsestate(NULL);
123 Assert(sourceText != NULL); /* required as of 8.4 */
125 pstate->p_sourcetext = sourceText;
127 parse_variable_parameters(pstate, paramTypes, numParams);
129 query = transformTopLevelStmt(pstate, parseTree);
131 /* make sure all is well with parameter types */
132 check_variable_parameters(pstate, query);
134 if (post_parse_analyze_hook)
135 (*post_parse_analyze_hook) (pstate, query);
137 free_parsestate(pstate);
144 * Entry point for recursively analyzing a sub-statement.
147 parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
148 CommonTableExpr *parentCTE,
149 bool locked_from_parent)
151 ParseState *pstate = make_parsestate(parentParseState);
154 pstate->p_parent_cte = parentCTE;
155 pstate->p_locked_from_parent = locked_from_parent;
157 query = transformStmt(pstate, parseTree);
159 free_parsestate(pstate);
165 * transformTopLevelStmt -
166 * transform a Parse tree into a Query tree.
168 * The only thing we do here that we don't do in transformStmt() is to
169 * convert SELECT ... INTO into CREATE TABLE AS. Since utility statements
170 * aren't allowed within larger statements, this is only allowed at the top
171 * of the parse tree, and so we only try it before entering the recursive
172 * transformStmt() processing.
175 transformTopLevelStmt(ParseState *pstate, Node *parseTree)
177 if (IsA(parseTree, SelectStmt))
179 SelectStmt *stmt = (SelectStmt *) parseTree;
181 /* If it's a set-operation tree, drill down to leftmost SelectStmt */
182 while (stmt && stmt->op != SETOP_NONE)
184 Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
186 if (stmt->intoClause)
188 CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
190 ctas->query = parseTree;
191 ctas->into = stmt->intoClause;
192 ctas->is_select_into = true;
195 * Remove the intoClause from the SelectStmt. This makes it safe
196 * for transformSelectStmt to complain if it finds intoClause set
197 * (implying that the INTO appeared in a disallowed place).
199 stmt->intoClause = NULL;
201 parseTree = (Node *) ctas;
205 return transformStmt(pstate, parseTree);
210 * recursively transform a Parse tree into a Query tree.
213 transformStmt(ParseState *pstate, Node *parseTree)
217 switch (nodeTag(parseTree))
220 * Optimizable statements
223 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
227 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
231 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
236 SelectStmt *n = (SelectStmt *) parseTree;
239 result = transformValuesClause(pstate, n);
240 else if (n->op == SETOP_NONE)
241 result = transformSelectStmt(pstate, n);
243 result = transformSetOperationStmt(pstate, n);
250 case T_DeclareCursorStmt:
251 result = transformDeclareCursorStmt(pstate,
252 (DeclareCursorStmt *) parseTree);
256 result = transformExplainStmt(pstate,
257 (ExplainStmt *) parseTree);
260 case T_CreateTableAsStmt:
261 result = transformCreateTableAsStmt(pstate,
262 (CreateTableAsStmt *) parseTree);
268 * other statements don't require any transformation; just return
269 * the original parsetree with a Query node plastered on top.
271 result = makeNode(Query);
272 result->commandType = CMD_UTILITY;
273 result->utilityStmt = (Node *) parseTree;
277 /* Mark as original query until we learn differently */
278 result->querySource = QSRC_ORIGINAL;
279 result->canSetTag = true;
285 * analyze_requires_snapshot
286 * Returns true if a snapshot must be set before doing parse analysis
287 * on the given raw parse tree.
289 * Classification here should match transformStmt(); but we also have to
290 * allow a NULL input (for Parse/Bind of an empty query string).
293 analyze_requires_snapshot(Node *parseTree)
297 if (parseTree == NULL)
300 switch (nodeTag(parseTree))
303 * Optimizable statements
315 case T_DeclareCursorStmt:
316 /* yes, because it's analyzed just like SELECT */
321 case T_CreateTableAsStmt:
322 /* yes, because we must analyze the contained statement */
327 /* other utility statements don't have any real parse analysis */
336 * transformDeleteStmt -
337 * transforms a Delete Statement
340 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
342 Query *qry = makeNode(Query);
345 qry->commandType = CMD_DELETE;
347 /* process the WITH clause independently of all else */
348 if (stmt->withClause)
350 qry->hasRecursive = stmt->withClause->recursive;
351 qry->cteList = transformWithClause(pstate, stmt->withClause);
352 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
355 /* set up range table with just the result rel */
356 qry->resultRelation = setTargetTable(pstate, stmt->relation,
357 interpretInhOption(stmt->relation->inhOpt),
361 qry->distinctClause = NIL;
364 * The USING clause is non-standard SQL syntax, and is equivalent in
365 * functionality to the FROM list that can be specified for UPDATE. The
366 * USING keyword is used rather than FROM because FROM is already a
367 * keyword in the DELETE syntax.
369 transformFromClause(pstate, stmt->usingClause);
371 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
373 qry->returningList = transformReturningList(pstate, stmt->returningList);
375 /* done building the range table and jointree */
376 qry->rtable = pstate->p_rtable;
377 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
379 qry->hasSubLinks = pstate->p_hasSubLinks;
380 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
381 if (pstate->p_hasWindowFuncs)
382 parseCheckWindowFuncs(pstate, qry);
383 qry->hasAggs = pstate->p_hasAggs;
384 if (pstate->p_hasAggs)
385 parseCheckAggregates(pstate, qry);
387 assign_query_collations(pstate, qry);
393 * transformInsertStmt -
394 * transform an Insert Statement
397 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
399 Query *qry = makeNode(Query);
400 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
401 List *exprList = NIL;
402 bool isGeneralSelect;
404 List *sub_relnamespace;
405 List *sub_varnamespace;
414 /* There can't be any outer WITH to worry about */
415 Assert(pstate->p_ctenamespace == NIL);
417 qry->commandType = CMD_INSERT;
418 pstate->p_is_insert = true;
420 /* process the WITH clause independently of all else */
421 if (stmt->withClause)
423 qry->hasRecursive = stmt->withClause->recursive;
424 qry->cteList = transformWithClause(pstate, stmt->withClause);
425 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
429 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
430 * VALUES list, or general SELECT input. We special-case VALUES, both for
431 * efficiency and so we can handle DEFAULT specifications.
433 * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
434 * VALUES clause. If we have any of those, treat it as a general SELECT;
435 * so it will work, but you can't use DEFAULT items together with those.
437 isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
438 selectStmt->sortClause != NIL ||
439 selectStmt->limitOffset != NULL ||
440 selectStmt->limitCount != NULL ||
441 selectStmt->lockingClause != NIL ||
442 selectStmt->withClause != NULL));
445 * If a non-nil rangetable/namespace was passed in, and we are doing
446 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
447 * SELECT. This can only happen if we are inside a CREATE RULE, and in
448 * that case we want the rule's OLD and NEW rtable entries to appear as
449 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
450 * The SELECT's joinlist is not affected however. We must do this before
451 * adding the target table to the INSERT's rtable.
455 sub_rtable = pstate->p_rtable;
456 pstate->p_rtable = NIL;
457 sub_relnamespace = pstate->p_relnamespace;
458 pstate->p_relnamespace = NIL;
459 sub_varnamespace = pstate->p_varnamespace;
460 pstate->p_varnamespace = NIL;
464 sub_rtable = NIL; /* not used, but keep compiler quiet */
465 sub_relnamespace = NIL;
466 sub_varnamespace = NIL;
470 * Must get write lock on INSERT target table before scanning SELECT, else
471 * we will grab the wrong kind of initial lock if the target table is also
472 * mentioned in the SELECT part. Note that the target table is not added
473 * to the joinlist or namespace.
475 qry->resultRelation = setTargetTable(pstate, stmt->relation,
476 false, false, ACL_INSERT);
478 /* Validate stmt->cols list, or build default list if no list given */
479 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
480 Assert(list_length(icolumns) == list_length(attrnos));
483 * Determine which variant of INSERT we have.
485 if (selectStmt == NULL)
488 * We have INSERT ... DEFAULT VALUES. We can handle this case by
489 * emitting an empty targetlist --- all columns will be defaulted when
490 * the planner expands the targetlist.
494 else if (isGeneralSelect)
497 * We make the sub-pstate a child of the outer pstate so that it can
498 * see any Param definitions supplied from above. Since the outer
499 * pstate's rtable and namespace are presently empty, there are no
500 * side-effects of exposing names the sub-SELECT shouldn't be able to
503 ParseState *sub_pstate = make_parsestate(pstate);
507 * Process the source SELECT.
509 * It is important that this be handled just like a standalone SELECT;
510 * otherwise the behavior of SELECT within INSERT might be different
511 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
512 * bugs of just that nature...)
514 sub_pstate->p_rtable = sub_rtable;
515 sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
516 sub_pstate->p_relnamespace = sub_relnamespace;
517 sub_pstate->p_varnamespace = sub_varnamespace;
519 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
521 free_parsestate(sub_pstate);
523 /* The grammar should have produced a SELECT */
524 if (!IsA(selectQuery, Query) ||
525 selectQuery->commandType != CMD_SELECT ||
526 selectQuery->utilityStmt != NULL)
527 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
530 * Make the source be a subquery in the INSERT's rangetable, and add
531 * it to the INSERT's joinlist.
533 rte = addRangeTableEntryForSubquery(pstate,
535 makeAlias("*SELECT*", NIL),
537 rtr = makeNode(RangeTblRef);
538 /* assume new rte is at end */
539 rtr->rtindex = list_length(pstate->p_rtable);
540 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
541 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
544 * Generate an expression list for the INSERT that selects all the
545 * non-resjunk columns from the subquery. (INSERT's tlist must be
546 * separate from the subquery's tlist because we may add columns,
547 * insert datatype coercions, etc.)
549 * HACK: unknown-type constants and params in the SELECT's targetlist
550 * are copied up as-is rather than being referenced as subquery
551 * outputs. This is to ensure that when we try to coerce them to
552 * the target column's datatype, the right things happen (see
553 * special cases in coerce_type). Otherwise, this fails:
554 * INSERT INTO foo SELECT 'bar', ... FROM baz
558 foreach(lc, selectQuery->targetList)
560 TargetEntry *tle = (TargetEntry *) lfirst(lc);
566 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
567 exprType((Node *) tle->expr) == UNKNOWNOID)
571 Var *var = makeVarFromTargetEntry(rtr->rtindex, tle);
573 var->location = exprLocation((Node *) tle->expr);
576 exprList = lappend(exprList, expr);
579 /* Prepare row for assignment to target table */
580 exprList = transformInsertRow(pstate, exprList,
584 else if (list_length(selectStmt->valuesLists) > 1)
587 * Process INSERT ... VALUES with multiple VALUES sublists. We
588 * generate a VALUES RTE holding the transformed expression lists, and
589 * build up a targetlist containing Vars that reference the VALUES
592 List *exprsLists = NIL;
593 List *collations = NIL;
594 int sublist_length = -1;
597 Assert(selectStmt->intoClause == NULL);
599 foreach(lc, selectStmt->valuesLists)
601 List *sublist = (List *) lfirst(lc);
603 /* Do basic expression transformation (same as a ROW() expr) */
604 sublist = transformExpressionList(pstate, sublist);
607 * All the sublists must be the same length, *after*
608 * transformation (which might expand '*' into multiple items).
609 * The VALUES RTE can't handle anything different.
611 if (sublist_length < 0)
613 /* Remember post-transformation length of first sublist */
614 sublist_length = list_length(sublist);
616 else if (sublist_length != list_length(sublist))
619 (errcode(ERRCODE_SYNTAX_ERROR),
620 errmsg("VALUES lists must all be the same length"),
621 parser_errposition(pstate,
622 exprLocation((Node *) sublist))));
625 /* Prepare row for assignment to target table */
626 sublist = transformInsertRow(pstate, sublist,
631 * We must assign collations now because assign_query_collations
632 * doesn't process rangetable entries. We just assign all the
633 * collations independently in each row, and don't worry about
634 * whether they are consistent vertically. The outer INSERT query
635 * isn't going to care about the collations of the VALUES columns,
636 * so it's not worth the effort to identify a common collation for
637 * each one here. (But note this does have one user-visible
638 * consequence: INSERT ... VALUES won't complain about conflicting
639 * explicit COLLATEs in a column, whereas the same VALUES
640 * construct in another context would complain.)
642 assign_list_collations(pstate, sublist);
644 exprsLists = lappend(exprsLists, sublist);
648 * Although we don't really need collation info, let's just make sure
649 * we provide a correctly-sized list in the VALUES RTE.
651 for (i = 0; i < sublist_length; i++)
652 collations = lappend_oid(collations, InvalidOid);
655 * There mustn't have been any table references in the expressions,
656 * else strange things would happen, like Cartesian products of those
657 * tables with the VALUES list ...
659 if (pstate->p_joinlist != NIL)
661 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
662 errmsg("VALUES must not contain table references"),
663 parser_errposition(pstate,
664 locate_var_of_level((Node *) exprsLists, 0))));
667 * Another thing we can't currently support is NEW/OLD references in
668 * rules --- seems we'd need something like SQL99's LATERAL construct
669 * to ensure that the values would be available while evaluating the
670 * VALUES RTE. This is a shame. FIXME
672 if (list_length(pstate->p_rtable) != 1 &&
673 contain_vars_of_level((Node *) exprsLists, 0))
675 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
676 errmsg("VALUES must not contain OLD or NEW references"),
677 errhint("Use SELECT ... UNION ALL ... instead."),
678 parser_errposition(pstate,
679 locate_var_of_level((Node *) exprsLists, 0))));
682 * Generate the VALUES RTE
684 rte = addRangeTableEntryForValues(pstate, exprsLists, collations,
686 rtr = makeNode(RangeTblRef);
687 /* assume new rte is at end */
688 rtr->rtindex = list_length(pstate->p_rtable);
689 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
690 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
693 * Generate list of Vars referencing the RTE
695 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
700 * Process INSERT ... VALUES with a single VALUES sublist.
701 * We treat this separately for efficiency and for historical
702 * compatibility --- specifically, allowing table references,
704 * INSERT INTO foo VALUES(bar.*)
706 * The sublist is just computed directly as the Query's targetlist,
707 * with no VALUES RTE. So it works just like SELECT without FROM.
710 List *valuesLists = selectStmt->valuesLists;
712 Assert(list_length(valuesLists) == 1);
713 Assert(selectStmt->intoClause == NULL);
715 /* Do basic expression transformation (same as a ROW() expr) */
716 exprList = transformExpressionList(pstate,
717 (List *) linitial(valuesLists));
719 /* Prepare row for assignment to target table */
720 exprList = transformInsertRow(pstate, exprList,
726 * Generate query's target list using the computed list of expressions.
727 * Also, mark all the target columns as needing insert permissions.
729 rte = pstate->p_target_rangetblentry;
730 qry->targetList = NIL;
731 icols = list_head(icolumns);
732 attnos = list_head(attrnos);
733 foreach(lc, exprList)
735 Expr *expr = (Expr *) lfirst(lc);
740 col = (ResTarget *) lfirst(icols);
741 Assert(IsA(col, ResTarget));
742 attr_num = (AttrNumber) lfirst_int(attnos);
744 tle = makeTargetEntry(expr,
748 qry->targetList = lappend(qry->targetList, tle);
750 rte->modifiedCols = bms_add_member(rte->modifiedCols,
751 attr_num - FirstLowInvalidHeapAttributeNumber);
753 icols = lnext(icols);
754 attnos = lnext(attnos);
758 * If we have a RETURNING clause, we need to add the target relation to
759 * the query namespace before processing it, so that Var references in
760 * RETURNING will work. Also, remove any namespace entries added in a
761 * sub-SELECT or VALUES list.
763 if (stmt->returningList)
765 pstate->p_relnamespace = NIL;
766 pstate->p_varnamespace = NIL;
767 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
769 qry->returningList = transformReturningList(pstate,
770 stmt->returningList);
773 /* done building the range table and jointree */
774 qry->rtable = pstate->p_rtable;
775 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
777 qry->hasSubLinks = pstate->p_hasSubLinks;
778 /* aggregates not allowed (but subselects are okay) */
779 if (pstate->p_hasAggs)
781 (errcode(ERRCODE_GROUPING_ERROR),
782 errmsg("cannot use aggregate function in VALUES"),
783 parser_errposition(pstate,
784 locate_agg_of_level((Node *) qry, 0))));
785 if (pstate->p_hasWindowFuncs)
787 (errcode(ERRCODE_WINDOWING_ERROR),
788 errmsg("cannot use window function in VALUES"),
789 parser_errposition(pstate,
790 locate_windowfunc((Node *) qry))));
792 assign_query_collations(pstate, qry);
798 * Prepare an INSERT row for assignment to the target table.
800 * The row might be either a VALUES row, or variables referencing a
804 transformInsertRow(ParseState *pstate, List *exprlist,
805 List *stmtcols, List *icolumns, List *attrnos)
813 * Check length of expr list. It must not have more expressions than
814 * there are target columns. We allow fewer, but only if no explicit
815 * columns list was given (the remaining columns are implicitly
816 * defaulted). Note we must check this *after* transformation because
817 * that could expand '*' into multiple items.
819 if (list_length(exprlist) > list_length(icolumns))
821 (errcode(ERRCODE_SYNTAX_ERROR),
822 errmsg("INSERT has more expressions than target columns"),
823 parser_errposition(pstate,
824 exprLocation(list_nth(exprlist,
825 list_length(icolumns))))));
826 if (stmtcols != NIL &&
827 list_length(exprlist) < list_length(icolumns))
830 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
831 * where the user accidentally created a RowExpr instead of separate
832 * columns. Add a suitable hint if that seems to be the problem,
833 * because the main error message is quite misleading for this case.
834 * (If there's no stmtcols, you'll get something about data type
835 * mismatch, which is less misleading so we don't worry about giving a
836 * hint in that case.)
839 (errcode(ERRCODE_SYNTAX_ERROR),
840 errmsg("INSERT has more target columns than expressions"),
841 ((list_length(exprlist) == 1 &&
842 count_rowexpr_columns(pstate, linitial(exprlist)) ==
843 list_length(icolumns)) ?
844 errhint("The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?") : 0),
845 parser_errposition(pstate,
846 exprLocation(list_nth(icolumns,
847 list_length(exprlist))))));
851 * Prepare columns for assignment to target table.
854 icols = list_head(icolumns);
855 attnos = list_head(attrnos);
856 foreach(lc, exprlist)
858 Expr *expr = (Expr *) lfirst(lc);
861 col = (ResTarget *) lfirst(icols);
862 Assert(IsA(col, ResTarget));
864 expr = transformAssignedExpr(pstate, expr,
870 result = lappend(result, expr);
872 icols = lnext(icols);
873 attnos = lnext(attnos);
880 * count_rowexpr_columns -
881 * get number of columns contained in a ROW() expression;
882 * return -1 if expression isn't a RowExpr or a Var referencing one.
884 * This is currently used only for hint purposes, so we aren't terribly
885 * tense about recognizing all possible cases. The Var case is interesting
886 * because that's what we'll get in the INSERT ... SELECT (...) case.
889 count_rowexpr_columns(ParseState *pstate, Node *expr)
893 if (IsA(expr, RowExpr))
894 return list_length(((RowExpr *) expr)->args);
897 Var *var = (Var *) expr;
898 AttrNumber attnum = var->varattno;
900 if (attnum > 0 && var->vartype == RECORDOID)
904 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
905 if (rte->rtekind == RTE_SUBQUERY)
907 /* Subselect-in-FROM: examine sub-select's output expr */
908 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
911 if (ste == NULL || ste->resjunk)
913 expr = (Node *) ste->expr;
914 if (IsA(expr, RowExpr))
915 return list_length(((RowExpr *) expr)->args);
924 * transformSelectStmt -
925 * transforms a Select Statement
927 * Note: this covers only cases with no set operations and no VALUES lists;
928 * see below for the other cases.
931 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
933 Query *qry = makeNode(Query);
937 qry->commandType = CMD_SELECT;
939 /* process the WITH clause independently of all else */
940 if (stmt->withClause)
942 qry->hasRecursive = stmt->withClause->recursive;
943 qry->cteList = transformWithClause(pstate, stmt->withClause);
944 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
947 /* Complain if we get called from someplace where INTO is not allowed */
948 if (stmt->intoClause)
950 (errcode(ERRCODE_SYNTAX_ERROR),
951 errmsg("SELECT ... INTO is not allowed here"),
952 parser_errposition(pstate,
953 exprLocation((Node *) stmt->intoClause))));
955 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
956 pstate->p_locking_clause = stmt->lockingClause;
958 /* make WINDOW info available for window functions, too */
959 pstate->p_windowdefs = stmt->windowClause;
961 /* process the FROM clause */
962 transformFromClause(pstate, stmt->fromClause);
964 /* transform targetlist */
965 qry->targetList = transformTargetList(pstate, stmt->targetList);
967 /* mark column origins */
968 markTargetListOrigins(pstate, qry->targetList);
970 /* transform WHERE */
971 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
974 * Initial processing of HAVING clause is just like WHERE clause.
976 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
980 * Transform sorting/grouping stuff. Do ORDER BY first because both
981 * transformGroupClause and transformDistinctClause need the results. Note
982 * that these functions can also change the targetList, so it's passed to
985 qry->sortClause = transformSortClause(pstate,
988 true /* fix unknowns */ ,
989 false /* allow SQL92 rules */ );
991 qry->groupClause = transformGroupClause(pstate,
995 false /* allow SQL92 rules */ );
997 if (stmt->distinctClause == NIL)
999 qry->distinctClause = NIL;
1000 qry->hasDistinctOn = false;
1002 else if (linitial(stmt->distinctClause) == NULL)
1004 /* We had SELECT DISTINCT */
1005 qry->distinctClause = transformDistinctClause(pstate,
1009 qry->hasDistinctOn = false;
1013 /* We had SELECT DISTINCT ON */
1014 qry->distinctClause = transformDistinctOnClause(pstate,
1015 stmt->distinctClause,
1018 qry->hasDistinctOn = true;
1021 /* transform LIMIT */
1022 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1024 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1027 /* transform window clauses after we have seen all window functions */
1028 qry->windowClause = transformWindowDefinitions(pstate,
1029 pstate->p_windowdefs,
1032 qry->rtable = pstate->p_rtable;
1033 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1035 qry->hasSubLinks = pstate->p_hasSubLinks;
1036 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1037 if (pstate->p_hasWindowFuncs)
1038 parseCheckWindowFuncs(pstate, qry);
1039 qry->hasAggs = pstate->p_hasAggs;
1040 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1041 parseCheckAggregates(pstate, qry);
1043 foreach(l, stmt->lockingClause)
1045 transformLockingClause(pstate, qry,
1046 (LockingClause *) lfirst(l), false);
1049 assign_query_collations(pstate, qry);
1055 * transformValuesClause -
1056 * transforms a VALUES clause that's being used as a standalone SELECT
1058 * We build a Query containing a VALUES RTE, rather as if one had written
1059 * SELECT * FROM (VALUES ...) AS "*VALUES*"
1062 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
1064 Query *qry = makeNode(Query);
1067 List **colexprs = NULL;
1068 int sublist_length = -1;
1075 qry->commandType = CMD_SELECT;
1077 /* Most SELECT stuff doesn't apply in a VALUES clause */
1078 Assert(stmt->distinctClause == NIL);
1079 Assert(stmt->intoClause == NULL);
1080 Assert(stmt->targetList == NIL);
1081 Assert(stmt->fromClause == NIL);
1082 Assert(stmt->whereClause == NULL);
1083 Assert(stmt->groupClause == NIL);
1084 Assert(stmt->havingClause == NULL);
1085 Assert(stmt->windowClause == NIL);
1086 Assert(stmt->op == SETOP_NONE);
1088 /* process the WITH clause independently of all else */
1089 if (stmt->withClause)
1091 qry->hasRecursive = stmt->withClause->recursive;
1092 qry->cteList = transformWithClause(pstate, stmt->withClause);
1093 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1097 * For each row of VALUES, transform the raw expressions. This is also a
1098 * handy place to reject DEFAULT nodes, which the grammar allows for
1101 * Note that the intermediate representation we build is column-organized
1102 * not row-organized. That simplifies the type and collation processing
1105 foreach(lc, stmt->valuesLists)
1107 List *sublist = (List *) lfirst(lc);
1109 /* Do basic expression transformation (same as a ROW() expr) */
1110 sublist = transformExpressionList(pstate, sublist);
1113 * All the sublists must be the same length, *after* transformation
1114 * (which might expand '*' into multiple items). The VALUES RTE can't
1115 * handle anything different.
1117 if (sublist_length < 0)
1119 /* Remember post-transformation length of first sublist */
1120 sublist_length = list_length(sublist);
1121 /* and allocate array for per-column lists */
1122 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1124 else if (sublist_length != list_length(sublist))
1127 (errcode(ERRCODE_SYNTAX_ERROR),
1128 errmsg("VALUES lists must all be the same length"),
1129 parser_errposition(pstate,
1130 exprLocation((Node *) sublist))));
1133 /* Check for DEFAULT and build per-column expression lists */
1135 foreach(lc2, sublist)
1137 Node *col = (Node *) lfirst(lc2);
1139 if (IsA(col, SetToDefault))
1141 (errcode(ERRCODE_SYNTAX_ERROR),
1142 errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
1143 parser_errposition(pstate, exprLocation(col))));
1144 colexprs[i] = lappend(colexprs[i], col);
1148 /* Release sub-list's cells to save memory */
1153 * Now resolve the common types of the columns, and coerce everything to
1154 * those types. Then identify the common collation, if any, of each
1157 * We must do collation processing now because (1) assign_query_collations
1158 * doesn't process rangetable entries, and (2) we need to label the VALUES
1159 * RTE with column collations for use in the outer query. We don't
1160 * consider conflict of implicit collations to be an error here; instead
1161 * the column will just show InvalidOid as its collation, and you'll get a
1162 * failure later if that results in failure to resolve a collation.
1164 * Note we modify the per-column expression lists in-place.
1167 for (i = 0; i < sublist_length; i++)
1172 coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1174 foreach(lc, colexprs[i])
1176 Node *col = (Node *) lfirst(lc);
1178 col = coerce_to_common_type(pstate, col, coltype, "VALUES");
1179 lfirst(lc) = (void *) col;
1182 colcoll = select_common_collation(pstate, colexprs[i], true);
1184 collations = lappend_oid(collations, colcoll);
1188 * Finally, rearrange the coerced expressions into row-organized lists.
1191 foreach(lc, colexprs[0])
1193 Node *col = (Node *) lfirst(lc);
1196 sublist = list_make1(col);
1197 exprsLists = lappend(exprsLists, sublist);
1199 list_free(colexprs[0]);
1200 for (i = 1; i < sublist_length; i++)
1202 forboth(lc, colexprs[i], lc2, exprsLists)
1204 Node *col = (Node *) lfirst(lc);
1205 List *sublist = lfirst(lc2);
1207 /* sublist pointer in exprsLists won't need adjustment */
1208 (void) lappend(sublist, col);
1210 list_free(colexprs[i]);
1214 * Generate the VALUES RTE
1216 rte = addRangeTableEntryForValues(pstate, exprsLists, collations,
1218 rtr = makeNode(RangeTblRef);
1219 /* assume new rte is at end */
1220 rtr->rtindex = list_length(pstate->p_rtable);
1221 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1222 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1223 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1224 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1227 * Generate a targetlist as though expanding "*"
1229 Assert(pstate->p_next_resno == 1);
1230 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
1233 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1236 qry->sortClause = transformSortClause(pstate,
1239 true /* fix unknowns */ ,
1240 false /* allow SQL92 rules */ );
1242 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1244 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1247 if (stmt->lockingClause)
1249 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1250 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1253 * There mustn't have been any table references in the expressions, else
1254 * strange things would happen, like Cartesian products of those tables
1255 * with the VALUES list. We have to check this after parsing ORDER BY et
1256 * al since those could insert more junk.
1258 if (list_length(pstate->p_joinlist) != 1)
1260 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1261 errmsg("VALUES must not contain table references"),
1262 parser_errposition(pstate,
1263 locate_var_of_level((Node *) exprsLists, 0))));
1266 * Another thing we can't currently support is NEW/OLD references in rules
1267 * --- seems we'd need something like SQL99's LATERAL construct to ensure
1268 * that the values would be available while evaluating the VALUES RTE.
1269 * This is a shame. FIXME
1271 if (list_length(pstate->p_rtable) != 1 &&
1272 contain_vars_of_level((Node *) exprsLists, 0))
1274 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1275 errmsg("VALUES must not contain OLD or NEW references"),
1276 errhint("Use SELECT ... UNION ALL ... instead."),
1277 parser_errposition(pstate,
1278 locate_var_of_level((Node *) exprsLists, 0))));
1280 qry->rtable = pstate->p_rtable;
1281 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1283 qry->hasSubLinks = pstate->p_hasSubLinks;
1284 /* aggregates not allowed (but subselects are okay) */
1285 if (pstate->p_hasAggs)
1287 (errcode(ERRCODE_GROUPING_ERROR),
1288 errmsg("cannot use aggregate function in VALUES"),
1289 parser_errposition(pstate,
1290 locate_agg_of_level((Node *) exprsLists, 0))));
1291 if (pstate->p_hasWindowFuncs)
1293 (errcode(ERRCODE_WINDOWING_ERROR),
1294 errmsg("cannot use window function in VALUES"),
1295 parser_errposition(pstate,
1296 locate_windowfunc((Node *) exprsLists))));
1298 assign_query_collations(pstate, qry);
1304 * transformSetOperationStmt -
1305 * transforms a set-operations tree
1307 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1308 * structure to it. We must transform each leaf SELECT and build up a top-
1309 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1310 * The tree of set operations is converted into the setOperations field of
1311 * the top-level Query.
1314 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1316 Query *qry = makeNode(Query);
1317 SelectStmt *leftmostSelect;
1319 Query *leftmostQuery;
1320 SetOperationStmt *sostmt;
1324 List *lockingClause;
1326 ListCell *left_tlist,
1335 int sv_rtable_length;
1336 RangeTblEntry *jrte;
1339 qry->commandType = CMD_SELECT;
1341 /* process the WITH clause independently of all else */
1342 if (stmt->withClause)
1344 qry->hasRecursive = stmt->withClause->recursive;
1345 qry->cteList = transformWithClause(pstate, stmt->withClause);
1346 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1350 * Find leftmost leaf SelectStmt. We currently only need to do this in
1351 * order to deliver a suitable error message if there's an INTO clause
1352 * there, implying the set-op tree is in a context that doesn't allow
1353 * INTO. (transformSetOperationTree would throw error anyway, but it
1354 * seems worth the trouble to throw a different error for non-leftmost
1355 * INTO, so we produce that error in transformSetOperationTree.)
1357 leftmostSelect = stmt->larg;
1358 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1359 leftmostSelect = leftmostSelect->larg;
1360 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1361 leftmostSelect->larg == NULL);
1362 if (leftmostSelect->intoClause)
1364 (errcode(ERRCODE_SYNTAX_ERROR),
1365 errmsg("SELECT ... INTO is not allowed here"),
1366 parser_errposition(pstate,
1367 exprLocation((Node *) leftmostSelect->intoClause))));
1370 * We need to extract ORDER BY and other top-level clauses here and
1371 * not let transformSetOperationTree() see them --- else it'll just
1372 * recurse right back here!
1374 sortClause = stmt->sortClause;
1375 limitOffset = stmt->limitOffset;
1376 limitCount = stmt->limitCount;
1377 lockingClause = stmt->lockingClause;
1379 stmt->sortClause = NIL;
1380 stmt->limitOffset = NULL;
1381 stmt->limitCount = NULL;
1382 stmt->lockingClause = NIL;
1384 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1387 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1388 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1391 * Recursively transform the components of the tree.
1393 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1396 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1397 qry->setOperations = (Node *) sostmt;
1400 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1402 node = sostmt->larg;
1403 while (node && IsA(node, SetOperationStmt))
1404 node = ((SetOperationStmt *) node)->larg;
1405 Assert(node && IsA(node, RangeTblRef));
1406 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1407 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1408 Assert(leftmostQuery != NULL);
1411 * Generate dummy targetlist for outer query using column names of
1412 * leftmost select and common datatypes/collations of topmost set
1413 * operation. Also make lists of the dummy vars and their names for use
1414 * in parsing ORDER BY.
1416 * Note: we use leftmostRTI as the varno of the dummy variables. It
1417 * shouldn't matter too much which RT index they have, as long as they
1418 * have one that corresponds to a real RT entry; else funny things may
1419 * happen when the tree is mashed by rule rewriting.
1421 qry->targetList = NIL;
1424 left_tlist = list_head(leftmostQuery->targetList);
1426 forthree(lct, sostmt->colTypes,
1427 lcm, sostmt->colTypmods,
1428 lcc, sostmt->colCollations)
1430 Oid colType = lfirst_oid(lct);
1431 int32 colTypmod = lfirst_int(lcm);
1432 Oid colCollation = lfirst_oid(lcc);
1433 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1438 Assert(!lefttle->resjunk);
1439 colName = pstrdup(lefttle->resname);
1440 var = makeVar(leftmostRTI,
1446 var->location = exprLocation((Node *) lefttle->expr);
1447 tle = makeTargetEntry((Expr *) var,
1448 (AttrNumber) pstate->p_next_resno++,
1451 qry->targetList = lappend(qry->targetList, tle);
1452 targetvars = lappend(targetvars, var);
1453 targetnames = lappend(targetnames, makeString(colName));
1454 left_tlist = lnext(left_tlist);
1458 * As a first step towards supporting sort clauses that are expressions
1459 * using the output columns, generate a varnamespace entry that makes the
1460 * output columns visible. A Join RTE node is handy for this, since we
1461 * can easily control the Vars generated upon matches.
1463 * Note: we don't yet do anything useful with such cases, but at least
1464 * "ORDER BY upper(foo)" will draw the right error message rather than
1467 sv_rtable_length = list_length(pstate->p_rtable);
1469 jrte = addRangeTableEntryForJoin(pstate,
1476 sv_relnamespace = pstate->p_relnamespace;
1477 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1479 sv_varnamespace = pstate->p_varnamespace;
1480 pstate->p_varnamespace = list_make1(jrte);
1483 * For now, we don't support resjunk sort clauses on the output of a
1484 * setOperation tree --- you can only use the SQL92-spec options of
1485 * selecting an output column by name or number. Enforce by checking that
1486 * transformSortClause doesn't add any items to tlist.
1488 tllen = list_length(qry->targetList);
1490 qry->sortClause = transformSortClause(pstate,
1493 false /* no unknowns expected */ ,
1494 false /* allow SQL92 rules */ );
1496 pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1497 pstate->p_relnamespace = sv_relnamespace;
1498 pstate->p_varnamespace = sv_varnamespace;
1500 if (tllen != list_length(qry->targetList))
1502 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1503 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1504 errdetail("Only result column names can be used, not expressions or functions."),
1505 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1506 parser_errposition(pstate,
1507 exprLocation(list_nth(qry->targetList, tllen)))));
1509 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1511 qry->limitCount = transformLimitClause(pstate, limitCount,
1514 qry->rtable = pstate->p_rtable;
1515 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1517 qry->hasSubLinks = pstate->p_hasSubLinks;
1518 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1519 if (pstate->p_hasWindowFuncs)
1520 parseCheckWindowFuncs(pstate, qry);
1521 qry->hasAggs = pstate->p_hasAggs;
1522 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1523 parseCheckAggregates(pstate, qry);
1525 foreach(l, lockingClause)
1527 transformLockingClause(pstate, qry,
1528 (LockingClause *) lfirst(l), false);
1531 assign_query_collations(pstate, qry);
1537 * transformSetOperationTree
1538 * Recursively transform leaves and internal nodes of a set-op tree
1540 * In addition to returning the transformed node, if targetlist isn't NULL
1541 * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
1542 * set-op node these are the actual targetlist entries; otherwise they are
1543 * dummy entries created to carry the type, typmod, collation, and location
1544 * (for error messages) of each output column of the set-op node. This info
1545 * is needed only during the internal recursion of this function, so outside
1546 * callers pass NULL for targetlist. Note: the reason for passing the
1547 * actual targetlist entries of a leaf node is so that upper levels can
1548 * replace UNKNOWN Consts with properly-coerced constants.
1551 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1552 bool isTopLevel, List **targetlist)
1556 Assert(stmt && IsA(stmt, SelectStmt));
1559 * Validity-check both leaf and internal SELECTs for disallowed ops.
1561 if (stmt->intoClause)
1563 (errcode(ERRCODE_SYNTAX_ERROR),
1564 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1565 parser_errposition(pstate,
1566 exprLocation((Node *) stmt->intoClause))));
1568 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1569 if (stmt->lockingClause)
1571 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1572 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1575 * If an internal node of a set-op tree has ORDER BY, LIMIT, or FOR UPDATE
1576 * clauses attached, we need to treat it like a leaf node to generate an
1577 * independent sub-Query tree. Otherwise, it can be represented by a
1578 * SetOperationStmt node underneath the parent Query.
1580 if (stmt->op == SETOP_NONE)
1582 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1587 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1588 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1589 stmt->lockingClause)
1597 /* Process leaf SELECT */
1599 char selectName[32];
1600 RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
1605 * Transform SelectStmt into a Query.
1607 * Note: previously transformed sub-queries don't affect the parsing
1608 * of this sub-query, because they are not in the toplevel pstate's
1611 selectQuery = parse_sub_analyze((Node *) stmt, pstate, NULL, false);
1614 * Check for bogus references to Vars on the current query level (but
1615 * upper-level references are okay). Normally this can't happen
1616 * because the namespace will be empty, but it could happen if we are
1619 if (pstate->p_relnamespace || pstate->p_varnamespace)
1621 if (contain_vars_of_level((Node *) selectQuery, 1))
1623 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1624 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1625 parser_errposition(pstate,
1626 locate_var_of_level((Node *) selectQuery, 1))));
1630 * Extract a list of the non-junk TLEs for upper-level processing.
1635 foreach(tl, selectQuery->targetList)
1637 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1640 *targetlist = lappend(*targetlist, tle);
1645 * Make the leaf query be a subquery in the top-level rangetable.
1647 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1648 list_length(pstate->p_rtable) + 1);
1649 rte = addRangeTableEntryForSubquery(pstate,
1651 makeAlias(selectName, NIL),
1655 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1657 rtr = makeNode(RangeTblRef);
1658 /* assume new rte is at end */
1659 rtr->rtindex = list_length(pstate->p_rtable);
1660 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1661 return (Node *) rtr;
1665 /* Process an internal node (set operation node) */
1666 SetOperationStmt *op = makeNode(SetOperationStmt);
1671 const char *context;
1673 context = (stmt->op == SETOP_UNION ? "UNION" :
1674 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1678 op->all = stmt->all;
1681 * Recursively transform the left child node.
1683 op->larg = transformSetOperationTree(pstate, stmt->larg,
1688 * If we are processing a recursive union query, now is the time to
1689 * examine the non-recursive term's output columns and mark the
1690 * containing CTE as having those result columns. We should do this
1691 * only at the topmost setop of the CTE, of course.
1694 pstate->p_parent_cte &&
1695 pstate->p_parent_cte->cterecursive)
1696 determineRecursiveColTypes(pstate, op->larg, ltargetlist);
1699 * Recursively transform the right child node.
1701 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1706 * Verify that the two children have the same number of non-junk
1707 * columns, and determine the types of the merged output columns.
1709 if (list_length(ltargetlist) != list_length(rtargetlist))
1711 (errcode(ERRCODE_SYNTAX_ERROR),
1712 errmsg("each %s query must have the same number of columns",
1714 parser_errposition(pstate,
1715 exprLocation((Node *) rtargetlist))));
1720 op->colTypmods = NIL;
1721 op->colCollations = NIL;
1722 op->groupClauses = NIL;
1723 forboth(ltl, ltargetlist, rtl, rtargetlist)
1725 TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
1726 TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
1727 Node *lcolnode = (Node *) ltle->expr;
1728 Node *rcolnode = (Node *) rtle->expr;
1729 Oid lcoltype = exprType(lcolnode);
1730 Oid rcoltype = exprType(rcolnode);
1731 int32 lcoltypmod = exprTypmod(lcolnode);
1732 int32 rcoltypmod = exprTypmod(rcolnode);
1739 /* select common type, same as CASE et al */
1740 rescoltype = select_common_type(pstate,
1741 list_make2(lcolnode, rcolnode),
1744 bestlocation = exprLocation(bestexpr);
1745 /* if same type and same typmod, use typmod; else default */
1746 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1747 rescoltypmod = lcoltypmod;
1752 * Verify the coercions are actually possible. If not, we'd fail
1753 * later anyway, but we want to fail now while we have sufficient
1754 * context to produce an error cursor position.
1756 * For all non-UNKNOWN-type cases, we verify coercibility but we
1757 * don't modify the child's expression, for fear of changing the
1758 * child query's semantics.
1760 * If a child expression is an UNKNOWN-type Const or Param, we
1761 * want to replace it with the coerced expression. This can only
1762 * happen when the child is a leaf set-op node. It's safe to
1763 * replace the expression because if the child query's semantics
1764 * depended on the type of this output column, it'd have already
1765 * coerced the UNKNOWN to something else. We want to do this
1766 * because (a) we want to verify that a Const is valid for the
1767 * target type, or resolve the actual type of an UNKNOWN Param,
1768 * and (b) we want to avoid unnecessary discrepancies between the
1769 * output type of the child query and the resolved target type.
1770 * Such a discrepancy would disable optimization in the planner.
1772 * If it's some other UNKNOWN-type node, eg a Var, we do nothing
1773 * (knowing that coerce_to_common_type would fail). The planner
1774 * is sometimes able to fold an UNKNOWN Var to a constant before
1775 * it has to coerce the type, so failing now would just break
1776 * cases that might work.
1778 if (lcoltype != UNKNOWNOID)
1779 lcolnode = coerce_to_common_type(pstate, lcolnode,
1780 rescoltype, context);
1781 else if (IsA(lcolnode, Const) ||
1782 IsA(lcolnode, Param))
1784 lcolnode = coerce_to_common_type(pstate, lcolnode,
1785 rescoltype, context);
1786 ltle->expr = (Expr *) lcolnode;
1789 if (rcoltype != UNKNOWNOID)
1790 rcolnode = coerce_to_common_type(pstate, rcolnode,
1791 rescoltype, context);
1792 else if (IsA(rcolnode, Const) ||
1793 IsA(rcolnode, Param))
1795 rcolnode = coerce_to_common_type(pstate, rcolnode,
1796 rescoltype, context);
1797 rtle->expr = (Expr *) rcolnode;
1801 * Select common collation. A common collation is required for
1802 * all set operators except UNION ALL; see SQL:2008 7.13 <query
1803 * expression> Syntax Rule 15c. (If we fail to identify a common
1804 * collation for a UNION ALL column, the curCollations element
1805 * will be set to InvalidOid, which may result in a runtime error
1806 * if something at a higher query level wants to use the column's
1809 rescolcoll = select_common_collation(pstate,
1810 list_make2(lcolnode, rcolnode),
1811 (op->op == SETOP_UNION && op->all));
1814 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1815 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1816 op->colCollations = lappend_oid(op->colCollations, rescolcoll);
1819 * For all cases except UNION ALL, identify the grouping operators
1820 * (and, if available, sorting operators) that will be used to
1821 * eliminate duplicates.
1823 if (op->op != SETOP_UNION || !op->all)
1825 SortGroupClause *grpcl = makeNode(SortGroupClause);
1829 ParseCallbackState pcbstate;
1831 setup_parser_errposition_callback(&pcbstate, pstate,
1834 /* determine the eqop and optional sortop */
1835 get_sort_group_operators(rescoltype,
1837 &sortop, &eqop, NULL,
1840 cancel_parser_errposition_callback(&pcbstate);
1842 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1843 grpcl->tleSortGroupRef = 0;
1845 grpcl->sortop = sortop;
1846 grpcl->nulls_first = false; /* OK with or without sortop */
1847 grpcl->hashable = hashable;
1849 op->groupClauses = lappend(op->groupClauses, grpcl);
1853 * Construct a dummy tlist entry to return. We use a SetToDefault
1854 * node for the expression, since it carries exactly the fields
1855 * needed, but any other expression node type would do as well.
1859 SetToDefault *rescolnode = makeNode(SetToDefault);
1860 TargetEntry *restle;
1862 rescolnode->typeId = rescoltype;
1863 rescolnode->typeMod = rescoltypmod;
1864 rescolnode->collation = rescolcoll;
1865 rescolnode->location = bestlocation;
1866 restle = makeTargetEntry((Expr *) rescolnode,
1867 0, /* no need to set resno */
1870 *targetlist = lappend(*targetlist, restle);
1879 * Process the outputs of the non-recursive term of a recursive union
1880 * to set up the parent CTE's columns
1883 determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
1887 Query *leftmostQuery;
1889 ListCell *left_tlist;
1894 * Find leftmost leaf SELECT
1897 while (node && IsA(node, SetOperationStmt))
1898 node = ((SetOperationStmt *) node)->larg;
1899 Assert(node && IsA(node, RangeTblRef));
1900 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1901 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1902 Assert(leftmostQuery != NULL);
1905 * Generate dummy targetlist using column names of leftmost select and
1906 * dummy result expressions of the non-recursive term.
1909 left_tlist = list_head(leftmostQuery->targetList);
1912 foreach(nrtl, nrtargetlist)
1914 TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
1915 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1919 Assert(!lefttle->resjunk);
1920 colName = pstrdup(lefttle->resname);
1921 tle = makeTargetEntry(nrtle->expr,
1925 targetList = lappend(targetList, tle);
1926 left_tlist = lnext(left_tlist);
1929 /* Now build CTE's output column info using dummy targetlist */
1930 analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
1935 * transformUpdateStmt -
1936 * transforms an update statement
1939 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1941 Query *qry = makeNode(Query);
1942 RangeTblEntry *target_rte;
1944 ListCell *origTargetList;
1947 qry->commandType = CMD_UPDATE;
1948 pstate->p_is_update = true;
1950 /* process the WITH clause independently of all else */
1951 if (stmt->withClause)
1953 qry->hasRecursive = stmt->withClause->recursive;
1954 qry->cteList = transformWithClause(pstate, stmt->withClause);
1955 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1958 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1959 interpretInhOption(stmt->relation->inhOpt),
1964 * the FROM clause is non-standard SQL syntax. We used to be able to do
1965 * this with REPLACE in POSTQUEL so we keep the feature.
1967 transformFromClause(pstate, stmt->fromClause);
1969 qry->targetList = transformTargetList(pstate, stmt->targetList);
1971 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1973 qry->returningList = transformReturningList(pstate, stmt->returningList);
1975 qry->rtable = pstate->p_rtable;
1976 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1978 qry->hasSubLinks = pstate->p_hasSubLinks;
1981 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1982 * an implementation point of view, this is forced because the implicit
1983 * ctid reference would otherwise be an ungrouped variable.)
1985 if (pstate->p_hasAggs)
1987 (errcode(ERRCODE_GROUPING_ERROR),
1988 errmsg("cannot use aggregate function in UPDATE"),
1989 parser_errposition(pstate,
1990 locate_agg_of_level((Node *) qry, 0))));
1991 if (pstate->p_hasWindowFuncs)
1993 (errcode(ERRCODE_WINDOWING_ERROR),
1994 errmsg("cannot use window function in UPDATE"),
1995 parser_errposition(pstate,
1996 locate_windowfunc((Node *) qry))));
1999 * Now we are done with SELECT-like processing, and can get on with
2000 * transforming the target list to match the UPDATE target columns.
2003 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2004 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2005 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2007 /* Prepare non-junk columns for assignment to target table */
2008 target_rte = pstate->p_target_rangetblentry;
2009 origTargetList = list_head(stmt->targetList);
2011 foreach(tl, qry->targetList)
2013 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2014 ResTarget *origTarget;
2020 * Resjunk nodes need no additional processing, but be sure they
2021 * have resnos that do not match any target columns; else rewriter
2022 * or planner might get confused. They don't need a resname
2025 tle->resno = (AttrNumber) pstate->p_next_resno++;
2026 tle->resname = NULL;
2029 if (origTargetList == NULL)
2030 elog(ERROR, "UPDATE target count mismatch --- internal error");
2031 origTarget = (ResTarget *) lfirst(origTargetList);
2032 Assert(IsA(origTarget, ResTarget));
2034 attrno = attnameAttNum(pstate->p_target_relation,
2035 origTarget->name, true);
2036 if (attrno == InvalidAttrNumber)
2038 (errcode(ERRCODE_UNDEFINED_COLUMN),
2039 errmsg("column \"%s\" of relation \"%s\" does not exist",
2041 RelationGetRelationName(pstate->p_target_relation)),
2042 parser_errposition(pstate, origTarget->location)));
2044 updateTargetListEntry(pstate, tle, origTarget->name,
2046 origTarget->indirection,
2047 origTarget->location);
2049 /* Mark the target column as requiring update permissions */
2050 target_rte->modifiedCols = bms_add_member(target_rte->modifiedCols,
2051 attrno - FirstLowInvalidHeapAttributeNumber);
2053 origTargetList = lnext(origTargetList);
2055 if (origTargetList != NULL)
2056 elog(ERROR, "UPDATE target count mismatch --- internal error");
2058 assign_query_collations(pstate, qry);
2064 * transformReturningList -
2065 * handle a RETURNING clause in INSERT/UPDATE/DELETE
2068 transformReturningList(ParseState *pstate, List *returningList)
2071 int save_next_resno;
2073 bool save_hasWindowFuncs;
2076 if (returningList == NIL)
2077 return NIL; /* nothing to do */
2080 * We need to assign resnos starting at one in the RETURNING list. Save
2081 * and restore the main tlist's value of p_next_resno, just in case
2082 * someone looks at it later (probably won't happen).
2084 save_next_resno = pstate->p_next_resno;
2085 pstate->p_next_resno = 1;
2087 /* save other state so that we can detect disallowed stuff */
2088 save_hasAggs = pstate->p_hasAggs;
2089 pstate->p_hasAggs = false;
2090 save_hasWindowFuncs = pstate->p_hasWindowFuncs;
2091 pstate->p_hasWindowFuncs = false;
2092 length_rtable = list_length(pstate->p_rtable);
2094 /* transform RETURNING identically to a SELECT targetlist */
2095 rlist = transformTargetList(pstate, returningList);
2097 /* check for disallowed stuff */
2099 /* aggregates not allowed (but subselects are okay) */
2100 if (pstate->p_hasAggs)
2102 (errcode(ERRCODE_GROUPING_ERROR),
2103 errmsg("cannot use aggregate function in RETURNING"),
2104 parser_errposition(pstate,
2105 locate_agg_of_level((Node *) rlist, 0))));
2106 if (pstate->p_hasWindowFuncs)
2108 (errcode(ERRCODE_WINDOWING_ERROR),
2109 errmsg("cannot use window function in RETURNING"),
2110 parser_errposition(pstate,
2111 locate_windowfunc((Node *) rlist))));
2113 /* no new relation references please */
2114 if (list_length(pstate->p_rtable) != length_rtable)
2119 /* try to locate such a reference to point to */
2120 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
2122 vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
2127 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2128 errmsg("RETURNING cannot contain references to other relations"),
2129 parser_errposition(pstate, vlocation)));
2132 /* mark column origins */
2133 markTargetListOrigins(pstate, rlist);
2136 pstate->p_next_resno = save_next_resno;
2137 pstate->p_hasAggs = save_hasAggs;
2138 pstate->p_hasWindowFuncs = save_hasWindowFuncs;
2145 * transformDeclareCursorStmt -
2146 * transform a DECLARE CURSOR Statement
2148 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
2149 * significantly different from a SELECT) as far as parsing/rewriting/planning
2150 * are concerned, but it's not passed to the executor and so in that sense is
2151 * a utility statement. We transform it into a Query exactly as if it were
2152 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
2153 * field to carry the cursor name and options.
2156 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2161 * Don't allow both SCROLL and NO SCROLL to be specified
2163 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2164 (stmt->options & CURSOR_OPT_NO_SCROLL))
2166 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2167 errmsg("cannot specify both SCROLL and NO SCROLL")));
2169 result = transformStmt(pstate, stmt->query);
2171 /* Grammar should not have allowed anything but SELECT */
2172 if (!IsA(result, Query) ||
2173 result->commandType != CMD_SELECT ||
2174 result->utilityStmt != NULL)
2175 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
2178 * We also disallow data-modifying WITH in a cursor. (This could be
2179 * allowed, but the semantics of when the updates occur might be
2182 if (result->hasModifyingCTE)
2184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2185 errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
2187 /* FOR UPDATE and WITH HOLD are not compatible */
2188 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
2190 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2191 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
2192 errdetail("Holdable cursors must be READ ONLY.")));
2194 /* FOR UPDATE and SCROLL are not compatible */
2195 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
2197 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2198 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
2199 errdetail("Scrollable cursors must be READ ONLY.")));
2201 /* FOR UPDATE and INSENSITIVE are not compatible */
2202 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
2204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2205 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
2206 errdetail("Insensitive cursors must be READ ONLY.")));
2208 /* We won't need the raw querytree any more */
2211 result->utilityStmt = (Node *) stmt;
2218 * transformExplainStmt -
2219 * transform an EXPLAIN Statement
2221 * EXPLAIN is like other utility statements in that we emit it as a
2222 * CMD_UTILITY Query node; however, we must first transform the contained
2223 * query. We used to postpone that until execution, but it's really necessary
2224 * to do it during the normal parse analysis phase to ensure that side effects
2225 * of parser hooks happen at the expected time.
2228 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
2232 /* transform contained query, allowing SELECT INTO */
2233 stmt->query = (Node *) transformTopLevelStmt(pstate, stmt->query);
2235 /* represent the command as a utility Query */
2236 result = makeNode(Query);
2237 result->commandType = CMD_UTILITY;
2238 result->utilityStmt = (Node *) stmt;
2245 * transformCreateTableAsStmt -
2246 * transform a CREATE TABLE AS (or SELECT ... INTO) Statement
2248 * As with EXPLAIN, transform the contained statement now.
2251 transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
2255 /* transform contained query */
2256 stmt->query = (Node *) transformStmt(pstate, stmt->query);
2258 /* represent the command as a utility Query */
2259 result = makeNode(Query);
2260 result->commandType = CMD_UTILITY;
2261 result->utilityStmt = (Node *) stmt;
2268 * Check for features that are not supported together with FOR UPDATE/SHARE.
2270 * exported so planner can check again after rewriting, query pullup, etc
2273 CheckSelectLocking(Query *qry)
2275 if (qry->setOperations)
2277 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2278 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2279 if (qry->distinctClause != NIL)
2281 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2282 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
2283 if (qry->groupClause != NIL)
2285 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2286 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
2287 if (qry->havingQual != NULL)
2289 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2290 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
2293 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2294 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
2295 if (qry->hasWindowFuncs)
2297 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2298 errmsg("SELECT FOR UPDATE/SHARE is not allowed with window functions")));
2299 if (expression_returns_set((Node *) qry->targetList))
2301 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2302 errmsg("SELECT FOR UPDATE/SHARE is not allowed with set-returning functions in the target list")));
2306 * Transform a FOR UPDATE/SHARE clause
2308 * This basically involves replacing names by integer relids.
2310 * NB: if you need to change this, see also markQueryForLocking()
2311 * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
2314 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc,
2317 List *lockedRels = lc->lockedRels;
2321 LockingClause *allrels;
2323 CheckSelectLocking(qry);
2325 /* make a clause we can pass down to subqueries to select all rels */
2326 allrels = makeNode(LockingClause);
2327 allrels->lockedRels = NIL; /* indicates all rels */
2328 allrels->forUpdate = lc->forUpdate;
2329 allrels->noWait = lc->noWait;
2331 if (lockedRels == NIL)
2333 /* all regular tables used in query */
2335 foreach(rt, qry->rtable)
2337 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2340 switch (rte->rtekind)
2343 /* ignore foreign tables */
2344 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2346 applyLockingClause(qry, i,
2347 lc->forUpdate, lc->noWait, pushedDown);
2348 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2351 applyLockingClause(qry, i,
2352 lc->forUpdate, lc->noWait, pushedDown);
2355 * FOR UPDATE/SHARE of subquery is propagated to all of
2356 * subquery's rels, too. We could do this later (based on
2357 * the marking of the subquery RTE) but it is convenient
2358 * to have local knowledge in each query level about which
2359 * rels need to be opened with RowShareLock.
2361 transformLockingClause(pstate, rte->subquery,
2365 /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
2372 /* just the named tables */
2373 foreach(l, lockedRels)
2375 RangeVar *thisrel = (RangeVar *) lfirst(l);
2377 /* For simplicity we insist on unqualified alias names here */
2378 if (thisrel->catalogname || thisrel->schemaname)
2380 (errcode(ERRCODE_SYNTAX_ERROR),
2381 errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
2382 parser_errposition(pstate, thisrel->location)));
2385 foreach(rt, qry->rtable)
2387 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2390 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2392 switch (rte->rtekind)
2395 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2397 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2398 errmsg("SELECT FOR UPDATE/SHARE cannot be used with foreign table \"%s\"",
2399 rte->eref->aliasname),
2400 parser_errposition(pstate, thisrel->location)));
2401 applyLockingClause(qry, i,
2402 lc->forUpdate, lc->noWait,
2404 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2407 applyLockingClause(qry, i,
2408 lc->forUpdate, lc->noWait,
2410 /* see comment above */
2411 transformLockingClause(pstate, rte->subquery,
2416 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2417 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2418 parser_errposition(pstate, thisrel->location)));
2422 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2423 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2424 parser_errposition(pstate, thisrel->location)));
2428 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2429 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2430 parser_errposition(pstate, thisrel->location)));
2434 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2435 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a WITH query"),
2436 parser_errposition(pstate, thisrel->location)));
2439 elog(ERROR, "unrecognized RTE type: %d",
2440 (int) rte->rtekind);
2443 break; /* out of foreach loop */
2448 (errcode(ERRCODE_UNDEFINED_TABLE),
2449 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2451 parser_errposition(pstate, thisrel->location)));
2457 * Record locking info for a single rangetable item
2460 applyLockingClause(Query *qry, Index rtindex,
2461 bool forUpdate, bool noWait, bool pushedDown)
2465 /* If it's an explicit clause, make sure hasForUpdate gets set */
2467 qry->hasForUpdate = true;
2469 /* Check for pre-existing entry for same rtindex */
2470 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
2473 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2474 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
2475 * and exclusive lock at the same time; it'll end up being exclusive
2478 * We also consider that NOWAIT wins if it's specified both ways. This
2479 * is a bit more debatable but raising an error doesn't seem helpful.
2480 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2481 * internally contains a plain FOR UPDATE spec.)
2483 * And of course pushedDown becomes false if any clause is explicit.
2485 rc->forUpdate |= forUpdate;
2486 rc->noWait |= noWait;
2487 rc->pushedDown &= pushedDown;
2491 /* Make a new RowMarkClause */
2492 rc = makeNode(RowMarkClause);
2494 rc->forUpdate = forUpdate;
2495 rc->noWait = noWait;
2496 rc->pushedDown = pushedDown;
2497 qry->rowMarks = lappend(qry->rowMarks, rc);