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.386 2009/01/01 17:23:45 momjian Exp $
22 *-------------------------------------------------------------------------
27 #include "catalog/pg_type.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/var.h"
31 #include "parser/analyze.h"
32 #include "parser/parse_agg.h"
33 #include "parser/parse_clause.h"
34 #include "parser/parse_coerce.h"
35 #include "parser/parse_cte.h"
36 #include "parser/parse_oper.h"
37 #include "parser/parse_relation.h"
38 #include "parser/parse_target.h"
39 #include "parser/parsetree.h"
40 #include "rewrite/rewriteManip.h"
41 #include "utils/rel.h"
44 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
45 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
46 static List *transformInsertRow(ParseState *pstate, List *exprlist,
47 List *stmtcols, List *icolumns, List *attrnos);
48 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
49 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
50 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
51 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
53 static void applyColumnNames(List *dst, List *src);
54 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
55 static List *transformReturningList(ParseState *pstate, List *returningList);
56 static Query *transformDeclareCursorStmt(ParseState *pstate,
57 DeclareCursorStmt *stmt);
58 static Query *transformExplainStmt(ParseState *pstate,
60 static void transformLockingClause(ParseState *pstate,
61 Query *qry, LockingClause *lc);
62 static bool check_parameter_resolution_walker(Node *node, ParseState *pstate);
67 * Analyze a raw parse tree and transform it to Query form.
69 * Optionally, information about $n parameter types can be supplied.
70 * References to $n indexes not defined by paramTypes[] are disallowed.
72 * The result is a Query node. Optimizable statements require considerable
73 * transformation, while utility-type statements are simply hung off
74 * a dummy CMD_UTILITY Query node.
77 parse_analyze(Node *parseTree, const char *sourceText,
78 Oid *paramTypes, int numParams)
80 ParseState *pstate = make_parsestate(NULL);
83 Assert(sourceText != NULL); /* required as of 8.4 */
85 pstate->p_sourcetext = sourceText;
86 pstate->p_paramtypes = paramTypes;
87 pstate->p_numparams = numParams;
88 pstate->p_variableparams = false;
90 query = transformStmt(pstate, parseTree);
92 free_parsestate(pstate);
98 * parse_analyze_varparams
100 * This variant is used when it's okay to deduce information about $n
101 * symbol datatypes from context. The passed-in paramTypes[] array can
102 * be modified or enlarged (via repalloc).
105 parse_analyze_varparams(Node *parseTree, const char *sourceText,
106 Oid **paramTypes, int *numParams)
108 ParseState *pstate = make_parsestate(NULL);
111 Assert(sourceText != NULL); /* required as of 8.4 */
113 pstate->p_sourcetext = sourceText;
114 pstate->p_paramtypes = *paramTypes;
115 pstate->p_numparams = *numParams;
116 pstate->p_variableparams = true;
118 query = transformStmt(pstate, parseTree);
120 /* make sure all is well with parameter types */
121 if (pstate->p_numparams > 0)
122 check_parameter_resolution_walker((Node *) query, pstate);
124 *paramTypes = pstate->p_paramtypes;
125 *numParams = pstate->p_numparams;
127 free_parsestate(pstate);
134 * Entry point for recursively analyzing a sub-statement.
137 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
139 ParseState *pstate = make_parsestate(parentParseState);
142 query = transformStmt(pstate, parseTree);
144 free_parsestate(pstate);
151 * transform a Parse tree into a Query tree.
154 transformStmt(ParseState *pstate, Node *parseTree)
158 switch (nodeTag(parseTree))
161 * Optimizable statements
164 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
168 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
172 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
177 SelectStmt *n = (SelectStmt *) parseTree;
180 result = transformValuesClause(pstate, n);
181 else if (n->op == SETOP_NONE)
182 result = transformSelectStmt(pstate, n);
184 result = transformSetOperationStmt(pstate, n);
191 case T_DeclareCursorStmt:
192 result = transformDeclareCursorStmt(pstate,
193 (DeclareCursorStmt *) parseTree);
197 result = transformExplainStmt(pstate,
198 (ExplainStmt *) parseTree);
204 * other statements don't require any transformation; just return
205 * the original parsetree with a Query node plastered on top.
207 result = makeNode(Query);
208 result->commandType = CMD_UTILITY;
209 result->utilityStmt = (Node *) parseTree;
213 /* Mark as original query until we learn differently */
214 result->querySource = QSRC_ORIGINAL;
215 result->canSetTag = true;
221 * analyze_requires_snapshot
222 * Returns true if a snapshot must be set before doing parse analysis
223 * on the given raw parse tree.
225 * Classification here should match transformStmt().
228 analyze_requires_snapshot(Node *parseTree)
232 switch (nodeTag(parseTree))
235 * Optimizable statements
247 case T_DeclareCursorStmt:
248 /* yes, because it's analyzed just like SELECT */
254 * We only need a snapshot in varparams case, but it doesn't seem
255 * worth complicating this function's API to distinguish that.
261 /* utility statements don't have any active parse analysis */
270 * transformDeleteStmt -
271 * transforms a Delete Statement
274 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
276 Query *qry = makeNode(Query);
279 qry->commandType = CMD_DELETE;
281 /* set up range table with just the result rel */
282 qry->resultRelation = setTargetTable(pstate, stmt->relation,
283 interpretInhOption(stmt->relation->inhOpt),
287 qry->distinctClause = NIL;
290 * The USING clause is non-standard SQL syntax, and is equivalent in
291 * functionality to the FROM list that can be specified for UPDATE. The
292 * USING keyword is used rather than FROM because FROM is already a
293 * keyword in the DELETE syntax.
295 transformFromClause(pstate, stmt->usingClause);
297 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
299 qry->returningList = transformReturningList(pstate, stmt->returningList);
301 /* done building the range table and jointree */
302 qry->rtable = pstate->p_rtable;
303 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
305 qry->hasSubLinks = pstate->p_hasSubLinks;
306 qry->hasAggs = pstate->p_hasAggs;
307 if (pstate->p_hasAggs)
308 parseCheckAggregates(pstate, qry);
309 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
310 if (pstate->p_hasWindowFuncs)
311 parseCheckWindowFuncs(pstate, qry);
317 * transformInsertStmt -
318 * transform an Insert Statement
321 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
323 Query *qry = makeNode(Query);
324 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
325 List *exprList = NIL;
326 bool isGeneralSelect;
328 List *sub_relnamespace;
329 List *sub_varnamespace;
338 qry->commandType = CMD_INSERT;
339 pstate->p_is_insert = true;
342 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
343 * VALUES list, or general SELECT input. We special-case VALUES, both for
344 * efficiency and so we can handle DEFAULT specifications.
346 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
349 * If a non-nil rangetable/namespace was passed in, and we are doing
350 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
351 * SELECT. This can only happen if we are inside a CREATE RULE, and in
352 * that case we want the rule's OLD and NEW rtable entries to appear as
353 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
354 * The SELECT's joinlist is not affected however. We must do this before
355 * adding the target table to the INSERT's rtable.
359 sub_rtable = pstate->p_rtable;
360 pstate->p_rtable = NIL;
361 sub_relnamespace = pstate->p_relnamespace;
362 pstate->p_relnamespace = NIL;
363 sub_varnamespace = pstate->p_varnamespace;
364 pstate->p_varnamespace = NIL;
365 /* There can't be any outer WITH to worry about */
366 Assert(pstate->p_ctenamespace == NIL);
370 sub_rtable = NIL; /* not used, but keep compiler quiet */
371 sub_relnamespace = NIL;
372 sub_varnamespace = NIL;
376 * Must get write lock on INSERT target table before scanning SELECT, else
377 * we will grab the wrong kind of initial lock if the target table is also
378 * mentioned in the SELECT part. Note that the target table is not added
379 * to the joinlist or namespace.
381 qry->resultRelation = setTargetTable(pstate, stmt->relation,
382 false, false, ACL_INSERT);
384 /* Validate stmt->cols list, or build default list if no list given */
385 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
386 Assert(list_length(icolumns) == list_length(attrnos));
389 * Determine which variant of INSERT we have.
391 if (selectStmt == NULL)
394 * We have INSERT ... DEFAULT VALUES. We can handle this case by
395 * emitting an empty targetlist --- all columns will be defaulted when
396 * the planner expands the targetlist.
400 else if (isGeneralSelect)
403 * We make the sub-pstate a child of the outer pstate so that it can
404 * see any Param definitions supplied from above. Since the outer
405 * pstate's rtable and namespace are presently empty, there are no
406 * side-effects of exposing names the sub-SELECT shouldn't be able to
409 ParseState *sub_pstate = make_parsestate(pstate);
413 * Process the source SELECT.
415 * It is important that this be handled just like a standalone SELECT;
416 * otherwise the behavior of SELECT within INSERT might be different
417 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
418 * bugs of just that nature...)
420 sub_pstate->p_rtable = sub_rtable;
421 sub_pstate->p_relnamespace = sub_relnamespace;
422 sub_pstate->p_varnamespace = sub_varnamespace;
424 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
426 free_parsestate(sub_pstate);
428 /* The grammar should have produced a SELECT, but it might have INTO */
429 if (!IsA(selectQuery, Query) ||
430 selectQuery->commandType != CMD_SELECT ||
431 selectQuery->utilityStmt != NULL)
432 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
433 if (selectQuery->intoClause)
435 (errcode(ERRCODE_SYNTAX_ERROR),
436 errmsg("INSERT ... SELECT cannot specify INTO"),
437 parser_errposition(pstate,
438 exprLocation((Node *) selectQuery->intoClause))));
441 * Make the source be a subquery in the INSERT's rangetable, and add
442 * it to the INSERT's joinlist.
444 rte = addRangeTableEntryForSubquery(pstate,
446 makeAlias("*SELECT*", NIL),
448 rtr = makeNode(RangeTblRef);
449 /* assume new rte is at end */
450 rtr->rtindex = list_length(pstate->p_rtable);
451 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
452 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
455 * Generate an expression list for the INSERT that selects all the
456 * non-resjunk columns from the subquery. (INSERT's tlist must be
457 * separate from the subquery's tlist because we may add columns,
458 * insert datatype coercions, etc.)
460 * HACK: unknown-type constants and params in the SELECT's targetlist
461 * are copied up as-is rather than being referenced as subquery
462 * outputs. This is to ensure that when we try to coerce them to
463 * the target column's datatype, the right things happen (see
464 * special cases in coerce_type). Otherwise, this fails:
465 * INSERT INTO foo SELECT 'bar', ... FROM baz
469 foreach(lc, selectQuery->targetList)
471 TargetEntry *tle = (TargetEntry *) lfirst(lc);
477 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
478 exprType((Node *) tle->expr) == UNKNOWNOID)
482 Var *var = makeVar(rtr->rtindex,
484 exprType((Node *) tle->expr),
485 exprTypmod((Node *) tle->expr),
487 var->location = exprLocation((Node *) tle->expr);
490 exprList = lappend(exprList, expr);
493 /* Prepare row for assignment to target table */
494 exprList = transformInsertRow(pstate, exprList,
498 else if (list_length(selectStmt->valuesLists) > 1)
501 * Process INSERT ... VALUES with multiple VALUES sublists. We
502 * generate a VALUES RTE holding the transformed expression lists, and
503 * build up a targetlist containing Vars that reference the VALUES
506 List *exprsLists = NIL;
507 int sublist_length = -1;
509 /* process the WITH clause */
510 if (selectStmt->withClause)
512 qry->hasRecursive = selectStmt->withClause->recursive;
513 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
516 foreach(lc, selectStmt->valuesLists)
518 List *sublist = (List *) lfirst(lc);
520 /* Do basic expression transformation (same as a ROW() expr) */
521 sublist = transformExpressionList(pstate, sublist);
524 * All the sublists must be the same length, *after*
525 * transformation (which might expand '*' into multiple items).
526 * The VALUES RTE can't handle anything different.
528 if (sublist_length < 0)
530 /* Remember post-transformation length of first sublist */
531 sublist_length = list_length(sublist);
533 else if (sublist_length != list_length(sublist))
536 (errcode(ERRCODE_SYNTAX_ERROR),
537 errmsg("VALUES lists must all be the same length"),
538 parser_errposition(pstate,
539 exprLocation((Node *) sublist))));
542 /* Prepare row for assignment to target table */
543 sublist = transformInsertRow(pstate, sublist,
547 exprsLists = lappend(exprsLists, sublist);
551 * There mustn't have been any table references in the expressions,
552 * else strange things would happen, like Cartesian products of those
553 * tables with the VALUES list ...
555 if (pstate->p_joinlist != NIL)
557 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
558 errmsg("VALUES must not contain table references"),
559 parser_errposition(pstate,
560 locate_var_of_level((Node *) exprsLists, 0))));
563 * Another thing we can't currently support is NEW/OLD references in
564 * rules --- seems we'd need something like SQL99's LATERAL construct
565 * to ensure that the values would be available while evaluating the
566 * VALUES RTE. This is a shame. FIXME
568 if (list_length(pstate->p_rtable) != 1 &&
569 contain_vars_of_level((Node *) exprsLists, 0))
571 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
572 errmsg("VALUES must not contain OLD or NEW references"),
573 errhint("Use SELECT ... UNION ALL ... instead."),
574 parser_errposition(pstate,
575 locate_var_of_level((Node *) exprsLists, 0))));
578 * Generate the VALUES RTE
580 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
581 rtr = makeNode(RangeTblRef);
582 /* assume new rte is at end */
583 rtr->rtindex = list_length(pstate->p_rtable);
584 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
585 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
588 * Generate list of Vars referencing the RTE
590 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
595 * Process INSERT ... VALUES with a single VALUES sublist.
596 * We treat this separately for efficiency and for historical
597 * compatibility --- specifically, allowing table references,
599 * INSERT INTO foo VALUES(bar.*)
601 * The sublist is just computed directly as the Query's targetlist,
602 * with no VALUES RTE. So it works just like SELECT without FROM.
605 List *valuesLists = selectStmt->valuesLists;
607 Assert(list_length(valuesLists) == 1);
609 /* process the WITH clause */
610 if (selectStmt->withClause)
612 qry->hasRecursive = selectStmt->withClause->recursive;
613 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
616 /* Do basic expression transformation (same as a ROW() expr) */
617 exprList = transformExpressionList(pstate,
618 (List *) linitial(valuesLists));
620 /* Prepare row for assignment to target table */
621 exprList = transformInsertRow(pstate, exprList,
627 * Generate query's target list using the computed list of expressions.
629 qry->targetList = NIL;
630 icols = list_head(icolumns);
631 attnos = list_head(attrnos);
632 foreach(lc, exprList)
634 Expr *expr = (Expr *) lfirst(lc);
638 col = (ResTarget *) lfirst(icols);
639 Assert(IsA(col, ResTarget));
641 tle = makeTargetEntry(expr,
642 (AttrNumber) lfirst_int(attnos),
645 qry->targetList = lappend(qry->targetList, tle);
647 icols = lnext(icols);
648 attnos = lnext(attnos);
652 * If we have a RETURNING clause, we need to add the target relation to
653 * the query namespace before processing it, so that Var references in
654 * RETURNING will work. Also, remove any namespace entries added in a
655 * sub-SELECT or VALUES list.
657 if (stmt->returningList)
659 pstate->p_relnamespace = NIL;
660 pstate->p_varnamespace = NIL;
661 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
663 qry->returningList = transformReturningList(pstate,
664 stmt->returningList);
667 /* done building the range table and jointree */
668 qry->rtable = pstate->p_rtable;
669 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
671 qry->hasSubLinks = pstate->p_hasSubLinks;
672 /* aggregates not allowed (but subselects are okay) */
673 if (pstate->p_hasAggs)
675 (errcode(ERRCODE_GROUPING_ERROR),
676 errmsg("cannot use aggregate function in VALUES"),
677 parser_errposition(pstate,
678 locate_agg_of_level((Node *) qry, 0))));
679 if (pstate->p_hasWindowFuncs)
681 (errcode(ERRCODE_WINDOWING_ERROR),
682 errmsg("cannot use window function in VALUES"),
683 parser_errposition(pstate,
684 locate_windowfunc((Node *) qry))));
690 * Prepare an INSERT row for assignment to the target table.
692 * The row might be either a VALUES row, or variables referencing a
696 transformInsertRow(ParseState *pstate, List *exprlist,
697 List *stmtcols, List *icolumns, List *attrnos)
705 * Check length of expr list. It must not have more expressions than
706 * there are target columns. We allow fewer, but only if no explicit
707 * columns list was given (the remaining columns are implicitly
708 * defaulted). Note we must check this *after* transformation because
709 * that could expand '*' into multiple items.
711 if (list_length(exprlist) > list_length(icolumns))
713 (errcode(ERRCODE_SYNTAX_ERROR),
714 errmsg("INSERT has more expressions than target columns"),
715 parser_errposition(pstate,
716 exprLocation(list_nth(exprlist,
717 list_length(icolumns))))));
718 if (stmtcols != NIL &&
719 list_length(exprlist) < list_length(icolumns))
721 (errcode(ERRCODE_SYNTAX_ERROR),
722 errmsg("INSERT has more target columns than expressions"),
723 parser_errposition(pstate,
724 exprLocation(list_nth(icolumns,
725 list_length(exprlist))))));
728 * Prepare columns for assignment to target table.
731 icols = list_head(icolumns);
732 attnos = list_head(attrnos);
733 foreach(lc, exprlist)
735 Expr *expr = (Expr *) lfirst(lc);
738 col = (ResTarget *) lfirst(icols);
739 Assert(IsA(col, ResTarget));
741 expr = transformAssignedExpr(pstate, expr,
747 result = lappend(result, expr);
749 icols = lnext(icols);
750 attnos = lnext(attnos);
758 * transformSelectStmt -
759 * transforms a Select Statement
761 * Note: this covers only cases with no set operations and no VALUES lists;
762 * see below for the other cases.
765 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
767 Query *qry = makeNode(Query);
771 qry->commandType = CMD_SELECT;
773 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
774 pstate->p_locking_clause = stmt->lockingClause;
776 /* make WINDOW info available for window functions, too */
777 pstate->p_windowdefs = stmt->windowClause;
779 /* process the WITH clause */
780 if (stmt->withClause)
782 qry->hasRecursive = stmt->withClause->recursive;
783 qry->cteList = transformWithClause(pstate, stmt->withClause);
786 /* process the FROM clause */
787 transformFromClause(pstate, stmt->fromClause);
789 /* transform targetlist */
790 qry->targetList = transformTargetList(pstate, stmt->targetList);
792 /* mark column origins */
793 markTargetListOrigins(pstate, qry->targetList);
795 /* transform WHERE */
796 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
799 * Initial processing of HAVING clause is just like WHERE clause.
801 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
805 * Transform sorting/grouping stuff. Do ORDER BY first because both
806 * transformGroupClause and transformDistinctClause need the results.
807 * Note that these functions can also change the targetList, so it's
808 * passed to them by reference.
810 qry->sortClause = transformSortClause(pstate,
813 true /* fix unknowns */ );
815 qry->groupClause = transformGroupClause(pstate,
821 if (stmt->distinctClause == NIL)
823 qry->distinctClause = NIL;
824 qry->hasDistinctOn = false;
826 else if (linitial(stmt->distinctClause) == NULL)
828 /* We had SELECT DISTINCT */
829 qry->distinctClause = transformDistinctClause(pstate,
832 qry->hasDistinctOn = false;
836 /* We had SELECT DISTINCT ON */
837 qry->distinctClause = transformDistinctOnClause(pstate,
838 stmt->distinctClause,
841 qry->hasDistinctOn = true;
844 /* transform LIMIT */
845 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
847 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
850 /* transform window clauses after we have seen all window functions */
851 qry->windowClause = transformWindowDefinitions(pstate,
852 pstate->p_windowdefs,
855 /* handle any SELECT INTO/CREATE TABLE AS spec */
856 if (stmt->intoClause)
858 qry->intoClause = stmt->intoClause;
859 if (stmt->intoClause->colNames)
860 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
863 qry->rtable = pstate->p_rtable;
864 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
866 qry->hasSubLinks = pstate->p_hasSubLinks;
867 qry->hasAggs = pstate->p_hasAggs;
868 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
869 parseCheckAggregates(pstate, qry);
870 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
871 if (pstate->p_hasWindowFuncs)
872 parseCheckWindowFuncs(pstate, qry);
874 foreach(l, stmt->lockingClause)
876 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
883 * transformValuesClause -
884 * transforms a VALUES clause that's being used as a standalone SELECT
886 * We build a Query containing a VALUES RTE, rather as if one had written
887 * SELECT * FROM (VALUES ...)
890 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
892 Query *qry = makeNode(Query);
893 List *exprsLists = NIL;
894 List **colexprs = NULL;
895 Oid *coltypes = NULL;
896 int sublist_length = -1;
904 qry->commandType = CMD_SELECT;
906 /* Most SELECT stuff doesn't apply in a VALUES clause */
907 Assert(stmt->distinctClause == NIL);
908 Assert(stmt->targetList == NIL);
909 Assert(stmt->fromClause == NIL);
910 Assert(stmt->whereClause == NULL);
911 Assert(stmt->groupClause == NIL);
912 Assert(stmt->havingClause == NULL);
913 Assert(stmt->windowClause == NIL);
914 Assert(stmt->op == SETOP_NONE);
916 /* process the WITH clause */
917 if (stmt->withClause)
919 qry->hasRecursive = stmt->withClause->recursive;
920 qry->cteList = transformWithClause(pstate, stmt->withClause);
924 * For each row of VALUES, transform the raw expressions and gather type
925 * information. This is also a handy place to reject DEFAULT nodes, which
926 * the grammar allows for simplicity.
928 foreach(lc, stmt->valuesLists)
930 List *sublist = (List *) lfirst(lc);
932 /* Do basic expression transformation (same as a ROW() expr) */
933 sublist = transformExpressionList(pstate, sublist);
936 * All the sublists must be the same length, *after* transformation
937 * (which might expand '*' into multiple items). The VALUES RTE can't
938 * handle anything different.
940 if (sublist_length < 0)
942 /* Remember post-transformation length of first sublist */
943 sublist_length = list_length(sublist);
944 /* and allocate arrays for per-column info */
945 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
946 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
948 else if (sublist_length != list_length(sublist))
951 (errcode(ERRCODE_SYNTAX_ERROR),
952 errmsg("VALUES lists must all be the same length"),
953 parser_errposition(pstate,
954 exprLocation((Node *) sublist))));
957 exprsLists = lappend(exprsLists, sublist);
959 /* Check for DEFAULT and build per-column expression lists */
961 foreach(lc2, sublist)
963 Node *col = (Node *) lfirst(lc2);
965 if (IsA(col, SetToDefault))
967 (errcode(ERRCODE_SYNTAX_ERROR),
968 errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
969 parser_errposition(pstate, exprLocation(col))));
970 colexprs[i] = lappend(colexprs[i], col);
976 * Now resolve the common types of the columns, and coerce everything to
979 for (i = 0; i < sublist_length; i++)
981 coltypes[i] = select_common_type(pstate, colexprs[i], "VALUES", NULL);
985 foreach(lc, exprsLists)
987 List *sublist = (List *) lfirst(lc);
988 List *newsublist = NIL;
991 foreach(lc2, sublist)
993 Node *col = (Node *) lfirst(lc2);
995 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
996 newsublist = lappend(newsublist, col);
1000 newExprsLists = lappend(newExprsLists, newsublist);
1004 * Generate the VALUES RTE
1006 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
1007 rtr = makeNode(RangeTblRef);
1008 /* assume new rte is at end */
1009 rtr->rtindex = list_length(pstate->p_rtable);
1010 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1011 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1012 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1015 * Generate a targetlist as though expanding "*"
1017 Assert(pstate->p_next_resno == 1);
1018 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
1021 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1024 qry->sortClause = transformSortClause(pstate,
1027 true /* fix unknowns */ );
1029 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1031 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1034 if (stmt->lockingClause)
1036 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1037 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1039 /* handle any CREATE TABLE AS spec */
1040 if (stmt->intoClause)
1042 qry->intoClause = stmt->intoClause;
1043 if (stmt->intoClause->colNames)
1044 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
1048 * There mustn't have been any table references in the expressions, else
1049 * strange things would happen, like Cartesian products of those tables
1050 * with the VALUES list. We have to check this after parsing ORDER BY et
1051 * al since those could insert more junk.
1053 if (list_length(pstate->p_joinlist) != 1)
1055 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1056 errmsg("VALUES must not contain table references"),
1057 parser_errposition(pstate,
1058 locate_var_of_level((Node *) newExprsLists, 0))));
1061 * Another thing we can't currently support is NEW/OLD references in rules
1062 * --- seems we'd need something like SQL99's LATERAL construct to ensure
1063 * that the values would be available while evaluating the VALUES RTE.
1064 * This is a shame. FIXME
1066 if (list_length(pstate->p_rtable) != 1 &&
1067 contain_vars_of_level((Node *) newExprsLists, 0))
1069 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1070 errmsg("VALUES must not contain OLD or NEW references"),
1071 errhint("Use SELECT ... UNION ALL ... instead."),
1072 parser_errposition(pstate,
1073 locate_var_of_level((Node *) newExprsLists, 0))));
1075 qry->rtable = pstate->p_rtable;
1076 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1078 qry->hasSubLinks = pstate->p_hasSubLinks;
1079 /* aggregates not allowed (but subselects are okay) */
1080 if (pstate->p_hasAggs)
1082 (errcode(ERRCODE_GROUPING_ERROR),
1083 errmsg("cannot use aggregate function in VALUES"),
1084 parser_errposition(pstate,
1085 locate_agg_of_level((Node *) newExprsLists, 0))));
1086 if (pstate->p_hasWindowFuncs)
1088 (errcode(ERRCODE_WINDOWING_ERROR),
1089 errmsg("cannot use window function in VALUES"),
1090 parser_errposition(pstate,
1091 locate_windowfunc((Node *) newExprsLists))));
1097 * transformSetOperationStmt -
1098 * transforms a set-operations tree
1100 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1101 * structure to it. We must transform each leaf SELECT and build up a top-
1102 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1103 * The tree of set operations is converted into the setOperations field of
1104 * the top-level Query.
1107 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1109 Query *qry = makeNode(Query);
1110 SelectStmt *leftmostSelect;
1112 Query *leftmostQuery;
1113 SetOperationStmt *sostmt;
1115 List *intoColNames = NIL;
1119 List *lockingClause;
1121 ListCell *left_tlist,
1130 RangeTblEntry *jrte;
1133 qry->commandType = CMD_SELECT;
1136 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1137 * and from the top-level node.
1139 leftmostSelect = stmt->larg;
1140 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1141 leftmostSelect = leftmostSelect->larg;
1142 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1143 leftmostSelect->larg == NULL);
1144 if (leftmostSelect->intoClause)
1146 qry->intoClause = leftmostSelect->intoClause;
1147 intoColNames = leftmostSelect->intoClause->colNames;
1150 /* clear this to prevent complaints in transformSetOperationTree() */
1151 leftmostSelect->intoClause = NULL;
1154 * These are not one-time, exactly, but we want to process them here and
1155 * not let transformSetOperationTree() see them --- else it'll just
1156 * recurse right back here!
1158 sortClause = stmt->sortClause;
1159 limitOffset = stmt->limitOffset;
1160 limitCount = stmt->limitCount;
1161 lockingClause = stmt->lockingClause;
1163 stmt->sortClause = NIL;
1164 stmt->limitOffset = NULL;
1165 stmt->limitCount = NULL;
1166 stmt->lockingClause = NIL;
1168 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1171 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1172 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1174 /* process the WITH clause */
1175 if (stmt->withClause)
1177 qry->hasRecursive = stmt->withClause->recursive;
1178 qry->cteList = transformWithClause(pstate, stmt->withClause);
1182 * Recursively transform the components of the tree.
1184 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1186 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1187 qry->setOperations = (Node *) sostmt;
1190 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1192 node = sostmt->larg;
1193 while (node && IsA(node, SetOperationStmt))
1194 node = ((SetOperationStmt *) node)->larg;
1195 Assert(node && IsA(node, RangeTblRef));
1196 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1197 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1198 Assert(leftmostQuery != NULL);
1201 * Generate dummy targetlist for outer query using column names of
1202 * leftmost select and common datatypes of topmost set operation. Also
1203 * make lists of the dummy vars and their names for use in parsing ORDER
1206 * Note: we use leftmostRTI as the varno of the dummy variables. It
1207 * shouldn't matter too much which RT index they have, as long as they
1208 * have one that corresponds to a real RT entry; else funny things may
1209 * happen when the tree is mashed by rule rewriting.
1211 qry->targetList = NIL;
1214 left_tlist = list_head(leftmostQuery->targetList);
1216 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1218 Oid colType = lfirst_oid(lct);
1219 int32 colTypmod = lfirst_int(lcm);
1220 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1225 Assert(!lefttle->resjunk);
1226 colName = pstrdup(lefttle->resname);
1227 var = makeVar(leftmostRTI,
1232 var->location = exprLocation((Node *) lefttle->expr);
1233 tle = makeTargetEntry((Expr *) var,
1234 (AttrNumber) pstate->p_next_resno++,
1237 qry->targetList = lappend(qry->targetList, tle);
1238 targetvars = lappend(targetvars, var);
1239 targetnames = lappend(targetnames, makeString(colName));
1240 left_tlist = lnext(left_tlist);
1244 * As a first step towards supporting sort clauses that are expressions
1245 * using the output columns, generate a varnamespace entry that makes the
1246 * output columns visible. A Join RTE node is handy for this, since we
1247 * can easily control the Vars generated upon matches.
1249 * Note: we don't yet do anything useful with such cases, but at least
1250 * "ORDER BY upper(foo)" will draw the right error message rather than
1253 jrte = addRangeTableEntryForJoin(NULL,
1260 sv_rtable = pstate->p_rtable;
1261 pstate->p_rtable = list_make1(jrte);
1263 sv_relnamespace = pstate->p_relnamespace;
1264 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1266 sv_varnamespace = pstate->p_varnamespace;
1267 pstate->p_varnamespace = list_make1(jrte);
1270 * For now, we don't support resjunk sort clauses on the output of a
1271 * setOperation tree --- you can only use the SQL92-spec options of
1272 * selecting an output column by name or number. Enforce by checking that
1273 * transformSortClause doesn't add any items to tlist.
1275 tllen = list_length(qry->targetList);
1277 qry->sortClause = transformSortClause(pstate,
1280 false /* no unknowns expected */ );
1282 pstate->p_rtable = sv_rtable;
1283 pstate->p_relnamespace = sv_relnamespace;
1284 pstate->p_varnamespace = sv_varnamespace;
1286 if (tllen != list_length(qry->targetList))
1288 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1289 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1290 errdetail("Only result column names can be used, not expressions or functions."),
1291 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1292 parser_errposition(pstate,
1293 exprLocation(list_nth(qry->targetList, tllen)))));
1295 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1297 qry->limitCount = transformLimitClause(pstate, limitCount,
1301 * Handle SELECT INTO/CREATE TABLE AS.
1303 * Any column names from CREATE TABLE AS need to be attached to both the
1304 * top level and the leftmost subquery. We do not do this earlier because
1305 * we do *not* want sortClause processing to be affected.
1309 applyColumnNames(qry->targetList, intoColNames);
1310 applyColumnNames(leftmostQuery->targetList, intoColNames);
1313 qry->rtable = pstate->p_rtable;
1314 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1316 qry->hasSubLinks = pstate->p_hasSubLinks;
1317 qry->hasAggs = pstate->p_hasAggs;
1318 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1319 parseCheckAggregates(pstate, qry);
1320 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1321 if (pstate->p_hasWindowFuncs)
1322 parseCheckWindowFuncs(pstate, qry);
1324 foreach(l, lockingClause)
1326 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
1333 * transformSetOperationTree
1334 * Recursively transform leaves and internal nodes of a set-op tree
1336 * In addition to returning the transformed node, we return a list of
1337 * expression nodes showing the type, typmod, and location (for error messages)
1338 * of each output column of the set-op node. This is used only during the
1339 * internal recursion of this function. At the upper levels we use
1340 * SetToDefault nodes for this purpose, since they carry exactly the fields
1341 * needed, but any other expression node type would do as well.
1344 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1349 Assert(stmt && IsA(stmt, SelectStmt));
1352 * Validity-check both leaf and internal SELECTs for disallowed ops.
1354 if (stmt->intoClause)
1356 (errcode(ERRCODE_SYNTAX_ERROR),
1357 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1358 parser_errposition(pstate,
1359 exprLocation((Node *) stmt->intoClause))));
1361 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1362 if (stmt->lockingClause)
1364 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1365 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1368 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1369 * clauses attached, we need to treat it like a leaf node to generate an
1370 * independent sub-Query tree. Otherwise, it can be represented by a
1371 * SetOperationStmt node underneath the parent Query.
1373 if (stmt->op == SETOP_NONE)
1375 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1380 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1381 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1382 stmt->lockingClause)
1390 /* Process leaf SELECT */
1392 char selectName[32];
1398 * Transform SelectStmt into a Query.
1400 * Note: previously transformed sub-queries don't affect the parsing
1401 * of this sub-query, because they are not in the toplevel pstate's
1404 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1407 * Check for bogus references to Vars on the current query level (but
1408 * upper-level references are okay). Normally this can't happen
1409 * because the namespace will be empty, but it could happen if we are
1412 if (pstate->p_relnamespace || pstate->p_varnamespace)
1414 if (contain_vars_of_level((Node *) selectQuery, 1))
1416 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1417 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1418 parser_errposition(pstate,
1419 locate_var_of_level((Node *) selectQuery, 1))));
1423 * Extract a list of the result expressions for upper-level checking.
1426 foreach(tl, selectQuery->targetList)
1428 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1431 *colInfo = lappend(*colInfo, tle->expr);
1435 * Make the leaf query be a subquery in the top-level rangetable.
1437 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1438 list_length(pstate->p_rtable) + 1);
1439 rte = addRangeTableEntryForSubquery(pstate,
1441 makeAlias(selectName, NIL),
1445 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1447 rtr = makeNode(RangeTblRef);
1448 /* assume new rte is at end */
1449 rtr->rtindex = list_length(pstate->p_rtable);
1450 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1451 return (Node *) rtr;
1455 /* Process an internal node (set operation node) */
1456 SetOperationStmt *op = makeNode(SetOperationStmt);
1461 const char *context;
1463 context = (stmt->op == SETOP_UNION ? "UNION" :
1464 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1468 op->all = stmt->all;
1471 * Recursively transform the child nodes.
1473 op->larg = transformSetOperationTree(pstate, stmt->larg,
1475 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1479 * Verify that the two children have the same number of non-junk
1480 * columns, and determine the types of the merged output columns.
1482 if (list_length(lcolinfo) != list_length(rcolinfo))
1484 (errcode(ERRCODE_SYNTAX_ERROR),
1485 errmsg("each %s query must have the same number of columns",
1487 parser_errposition(pstate,
1488 exprLocation((Node *) rcolinfo))));
1492 op->colTypmods = NIL;
1493 op->groupClauses = NIL;
1494 forboth(lci, lcolinfo, rci, rcolinfo)
1496 Node *lcolinfo = (Node *) lfirst(lci);
1497 Node *rcolinfo = (Node *) lfirst(rci);
1498 Oid lcoltype = exprType(lcolinfo);
1499 Oid rcoltype = exprType(rcolinfo);
1500 int32 lcoltypmod = exprTypmod(lcolinfo);
1501 int32 rcoltypmod = exprTypmod(rcolinfo);
1503 SetToDefault *rescolinfo;
1507 /* select common type, same as CASE et al */
1508 rescoltype = select_common_type(pstate,
1509 list_make2(lcolinfo, rcolinfo),
1512 /* if same type and same typmod, use typmod; else default */
1513 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1514 rescoltypmod = lcoltypmod;
1518 /* verify the coercions are actually possible */
1519 (void) coerce_to_common_type(pstate, lcolinfo,
1520 rescoltype, context);
1521 (void) coerce_to_common_type(pstate, rcolinfo,
1522 rescoltype, context);
1525 rescolinfo = makeNode(SetToDefault);
1526 rescolinfo->typeId = rescoltype;
1527 rescolinfo->typeMod = rescoltypmod;
1528 rescolinfo->location = exprLocation(bestexpr);
1529 *colInfo = lappend(*colInfo, rescolinfo);
1531 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1532 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1535 * For all cases except UNION ALL, identify the grouping operators
1536 * (and, if available, sorting operators) that will be used to
1537 * eliminate duplicates.
1539 if (op->op != SETOP_UNION || !op->all)
1541 SortGroupClause *grpcl = makeNode(SortGroupClause);
1544 ParseCallbackState pcbstate;
1546 setup_parser_errposition_callback(&pcbstate, pstate,
1547 rescolinfo->location);
1549 /* determine the eqop and optional sortop */
1550 get_sort_group_operators(rescoltype,
1552 &sortop, &eqop, NULL);
1554 cancel_parser_errposition_callback(&pcbstate);
1556 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1557 grpcl->tleSortGroupRef = 0;
1559 grpcl->sortop = sortop;
1560 grpcl->nulls_first = false; /* OK with or without sortop */
1562 op->groupClauses = lappend(op->groupClauses, grpcl);
1571 * Attach column names from a ColumnDef list to a TargetEntry list
1572 * (for CREATE TABLE AS)
1575 applyColumnNames(List *dst, List *src)
1580 src_item = list_head(src);
1582 foreach(dst_item, dst)
1584 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1587 /* junk targets don't count */
1591 /* fewer ColumnDefs than target entries is OK */
1592 if (src_item == NULL)
1595 s = (ColumnDef *) lfirst(src_item);
1596 src_item = lnext(src_item);
1598 d->resname = pstrdup(s->colname);
1601 /* more ColumnDefs than target entries is not OK */
1602 if (src_item != NULL)
1604 (errcode(ERRCODE_SYNTAX_ERROR),
1605 errmsg("CREATE TABLE AS specifies too many column names")));
1610 * transformUpdateStmt -
1611 * transforms an update statement
1614 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1616 Query *qry = makeNode(Query);
1618 ListCell *origTargetList;
1621 qry->commandType = CMD_UPDATE;
1622 pstate->p_is_update = true;
1624 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1625 interpretInhOption(stmt->relation->inhOpt),
1630 * the FROM clause is non-standard SQL syntax. We used to be able to do
1631 * this with REPLACE in POSTQUEL so we keep the feature.
1633 transformFromClause(pstate, stmt->fromClause);
1635 qry->targetList = transformTargetList(pstate, stmt->targetList);
1637 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1639 qry->returningList = transformReturningList(pstate, stmt->returningList);
1641 qry->rtable = pstate->p_rtable;
1642 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1644 qry->hasSubLinks = pstate->p_hasSubLinks;
1647 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1648 * an implementation point of view, this is forced because the implicit
1649 * ctid reference would otherwise be an ungrouped variable.)
1651 if (pstate->p_hasAggs)
1653 (errcode(ERRCODE_GROUPING_ERROR),
1654 errmsg("cannot use aggregate function in UPDATE"),
1655 parser_errposition(pstate,
1656 locate_agg_of_level((Node *) qry, 0))));
1657 if (pstate->p_hasWindowFuncs)
1659 (errcode(ERRCODE_WINDOWING_ERROR),
1660 errmsg("cannot use window function in UPDATE"),
1661 parser_errposition(pstate,
1662 locate_windowfunc((Node *) qry))));
1665 * Now we are done with SELECT-like processing, and can get on with
1666 * transforming the target list to match the UPDATE target columns.
1669 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1670 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1671 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1673 /* Prepare non-junk columns for assignment to target table */
1674 origTargetList = list_head(stmt->targetList);
1676 foreach(tl, qry->targetList)
1678 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1679 ResTarget *origTarget;
1685 * Resjunk nodes need no additional processing, but be sure they
1686 * have resnos that do not match any target columns; else rewriter
1687 * or planner might get confused. They don't need a resname
1690 tle->resno = (AttrNumber) pstate->p_next_resno++;
1691 tle->resname = NULL;
1694 if (origTargetList == NULL)
1695 elog(ERROR, "UPDATE target count mismatch --- internal error");
1696 origTarget = (ResTarget *) lfirst(origTargetList);
1697 Assert(IsA(origTarget, ResTarget));
1699 attrno = attnameAttNum(pstate->p_target_relation,
1700 origTarget->name, true);
1701 if (attrno == InvalidAttrNumber)
1703 (errcode(ERRCODE_UNDEFINED_COLUMN),
1704 errmsg("column \"%s\" of relation \"%s\" does not exist",
1706 RelationGetRelationName(pstate->p_target_relation)),
1707 parser_errposition(pstate, origTarget->location)));
1709 updateTargetListEntry(pstate, tle, origTarget->name,
1711 origTarget->indirection,
1712 origTarget->location);
1714 origTargetList = lnext(origTargetList);
1716 if (origTargetList != NULL)
1717 elog(ERROR, "UPDATE target count mismatch --- internal error");
1723 * transformReturningList -
1724 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1727 transformReturningList(ParseState *pstate, List *returningList)
1730 int save_next_resno;
1732 bool save_hasWindowFuncs;
1735 if (returningList == NIL)
1736 return NIL; /* nothing to do */
1739 * We need to assign resnos starting at one in the RETURNING list. Save
1740 * and restore the main tlist's value of p_next_resno, just in case
1741 * someone looks at it later (probably won't happen).
1743 save_next_resno = pstate->p_next_resno;
1744 pstate->p_next_resno = 1;
1746 /* save other state so that we can detect disallowed stuff */
1747 save_hasAggs = pstate->p_hasAggs;
1748 pstate->p_hasAggs = false;
1749 save_hasWindowFuncs = pstate->p_hasWindowFuncs;
1750 pstate->p_hasWindowFuncs = false;
1751 length_rtable = list_length(pstate->p_rtable);
1753 /* transform RETURNING identically to a SELECT targetlist */
1754 rlist = transformTargetList(pstate, returningList);
1756 /* check for disallowed stuff */
1758 /* aggregates not allowed (but subselects are okay) */
1759 if (pstate->p_hasAggs)
1761 (errcode(ERRCODE_GROUPING_ERROR),
1762 errmsg("cannot use aggregate function in RETURNING"),
1763 parser_errposition(pstate,
1764 locate_agg_of_level((Node *) rlist, 0))));
1765 if (pstate->p_hasWindowFuncs)
1767 (errcode(ERRCODE_WINDOWING_ERROR),
1768 errmsg("cannot use window function in RETURNING"),
1769 parser_errposition(pstate,
1770 locate_windowfunc((Node *) rlist))));
1772 /* no new relation references please */
1773 if (list_length(pstate->p_rtable) != length_rtable)
1778 /* try to locate such a reference to point to */
1779 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
1781 vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
1786 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1787 errmsg("RETURNING cannot contain references to other relations"),
1788 parser_errposition(pstate, vlocation)));
1791 /* mark column origins */
1792 markTargetListOrigins(pstate, rlist);
1795 pstate->p_next_resno = save_next_resno;
1796 pstate->p_hasAggs = save_hasAggs;
1797 pstate->p_hasWindowFuncs = save_hasWindowFuncs;
1804 * transformDeclareCursorStmt -
1805 * transform a DECLARE CURSOR Statement
1807 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1808 * significantly different from a SELECT) as far as parsing/rewriting/planning
1809 * are concerned, but it's not passed to the executor and so in that sense is
1810 * a utility statement. We transform it into a Query exactly as if it were
1811 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1812 * field to carry the cursor name and options.
1815 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1820 * Don't allow both SCROLL and NO SCROLL to be specified
1822 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1823 (stmt->options & CURSOR_OPT_NO_SCROLL))
1825 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1826 errmsg("cannot specify both SCROLL and NO SCROLL")));
1828 result = transformStmt(pstate, stmt->query);
1830 /* Grammar should not have allowed anything but SELECT */
1831 if (!IsA(result, Query) ||
1832 result->commandType != CMD_SELECT ||
1833 result->utilityStmt != NULL)
1834 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
1836 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1837 if (result->intoClause)
1839 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1840 errmsg("DECLARE CURSOR cannot specify INTO"),
1841 parser_errposition(pstate,
1842 exprLocation((Node *) result->intoClause))));
1844 /* FOR UPDATE and WITH HOLD are not compatible */
1845 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1847 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1848 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1849 errdetail("Holdable cursors must be READ ONLY.")));
1851 /* FOR UPDATE and SCROLL are not compatible */
1852 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1854 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1855 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1856 errdetail("Scrollable cursors must be READ ONLY.")));
1858 /* FOR UPDATE and INSENSITIVE are not compatible */
1859 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1861 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1862 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1863 errdetail("Insensitive cursors must be READ ONLY.")));
1865 /* We won't need the raw querytree any more */
1868 result->utilityStmt = (Node *) stmt;
1875 * transformExplainStmt -
1876 * transform an EXPLAIN Statement
1878 * EXPLAIN is just like other utility statements in that we emit it as a
1879 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1880 * However, if p_variableparams is set, it could be that the client is
1881 * expecting us to resolve parameter types in something like
1882 * EXPLAIN SELECT * FROM tab WHERE col = $1
1883 * To deal with such cases, we run parse analysis and throw away the result;
1884 * this is a bit grotty but not worth contorting the rest of the system for.
1885 * (The approach we use for DECLARE CURSOR won't work because the statement
1886 * being explained isn't necessarily a SELECT, and in particular might rewrite
1887 * to multiple parsetrees.)
1890 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1894 if (pstate->p_variableparams)
1896 /* Since parse analysis scribbles on its input, copy the tree first! */
1897 (void) transformStmt(pstate, copyObject(stmt->query));
1900 /* Now return the untransformed command as a utility Query */
1901 result = makeNode(Query);
1902 result->commandType = CMD_UTILITY;
1903 result->utilityStmt = (Node *) stmt;
1909 /* exported so planner can check again after rewriting, query pullup, etc */
1911 CheckSelectLocking(Query *qry)
1913 if (qry->setOperations)
1915 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1916 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1917 if (qry->distinctClause != NIL)
1919 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1920 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1921 if (qry->groupClause != NIL)
1923 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1924 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1925 if (qry->havingQual != NULL)
1927 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1928 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1931 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1932 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1933 if (qry->hasWindowFuncs)
1935 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1936 errmsg("SELECT FOR UPDATE/SHARE is not allowed with window functions")));
1940 * Transform a FOR UPDATE/SHARE clause
1942 * This basically involves replacing names by integer relids.
1944 * NB: if you need to change this, see also markQueryForLocking()
1945 * in rewriteHandler.c, and isLockedRel() in parse_relation.c.
1948 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc)
1950 List *lockedRels = lc->lockedRels;
1954 LockingClause *allrels;
1956 CheckSelectLocking(qry);
1958 /* make a clause we can pass down to subqueries to select all rels */
1959 allrels = makeNode(LockingClause);
1960 allrels->lockedRels = NIL; /* indicates all rels */
1961 allrels->forUpdate = lc->forUpdate;
1962 allrels->noWait = lc->noWait;
1964 if (lockedRels == NIL)
1966 /* all regular tables used in query */
1968 foreach(rt, qry->rtable)
1970 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1973 switch (rte->rtekind)
1976 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1977 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1982 * FOR UPDATE/SHARE of subquery is propagated to all of
1985 transformLockingClause(pstate, rte->subquery, allrels);
1990 * We allow FOR UPDATE/SHARE of a WITH query to be
1991 * propagated into the WITH, but it doesn't seem
1992 * very sane to allow this for a reference to an
1993 * outer-level WITH. And it definitely wouldn't
1994 * work for a self-reference, since we're not done
1995 * analyzing the CTE anyway.
1997 CommonTableExpr *cte;
1999 if (rte->ctelevelsup > 0 || rte->self_reference)
2001 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2002 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query")));
2003 cte = GetCTEForRTE(pstate, rte, -1);
2004 /* should be analyzed by now */
2005 Assert(IsA(cte->ctequery, Query));
2006 transformLockingClause(pstate,
2007 (Query *) cte->ctequery,
2012 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
2019 /* just the named tables */
2020 foreach(l, lockedRels)
2022 RangeVar *thisrel = (RangeVar *) lfirst(l);
2024 /* For simplicity we insist on unqualified alias names here */
2025 if (thisrel->catalogname || thisrel->schemaname)
2027 (errcode(ERRCODE_SYNTAX_ERROR),
2028 errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
2029 parser_errposition(pstate, thisrel->location)));
2032 foreach(rt, qry->rtable)
2034 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2037 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2039 switch (rte->rtekind)
2042 applyLockingClause(qry, i,
2043 lc->forUpdate, lc->noWait);
2044 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2049 * FOR UPDATE/SHARE of subquery is propagated to
2050 * all of subquery's rels
2052 transformLockingClause(pstate, rte->subquery, allrels);
2056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2057 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2058 parser_errposition(pstate, thisrel->location)));
2062 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2063 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD"),
2064 parser_errposition(pstate, thisrel->location)));
2068 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2069 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2070 parser_errposition(pstate, thisrel->location)));
2074 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2075 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2076 parser_errposition(pstate, thisrel->location)));
2081 * We allow FOR UPDATE/SHARE of a WITH query
2082 * to be propagated into the WITH, but it
2083 * doesn't seem very sane to allow this for a
2084 * reference to an outer-level WITH. And it
2085 * definitely wouldn't work for a
2086 * self-reference, since we're not done
2087 * analyzing the CTE anyway.
2089 CommonTableExpr *cte;
2091 if (rte->ctelevelsup > 0 || rte->self_reference)
2093 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2094 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query"),
2095 parser_errposition(pstate, thisrel->location)));
2096 cte = GetCTEForRTE(pstate, rte, -1);
2097 /* should be analyzed by now */
2098 Assert(IsA(cte->ctequery, Query));
2099 transformLockingClause(pstate,
2100 (Query *) cte->ctequery,
2105 elog(ERROR, "unrecognized RTE type: %d",
2106 (int) rte->rtekind);
2109 break; /* out of foreach loop */
2114 (errcode(ERRCODE_UNDEFINED_TABLE),
2115 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2117 parser_errposition(pstate, thisrel->location)));
2123 * Record locking info for a single rangetable item
2126 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
2130 /* Check for pre-existing entry for same rtindex */
2131 if ((rc = get_rowmark(qry, rtindex)) != NULL)
2134 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2135 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
2136 * and exclusive lock at the same time; it'll end up being exclusive
2139 * We also consider that NOWAIT wins if it's specified both ways. This
2140 * is a bit more debatable but raising an error doesn't seem helpful.
2141 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2142 * internally contains a plain FOR UPDATE spec.)
2144 rc->forUpdate |= forUpdate;
2145 rc->noWait |= noWait;
2149 /* Make a new RowMarkClause */
2150 rc = makeNode(RowMarkClause);
2153 rc->forUpdate = forUpdate;
2154 rc->noWait = noWait;
2155 rc->isParent = false;
2156 qry->rowMarks = lappend(qry->rowMarks, rc);
2161 * Traverse a fully-analyzed tree to verify that parameter symbols
2162 * match their types. We need this because some Params might still
2163 * be UNKNOWN, if there wasn't anything to force their coercion,
2164 * and yet other instances seen later might have gotten coerced.
2167 check_parameter_resolution_walker(Node *node, ParseState *pstate)
2171 if (IsA(node, Param))
2173 Param *param = (Param *) node;
2175 if (param->paramkind == PARAM_EXTERN)
2177 int paramno = param->paramid;
2179 if (paramno <= 0 || /* shouldn't happen, but... */
2180 paramno > pstate->p_numparams)
2182 (errcode(ERRCODE_UNDEFINED_PARAMETER),
2183 errmsg("there is no parameter $%d", paramno),
2184 parser_errposition(pstate, param->location)));
2186 if (param->paramtype != pstate->p_paramtypes[paramno - 1])
2188 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
2189 errmsg("could not determine data type of parameter $%d",
2191 parser_errposition(pstate, param->location)));
2195 if (IsA(node, Query))
2197 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2198 return query_tree_walker((Query *) node,
2199 check_parameter_resolution_walker,
2200 (void *) pstate, 0);
2202 return expression_tree_walker(node, check_parameter_resolution_walker,