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-2007, 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.369 2007/10/25 13:48:57 tgl Exp $
22 *-------------------------------------------------------------------------
27 #include "catalog/pg_type.h"
28 #include "nodes/makefuncs.h"
29 #include "optimizer/clauses.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_expr.h"
36 #include "parser/parse_relation.h"
37 #include "parser/parse_target.h"
38 #include "parser/parsetree.h"
45 } check_parameter_resolution_context;
48 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
49 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
50 static List *transformInsertRow(ParseState *pstate, List *exprlist,
51 List *stmtcols, List *icolumns, List *attrnos);
52 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
53 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
54 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
55 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
56 static void getSetColTypes(ParseState *pstate, Node *node,
57 List **colTypes, List **colTypmods);
58 static void applyColumnNames(List *dst, List *src);
59 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
60 static List *transformReturningList(ParseState *pstate, List *returningList);
61 static Query *transformDeclareCursorStmt(ParseState *pstate,
62 DeclareCursorStmt *stmt);
63 static Query *transformExplainStmt(ParseState *pstate,
65 static void transformLockingClause(Query *qry, LockingClause *lc);
66 static bool check_parameter_resolution_walker(Node *node,
67 check_parameter_resolution_context *context);
72 * Analyze a raw parse tree and transform it to Query form.
74 * If available, pass the source text from which the raw parse tree was
75 * generated; it's OK to pass NULL if this is not available.
77 * Optionally, information about $n parameter types can be supplied.
78 * References to $n indexes not defined by paramTypes[] are disallowed.
80 * The result is a Query node. Optimizable statements require considerable
81 * transformation, while utility-type statements are simply hung off
82 * a dummy CMD_UTILITY Query node.
85 parse_analyze(Node *parseTree, const char *sourceText,
86 Oid *paramTypes, int numParams)
88 ParseState *pstate = make_parsestate(NULL);
91 pstate->p_sourcetext = sourceText;
92 pstate->p_paramtypes = paramTypes;
93 pstate->p_numparams = numParams;
94 pstate->p_variableparams = false;
96 query = transformStmt(pstate, parseTree);
98 free_parsestate(pstate);
104 * parse_analyze_varparams
106 * This variant is used when it's okay to deduce information about $n
107 * symbol datatypes from context. The passed-in paramTypes[] array can
108 * be modified or enlarged (via repalloc).
111 parse_analyze_varparams(Node *parseTree, const char *sourceText,
112 Oid **paramTypes, int *numParams)
114 ParseState *pstate = make_parsestate(NULL);
117 pstate->p_sourcetext = sourceText;
118 pstate->p_paramtypes = *paramTypes;
119 pstate->p_numparams = *numParams;
120 pstate->p_variableparams = true;
122 query = transformStmt(pstate, parseTree);
124 *paramTypes = pstate->p_paramtypes;
125 *numParams = pstate->p_numparams;
127 free_parsestate(pstate);
129 /* make sure all is well with parameter types */
132 check_parameter_resolution_context context;
134 context.paramTypes = *paramTypes;
135 context.numParams = *numParams;
136 check_parameter_resolution_walker((Node *) query, &context);
144 * Entry point for recursively analyzing a sub-statement.
147 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
149 ParseState *pstate = make_parsestate(parentParseState);
152 query = transformStmt(pstate, parseTree);
154 free_parsestate(pstate);
161 * transform a Parse tree into a Query tree.
164 transformStmt(ParseState *pstate, Node *parseTree)
168 switch (nodeTag(parseTree))
171 * Optimizable statements
174 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
178 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
182 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
187 SelectStmt *n = (SelectStmt *) parseTree;
190 result = transformValuesClause(pstate, n);
191 else if (n->op == SETOP_NONE)
192 result = transformSelectStmt(pstate, n);
194 result = transformSetOperationStmt(pstate, n);
201 case T_DeclareCursorStmt:
202 result = transformDeclareCursorStmt(pstate,
203 (DeclareCursorStmt *) parseTree);
207 result = transformExplainStmt(pstate,
208 (ExplainStmt *) parseTree);
214 * other statements don't require any transformation; just return
215 * the original parsetree with a Query node plastered on top.
217 result = makeNode(Query);
218 result->commandType = CMD_UTILITY;
219 result->utilityStmt = (Node *) parseTree;
223 /* Mark as original query until we learn differently */
224 result->querySource = QSRC_ORIGINAL;
225 result->canSetTag = true;
231 * transformDeleteStmt -
232 * transforms a Delete Statement
235 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
237 Query *qry = makeNode(Query);
240 qry->commandType = CMD_DELETE;
242 /* set up range table with just the result rel */
243 qry->resultRelation = setTargetTable(pstate, stmt->relation,
244 interpretInhOption(stmt->relation->inhOpt),
248 qry->distinctClause = NIL;
251 * The USING clause is non-standard SQL syntax, and is equivalent in
252 * functionality to the FROM list that can be specified for UPDATE. The
253 * USING keyword is used rather than FROM because FROM is already a
254 * keyword in the DELETE syntax.
256 transformFromClause(pstate, stmt->usingClause);
258 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
260 qry->returningList = transformReturningList(pstate, stmt->returningList);
262 /* done building the range table and jointree */
263 qry->rtable = pstate->p_rtable;
264 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
266 qry->hasSubLinks = pstate->p_hasSubLinks;
267 qry->hasAggs = pstate->p_hasAggs;
268 if (pstate->p_hasAggs)
269 parseCheckAggregates(pstate, qry);
275 * transformInsertStmt -
276 * transform an Insert Statement
279 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
281 Query *qry = makeNode(Query);
282 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
283 List *exprList = NIL;
284 bool isGeneralSelect;
286 List *sub_relnamespace;
287 List *sub_varnamespace;
296 qry->commandType = CMD_INSERT;
297 pstate->p_is_insert = true;
300 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
301 * VALUES list, or general SELECT input. We special-case VALUES, both for
302 * efficiency and so we can handle DEFAULT specifications.
304 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
307 * If a non-nil rangetable/namespace was passed in, and we are doing
308 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
309 * SELECT. This can only happen if we are inside a CREATE RULE, and in
310 * that case we want the rule's OLD and NEW rtable entries to appear as
311 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
312 * The SELECT's joinlist is not affected however. We must do this before
313 * adding the target table to the INSERT's rtable.
317 sub_rtable = pstate->p_rtable;
318 pstate->p_rtable = NIL;
319 sub_relnamespace = pstate->p_relnamespace;
320 pstate->p_relnamespace = NIL;
321 sub_varnamespace = pstate->p_varnamespace;
322 pstate->p_varnamespace = NIL;
326 sub_rtable = NIL; /* not used, but keep compiler quiet */
327 sub_relnamespace = NIL;
328 sub_varnamespace = NIL;
332 * Must get write lock on INSERT target table before scanning SELECT, else
333 * we will grab the wrong kind of initial lock if the target table is also
334 * mentioned in the SELECT part. Note that the target table is not added
335 * to the joinlist or namespace.
337 qry->resultRelation = setTargetTable(pstate, stmt->relation,
338 false, false, ACL_INSERT);
340 /* Validate stmt->cols list, or build default list if no list given */
341 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
342 Assert(list_length(icolumns) == list_length(attrnos));
345 * Determine which variant of INSERT we have.
347 if (selectStmt == NULL)
350 * We have INSERT ... DEFAULT VALUES. We can handle this case by
351 * emitting an empty targetlist --- all columns will be defaulted when
352 * the planner expands the targetlist.
356 else if (isGeneralSelect)
359 * We make the sub-pstate a child of the outer pstate so that it can
360 * see any Param definitions supplied from above. Since the outer
361 * pstate's rtable and namespace are presently empty, there are no
362 * side-effects of exposing names the sub-SELECT shouldn't be able to
365 ParseState *sub_pstate = make_parsestate(pstate);
369 * Process the source SELECT.
371 * It is important that this be handled just like a standalone SELECT;
372 * otherwise the behavior of SELECT within INSERT might be different
373 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
374 * bugs of just that nature...)
376 sub_pstate->p_rtable = sub_rtable;
377 sub_pstate->p_relnamespace = sub_relnamespace;
378 sub_pstate->p_varnamespace = sub_varnamespace;
380 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
382 free_parsestate(sub_pstate);
384 /* The grammar should have produced a SELECT, but it might have INTO */
385 Assert(IsA(selectQuery, Query));
386 Assert(selectQuery->commandType == CMD_SELECT);
387 Assert(selectQuery->utilityStmt == NULL);
388 if (selectQuery->intoClause)
390 (errcode(ERRCODE_SYNTAX_ERROR),
391 errmsg("INSERT ... SELECT cannot specify INTO")));
394 * Make the source be a subquery in the INSERT's rangetable, and add
395 * it to the INSERT's joinlist.
397 rte = addRangeTableEntryForSubquery(pstate,
399 makeAlias("*SELECT*", NIL),
401 rtr = makeNode(RangeTblRef);
402 /* assume new rte is at end */
403 rtr->rtindex = list_length(pstate->p_rtable);
404 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
405 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
408 * Generate an expression list for the INSERT that selects all the
409 * non-resjunk columns from the subquery. (INSERT's tlist must be
410 * separate from the subquery's tlist because we may add columns,
411 * insert datatype coercions, etc.)
413 * HACK: unknown-type constants and params in the SELECT's targetlist
414 * are copied up as-is rather than being referenced as subquery
415 * outputs. This is to ensure that when we try to coerce them to
416 * the target column's datatype, the right things happen (see
417 * special cases in coerce_type). Otherwise, this fails:
418 * INSERT INTO foo SELECT 'bar', ... FROM baz
422 foreach(lc, selectQuery->targetList)
424 TargetEntry *tle = (TargetEntry *) lfirst(lc);
430 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
431 exprType((Node *) tle->expr) == UNKNOWNOID)
434 expr = (Expr *) makeVar(rtr->rtindex,
436 exprType((Node *) tle->expr),
437 exprTypmod((Node *) tle->expr),
439 exprList = lappend(exprList, expr);
442 /* Prepare row for assignment to target table */
443 exprList = transformInsertRow(pstate, exprList,
447 else if (list_length(selectStmt->valuesLists) > 1)
450 * Process INSERT ... VALUES with multiple VALUES sublists. We
451 * generate a VALUES RTE holding the transformed expression lists, and
452 * build up a targetlist containing Vars that reference the VALUES
455 List *exprsLists = NIL;
456 int sublist_length = -1;
458 foreach(lc, selectStmt->valuesLists)
460 List *sublist = (List *) lfirst(lc);
462 /* Do basic expression transformation (same as a ROW() expr) */
463 sublist = transformExpressionList(pstate, sublist);
466 * All the sublists must be the same length, *after*
467 * transformation (which might expand '*' into multiple items).
468 * The VALUES RTE can't handle anything different.
470 if (sublist_length < 0)
472 /* Remember post-transformation length of first sublist */
473 sublist_length = list_length(sublist);
475 else if (sublist_length != list_length(sublist))
478 (errcode(ERRCODE_SYNTAX_ERROR),
479 errmsg("VALUES lists must all be the same length")));
482 /* Prepare row for assignment to target table */
483 sublist = transformInsertRow(pstate, sublist,
487 exprsLists = lappend(exprsLists, sublist);
491 * There mustn't have been any table references in the expressions,
492 * else strange things would happen, like Cartesian products of those
493 * tables with the VALUES list ...
495 if (pstate->p_joinlist != NIL)
497 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
498 errmsg("VALUES must not contain table references")));
501 * Another thing we can't currently support is NEW/OLD references in
502 * rules --- seems we'd need something like SQL99's LATERAL construct
503 * to ensure that the values would be available while evaluating the
504 * VALUES RTE. This is a shame. FIXME
506 if (list_length(pstate->p_rtable) != 1 &&
507 contain_vars_of_level((Node *) exprsLists, 0))
509 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
510 errmsg("VALUES must not contain OLD or NEW references"),
511 errhint("Use SELECT ... UNION ALL ... instead.")));
514 * Generate the VALUES RTE
516 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
517 rtr = makeNode(RangeTblRef);
518 /* assume new rte is at end */
519 rtr->rtindex = list_length(pstate->p_rtable);
520 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
521 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
524 * Generate list of Vars referencing the RTE
526 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
531 * Process INSERT ... VALUES with a single VALUES sublist.
532 * We treat this separately for efficiency and for historical
533 * compatibility --- specifically, allowing table references,
535 * INSERT INTO foo VALUES(bar.*)
537 * The sublist is just computed directly as the Query's targetlist,
538 * with no VALUES RTE. So it works just like SELECT without FROM.
541 List *valuesLists = selectStmt->valuesLists;
543 Assert(list_length(valuesLists) == 1);
545 /* Do basic expression transformation (same as a ROW() expr) */
546 exprList = transformExpressionList(pstate,
547 (List *) linitial(valuesLists));
549 /* Prepare row for assignment to target table */
550 exprList = transformInsertRow(pstate, exprList,
556 * Generate query's target list using the computed list of expressions.
558 qry->targetList = NIL;
559 icols = list_head(icolumns);
560 attnos = list_head(attrnos);
561 foreach(lc, exprList)
563 Expr *expr = (Expr *) lfirst(lc);
567 col = (ResTarget *) lfirst(icols);
568 Assert(IsA(col, ResTarget));
570 tle = makeTargetEntry(expr,
571 (AttrNumber) lfirst_int(attnos),
574 qry->targetList = lappend(qry->targetList, tle);
576 icols = lnext(icols);
577 attnos = lnext(attnos);
581 * If we have a RETURNING clause, we need to add the target relation to
582 * the query namespace before processing it, so that Var references in
583 * RETURNING will work. Also, remove any namespace entries added in a
584 * sub-SELECT or VALUES list.
586 if (stmt->returningList)
588 pstate->p_relnamespace = NIL;
589 pstate->p_varnamespace = NIL;
590 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
592 qry->returningList = transformReturningList(pstate,
593 stmt->returningList);
596 /* done building the range table and jointree */
597 qry->rtable = pstate->p_rtable;
598 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
600 qry->hasSubLinks = pstate->p_hasSubLinks;
601 /* aggregates not allowed (but subselects are okay) */
602 if (pstate->p_hasAggs)
604 (errcode(ERRCODE_GROUPING_ERROR),
605 errmsg("cannot use aggregate function in VALUES")));
611 * Prepare an INSERT row for assignment to the target table.
613 * The row might be either a VALUES row, or variables referencing a
617 transformInsertRow(ParseState *pstate, List *exprlist,
618 List *stmtcols, List *icolumns, List *attrnos)
626 * Check length of expr list. It must not have more expressions than
627 * there are target columns. We allow fewer, but only if no explicit
628 * columns list was given (the remaining columns are implicitly
629 * defaulted). Note we must check this *after* transformation because
630 * that could expand '*' into multiple items.
632 if (list_length(exprlist) > list_length(icolumns))
634 (errcode(ERRCODE_SYNTAX_ERROR),
635 errmsg("INSERT has more expressions than target columns")));
636 if (stmtcols != NIL &&
637 list_length(exprlist) < list_length(icolumns))
639 (errcode(ERRCODE_SYNTAX_ERROR),
640 errmsg("INSERT has more target columns than expressions")));
643 * Prepare columns for assignment to target table.
646 icols = list_head(icolumns);
647 attnos = list_head(attrnos);
648 foreach(lc, exprlist)
650 Expr *expr = (Expr *) lfirst(lc);
653 col = (ResTarget *) lfirst(icols);
654 Assert(IsA(col, ResTarget));
656 expr = transformAssignedExpr(pstate, expr,
662 result = lappend(result, expr);
664 icols = lnext(icols);
665 attnos = lnext(attnos);
673 * transformSelectStmt -
674 * transforms a Select Statement
676 * Note: this covers only cases with no set operations and no VALUES lists;
677 * see below for the other cases.
680 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
682 Query *qry = makeNode(Query);
686 qry->commandType = CMD_SELECT;
688 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
689 pstate->p_locking_clause = stmt->lockingClause;
691 /* process the FROM clause */
692 transformFromClause(pstate, stmt->fromClause);
694 /* transform targetlist */
695 qry->targetList = transformTargetList(pstate, stmt->targetList);
697 /* mark column origins */
698 markTargetListOrigins(pstate, qry->targetList);
700 /* transform WHERE */
701 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
704 * Initial processing of HAVING clause is just like WHERE clause.
706 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
710 * Transform sorting/grouping stuff. Do ORDER BY first because both
711 * transformGroupClause and transformDistinctClause need the results.
713 qry->sortClause = transformSortClause(pstate,
716 true /* fix unknowns */ );
718 qry->groupClause = transformGroupClause(pstate,
723 qry->distinctClause = transformDistinctClause(pstate,
724 stmt->distinctClause,
728 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
730 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
733 /* handle any SELECT INTO/CREATE TABLE AS spec */
734 if (stmt->intoClause)
736 qry->intoClause = stmt->intoClause;
737 if (stmt->intoClause->colNames)
738 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
741 qry->rtable = pstate->p_rtable;
742 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
744 qry->hasSubLinks = pstate->p_hasSubLinks;
745 qry->hasAggs = pstate->p_hasAggs;
746 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
747 parseCheckAggregates(pstate, qry);
749 foreach(l, stmt->lockingClause)
751 transformLockingClause(qry, (LockingClause *) lfirst(l));
758 * transformValuesClause -
759 * transforms a VALUES clause that's being used as a standalone SELECT
761 * We build a Query containing a VALUES RTE, rather as if one had written
762 * SELECT * FROM (VALUES ...)
765 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
767 Query *qry = makeNode(Query);
768 List *exprsLists = NIL;
769 List **coltype_lists = NULL;
770 Oid *coltypes = NULL;
771 int sublist_length = -1;
779 qry->commandType = CMD_SELECT;
781 /* Most SELECT stuff doesn't apply in a VALUES clause */
782 Assert(stmt->distinctClause == NIL);
783 Assert(stmt->targetList == NIL);
784 Assert(stmt->fromClause == NIL);
785 Assert(stmt->whereClause == NULL);
786 Assert(stmt->groupClause == NIL);
787 Assert(stmt->havingClause == NULL);
788 Assert(stmt->op == SETOP_NONE);
791 * For each row of VALUES, transform the raw expressions and gather type
792 * information. This is also a handy place to reject DEFAULT nodes, which
793 * the grammar allows for simplicity.
795 foreach(lc, stmt->valuesLists)
797 List *sublist = (List *) lfirst(lc);
799 /* Do basic expression transformation (same as a ROW() expr) */
800 sublist = transformExpressionList(pstate, sublist);
803 * All the sublists must be the same length, *after* transformation
804 * (which might expand '*' into multiple items). The VALUES RTE can't
805 * handle anything different.
807 if (sublist_length < 0)
809 /* Remember post-transformation length of first sublist */
810 sublist_length = list_length(sublist);
811 /* and allocate arrays for column-type info */
812 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
813 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
815 else if (sublist_length != list_length(sublist))
818 (errcode(ERRCODE_SYNTAX_ERROR),
819 errmsg("VALUES lists must all be the same length")));
822 exprsLists = lappend(exprsLists, sublist);
825 foreach(lc2, sublist)
827 Node *col = (Node *) lfirst(lc2);
829 if (IsA(col, SetToDefault))
831 (errcode(ERRCODE_SYNTAX_ERROR),
832 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
833 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
839 * Now resolve the common types of the columns, and coerce everything to
842 for (i = 0; i < sublist_length; i++)
844 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
848 foreach(lc, exprsLists)
850 List *sublist = (List *) lfirst(lc);
851 List *newsublist = NIL;
854 foreach(lc2, sublist)
856 Node *col = (Node *) lfirst(lc2);
858 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
859 newsublist = lappend(newsublist, col);
863 newExprsLists = lappend(newExprsLists, newsublist);
867 * Generate the VALUES RTE
869 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
870 rtr = makeNode(RangeTblRef);
871 /* assume new rte is at end */
872 rtr->rtindex = list_length(pstate->p_rtable);
873 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
874 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
875 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
878 * Generate a targetlist as though expanding "*"
880 Assert(pstate->p_next_resno == 1);
881 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
884 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
887 qry->sortClause = transformSortClause(pstate,
890 true /* fix unknowns */ );
892 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
894 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
897 if (stmt->lockingClause)
899 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
900 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
902 /* handle any CREATE TABLE AS spec */
903 if (stmt->intoClause)
905 qry->intoClause = stmt->intoClause;
906 if (stmt->intoClause->colNames)
907 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
911 * There mustn't have been any table references in the expressions, else
912 * strange things would happen, like Cartesian products of those tables
913 * with the VALUES list. We have to check this after parsing ORDER BY et
914 * al since those could insert more junk.
916 if (list_length(pstate->p_joinlist) != 1)
918 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
919 errmsg("VALUES must not contain table references")));
922 * Another thing we can't currently support is NEW/OLD references in rules
923 * --- seems we'd need something like SQL99's LATERAL construct to ensure
924 * that the values would be available while evaluating the VALUES RTE.
925 * This is a shame. FIXME
927 if (list_length(pstate->p_rtable) != 1 &&
928 contain_vars_of_level((Node *) newExprsLists, 0))
930 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
931 errmsg("VALUES must not contain OLD or NEW references"),
932 errhint("Use SELECT ... UNION ALL ... instead.")));
934 qry->rtable = pstate->p_rtable;
935 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
937 qry->hasSubLinks = pstate->p_hasSubLinks;
938 /* aggregates not allowed (but subselects are okay) */
939 if (pstate->p_hasAggs)
941 (errcode(ERRCODE_GROUPING_ERROR),
942 errmsg("cannot use aggregate function in VALUES")));
948 * transformSetOperationStmt -
949 * transforms a set-operations tree
951 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
952 * structure to it. We must transform each leaf SELECT and build up a top-
953 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
954 * The tree of set operations is converted into the setOperations field of
955 * the top-level Query.
958 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
960 Query *qry = makeNode(Query);
961 SelectStmt *leftmostSelect;
963 Query *leftmostQuery;
964 SetOperationStmt *sostmt;
965 List *intoColNames = NIL;
971 ListCell *left_tlist,
983 qry->commandType = CMD_SELECT;
986 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
987 * and from the top-level node.
989 leftmostSelect = stmt->larg;
990 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
991 leftmostSelect = leftmostSelect->larg;
992 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
993 leftmostSelect->larg == NULL);
994 if (leftmostSelect->intoClause)
996 qry->intoClause = leftmostSelect->intoClause;
997 intoColNames = leftmostSelect->intoClause->colNames;
1000 /* clear this to prevent complaints in transformSetOperationTree() */
1001 leftmostSelect->intoClause = NULL;
1004 * These are not one-time, exactly, but we want to process them here and
1005 * not let transformSetOperationTree() see them --- else it'll just
1006 * recurse right back here!
1008 sortClause = stmt->sortClause;
1009 limitOffset = stmt->limitOffset;
1010 limitCount = stmt->limitCount;
1011 lockingClause = stmt->lockingClause;
1013 stmt->sortClause = NIL;
1014 stmt->limitOffset = NULL;
1015 stmt->limitCount = NULL;
1016 stmt->lockingClause = NIL;
1018 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1022 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1025 * Recursively transform the components of the tree.
1027 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1028 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1029 qry->setOperations = (Node *) sostmt;
1032 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1034 node = sostmt->larg;
1035 while (node && IsA(node, SetOperationStmt))
1036 node = ((SetOperationStmt *) node)->larg;
1037 Assert(node && IsA(node, RangeTblRef));
1038 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1039 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1040 Assert(leftmostQuery != NULL);
1043 * Generate dummy targetlist for outer query using column names of
1044 * leftmost select and common datatypes of topmost set operation. Also
1045 * make lists of the dummy vars and their names for use in parsing ORDER
1048 * Note: we use leftmostRTI as the varno of the dummy variables. It
1049 * shouldn't matter too much which RT index they have, as long as they
1050 * have one that corresponds to a real RT entry; else funny things may
1051 * happen when the tree is mashed by rule rewriting.
1053 qry->targetList = NIL;
1056 left_tlist = list_head(leftmostQuery->targetList);
1058 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1060 Oid colType = lfirst_oid(lct);
1061 int32 colTypmod = lfirst_int(lcm);
1062 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1067 Assert(!lefttle->resjunk);
1068 colName = pstrdup(lefttle->resname);
1069 expr = (Expr *) makeVar(leftmostRTI,
1074 tle = makeTargetEntry(expr,
1075 (AttrNumber) pstate->p_next_resno++,
1078 qry->targetList = lappend(qry->targetList, tle);
1079 targetvars = lappend(targetvars, expr);
1080 targetnames = lappend(targetnames, makeString(colName));
1081 left_tlist = lnext(left_tlist);
1085 * As a first step towards supporting sort clauses that are expressions
1086 * using the output columns, generate a varnamespace entry that makes the
1087 * output columns visible. A Join RTE node is handy for this, since we
1088 * can easily control the Vars generated upon matches.
1090 * Note: we don't yet do anything useful with such cases, but at least
1091 * "ORDER BY upper(foo)" will draw the right error message rather than
1094 jrte = addRangeTableEntryForJoin(NULL,
1101 sv_rtable = pstate->p_rtable;
1102 pstate->p_rtable = list_make1(jrte);
1104 sv_relnamespace = pstate->p_relnamespace;
1105 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1107 sv_varnamespace = pstate->p_varnamespace;
1108 pstate->p_varnamespace = list_make1(jrte);
1111 * For now, we don't support resjunk sort clauses on the output of a
1112 * setOperation tree --- you can only use the SQL92-spec options of
1113 * selecting an output column by name or number. Enforce by checking that
1114 * transformSortClause doesn't add any items to tlist.
1116 tllen = list_length(qry->targetList);
1118 qry->sortClause = transformSortClause(pstate,
1121 false /* no unknowns expected */ );
1123 pstate->p_rtable = sv_rtable;
1124 pstate->p_relnamespace = sv_relnamespace;
1125 pstate->p_varnamespace = sv_varnamespace;
1127 if (tllen != list_length(qry->targetList))
1129 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1130 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1131 errdetail("Only result column names can be used, not expressions or functions."),
1132 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
1134 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1136 qry->limitCount = transformLimitClause(pstate, limitCount,
1140 * Handle SELECT INTO/CREATE TABLE AS.
1142 * Any column names from CREATE TABLE AS need to be attached to both the
1143 * top level and the leftmost subquery. We do not do this earlier because
1144 * we do *not* want sortClause processing to be affected.
1148 applyColumnNames(qry->targetList, intoColNames);
1149 applyColumnNames(leftmostQuery->targetList, intoColNames);
1152 qry->rtable = pstate->p_rtable;
1153 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1155 qry->hasSubLinks = pstate->p_hasSubLinks;
1156 qry->hasAggs = pstate->p_hasAggs;
1157 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1158 parseCheckAggregates(pstate, qry);
1160 foreach(l, lockingClause)
1162 transformLockingClause(qry, (LockingClause *) lfirst(l));
1169 * transformSetOperationTree
1170 * Recursively transform leaves and internal nodes of a set-op tree
1173 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
1177 Assert(stmt && IsA(stmt, SelectStmt));
1180 * Validity-check both leaf and internal SELECTs for disallowed ops.
1182 if (stmt->intoClause)
1184 (errcode(ERRCODE_SYNTAX_ERROR),
1185 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
1186 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1187 if (stmt->lockingClause)
1189 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1190 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1193 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1194 * clauses attached, we need to treat it like a leaf node to generate an
1195 * independent sub-Query tree. Otherwise, it can be represented by a
1196 * SetOperationStmt node underneath the parent Query.
1198 if (stmt->op == SETOP_NONE)
1200 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1205 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1206 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1207 stmt->lockingClause)
1215 /* Process leaf SELECT */
1217 char selectName[32];
1222 * Transform SelectStmt into a Query.
1224 * Note: previously transformed sub-queries don't affect the parsing
1225 * of this sub-query, because they are not in the toplevel pstate's
1228 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1231 * Check for bogus references to Vars on the current query level (but
1232 * upper-level references are okay). Normally this can't happen
1233 * because the namespace will be empty, but it could happen if we are
1236 if (pstate->p_relnamespace || pstate->p_varnamespace)
1238 if (contain_vars_of_level((Node *) selectQuery, 1))
1240 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1241 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
1245 * Make the leaf query be a subquery in the top-level rangetable.
1247 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1248 list_length(pstate->p_rtable) + 1);
1249 rte = addRangeTableEntryForSubquery(pstate,
1251 makeAlias(selectName, NIL),
1255 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1257 rtr = makeNode(RangeTblRef);
1258 /* assume new rte is at end */
1259 rtr->rtindex = list_length(pstate->p_rtable);
1260 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1261 return (Node *) rtr;
1265 /* Process an internal node (set operation node) */
1266 SetOperationStmt *op = makeNode(SetOperationStmt);
1275 const char *context;
1277 context = (stmt->op == SETOP_UNION ? "UNION" :
1278 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1282 op->all = stmt->all;
1285 * Recursively transform the child nodes.
1287 op->larg = transformSetOperationTree(pstate, stmt->larg);
1288 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
1291 * Verify that the two children have the same number of non-junk
1292 * columns, and determine the types of the merged output columns.
1294 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
1295 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
1296 if (list_length(lcoltypes) != list_length(rcoltypes))
1298 (errcode(ERRCODE_SYNTAX_ERROR),
1299 errmsg("each %s query must have the same number of columns",
1301 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
1302 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
1305 op->colTypmods = NIL;
1306 /* don't have a "foreach4", so chase two of the lists by hand */
1307 lcm = list_head(lcoltypmods);
1308 rcm = list_head(rcoltypmods);
1309 forboth(lct, lcoltypes, rct, rcoltypes)
1311 Oid lcoltype = lfirst_oid(lct);
1312 Oid rcoltype = lfirst_oid(rct);
1313 int32 lcoltypmod = lfirst_int(lcm);
1314 int32 rcoltypmod = lfirst_int(rcm);
1318 /* select common type, same as CASE et al */
1319 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
1321 /* if same type and same typmod, use typmod; else default */
1322 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1323 rescoltypmod = lcoltypmod;
1326 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1327 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1339 * Get output column types/typmods of an (already transformed) set-op node
1342 getSetColTypes(ParseState *pstate, Node *node,
1343 List **colTypes, List **colTypmods)
1347 if (IsA(node, RangeTblRef))
1349 RangeTblRef *rtr = (RangeTblRef *) node;
1350 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
1351 Query *selectQuery = rte->subquery;
1354 Assert(selectQuery != NULL);
1355 /* Get types of non-junk columns */
1356 foreach(tl, selectQuery->targetList)
1358 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1362 *colTypes = lappend_oid(*colTypes,
1363 exprType((Node *) tle->expr));
1364 *colTypmods = lappend_int(*colTypmods,
1365 exprTypmod((Node *) tle->expr));
1368 else if (IsA(node, SetOperationStmt))
1370 SetOperationStmt *op = (SetOperationStmt *) node;
1372 /* Result already computed during transformation of node */
1373 Assert(op->colTypes != NIL);
1374 *colTypes = op->colTypes;
1375 *colTypmods = op->colTypmods;
1378 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
1382 * Attach column names from a ColumnDef list to a TargetEntry list
1383 * (for CREATE TABLE AS)
1386 applyColumnNames(List *dst, List *src)
1391 src_item = list_head(src);
1393 foreach(dst_item, dst)
1395 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1398 /* junk targets don't count */
1402 /* fewer ColumnDefs than target entries is OK */
1403 if (src_item == NULL)
1406 s = (ColumnDef *) lfirst(src_item);
1407 src_item = lnext(src_item);
1409 d->resname = pstrdup(s->colname);
1412 /* more ColumnDefs than target entries is not OK */
1413 if (src_item != NULL)
1415 (errcode(ERRCODE_SYNTAX_ERROR),
1416 errmsg("CREATE TABLE AS specifies too many column names")));
1421 * transformUpdateStmt -
1422 * transforms an update statement
1425 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1427 Query *qry = makeNode(Query);
1429 ListCell *origTargetList;
1432 qry->commandType = CMD_UPDATE;
1433 pstate->p_is_update = true;
1435 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1436 interpretInhOption(stmt->relation->inhOpt),
1441 * the FROM clause is non-standard SQL syntax. We used to be able to do
1442 * this with REPLACE in POSTQUEL so we keep the feature.
1444 transformFromClause(pstate, stmt->fromClause);
1446 qry->targetList = transformTargetList(pstate, stmt->targetList);
1448 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1450 qry->returningList = transformReturningList(pstate, stmt->returningList);
1452 qry->rtable = pstate->p_rtable;
1453 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1455 qry->hasSubLinks = pstate->p_hasSubLinks;
1458 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1459 * an implementation point of view, this is forced because the implicit
1460 * ctid reference would otherwise be an ungrouped variable.)
1462 if (pstate->p_hasAggs)
1464 (errcode(ERRCODE_GROUPING_ERROR),
1465 errmsg("cannot use aggregate function in UPDATE")));
1468 * Now we are done with SELECT-like processing, and can get on with
1469 * transforming the target list to match the UPDATE target columns.
1472 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1473 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1474 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1476 /* Prepare non-junk columns for assignment to target table */
1477 origTargetList = list_head(stmt->targetList);
1479 foreach(tl, qry->targetList)
1481 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1482 ResTarget *origTarget;
1488 * Resjunk nodes need no additional processing, but be sure they
1489 * have resnos that do not match any target columns; else rewriter
1490 * or planner might get confused. They don't need a resname
1493 tle->resno = (AttrNumber) pstate->p_next_resno++;
1494 tle->resname = NULL;
1497 if (origTargetList == NULL)
1498 elog(ERROR, "UPDATE target count mismatch --- internal error");
1499 origTarget = (ResTarget *) lfirst(origTargetList);
1500 Assert(IsA(origTarget, ResTarget));
1502 attrno = attnameAttNum(pstate->p_target_relation,
1503 origTarget->name, true);
1504 if (attrno == InvalidAttrNumber)
1506 (errcode(ERRCODE_UNDEFINED_COLUMN),
1507 errmsg("column \"%s\" of relation \"%s\" does not exist",
1509 RelationGetRelationName(pstate->p_target_relation)),
1510 parser_errposition(pstate, origTarget->location)));
1512 updateTargetListEntry(pstate, tle, origTarget->name,
1514 origTarget->indirection,
1515 origTarget->location);
1517 origTargetList = lnext(origTargetList);
1519 if (origTargetList != NULL)
1520 elog(ERROR, "UPDATE target count mismatch --- internal error");
1526 * transformReturningList -
1527 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1530 transformReturningList(ParseState *pstate, List *returningList)
1533 int save_next_resno;
1537 if (returningList == NIL)
1538 return NIL; /* nothing to do */
1541 * We need to assign resnos starting at one in the RETURNING list. Save
1542 * and restore the main tlist's value of p_next_resno, just in case
1543 * someone looks at it later (probably won't happen).
1545 save_next_resno = pstate->p_next_resno;
1546 pstate->p_next_resno = 1;
1548 /* save other state so that we can detect disallowed stuff */
1549 save_hasAggs = pstate->p_hasAggs;
1550 pstate->p_hasAggs = false;
1551 length_rtable = list_length(pstate->p_rtable);
1553 /* transform RETURNING identically to a SELECT targetlist */
1554 rlist = transformTargetList(pstate, returningList);
1556 /* check for disallowed stuff */
1558 /* aggregates not allowed (but subselects are okay) */
1559 if (pstate->p_hasAggs)
1561 (errcode(ERRCODE_GROUPING_ERROR),
1562 errmsg("cannot use aggregate function in RETURNING")));
1564 /* no new relation references please */
1565 if (list_length(pstate->p_rtable) != length_rtable)
1567 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1568 errmsg("RETURNING cannot contain references to other relations")));
1570 /* mark column origins */
1571 markTargetListOrigins(pstate, rlist);
1574 pstate->p_next_resno = save_next_resno;
1575 pstate->p_hasAggs = save_hasAggs;
1582 * transformDeclareCursorStmt -
1583 * transform a DECLARE CURSOR Statement
1585 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1586 * significantly different from a SELECT) as far as parsing/rewriting/planning
1587 * are concerned, but it's not passed to the executor and so in that sense is
1588 * a utility statement. We transform it into a Query exactly as if it were
1589 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1590 * field to carry the cursor name and options.
1593 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1598 * Don't allow both SCROLL and NO SCROLL to be specified
1600 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1601 (stmt->options & CURSOR_OPT_NO_SCROLL))
1603 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1604 errmsg("cannot specify both SCROLL and NO SCROLL")));
1606 result = transformStmt(pstate, stmt->query);
1608 if (!IsA(result, Query) ||
1609 result->commandType != CMD_SELECT ||
1610 result->utilityStmt != NULL)
1611 elog(ERROR, "unexpected non-SELECT command in cursor statement");
1613 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1614 if (result->intoClause)
1616 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1617 errmsg("DECLARE CURSOR cannot specify INTO")));
1619 /* FOR UPDATE and WITH HOLD are not compatible */
1620 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1622 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1623 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1624 errdetail("Holdable cursors must be READ ONLY.")));
1626 /* FOR UPDATE and SCROLL are not compatible */
1627 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1629 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1630 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1631 errdetail("Scrollable cursors must be READ ONLY.")));
1633 /* FOR UPDATE and INSENSITIVE are not compatible */
1634 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1636 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1637 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1638 errdetail("Insensitive cursors must be READ ONLY.")));
1640 /* We won't need the raw querytree any more */
1643 result->utilityStmt = (Node *) stmt;
1650 * transformExplainStmt -
1651 * transform an EXPLAIN Statement
1653 * EXPLAIN is just like other utility statements in that we emit it as a
1654 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1655 * However, if p_variableparams is set, it could be that the client is
1656 * expecting us to resolve parameter types in something like
1657 * EXPLAIN SELECT * FROM tab WHERE col = $1
1658 * To deal with such cases, we run parse analysis and throw away the result;
1659 * this is a bit grotty but not worth contorting the rest of the system for.
1660 * (The approach we use for DECLARE CURSOR won't work because the statement
1661 * being explained isn't necessarily a SELECT, and in particular might rewrite
1662 * to multiple parsetrees.)
1665 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1669 if (pstate->p_variableparams)
1671 /* Since parse analysis scribbles on its input, copy the tree first! */
1672 (void) transformStmt(pstate, copyObject(stmt->query));
1675 /* Now return the untransformed command as a utility Query */
1676 result = makeNode(Query);
1677 result->commandType = CMD_UTILITY;
1678 result->utilityStmt = (Node *) stmt;
1684 /* exported so planner can check again after rewriting, query pullup, etc */
1686 CheckSelectLocking(Query *qry)
1688 if (qry->setOperations)
1690 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1691 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1692 if (qry->distinctClause != NIL)
1694 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1695 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1696 if (qry->groupClause != NIL)
1698 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1699 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1700 if (qry->havingQual != NULL)
1702 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1703 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1706 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1707 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1711 * Transform a FOR UPDATE/SHARE clause
1713 * This basically involves replacing names by integer relids.
1715 * NB: if you need to change this, see also markQueryForLocking()
1716 * in rewriteHandler.c.
1719 transformLockingClause(Query *qry, LockingClause *lc)
1721 List *lockedRels = lc->lockedRels;
1725 LockingClause *allrels;
1727 CheckSelectLocking(qry);
1729 /* make a clause we can pass down to subqueries to select all rels */
1730 allrels = makeNode(LockingClause);
1731 allrels->lockedRels = NIL; /* indicates all rels */
1732 allrels->forUpdate = lc->forUpdate;
1733 allrels->noWait = lc->noWait;
1735 if (lockedRels == NIL)
1737 /* all regular tables used in query */
1739 foreach(rt, qry->rtable)
1741 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1744 switch (rte->rtekind)
1747 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1748 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1753 * FOR UPDATE/SHARE of subquery is propagated to all of
1756 transformLockingClause(rte->subquery, allrels);
1759 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
1766 /* just the named tables */
1767 foreach(l, lockedRels)
1769 char *relname = strVal(lfirst(l));
1772 foreach(rt, qry->rtable)
1774 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1777 if (strcmp(rte->eref->aliasname, relname) == 0)
1779 switch (rte->rtekind)
1782 applyLockingClause(qry, i,
1783 lc->forUpdate, lc->noWait);
1784 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1789 * FOR UPDATE/SHARE of subquery is propagated to
1790 * all of subquery's rels
1792 transformLockingClause(rte->subquery, allrels);
1796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1797 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
1801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1802 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
1806 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1807 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
1811 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1812 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1815 elog(ERROR, "unrecognized RTE type: %d",
1816 (int) rte->rtekind);
1819 break; /* out of foreach loop */
1824 (errcode(ERRCODE_UNDEFINED_TABLE),
1825 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
1832 * Record locking info for a single rangetable item
1835 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
1839 /* Check for pre-existing entry for same rtindex */
1840 if ((rc = get_rowmark(qry, rtindex)) != NULL)
1843 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
1844 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
1845 * and exclusive lock at the same time; it'll end up being exclusive
1848 * We also consider that NOWAIT wins if it's specified both ways. This
1849 * is a bit more debatable but raising an error doesn't seem helpful.
1850 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
1851 * internally contains a plain FOR UPDATE spec.)
1853 rc->forUpdate |= forUpdate;
1854 rc->noWait |= noWait;
1858 /* Make a new RowMarkClause */
1859 rc = makeNode(RowMarkClause);
1861 rc->forUpdate = forUpdate;
1862 rc->noWait = noWait;
1863 qry->rowMarks = lappend(qry->rowMarks, rc);
1868 * Traverse a fully-analyzed tree to verify that parameter symbols
1869 * match their types. We need this because some Params might still
1870 * be UNKNOWN, if there wasn't anything to force their coercion,
1871 * and yet other instances seen later might have gotten coerced.
1874 check_parameter_resolution_walker(Node *node,
1875 check_parameter_resolution_context *context)
1879 if (IsA(node, Param))
1881 Param *param = (Param *) node;
1883 if (param->paramkind == PARAM_EXTERN)
1885 int paramno = param->paramid;
1887 if (paramno <= 0 || /* shouldn't happen, but... */
1888 paramno > context->numParams)
1890 (errcode(ERRCODE_UNDEFINED_PARAMETER),
1891 errmsg("there is no parameter $%d", paramno)));
1893 if (param->paramtype != context->paramTypes[paramno - 1])
1895 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1896 errmsg("could not determine data type of parameter $%d",
1901 if (IsA(node, Query))
1903 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1904 return query_tree_walker((Query *) node,
1905 check_parameter_resolution_walker,
1906 (void *) context, 0);
1908 return expression_tree_walker(node, check_parameter_resolution_walker,