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.389 2009/06/11 14:48:59 momjian 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 */
260 * We only need a snapshot in varparams case, but it doesn't seem
261 * worth complicating this function's API to distinguish that.
267 /* utility statements don't have any active parse analysis */
276 * transformDeleteStmt -
277 * transforms a Delete Statement
280 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
282 Query *qry = makeNode(Query);
285 qry->commandType = CMD_DELETE;
287 /* set up range table with just the result rel */
288 qry->resultRelation = setTargetTable(pstate, stmt->relation,
289 interpretInhOption(stmt->relation->inhOpt),
293 qry->distinctClause = NIL;
296 * The USING clause is non-standard SQL syntax, and is equivalent in
297 * functionality to the FROM list that can be specified for UPDATE. The
298 * USING keyword is used rather than FROM because FROM is already a
299 * keyword in the DELETE syntax.
301 transformFromClause(pstate, stmt->usingClause);
303 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
305 qry->returningList = transformReturningList(pstate, stmt->returningList);
307 /* done building the range table and jointree */
308 qry->rtable = pstate->p_rtable;
309 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
311 qry->hasSubLinks = pstate->p_hasSubLinks;
312 qry->hasAggs = pstate->p_hasAggs;
313 if (pstate->p_hasAggs)
314 parseCheckAggregates(pstate, qry);
315 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
316 if (pstate->p_hasWindowFuncs)
317 parseCheckWindowFuncs(pstate, qry);
323 * transformInsertStmt -
324 * transform an Insert Statement
327 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
329 Query *qry = makeNode(Query);
330 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
331 List *exprList = NIL;
332 bool isGeneralSelect;
334 List *sub_relnamespace;
335 List *sub_varnamespace;
344 qry->commandType = CMD_INSERT;
345 pstate->p_is_insert = true;
348 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
349 * VALUES list, or general SELECT input. We special-case VALUES, both for
350 * efficiency and so we can handle DEFAULT specifications.
352 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
355 * If a non-nil rangetable/namespace was passed in, and we are doing
356 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
357 * SELECT. This can only happen if we are inside a CREATE RULE, and in
358 * that case we want the rule's OLD and NEW rtable entries to appear as
359 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
360 * The SELECT's joinlist is not affected however. We must do this before
361 * adding the target table to the INSERT's rtable.
365 sub_rtable = pstate->p_rtable;
366 pstate->p_rtable = NIL;
367 sub_relnamespace = pstate->p_relnamespace;
368 pstate->p_relnamespace = NIL;
369 sub_varnamespace = pstate->p_varnamespace;
370 pstate->p_varnamespace = NIL;
371 /* There can't be any outer WITH to worry about */
372 Assert(pstate->p_ctenamespace == NIL);
376 sub_rtable = NIL; /* not used, but keep compiler quiet */
377 sub_relnamespace = NIL;
378 sub_varnamespace = NIL;
382 * Must get write lock on INSERT target table before scanning SELECT, else
383 * we will grab the wrong kind of initial lock if the target table is also
384 * mentioned in the SELECT part. Note that the target table is not added
385 * to the joinlist or namespace.
387 qry->resultRelation = setTargetTable(pstate, stmt->relation,
388 false, false, ACL_INSERT);
390 /* Validate stmt->cols list, or build default list if no list given */
391 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
392 Assert(list_length(icolumns) == list_length(attrnos));
395 * Determine which variant of INSERT we have.
397 if (selectStmt == NULL)
400 * We have INSERT ... DEFAULT VALUES. We can handle this case by
401 * emitting an empty targetlist --- all columns will be defaulted when
402 * the planner expands the targetlist.
406 else if (isGeneralSelect)
409 * We make the sub-pstate a child of the outer pstate so that it can
410 * see any Param definitions supplied from above. Since the outer
411 * pstate's rtable and namespace are presently empty, there are no
412 * side-effects of exposing names the sub-SELECT shouldn't be able to
415 ParseState *sub_pstate = make_parsestate(pstate);
419 * Process the source SELECT.
421 * It is important that this be handled just like a standalone SELECT;
422 * otherwise the behavior of SELECT within INSERT might be different
423 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
424 * bugs of just that nature...)
426 sub_pstate->p_rtable = sub_rtable;
427 sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
428 sub_pstate->p_relnamespace = sub_relnamespace;
429 sub_pstate->p_varnamespace = sub_varnamespace;
431 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
433 free_parsestate(sub_pstate);
435 /* The grammar should have produced a SELECT, but it might have INTO */
436 if (!IsA(selectQuery, Query) ||
437 selectQuery->commandType != CMD_SELECT ||
438 selectQuery->utilityStmt != NULL)
439 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
440 if (selectQuery->intoClause)
442 (errcode(ERRCODE_SYNTAX_ERROR),
443 errmsg("INSERT ... SELECT cannot specify INTO"),
444 parser_errposition(pstate,
445 exprLocation((Node *) selectQuery->intoClause))));
448 * Make the source be a subquery in the INSERT's rangetable, and add
449 * it to the INSERT's joinlist.
451 rte = addRangeTableEntryForSubquery(pstate,
453 makeAlias("*SELECT*", NIL),
455 rtr = makeNode(RangeTblRef);
456 /* assume new rte is at end */
457 rtr->rtindex = list_length(pstate->p_rtable);
458 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
459 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
462 * Generate an expression list for the INSERT that selects all the
463 * non-resjunk columns from the subquery. (INSERT's tlist must be
464 * separate from the subquery's tlist because we may add columns,
465 * insert datatype coercions, etc.)
467 * HACK: unknown-type constants and params in the SELECT's targetlist
468 * are copied up as-is rather than being referenced as subquery
469 * outputs. This is to ensure that when we try to coerce them to
470 * the target column's datatype, the right things happen (see
471 * special cases in coerce_type). Otherwise, this fails:
472 * INSERT INTO foo SELECT 'bar', ... FROM baz
476 foreach(lc, selectQuery->targetList)
478 TargetEntry *tle = (TargetEntry *) lfirst(lc);
484 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
485 exprType((Node *) tle->expr) == UNKNOWNOID)
489 Var *var = makeVar(rtr->rtindex,
491 exprType((Node *) tle->expr),
492 exprTypmod((Node *) tle->expr),
495 var->location = exprLocation((Node *) tle->expr);
498 exprList = lappend(exprList, expr);
501 /* Prepare row for assignment to target table */
502 exprList = transformInsertRow(pstate, exprList,
506 else if (list_length(selectStmt->valuesLists) > 1)
509 * Process INSERT ... VALUES with multiple VALUES sublists. We
510 * generate a VALUES RTE holding the transformed expression lists, and
511 * build up a targetlist containing Vars that reference the VALUES
514 List *exprsLists = NIL;
515 int sublist_length = -1;
517 /* process the WITH clause */
518 if (selectStmt->withClause)
520 qry->hasRecursive = selectStmt->withClause->recursive;
521 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
524 foreach(lc, selectStmt->valuesLists)
526 List *sublist = (List *) lfirst(lc);
528 /* Do basic expression transformation (same as a ROW() expr) */
529 sublist = transformExpressionList(pstate, sublist);
532 * All the sublists must be the same length, *after*
533 * transformation (which might expand '*' into multiple items).
534 * The VALUES RTE can't handle anything different.
536 if (sublist_length < 0)
538 /* Remember post-transformation length of first sublist */
539 sublist_length = list_length(sublist);
541 else if (sublist_length != list_length(sublist))
544 (errcode(ERRCODE_SYNTAX_ERROR),
545 errmsg("VALUES lists must all be the same length"),
546 parser_errposition(pstate,
547 exprLocation((Node *) sublist))));
550 /* Prepare row for assignment to target table */
551 sublist = transformInsertRow(pstate, sublist,
555 exprsLists = lappend(exprsLists, sublist);
559 * There mustn't have been any table references in the expressions,
560 * else strange things would happen, like Cartesian products of those
561 * tables with the VALUES list ...
563 if (pstate->p_joinlist != NIL)
565 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
566 errmsg("VALUES must not contain table references"),
567 parser_errposition(pstate,
568 locate_var_of_level((Node *) exprsLists, 0))));
571 * Another thing we can't currently support is NEW/OLD references in
572 * rules --- seems we'd need something like SQL99's LATERAL construct
573 * to ensure that the values would be available while evaluating the
574 * VALUES RTE. This is a shame. FIXME
576 if (list_length(pstate->p_rtable) != 1 &&
577 contain_vars_of_level((Node *) exprsLists, 0))
579 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
580 errmsg("VALUES must not contain OLD or NEW references"),
581 errhint("Use SELECT ... UNION ALL ... instead."),
582 parser_errposition(pstate,
583 locate_var_of_level((Node *) exprsLists, 0))));
586 * Generate the VALUES RTE
588 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
589 rtr = makeNode(RangeTblRef);
590 /* assume new rte is at end */
591 rtr->rtindex = list_length(pstate->p_rtable);
592 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
593 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
596 * Generate list of Vars referencing the RTE
598 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
603 * Process INSERT ... VALUES with a single VALUES sublist.
604 * We treat this separately for efficiency and for historical
605 * compatibility --- specifically, allowing table references,
607 * INSERT INTO foo VALUES(bar.*)
609 * The sublist is just computed directly as the Query's targetlist,
610 * with no VALUES RTE. So it works just like SELECT without FROM.
613 List *valuesLists = selectStmt->valuesLists;
615 Assert(list_length(valuesLists) == 1);
617 /* process the WITH clause */
618 if (selectStmt->withClause)
620 qry->hasRecursive = selectStmt->withClause->recursive;
621 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
624 /* Do basic expression transformation (same as a ROW() expr) */
625 exprList = transformExpressionList(pstate,
626 (List *) linitial(valuesLists));
628 /* Prepare row for assignment to target table */
629 exprList = transformInsertRow(pstate, exprList,
635 * Generate query's target list using the computed list of expressions.
636 * Also, mark all the target columns as needing insert permissions.
638 rte = pstate->p_target_rangetblentry;
639 qry->targetList = NIL;
640 icols = list_head(icolumns);
641 attnos = list_head(attrnos);
642 foreach(lc, exprList)
644 Expr *expr = (Expr *) lfirst(lc);
649 col = (ResTarget *) lfirst(icols);
650 Assert(IsA(col, ResTarget));
651 attr_num = (AttrNumber) lfirst_int(attnos);
653 tle = makeTargetEntry(expr,
657 qry->targetList = lappend(qry->targetList, tle);
659 rte->modifiedCols = bms_add_member(rte->modifiedCols,
660 attr_num - FirstLowInvalidHeapAttributeNumber);
662 icols = lnext(icols);
663 attnos = lnext(attnos);
667 * If we have a RETURNING clause, we need to add the target relation to
668 * the query namespace before processing it, so that Var references in
669 * RETURNING will work. Also, remove any namespace entries added in a
670 * sub-SELECT or VALUES list.
672 if (stmt->returningList)
674 pstate->p_relnamespace = NIL;
675 pstate->p_varnamespace = NIL;
676 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
678 qry->returningList = transformReturningList(pstate,
679 stmt->returningList);
682 /* done building the range table and jointree */
683 qry->rtable = pstate->p_rtable;
684 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
686 qry->hasSubLinks = pstate->p_hasSubLinks;
687 /* aggregates not allowed (but subselects are okay) */
688 if (pstate->p_hasAggs)
690 (errcode(ERRCODE_GROUPING_ERROR),
691 errmsg("cannot use aggregate function in VALUES"),
692 parser_errposition(pstate,
693 locate_agg_of_level((Node *) qry, 0))));
694 if (pstate->p_hasWindowFuncs)
696 (errcode(ERRCODE_WINDOWING_ERROR),
697 errmsg("cannot use window function in VALUES"),
698 parser_errposition(pstate,
699 locate_windowfunc((Node *) qry))));
705 * Prepare an INSERT row for assignment to the target table.
707 * The row might be either a VALUES row, or variables referencing a
711 transformInsertRow(ParseState *pstate, List *exprlist,
712 List *stmtcols, List *icolumns, List *attrnos)
720 * Check length of expr list. It must not have more expressions than
721 * there are target columns. We allow fewer, but only if no explicit
722 * columns list was given (the remaining columns are implicitly
723 * defaulted). Note we must check this *after* transformation because
724 * that could expand '*' into multiple items.
726 if (list_length(exprlist) > list_length(icolumns))
728 (errcode(ERRCODE_SYNTAX_ERROR),
729 errmsg("INSERT has more expressions than target columns"),
730 parser_errposition(pstate,
731 exprLocation(list_nth(exprlist,
732 list_length(icolumns))))));
733 if (stmtcols != NIL &&
734 list_length(exprlist) < list_length(icolumns))
736 (errcode(ERRCODE_SYNTAX_ERROR),
737 errmsg("INSERT has more target columns than expressions"),
738 parser_errposition(pstate,
739 exprLocation(list_nth(icolumns,
740 list_length(exprlist))))));
743 * Prepare columns for assignment to target table.
746 icols = list_head(icolumns);
747 attnos = list_head(attrnos);
748 foreach(lc, exprlist)
750 Expr *expr = (Expr *) lfirst(lc);
753 col = (ResTarget *) lfirst(icols);
754 Assert(IsA(col, ResTarget));
756 expr = transformAssignedExpr(pstate, expr,
762 result = lappend(result, expr);
764 icols = lnext(icols);
765 attnos = lnext(attnos);
773 * transformSelectStmt -
774 * transforms a Select Statement
776 * Note: this covers only cases with no set operations and no VALUES lists;
777 * see below for the other cases.
780 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
782 Query *qry = makeNode(Query);
786 qry->commandType = CMD_SELECT;
788 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
789 pstate->p_locking_clause = stmt->lockingClause;
791 /* make WINDOW info available for window functions, too */
792 pstate->p_windowdefs = stmt->windowClause;
794 /* process the WITH clause */
795 if (stmt->withClause)
797 qry->hasRecursive = stmt->withClause->recursive;
798 qry->cteList = transformWithClause(pstate, stmt->withClause);
801 /* process the FROM clause */
802 transformFromClause(pstate, stmt->fromClause);
804 /* transform targetlist */
805 qry->targetList = transformTargetList(pstate, stmt->targetList);
807 /* mark column origins */
808 markTargetListOrigins(pstate, qry->targetList);
810 /* transform WHERE */
811 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
814 * Initial processing of HAVING clause is just like WHERE clause.
816 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
820 * Transform sorting/grouping stuff. Do ORDER BY first because both
821 * transformGroupClause and transformDistinctClause need the results. Note
822 * that these functions can also change the targetList, so it's passed to
825 qry->sortClause = transformSortClause(pstate,
828 true /* fix unknowns */ );
830 qry->groupClause = transformGroupClause(pstate,
836 if (stmt->distinctClause == NIL)
838 qry->distinctClause = NIL;
839 qry->hasDistinctOn = false;
841 else if (linitial(stmt->distinctClause) == NULL)
843 /* We had SELECT DISTINCT */
844 qry->distinctClause = transformDistinctClause(pstate,
847 qry->hasDistinctOn = false;
851 /* We had SELECT DISTINCT ON */
852 qry->distinctClause = transformDistinctOnClause(pstate,
853 stmt->distinctClause,
856 qry->hasDistinctOn = true;
859 /* transform LIMIT */
860 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
862 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
865 /* transform window clauses after we have seen all window functions */
866 qry->windowClause = transformWindowDefinitions(pstate,
867 pstate->p_windowdefs,
870 /* handle any SELECT INTO/CREATE TABLE AS spec */
871 if (stmt->intoClause)
873 qry->intoClause = stmt->intoClause;
874 if (stmt->intoClause->colNames)
875 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
878 qry->rtable = pstate->p_rtable;
879 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
881 qry->hasSubLinks = pstate->p_hasSubLinks;
882 qry->hasAggs = pstate->p_hasAggs;
883 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
884 parseCheckAggregates(pstate, qry);
885 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
886 if (pstate->p_hasWindowFuncs)
887 parseCheckWindowFuncs(pstate, qry);
889 foreach(l, stmt->lockingClause)
891 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
898 * transformValuesClause -
899 * transforms a VALUES clause that's being used as a standalone SELECT
901 * We build a Query containing a VALUES RTE, rather as if one had written
902 * SELECT * FROM (VALUES ...)
905 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
907 Query *qry = makeNode(Query);
908 List *exprsLists = NIL;
909 List **colexprs = NULL;
910 Oid *coltypes = NULL;
911 int sublist_length = -1;
919 qry->commandType = CMD_SELECT;
921 /* Most SELECT stuff doesn't apply in a VALUES clause */
922 Assert(stmt->distinctClause == NIL);
923 Assert(stmt->targetList == NIL);
924 Assert(stmt->fromClause == NIL);
925 Assert(stmt->whereClause == NULL);
926 Assert(stmt->groupClause == NIL);
927 Assert(stmt->havingClause == NULL);
928 Assert(stmt->windowClause == NIL);
929 Assert(stmt->op == SETOP_NONE);
931 /* process the WITH clause */
932 if (stmt->withClause)
934 qry->hasRecursive = stmt->withClause->recursive;
935 qry->cteList = transformWithClause(pstate, stmt->withClause);
939 * For each row of VALUES, transform the raw expressions and gather type
940 * information. This is also a handy place to reject DEFAULT nodes, which
941 * the grammar allows for simplicity.
943 foreach(lc, stmt->valuesLists)
945 List *sublist = (List *) lfirst(lc);
947 /* Do basic expression transformation (same as a ROW() expr) */
948 sublist = transformExpressionList(pstate, sublist);
951 * All the sublists must be the same length, *after* transformation
952 * (which might expand '*' into multiple items). The VALUES RTE can't
953 * handle anything different.
955 if (sublist_length < 0)
957 /* Remember post-transformation length of first sublist */
958 sublist_length = list_length(sublist);
959 /* and allocate arrays for per-column info */
960 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
961 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
963 else if (sublist_length != list_length(sublist))
966 (errcode(ERRCODE_SYNTAX_ERROR),
967 errmsg("VALUES lists must all be the same length"),
968 parser_errposition(pstate,
969 exprLocation((Node *) sublist))));
972 exprsLists = lappend(exprsLists, sublist);
974 /* Check for DEFAULT and build per-column expression lists */
976 foreach(lc2, sublist)
978 Node *col = (Node *) lfirst(lc2);
980 if (IsA(col, SetToDefault))
982 (errcode(ERRCODE_SYNTAX_ERROR),
983 errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
984 parser_errposition(pstate, exprLocation(col))));
985 colexprs[i] = lappend(colexprs[i], col);
991 * Now resolve the common types of the columns, and coerce everything to
994 for (i = 0; i < sublist_length; i++)
996 coltypes[i] = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1000 foreach(lc, exprsLists)
1002 List *sublist = (List *) lfirst(lc);
1003 List *newsublist = NIL;
1006 foreach(lc2, sublist)
1008 Node *col = (Node *) lfirst(lc2);
1010 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
1011 newsublist = lappend(newsublist, col);
1015 newExprsLists = lappend(newExprsLists, newsublist);
1019 * Generate the VALUES RTE
1021 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
1022 rtr = makeNode(RangeTblRef);
1023 /* assume new rte is at end */
1024 rtr->rtindex = list_length(pstate->p_rtable);
1025 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1026 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1027 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1030 * Generate a targetlist as though expanding "*"
1032 Assert(pstate->p_next_resno == 1);
1033 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
1036 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1039 qry->sortClause = transformSortClause(pstate,
1042 true /* fix unknowns */ );
1044 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1046 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1049 if (stmt->lockingClause)
1051 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1052 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1054 /* handle any CREATE TABLE AS spec */
1055 if (stmt->intoClause)
1057 qry->intoClause = stmt->intoClause;
1058 if (stmt->intoClause->colNames)
1059 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
1063 * There mustn't have been any table references in the expressions, else
1064 * strange things would happen, like Cartesian products of those tables
1065 * with the VALUES list. We have to check this after parsing ORDER BY et
1066 * al since those could insert more junk.
1068 if (list_length(pstate->p_joinlist) != 1)
1070 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1071 errmsg("VALUES must not contain table references"),
1072 parser_errposition(pstate,
1073 locate_var_of_level((Node *) newExprsLists, 0))));
1076 * Another thing we can't currently support is NEW/OLD references in rules
1077 * --- seems we'd need something like SQL99's LATERAL construct to ensure
1078 * that the values would be available while evaluating the VALUES RTE.
1079 * This is a shame. FIXME
1081 if (list_length(pstate->p_rtable) != 1 &&
1082 contain_vars_of_level((Node *) newExprsLists, 0))
1084 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1085 errmsg("VALUES must not contain OLD or NEW references"),
1086 errhint("Use SELECT ... UNION ALL ... instead."),
1087 parser_errposition(pstate,
1088 locate_var_of_level((Node *) newExprsLists, 0))));
1090 qry->rtable = pstate->p_rtable;
1091 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1093 qry->hasSubLinks = pstate->p_hasSubLinks;
1094 /* aggregates not allowed (but subselects are okay) */
1095 if (pstate->p_hasAggs)
1097 (errcode(ERRCODE_GROUPING_ERROR),
1098 errmsg("cannot use aggregate function in VALUES"),
1099 parser_errposition(pstate,
1100 locate_agg_of_level((Node *) newExprsLists, 0))));
1101 if (pstate->p_hasWindowFuncs)
1103 (errcode(ERRCODE_WINDOWING_ERROR),
1104 errmsg("cannot use window function in VALUES"),
1105 parser_errposition(pstate,
1106 locate_windowfunc((Node *) newExprsLists))));
1112 * transformSetOperationStmt -
1113 * transforms a set-operations tree
1115 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1116 * structure to it. We must transform each leaf SELECT and build up a top-
1117 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1118 * The tree of set operations is converted into the setOperations field of
1119 * the top-level Query.
1122 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1124 Query *qry = makeNode(Query);
1125 SelectStmt *leftmostSelect;
1127 Query *leftmostQuery;
1128 SetOperationStmt *sostmt;
1130 List *intoColNames = NIL;
1134 List *lockingClause;
1136 ListCell *left_tlist,
1144 int sv_rtable_length;
1145 RangeTblEntry *jrte;
1148 qry->commandType = CMD_SELECT;
1151 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1152 * and from the top-level node.
1154 leftmostSelect = stmt->larg;
1155 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1156 leftmostSelect = leftmostSelect->larg;
1157 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1158 leftmostSelect->larg == NULL);
1159 if (leftmostSelect->intoClause)
1161 qry->intoClause = leftmostSelect->intoClause;
1162 intoColNames = leftmostSelect->intoClause->colNames;
1165 /* clear this to prevent complaints in transformSetOperationTree() */
1166 leftmostSelect->intoClause = NULL;
1169 * These are not one-time, exactly, but we want to process them here and
1170 * not let transformSetOperationTree() see them --- else it'll just
1171 * recurse right back here!
1173 sortClause = stmt->sortClause;
1174 limitOffset = stmt->limitOffset;
1175 limitCount = stmt->limitCount;
1176 lockingClause = stmt->lockingClause;
1178 stmt->sortClause = NIL;
1179 stmt->limitOffset = NULL;
1180 stmt->limitCount = NULL;
1181 stmt->lockingClause = NIL;
1183 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1186 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1187 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1189 /* process the WITH clause */
1190 if (stmt->withClause)
1192 qry->hasRecursive = stmt->withClause->recursive;
1193 qry->cteList = transformWithClause(pstate, stmt->withClause);
1197 * Recursively transform the components of the tree.
1199 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1201 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1202 qry->setOperations = (Node *) sostmt;
1205 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1207 node = sostmt->larg;
1208 while (node && IsA(node, SetOperationStmt))
1209 node = ((SetOperationStmt *) node)->larg;
1210 Assert(node && IsA(node, RangeTblRef));
1211 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1212 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1213 Assert(leftmostQuery != NULL);
1216 * Generate dummy targetlist for outer query using column names of
1217 * leftmost select and common datatypes of topmost set operation. Also
1218 * make lists of the dummy vars and their names for use in parsing ORDER
1221 * Note: we use leftmostRTI as the varno of the dummy variables. It
1222 * shouldn't matter too much which RT index they have, as long as they
1223 * have one that corresponds to a real RT entry; else funny things may
1224 * happen when the tree is mashed by rule rewriting.
1226 qry->targetList = NIL;
1229 left_tlist = list_head(leftmostQuery->targetList);
1231 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1233 Oid colType = lfirst_oid(lct);
1234 int32 colTypmod = lfirst_int(lcm);
1235 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1240 Assert(!lefttle->resjunk);
1241 colName = pstrdup(lefttle->resname);
1242 var = makeVar(leftmostRTI,
1247 var->location = exprLocation((Node *) lefttle->expr);
1248 tle = makeTargetEntry((Expr *) var,
1249 (AttrNumber) pstate->p_next_resno++,
1252 qry->targetList = lappend(qry->targetList, tle);
1253 targetvars = lappend(targetvars, var);
1254 targetnames = lappend(targetnames, makeString(colName));
1255 left_tlist = lnext(left_tlist);
1259 * As a first step towards supporting sort clauses that are expressions
1260 * using the output columns, generate a varnamespace entry that makes the
1261 * output columns visible. A Join RTE node is handy for this, since we
1262 * can easily control the Vars generated upon matches.
1264 * Note: we don't yet do anything useful with such cases, but at least
1265 * "ORDER BY upper(foo)" will draw the right error message rather than
1268 sv_rtable_length = list_length(pstate->p_rtable);
1270 jrte = addRangeTableEntryForJoin(pstate,
1277 sv_relnamespace = pstate->p_relnamespace;
1278 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1280 sv_varnamespace = pstate->p_varnamespace;
1281 pstate->p_varnamespace = list_make1(jrte);
1284 * For now, we don't support resjunk sort clauses on the output of a
1285 * setOperation tree --- you can only use the SQL92-spec options of
1286 * selecting an output column by name or number. Enforce by checking that
1287 * transformSortClause doesn't add any items to tlist.
1289 tllen = list_length(qry->targetList);
1291 qry->sortClause = transformSortClause(pstate,
1294 false /* no unknowns expected */ );
1296 pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1297 pstate->p_relnamespace = sv_relnamespace;
1298 pstate->p_varnamespace = sv_varnamespace;
1300 if (tllen != list_length(qry->targetList))
1302 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1303 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1304 errdetail("Only result column names can be used, not expressions or functions."),
1305 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1306 parser_errposition(pstate,
1307 exprLocation(list_nth(qry->targetList, tllen)))));
1309 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1311 qry->limitCount = transformLimitClause(pstate, limitCount,
1315 * Handle SELECT INTO/CREATE TABLE AS.
1317 * Any column names from CREATE TABLE AS need to be attached to both the
1318 * top level and the leftmost subquery. We do not do this earlier because
1319 * we do *not* want sortClause processing to be affected.
1323 applyColumnNames(qry->targetList, intoColNames);
1324 applyColumnNames(leftmostQuery->targetList, intoColNames);
1327 qry->rtable = pstate->p_rtable;
1328 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1330 qry->hasSubLinks = pstate->p_hasSubLinks;
1331 qry->hasAggs = pstate->p_hasAggs;
1332 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1333 parseCheckAggregates(pstate, qry);
1334 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1335 if (pstate->p_hasWindowFuncs)
1336 parseCheckWindowFuncs(pstate, qry);
1338 foreach(l, lockingClause)
1340 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
1347 * transformSetOperationTree
1348 * Recursively transform leaves and internal nodes of a set-op tree
1350 * In addition to returning the transformed node, we return a list of
1351 * expression nodes showing the type, typmod, and location (for error messages)
1352 * of each output column of the set-op node. This is used only during the
1353 * internal recursion of this function. At the upper levels we use
1354 * SetToDefault nodes for this purpose, since they carry exactly the fields
1355 * needed, but any other expression node type would do as well.
1358 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1363 Assert(stmt && IsA(stmt, SelectStmt));
1366 * Validity-check both leaf and internal SELECTs for disallowed ops.
1368 if (stmt->intoClause)
1370 (errcode(ERRCODE_SYNTAX_ERROR),
1371 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1372 parser_errposition(pstate,
1373 exprLocation((Node *) stmt->intoClause))));
1375 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1376 if (stmt->lockingClause)
1378 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1379 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1382 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1383 * clauses attached, we need to treat it like a leaf node to generate an
1384 * independent sub-Query tree. Otherwise, it can be represented by a
1385 * SetOperationStmt node underneath the parent Query.
1387 if (stmt->op == SETOP_NONE)
1389 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1394 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1395 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1396 stmt->lockingClause)
1404 /* Process leaf SELECT */
1406 char selectName[32];
1412 * Transform SelectStmt into a Query.
1414 * Note: previously transformed sub-queries don't affect the parsing
1415 * of this sub-query, because they are not in the toplevel pstate's
1418 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1421 * Check for bogus references to Vars on the current query level (but
1422 * upper-level references are okay). Normally this can't happen
1423 * because the namespace will be empty, but it could happen if we are
1426 if (pstate->p_relnamespace || pstate->p_varnamespace)
1428 if (contain_vars_of_level((Node *) selectQuery, 1))
1430 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1431 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1432 parser_errposition(pstate,
1433 locate_var_of_level((Node *) selectQuery, 1))));
1437 * Extract a list of the result expressions for upper-level checking.
1440 foreach(tl, selectQuery->targetList)
1442 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1445 *colInfo = lappend(*colInfo, tle->expr);
1449 * Make the leaf query be a subquery in the top-level rangetable.
1451 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1452 list_length(pstate->p_rtable) + 1);
1453 rte = addRangeTableEntryForSubquery(pstate,
1455 makeAlias(selectName, NIL),
1459 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1461 rtr = makeNode(RangeTblRef);
1462 /* assume new rte is at end */
1463 rtr->rtindex = list_length(pstate->p_rtable);
1464 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1465 return (Node *) rtr;
1469 /* Process an internal node (set operation node) */
1470 SetOperationStmt *op = makeNode(SetOperationStmt);
1475 const char *context;
1477 context = (stmt->op == SETOP_UNION ? "UNION" :
1478 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1482 op->all = stmt->all;
1485 * Recursively transform the child nodes.
1487 op->larg = transformSetOperationTree(pstate, stmt->larg,
1489 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1493 * Verify that the two children have the same number of non-junk
1494 * columns, and determine the types of the merged output columns.
1496 if (list_length(lcolinfo) != list_length(rcolinfo))
1498 (errcode(ERRCODE_SYNTAX_ERROR),
1499 errmsg("each %s query must have the same number of columns",
1501 parser_errposition(pstate,
1502 exprLocation((Node *) rcolinfo))));
1506 op->colTypmods = NIL;
1507 op->groupClauses = NIL;
1508 forboth(lci, lcolinfo, rci, rcolinfo)
1510 Node *lcolinfo = (Node *) lfirst(lci);
1511 Node *rcolinfo = (Node *) lfirst(rci);
1512 Oid lcoltype = exprType(lcolinfo);
1513 Oid rcoltype = exprType(rcolinfo);
1514 int32 lcoltypmod = exprTypmod(lcolinfo);
1515 int32 rcoltypmod = exprTypmod(rcolinfo);
1517 SetToDefault *rescolinfo;
1521 /* select common type, same as CASE et al */
1522 rescoltype = select_common_type(pstate,
1523 list_make2(lcolinfo, rcolinfo),
1526 /* if same type and same typmod, use typmod; else default */
1527 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1528 rescoltypmod = lcoltypmod;
1532 /* verify the coercions are actually possible */
1533 (void) coerce_to_common_type(pstate, lcolinfo,
1534 rescoltype, context);
1535 (void) coerce_to_common_type(pstate, rcolinfo,
1536 rescoltype, context);
1539 rescolinfo = makeNode(SetToDefault);
1540 rescolinfo->typeId = rescoltype;
1541 rescolinfo->typeMod = rescoltypmod;
1542 rescolinfo->location = exprLocation(bestexpr);
1543 *colInfo = lappend(*colInfo, rescolinfo);
1545 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1546 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1549 * For all cases except UNION ALL, identify the grouping operators
1550 * (and, if available, sorting operators) that will be used to
1551 * eliminate duplicates.
1553 if (op->op != SETOP_UNION || !op->all)
1555 SortGroupClause *grpcl = makeNode(SortGroupClause);
1558 ParseCallbackState pcbstate;
1560 setup_parser_errposition_callback(&pcbstate, pstate,
1561 rescolinfo->location);
1563 /* determine the eqop and optional sortop */
1564 get_sort_group_operators(rescoltype,
1566 &sortop, &eqop, NULL);
1568 cancel_parser_errposition_callback(&pcbstate);
1570 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1571 grpcl->tleSortGroupRef = 0;
1573 grpcl->sortop = sortop;
1574 grpcl->nulls_first = false; /* OK with or without sortop */
1576 op->groupClauses = lappend(op->groupClauses, grpcl);
1585 * Attach column names from a ColumnDef list to a TargetEntry list
1586 * (for CREATE TABLE AS)
1589 applyColumnNames(List *dst, List *src)
1594 src_item = list_head(src);
1596 foreach(dst_item, dst)
1598 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1601 /* junk targets don't count */
1605 /* fewer ColumnDefs than target entries is OK */
1606 if (src_item == NULL)
1609 s = (ColumnDef *) lfirst(src_item);
1610 src_item = lnext(src_item);
1612 d->resname = pstrdup(s->colname);
1615 /* more ColumnDefs than target entries is not OK */
1616 if (src_item != NULL)
1618 (errcode(ERRCODE_SYNTAX_ERROR),
1619 errmsg("CREATE TABLE AS specifies too many column names")));
1624 * transformUpdateStmt -
1625 * transforms an update statement
1628 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1630 Query *qry = makeNode(Query);
1631 RangeTblEntry *target_rte;
1633 ListCell *origTargetList;
1636 qry->commandType = CMD_UPDATE;
1637 pstate->p_is_update = true;
1639 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1640 interpretInhOption(stmt->relation->inhOpt),
1645 * the FROM clause is non-standard SQL syntax. We used to be able to do
1646 * this with REPLACE in POSTQUEL so we keep the feature.
1648 transformFromClause(pstate, stmt->fromClause);
1650 qry->targetList = transformTargetList(pstate, stmt->targetList);
1652 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1654 qry->returningList = transformReturningList(pstate, stmt->returningList);
1656 qry->rtable = pstate->p_rtable;
1657 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1659 qry->hasSubLinks = pstate->p_hasSubLinks;
1662 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1663 * an implementation point of view, this is forced because the implicit
1664 * ctid reference would otherwise be an ungrouped variable.)
1666 if (pstate->p_hasAggs)
1668 (errcode(ERRCODE_GROUPING_ERROR),
1669 errmsg("cannot use aggregate function in UPDATE"),
1670 parser_errposition(pstate,
1671 locate_agg_of_level((Node *) qry, 0))));
1672 if (pstate->p_hasWindowFuncs)
1674 (errcode(ERRCODE_WINDOWING_ERROR),
1675 errmsg("cannot use window function in UPDATE"),
1676 parser_errposition(pstate,
1677 locate_windowfunc((Node *) qry))));
1680 * Now we are done with SELECT-like processing, and can get on with
1681 * transforming the target list to match the UPDATE target columns.
1684 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1685 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1686 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1688 /* Prepare non-junk columns for assignment to target table */
1689 target_rte = pstate->p_target_rangetblentry;
1690 origTargetList = list_head(stmt->targetList);
1692 foreach(tl, qry->targetList)
1694 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1695 ResTarget *origTarget;
1701 * Resjunk nodes need no additional processing, but be sure they
1702 * have resnos that do not match any target columns; else rewriter
1703 * or planner might get confused. They don't need a resname
1706 tle->resno = (AttrNumber) pstate->p_next_resno++;
1707 tle->resname = NULL;
1710 if (origTargetList == NULL)
1711 elog(ERROR, "UPDATE target count mismatch --- internal error");
1712 origTarget = (ResTarget *) lfirst(origTargetList);
1713 Assert(IsA(origTarget, ResTarget));
1715 attrno = attnameAttNum(pstate->p_target_relation,
1716 origTarget->name, true);
1717 if (attrno == InvalidAttrNumber)
1719 (errcode(ERRCODE_UNDEFINED_COLUMN),
1720 errmsg("column \"%s\" of relation \"%s\" does not exist",
1722 RelationGetRelationName(pstate->p_target_relation)),
1723 parser_errposition(pstate, origTarget->location)));
1725 updateTargetListEntry(pstate, tle, origTarget->name,
1727 origTarget->indirection,
1728 origTarget->location);
1730 /* Mark the target column as requiring update permissions */
1731 target_rte->modifiedCols = bms_add_member(target_rte->modifiedCols,
1732 attrno - FirstLowInvalidHeapAttributeNumber);
1734 origTargetList = lnext(origTargetList);
1736 if (origTargetList != NULL)
1737 elog(ERROR, "UPDATE target count mismatch --- internal error");
1743 * transformReturningList -
1744 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1747 transformReturningList(ParseState *pstate, List *returningList)
1750 int save_next_resno;
1752 bool save_hasWindowFuncs;
1755 if (returningList == NIL)
1756 return NIL; /* nothing to do */
1759 * We need to assign resnos starting at one in the RETURNING list. Save
1760 * and restore the main tlist's value of p_next_resno, just in case
1761 * someone looks at it later (probably won't happen).
1763 save_next_resno = pstate->p_next_resno;
1764 pstate->p_next_resno = 1;
1766 /* save other state so that we can detect disallowed stuff */
1767 save_hasAggs = pstate->p_hasAggs;
1768 pstate->p_hasAggs = false;
1769 save_hasWindowFuncs = pstate->p_hasWindowFuncs;
1770 pstate->p_hasWindowFuncs = false;
1771 length_rtable = list_length(pstate->p_rtable);
1773 /* transform RETURNING identically to a SELECT targetlist */
1774 rlist = transformTargetList(pstate, returningList);
1776 /* check for disallowed stuff */
1778 /* aggregates not allowed (but subselects are okay) */
1779 if (pstate->p_hasAggs)
1781 (errcode(ERRCODE_GROUPING_ERROR),
1782 errmsg("cannot use aggregate function in RETURNING"),
1783 parser_errposition(pstate,
1784 locate_agg_of_level((Node *) rlist, 0))));
1785 if (pstate->p_hasWindowFuncs)
1787 (errcode(ERRCODE_WINDOWING_ERROR),
1788 errmsg("cannot use window function in RETURNING"),
1789 parser_errposition(pstate,
1790 locate_windowfunc((Node *) rlist))));
1792 /* no new relation references please */
1793 if (list_length(pstate->p_rtable) != length_rtable)
1798 /* try to locate such a reference to point to */
1799 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
1801 vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
1806 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1807 errmsg("RETURNING cannot contain references to other relations"),
1808 parser_errposition(pstate, vlocation)));
1811 /* mark column origins */
1812 markTargetListOrigins(pstate, rlist);
1815 pstate->p_next_resno = save_next_resno;
1816 pstate->p_hasAggs = save_hasAggs;
1817 pstate->p_hasWindowFuncs = save_hasWindowFuncs;
1824 * transformDeclareCursorStmt -
1825 * transform a DECLARE CURSOR Statement
1827 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1828 * significantly different from a SELECT) as far as parsing/rewriting/planning
1829 * are concerned, but it's not passed to the executor and so in that sense is
1830 * a utility statement. We transform it into a Query exactly as if it were
1831 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1832 * field to carry the cursor name and options.
1835 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1840 * Don't allow both SCROLL and NO SCROLL to be specified
1842 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1843 (stmt->options & CURSOR_OPT_NO_SCROLL))
1845 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1846 errmsg("cannot specify both SCROLL and NO SCROLL")));
1848 result = transformStmt(pstate, stmt->query);
1850 /* Grammar should not have allowed anything but SELECT */
1851 if (!IsA(result, Query) ||
1852 result->commandType != CMD_SELECT ||
1853 result->utilityStmt != NULL)
1854 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
1856 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1857 if (result->intoClause)
1859 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1860 errmsg("DECLARE CURSOR cannot specify INTO"),
1861 parser_errposition(pstate,
1862 exprLocation((Node *) result->intoClause))));
1864 /* FOR UPDATE and WITH HOLD are not compatible */
1865 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1867 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1868 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1869 errdetail("Holdable cursors must be READ ONLY.")));
1871 /* FOR UPDATE and SCROLL are not compatible */
1872 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1875 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1876 errdetail("Scrollable cursors must be READ ONLY.")));
1878 /* FOR UPDATE and INSENSITIVE are not compatible */
1879 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1881 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1882 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1883 errdetail("Insensitive cursors must be READ ONLY.")));
1885 /* We won't need the raw querytree any more */
1888 result->utilityStmt = (Node *) stmt;
1895 * transformExplainStmt -
1896 * transform an EXPLAIN Statement
1898 * EXPLAIN is just like other utility statements in that we emit it as a
1899 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1900 * However, if p_variableparams is set, it could be that the client is
1901 * expecting us to resolve parameter types in something like
1902 * EXPLAIN SELECT * FROM tab WHERE col = $1
1903 * To deal with such cases, we run parse analysis and throw away the result;
1904 * this is a bit grotty but not worth contorting the rest of the system for.
1905 * (The approach we use for DECLARE CURSOR won't work because the statement
1906 * being explained isn't necessarily a SELECT, and in particular might rewrite
1907 * to multiple parsetrees.)
1910 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1914 if (pstate->p_variableparams)
1916 /* Since parse analysis scribbles on its input, copy the tree first! */
1917 (void) transformStmt(pstate, copyObject(stmt->query));
1920 /* Now return the untransformed command as a utility Query */
1921 result = makeNode(Query);
1922 result->commandType = CMD_UTILITY;
1923 result->utilityStmt = (Node *) stmt;
1929 /* exported so planner can check again after rewriting, query pullup, etc */
1931 CheckSelectLocking(Query *qry)
1933 if (qry->setOperations)
1935 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1936 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1937 if (qry->distinctClause != NIL)
1939 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1940 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1941 if (qry->groupClause != NIL)
1943 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1944 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1945 if (qry->havingQual != NULL)
1947 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1948 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1951 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1952 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1953 if (qry->hasWindowFuncs)
1955 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1956 errmsg("SELECT FOR UPDATE/SHARE is not allowed with window functions")));
1960 * Transform a FOR UPDATE/SHARE clause
1962 * This basically involves replacing names by integer relids.
1964 * NB: if you need to change this, see also markQueryForLocking()
1965 * in rewriteHandler.c, and isLockedRel() in parse_relation.c.
1968 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc)
1970 List *lockedRels = lc->lockedRels;
1974 LockingClause *allrels;
1976 CheckSelectLocking(qry);
1978 /* make a clause we can pass down to subqueries to select all rels */
1979 allrels = makeNode(LockingClause);
1980 allrels->lockedRels = NIL; /* indicates all rels */
1981 allrels->forUpdate = lc->forUpdate;
1982 allrels->noWait = lc->noWait;
1984 if (lockedRels == NIL)
1986 /* all regular tables used in query */
1988 foreach(rt, qry->rtable)
1990 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1993 switch (rte->rtekind)
1996 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1997 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2002 * FOR UPDATE/SHARE of subquery is propagated to all of
2005 transformLockingClause(pstate, rte->subquery, allrels);
2010 * We allow FOR UPDATE/SHARE of a WITH query to be
2011 * propagated into the WITH, but it doesn't seem very
2012 * sane to allow this for a reference to an
2013 * outer-level WITH. And it definitely wouldn't work
2014 * for a self-reference, since we're not done
2015 * analyzing the CTE anyway.
2017 CommonTableExpr *cte;
2019 if (rte->ctelevelsup > 0 || rte->self_reference)
2021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2022 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query")));
2023 cte = GetCTEForRTE(pstate, rte, -1);
2024 /* should be analyzed by now */
2025 Assert(IsA(cte->ctequery, Query));
2026 transformLockingClause(pstate,
2027 (Query *) cte->ctequery,
2032 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2039 /* just the named tables */
2040 foreach(l, lockedRels)
2042 RangeVar *thisrel = (RangeVar *) lfirst(l);
2044 /* For simplicity we insist on unqualified alias names here */
2045 if (thisrel->catalogname || thisrel->schemaname)
2047 (errcode(ERRCODE_SYNTAX_ERROR),
2048 errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
2049 parser_errposition(pstate, thisrel->location)));
2052 foreach(rt, qry->rtable)
2054 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2057 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2059 switch (rte->rtekind)
2062 applyLockingClause(qry, i,
2063 lc->forUpdate, lc->noWait);
2064 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2069 * FOR UPDATE/SHARE of subquery is propagated to
2070 * all of subquery's rels
2072 transformLockingClause(pstate, rte->subquery, allrels);
2076 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2077 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2078 parser_errposition(pstate, thisrel->location)));
2082 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2083 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD"),
2084 parser_errposition(pstate, thisrel->location)));
2088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2089 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2090 parser_errposition(pstate, thisrel->location)));
2094 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2095 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2096 parser_errposition(pstate, thisrel->location)));
2101 * We allow FOR UPDATE/SHARE of a WITH query
2102 * to be propagated into the WITH, but it
2103 * doesn't seem very sane to allow this for a
2104 * reference to an outer-level WITH. And it
2105 * definitely wouldn't work for a
2106 * self-reference, since we're not done
2107 * analyzing the CTE anyway.
2109 CommonTableExpr *cte;
2111 if (rte->ctelevelsup > 0 || rte->self_reference)
2113 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2114 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query"),
2115 parser_errposition(pstate, thisrel->location)));
2116 cte = GetCTEForRTE(pstate, rte, -1);
2117 /* should be analyzed by now */
2118 Assert(IsA(cte->ctequery, Query));
2119 transformLockingClause(pstate,
2120 (Query *) cte->ctequery,
2125 elog(ERROR, "unrecognized RTE type: %d",
2126 (int) rte->rtekind);
2129 break; /* out of foreach loop */
2134 (errcode(ERRCODE_UNDEFINED_TABLE),
2135 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2137 parser_errposition(pstate, thisrel->location)));
2143 * Record locking info for a single rangetable item
2146 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
2150 /* Check for pre-existing entry for same rtindex */
2151 if ((rc = get_rowmark(qry, rtindex)) != NULL)
2154 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2155 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
2156 * and exclusive lock at the same time; it'll end up being exclusive
2159 * We also consider that NOWAIT wins if it's specified both ways. This
2160 * is a bit more debatable but raising an error doesn't seem helpful.
2161 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2162 * internally contains a plain FOR UPDATE spec.)
2164 rc->forUpdate |= forUpdate;
2165 rc->noWait |= noWait;
2169 /* Make a new RowMarkClause */
2170 rc = makeNode(RowMarkClause);
2173 rc->forUpdate = forUpdate;
2174 rc->noWait = noWait;
2175 rc->isParent = false;
2176 qry->rowMarks = lappend(qry->rowMarks, rc);
2181 * Traverse a fully-analyzed tree to verify that parameter symbols
2182 * match their types. We need this because some Params might still
2183 * be UNKNOWN, if there wasn't anything to force their coercion,
2184 * and yet other instances seen later might have gotten coerced.
2187 check_parameter_resolution_walker(Node *node, ParseState *pstate)
2191 if (IsA(node, Param))
2193 Param *param = (Param *) node;
2195 if (param->paramkind == PARAM_EXTERN)
2197 int paramno = param->paramid;
2199 if (paramno <= 0 || /* shouldn't happen, but... */
2200 paramno > pstate->p_numparams)
2202 (errcode(ERRCODE_UNDEFINED_PARAMETER),
2203 errmsg("there is no parameter $%d", paramno),
2204 parser_errposition(pstate, param->location)));
2206 if (param->paramtype != pstate->p_paramtypes[paramno - 1])
2208 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
2209 errmsg("could not determine data type of parameter $%d",
2211 parser_errposition(pstate, param->location)));
2215 if (IsA(node, Query))
2217 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2218 return query_tree_walker((Query *) node,
2219 check_parameter_resolution_walker,
2220 (void *) pstate, 0);
2222 return expression_tree_walker(node, check_parameter_resolution_walker,