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-2008, 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.372 2008/06/19 00:46:04 alvherre 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"
39 #include "utils/rel.h"
46 } check_parameter_resolution_context;
49 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
50 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
51 static List *transformInsertRow(ParseState *pstate, List *exprlist,
52 List *stmtcols, List *icolumns, List *attrnos);
53 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
54 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
55 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
56 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
57 static void getSetColTypes(ParseState *pstate, Node *node,
58 List **colTypes, List **colTypmods);
59 static void applyColumnNames(List *dst, List *src);
60 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
61 static List *transformReturningList(ParseState *pstate, List *returningList);
62 static Query *transformDeclareCursorStmt(ParseState *pstate,
63 DeclareCursorStmt *stmt);
64 static Query *transformExplainStmt(ParseState *pstate,
66 static void transformLockingClause(Query *qry, LockingClause *lc);
67 static bool check_parameter_resolution_walker(Node *node,
68 check_parameter_resolution_context *context);
73 * Analyze a raw parse tree and transform it to Query form.
75 * If available, pass the source text from which the raw parse tree was
76 * generated; it's OK to pass NULL if this is not available.
78 * Optionally, information about $n parameter types can be supplied.
79 * References to $n indexes not defined by paramTypes[] are disallowed.
81 * The result is a Query node. Optimizable statements require considerable
82 * transformation, while utility-type statements are simply hung off
83 * a dummy CMD_UTILITY Query node.
86 parse_analyze(Node *parseTree, const char *sourceText,
87 Oid *paramTypes, int numParams)
89 ParseState *pstate = make_parsestate(NULL);
92 pstate->p_sourcetext = sourceText;
93 pstate->p_paramtypes = paramTypes;
94 pstate->p_numparams = numParams;
95 pstate->p_variableparams = false;
97 query = transformStmt(pstate, parseTree);
99 free_parsestate(pstate);
105 * parse_analyze_varparams
107 * This variant is used when it's okay to deduce information about $n
108 * symbol datatypes from context. The passed-in paramTypes[] array can
109 * be modified or enlarged (via repalloc).
112 parse_analyze_varparams(Node *parseTree, const char *sourceText,
113 Oid **paramTypes, int *numParams)
115 ParseState *pstate = make_parsestate(NULL);
118 pstate->p_sourcetext = sourceText;
119 pstate->p_paramtypes = *paramTypes;
120 pstate->p_numparams = *numParams;
121 pstate->p_variableparams = true;
123 query = transformStmt(pstate, parseTree);
125 *paramTypes = pstate->p_paramtypes;
126 *numParams = pstate->p_numparams;
128 free_parsestate(pstate);
130 /* make sure all is well with parameter types */
133 check_parameter_resolution_context context;
135 context.paramTypes = *paramTypes;
136 context.numParams = *numParams;
137 check_parameter_resolution_walker((Node *) query, &context);
145 * Entry point for recursively analyzing a sub-statement.
148 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
150 ParseState *pstate = make_parsestate(parentParseState);
153 query = transformStmt(pstate, parseTree);
155 free_parsestate(pstate);
162 * transform a Parse tree into a Query tree.
165 transformStmt(ParseState *pstate, Node *parseTree)
169 switch (nodeTag(parseTree))
172 * Optimizable statements
175 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
179 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
183 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
188 SelectStmt *n = (SelectStmt *) parseTree;
191 result = transformValuesClause(pstate, n);
192 else if (n->op == SETOP_NONE)
193 result = transformSelectStmt(pstate, n);
195 result = transformSetOperationStmt(pstate, n);
202 case T_DeclareCursorStmt:
203 result = transformDeclareCursorStmt(pstate,
204 (DeclareCursorStmt *) parseTree);
208 result = transformExplainStmt(pstate,
209 (ExplainStmt *) parseTree);
215 * other statements don't require any transformation; just return
216 * the original parsetree with a Query node plastered on top.
218 result = makeNode(Query);
219 result->commandType = CMD_UTILITY;
220 result->utilityStmt = (Node *) parseTree;
224 /* Mark as original query until we learn differently */
225 result->querySource = QSRC_ORIGINAL;
226 result->canSetTag = true;
232 * transformDeleteStmt -
233 * transforms a Delete Statement
236 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
238 Query *qry = makeNode(Query);
241 qry->commandType = CMD_DELETE;
243 /* set up range table with just the result rel */
244 qry->resultRelation = setTargetTable(pstate, stmt->relation,
245 interpretInhOption(stmt->relation->inhOpt),
249 qry->distinctClause = NIL;
252 * The USING clause is non-standard SQL syntax, and is equivalent in
253 * functionality to the FROM list that can be specified for UPDATE. The
254 * USING keyword is used rather than FROM because FROM is already a
255 * keyword in the DELETE syntax.
257 transformFromClause(pstate, stmt->usingClause);
259 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
261 qry->returningList = transformReturningList(pstate, stmt->returningList);
263 /* done building the range table and jointree */
264 qry->rtable = pstate->p_rtable;
265 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
267 qry->hasSubLinks = pstate->p_hasSubLinks;
268 qry->hasAggs = pstate->p_hasAggs;
269 if (pstate->p_hasAggs)
270 parseCheckAggregates(pstate, qry);
276 * transformInsertStmt -
277 * transform an Insert Statement
280 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
282 Query *qry = makeNode(Query);
283 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
284 List *exprList = NIL;
285 bool isGeneralSelect;
287 List *sub_relnamespace;
288 List *sub_varnamespace;
297 qry->commandType = CMD_INSERT;
298 pstate->p_is_insert = true;
301 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
302 * VALUES list, or general SELECT input. We special-case VALUES, both for
303 * efficiency and so we can handle DEFAULT specifications.
305 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
308 * If a non-nil rangetable/namespace was passed in, and we are doing
309 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
310 * SELECT. This can only happen if we are inside a CREATE RULE, and in
311 * that case we want the rule's OLD and NEW rtable entries to appear as
312 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
313 * The SELECT's joinlist is not affected however. We must do this before
314 * adding the target table to the INSERT's rtable.
318 sub_rtable = pstate->p_rtable;
319 pstate->p_rtable = NIL;
320 sub_relnamespace = pstate->p_relnamespace;
321 pstate->p_relnamespace = NIL;
322 sub_varnamespace = pstate->p_varnamespace;
323 pstate->p_varnamespace = NIL;
327 sub_rtable = NIL; /* not used, but keep compiler quiet */
328 sub_relnamespace = NIL;
329 sub_varnamespace = NIL;
333 * Must get write lock on INSERT target table before scanning SELECT, else
334 * we will grab the wrong kind of initial lock if the target table is also
335 * mentioned in the SELECT part. Note that the target table is not added
336 * to the joinlist or namespace.
338 qry->resultRelation = setTargetTable(pstate, stmt->relation,
339 false, false, ACL_INSERT);
341 /* Validate stmt->cols list, or build default list if no list given */
342 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
343 Assert(list_length(icolumns) == list_length(attrnos));
346 * Determine which variant of INSERT we have.
348 if (selectStmt == NULL)
351 * We have INSERT ... DEFAULT VALUES. We can handle this case by
352 * emitting an empty targetlist --- all columns will be defaulted when
353 * the planner expands the targetlist.
357 else if (isGeneralSelect)
360 * We make the sub-pstate a child of the outer pstate so that it can
361 * see any Param definitions supplied from above. Since the outer
362 * pstate's rtable and namespace are presently empty, there are no
363 * side-effects of exposing names the sub-SELECT shouldn't be able to
366 ParseState *sub_pstate = make_parsestate(pstate);
370 * Process the source SELECT.
372 * It is important that this be handled just like a standalone SELECT;
373 * otherwise the behavior of SELECT within INSERT might be different
374 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
375 * bugs of just that nature...)
377 sub_pstate->p_rtable = sub_rtable;
378 sub_pstate->p_relnamespace = sub_relnamespace;
379 sub_pstate->p_varnamespace = sub_varnamespace;
381 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
383 free_parsestate(sub_pstate);
385 /* The grammar should have produced a SELECT, but it might have INTO */
386 Assert(IsA(selectQuery, Query));
387 Assert(selectQuery->commandType == CMD_SELECT);
388 Assert(selectQuery->utilityStmt == NULL);
389 if (selectQuery->intoClause)
391 (errcode(ERRCODE_SYNTAX_ERROR),
392 errmsg("INSERT ... SELECT cannot specify INTO")));
395 * Make the source be a subquery in the INSERT's rangetable, and add
396 * it to the INSERT's joinlist.
398 rte = addRangeTableEntryForSubquery(pstate,
400 makeAlias("*SELECT*", NIL),
402 rtr = makeNode(RangeTblRef);
403 /* assume new rte is at end */
404 rtr->rtindex = list_length(pstate->p_rtable);
405 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
406 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
409 * Generate an expression list for the INSERT that selects all the
410 * non-resjunk columns from the subquery. (INSERT's tlist must be
411 * separate from the subquery's tlist because we may add columns,
412 * insert datatype coercions, etc.)
414 * HACK: unknown-type constants and params in the SELECT's targetlist
415 * are copied up as-is rather than being referenced as subquery
416 * outputs. This is to ensure that when we try to coerce them to
417 * the target column's datatype, the right things happen (see
418 * special cases in coerce_type). Otherwise, this fails:
419 * INSERT INTO foo SELECT 'bar', ... FROM baz
423 foreach(lc, selectQuery->targetList)
425 TargetEntry *tle = (TargetEntry *) lfirst(lc);
431 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
432 exprType((Node *) tle->expr) == UNKNOWNOID)
435 expr = (Expr *) makeVar(rtr->rtindex,
437 exprType((Node *) tle->expr),
438 exprTypmod((Node *) tle->expr),
440 exprList = lappend(exprList, expr);
443 /* Prepare row for assignment to target table */
444 exprList = transformInsertRow(pstate, exprList,
448 else if (list_length(selectStmt->valuesLists) > 1)
451 * Process INSERT ... VALUES with multiple VALUES sublists. We
452 * generate a VALUES RTE holding the transformed expression lists, and
453 * build up a targetlist containing Vars that reference the VALUES
456 List *exprsLists = NIL;
457 int sublist_length = -1;
459 foreach(lc, selectStmt->valuesLists)
461 List *sublist = (List *) lfirst(lc);
463 /* Do basic expression transformation (same as a ROW() expr) */
464 sublist = transformExpressionList(pstate, sublist);
467 * All the sublists must be the same length, *after*
468 * transformation (which might expand '*' into multiple items).
469 * The VALUES RTE can't handle anything different.
471 if (sublist_length < 0)
473 /* Remember post-transformation length of first sublist */
474 sublist_length = list_length(sublist);
476 else if (sublist_length != list_length(sublist))
479 (errcode(ERRCODE_SYNTAX_ERROR),
480 errmsg("VALUES lists must all be the same length")));
483 /* Prepare row for assignment to target table */
484 sublist = transformInsertRow(pstate, sublist,
488 exprsLists = lappend(exprsLists, sublist);
492 * There mustn't have been any table references in the expressions,
493 * else strange things would happen, like Cartesian products of those
494 * tables with the VALUES list ...
496 if (pstate->p_joinlist != NIL)
498 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
499 errmsg("VALUES must not contain table references")));
502 * Another thing we can't currently support is NEW/OLD references in
503 * rules --- seems we'd need something like SQL99's LATERAL construct
504 * to ensure that the values would be available while evaluating the
505 * VALUES RTE. This is a shame. FIXME
507 if (list_length(pstate->p_rtable) != 1 &&
508 contain_vars_of_level((Node *) exprsLists, 0))
510 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
511 errmsg("VALUES must not contain OLD or NEW references"),
512 errhint("Use SELECT ... UNION ALL ... instead.")));
515 * Generate the VALUES RTE
517 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
518 rtr = makeNode(RangeTblRef);
519 /* assume new rte is at end */
520 rtr->rtindex = list_length(pstate->p_rtable);
521 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
522 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
525 * Generate list of Vars referencing the RTE
527 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
532 * Process INSERT ... VALUES with a single VALUES sublist.
533 * We treat this separately for efficiency and for historical
534 * compatibility --- specifically, allowing table references,
536 * INSERT INTO foo VALUES(bar.*)
538 * The sublist is just computed directly as the Query's targetlist,
539 * with no VALUES RTE. So it works just like SELECT without FROM.
542 List *valuesLists = selectStmt->valuesLists;
544 Assert(list_length(valuesLists) == 1);
546 /* Do basic expression transformation (same as a ROW() expr) */
547 exprList = transformExpressionList(pstate,
548 (List *) linitial(valuesLists));
550 /* Prepare row for assignment to target table */
551 exprList = transformInsertRow(pstate, exprList,
557 * Generate query's target list using the computed list of expressions.
559 qry->targetList = NIL;
560 icols = list_head(icolumns);
561 attnos = list_head(attrnos);
562 foreach(lc, exprList)
564 Expr *expr = (Expr *) lfirst(lc);
568 col = (ResTarget *) lfirst(icols);
569 Assert(IsA(col, ResTarget));
571 tle = makeTargetEntry(expr,
572 (AttrNumber) lfirst_int(attnos),
575 qry->targetList = lappend(qry->targetList, tle);
577 icols = lnext(icols);
578 attnos = lnext(attnos);
582 * If we have a RETURNING clause, we need to add the target relation to
583 * the query namespace before processing it, so that Var references in
584 * RETURNING will work. Also, remove any namespace entries added in a
585 * sub-SELECT or VALUES list.
587 if (stmt->returningList)
589 pstate->p_relnamespace = NIL;
590 pstate->p_varnamespace = NIL;
591 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
593 qry->returningList = transformReturningList(pstate,
594 stmt->returningList);
597 /* done building the range table and jointree */
598 qry->rtable = pstate->p_rtable;
599 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
601 qry->hasSubLinks = pstate->p_hasSubLinks;
602 /* aggregates not allowed (but subselects are okay) */
603 if (pstate->p_hasAggs)
605 (errcode(ERRCODE_GROUPING_ERROR),
606 errmsg("cannot use aggregate function in VALUES")));
612 * Prepare an INSERT row for assignment to the target table.
614 * The row might be either a VALUES row, or variables referencing a
618 transformInsertRow(ParseState *pstate, List *exprlist,
619 List *stmtcols, List *icolumns, List *attrnos)
627 * Check length of expr list. It must not have more expressions than
628 * there are target columns. We allow fewer, but only if no explicit
629 * columns list was given (the remaining columns are implicitly
630 * defaulted). Note we must check this *after* transformation because
631 * that could expand '*' into multiple items.
633 if (list_length(exprlist) > list_length(icolumns))
635 (errcode(ERRCODE_SYNTAX_ERROR),
636 errmsg("INSERT has more expressions than target columns")));
637 if (stmtcols != NIL &&
638 list_length(exprlist) < list_length(icolumns))
640 (errcode(ERRCODE_SYNTAX_ERROR),
641 errmsg("INSERT has more target columns than expressions")));
644 * Prepare columns for assignment to target table.
647 icols = list_head(icolumns);
648 attnos = list_head(attrnos);
649 foreach(lc, exprlist)
651 Expr *expr = (Expr *) lfirst(lc);
654 col = (ResTarget *) lfirst(icols);
655 Assert(IsA(col, ResTarget));
657 expr = transformAssignedExpr(pstate, expr,
663 result = lappend(result, expr);
665 icols = lnext(icols);
666 attnos = lnext(attnos);
674 * transformSelectStmt -
675 * transforms a Select Statement
677 * Note: this covers only cases with no set operations and no VALUES lists;
678 * see below for the other cases.
681 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
683 Query *qry = makeNode(Query);
687 qry->commandType = CMD_SELECT;
689 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
690 pstate->p_locking_clause = stmt->lockingClause;
692 /* process the FROM clause */
693 transformFromClause(pstate, stmt->fromClause);
695 /* transform targetlist */
696 qry->targetList = transformTargetList(pstate, stmt->targetList);
698 /* mark column origins */
699 markTargetListOrigins(pstate, qry->targetList);
701 /* transform WHERE */
702 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
705 * Initial processing of HAVING clause is just like WHERE clause.
707 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
711 * Transform sorting/grouping stuff. Do ORDER BY first because both
712 * transformGroupClause and transformDistinctClause need the results.
714 qry->sortClause = transformSortClause(pstate,
717 true /* fix unknowns */ );
719 qry->groupClause = transformGroupClause(pstate,
724 qry->distinctClause = transformDistinctClause(pstate,
725 stmt->distinctClause,
729 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
731 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
734 /* handle any SELECT INTO/CREATE TABLE AS spec */
735 if (stmt->intoClause)
737 qry->intoClause = stmt->intoClause;
738 if (stmt->intoClause->colNames)
739 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
742 qry->rtable = pstate->p_rtable;
743 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
745 qry->hasSubLinks = pstate->p_hasSubLinks;
746 qry->hasAggs = pstate->p_hasAggs;
747 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
748 parseCheckAggregates(pstate, qry);
750 foreach(l, stmt->lockingClause)
752 transformLockingClause(qry, (LockingClause *) lfirst(l));
759 * transformValuesClause -
760 * transforms a VALUES clause that's being used as a standalone SELECT
762 * We build a Query containing a VALUES RTE, rather as if one had written
763 * SELECT * FROM (VALUES ...)
766 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
768 Query *qry = makeNode(Query);
769 List *exprsLists = NIL;
770 List **coltype_lists = NULL;
771 Oid *coltypes = NULL;
772 int sublist_length = -1;
780 qry->commandType = CMD_SELECT;
782 /* Most SELECT stuff doesn't apply in a VALUES clause */
783 Assert(stmt->distinctClause == NIL);
784 Assert(stmt->targetList == NIL);
785 Assert(stmt->fromClause == NIL);
786 Assert(stmt->whereClause == NULL);
787 Assert(stmt->groupClause == NIL);
788 Assert(stmt->havingClause == NULL);
789 Assert(stmt->op == SETOP_NONE);
792 * For each row of VALUES, transform the raw expressions and gather type
793 * information. This is also a handy place to reject DEFAULT nodes, which
794 * the grammar allows for simplicity.
796 foreach(lc, stmt->valuesLists)
798 List *sublist = (List *) lfirst(lc);
800 /* Do basic expression transformation (same as a ROW() expr) */
801 sublist = transformExpressionList(pstate, sublist);
804 * All the sublists must be the same length, *after* transformation
805 * (which might expand '*' into multiple items). The VALUES RTE can't
806 * handle anything different.
808 if (sublist_length < 0)
810 /* Remember post-transformation length of first sublist */
811 sublist_length = list_length(sublist);
812 /* and allocate arrays for column-type info */
813 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
814 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
816 else if (sublist_length != list_length(sublist))
819 (errcode(ERRCODE_SYNTAX_ERROR),
820 errmsg("VALUES lists must all be the same length")));
823 exprsLists = lappend(exprsLists, sublist);
826 foreach(lc2, sublist)
828 Node *col = (Node *) lfirst(lc2);
830 if (IsA(col, SetToDefault))
832 (errcode(ERRCODE_SYNTAX_ERROR),
833 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
834 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
840 * Now resolve the common types of the columns, and coerce everything to
843 for (i = 0; i < sublist_length; i++)
845 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
849 foreach(lc, exprsLists)
851 List *sublist = (List *) lfirst(lc);
852 List *newsublist = NIL;
855 foreach(lc2, sublist)
857 Node *col = (Node *) lfirst(lc2);
859 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
860 newsublist = lappend(newsublist, col);
864 newExprsLists = lappend(newExprsLists, newsublist);
868 * Generate the VALUES RTE
870 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
871 rtr = makeNode(RangeTblRef);
872 /* assume new rte is at end */
873 rtr->rtindex = list_length(pstate->p_rtable);
874 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
875 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
876 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
879 * Generate a targetlist as though expanding "*"
881 Assert(pstate->p_next_resno == 1);
882 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
885 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
888 qry->sortClause = transformSortClause(pstate,
891 true /* fix unknowns */ );
893 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
895 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
898 if (stmt->lockingClause)
900 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
901 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
903 /* handle any CREATE TABLE AS spec */
904 if (stmt->intoClause)
906 qry->intoClause = stmt->intoClause;
907 if (stmt->intoClause->colNames)
908 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
912 * There mustn't have been any table references in the expressions, else
913 * strange things would happen, like Cartesian products of those tables
914 * with the VALUES list. We have to check this after parsing ORDER BY et
915 * al since those could insert more junk.
917 if (list_length(pstate->p_joinlist) != 1)
919 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
920 errmsg("VALUES must not contain table references")));
923 * Another thing we can't currently support is NEW/OLD references in rules
924 * --- seems we'd need something like SQL99's LATERAL construct to ensure
925 * that the values would be available while evaluating the VALUES RTE.
926 * This is a shame. FIXME
928 if (list_length(pstate->p_rtable) != 1 &&
929 contain_vars_of_level((Node *) newExprsLists, 0))
931 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
932 errmsg("VALUES must not contain OLD or NEW references"),
933 errhint("Use SELECT ... UNION ALL ... instead.")));
935 qry->rtable = pstate->p_rtable;
936 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
938 qry->hasSubLinks = pstate->p_hasSubLinks;
939 /* aggregates not allowed (but subselects are okay) */
940 if (pstate->p_hasAggs)
942 (errcode(ERRCODE_GROUPING_ERROR),
943 errmsg("cannot use aggregate function in VALUES")));
949 * transformSetOperationStmt -
950 * transforms a set-operations tree
952 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
953 * structure to it. We must transform each leaf SELECT and build up a top-
954 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
955 * The tree of set operations is converted into the setOperations field of
956 * the top-level Query.
959 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
961 Query *qry = makeNode(Query);
962 SelectStmt *leftmostSelect;
964 Query *leftmostQuery;
965 SetOperationStmt *sostmt;
966 List *intoColNames = NIL;
972 ListCell *left_tlist,
984 qry->commandType = CMD_SELECT;
987 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
988 * and from the top-level node.
990 leftmostSelect = stmt->larg;
991 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
992 leftmostSelect = leftmostSelect->larg;
993 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
994 leftmostSelect->larg == NULL);
995 if (leftmostSelect->intoClause)
997 qry->intoClause = leftmostSelect->intoClause;
998 intoColNames = leftmostSelect->intoClause->colNames;
1001 /* clear this to prevent complaints in transformSetOperationTree() */
1002 leftmostSelect->intoClause = NULL;
1005 * These are not one-time, exactly, but we want to process them here and
1006 * not let transformSetOperationTree() see them --- else it'll just
1007 * recurse right back here!
1009 sortClause = stmt->sortClause;
1010 limitOffset = stmt->limitOffset;
1011 limitCount = stmt->limitCount;
1012 lockingClause = stmt->lockingClause;
1014 stmt->sortClause = NIL;
1015 stmt->limitOffset = NULL;
1016 stmt->limitCount = NULL;
1017 stmt->lockingClause = NIL;
1019 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1022 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1023 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1026 * Recursively transform the components of the tree.
1028 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1029 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1030 qry->setOperations = (Node *) sostmt;
1033 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1035 node = sostmt->larg;
1036 while (node && IsA(node, SetOperationStmt))
1037 node = ((SetOperationStmt *) node)->larg;
1038 Assert(node && IsA(node, RangeTblRef));
1039 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1040 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1041 Assert(leftmostQuery != NULL);
1044 * Generate dummy targetlist for outer query using column names of
1045 * leftmost select and common datatypes of topmost set operation. Also
1046 * make lists of the dummy vars and their names for use in parsing ORDER
1049 * Note: we use leftmostRTI as the varno of the dummy variables. It
1050 * shouldn't matter too much which RT index they have, as long as they
1051 * have one that corresponds to a real RT entry; else funny things may
1052 * happen when the tree is mashed by rule rewriting.
1054 qry->targetList = NIL;
1057 left_tlist = list_head(leftmostQuery->targetList);
1059 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1061 Oid colType = lfirst_oid(lct);
1062 int32 colTypmod = lfirst_int(lcm);
1063 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1068 Assert(!lefttle->resjunk);
1069 colName = pstrdup(lefttle->resname);
1070 expr = (Expr *) makeVar(leftmostRTI,
1075 tle = makeTargetEntry(expr,
1076 (AttrNumber) pstate->p_next_resno++,
1079 qry->targetList = lappend(qry->targetList, tle);
1080 targetvars = lappend(targetvars, expr);
1081 targetnames = lappend(targetnames, makeString(colName));
1082 left_tlist = lnext(left_tlist);
1086 * As a first step towards supporting sort clauses that are expressions
1087 * using the output columns, generate a varnamespace entry that makes the
1088 * output columns visible. A Join RTE node is handy for this, since we
1089 * can easily control the Vars generated upon matches.
1091 * Note: we don't yet do anything useful with such cases, but at least
1092 * "ORDER BY upper(foo)" will draw the right error message rather than
1095 jrte = addRangeTableEntryForJoin(NULL,
1102 sv_rtable = pstate->p_rtable;
1103 pstate->p_rtable = list_make1(jrte);
1105 sv_relnamespace = pstate->p_relnamespace;
1106 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1108 sv_varnamespace = pstate->p_varnamespace;
1109 pstate->p_varnamespace = list_make1(jrte);
1112 * For now, we don't support resjunk sort clauses on the output of a
1113 * setOperation tree --- you can only use the SQL92-spec options of
1114 * selecting an output column by name or number. Enforce by checking that
1115 * transformSortClause doesn't add any items to tlist.
1117 tllen = list_length(qry->targetList);
1119 qry->sortClause = transformSortClause(pstate,
1122 false /* no unknowns expected */ );
1124 pstate->p_rtable = sv_rtable;
1125 pstate->p_relnamespace = sv_relnamespace;
1126 pstate->p_varnamespace = sv_varnamespace;
1128 if (tllen != list_length(qry->targetList))
1130 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1131 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1132 errdetail("Only result column names can be used, not expressions or functions."),
1133 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
1135 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1137 qry->limitCount = transformLimitClause(pstate, limitCount,
1141 * Handle SELECT INTO/CREATE TABLE AS.
1143 * Any column names from CREATE TABLE AS need to be attached to both the
1144 * top level and the leftmost subquery. We do not do this earlier because
1145 * we do *not* want sortClause processing to be affected.
1149 applyColumnNames(qry->targetList, intoColNames);
1150 applyColumnNames(leftmostQuery->targetList, intoColNames);
1153 qry->rtable = pstate->p_rtable;
1154 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1156 qry->hasSubLinks = pstate->p_hasSubLinks;
1157 qry->hasAggs = pstate->p_hasAggs;
1158 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1159 parseCheckAggregates(pstate, qry);
1161 foreach(l, lockingClause)
1163 transformLockingClause(qry, (LockingClause *) lfirst(l));
1170 * transformSetOperationTree
1171 * Recursively transform leaves and internal nodes of a set-op tree
1174 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
1178 Assert(stmt && IsA(stmt, SelectStmt));
1181 * Validity-check both leaf and internal SELECTs for disallowed ops.
1183 if (stmt->intoClause)
1185 (errcode(ERRCODE_SYNTAX_ERROR),
1186 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
1187 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1188 if (stmt->lockingClause)
1190 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1191 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1194 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1195 * clauses attached, we need to treat it like a leaf node to generate an
1196 * independent sub-Query tree. Otherwise, it can be represented by a
1197 * SetOperationStmt node underneath the parent Query.
1199 if (stmt->op == SETOP_NONE)
1201 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1206 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1207 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1208 stmt->lockingClause)
1216 /* Process leaf SELECT */
1218 char selectName[32];
1223 * Transform SelectStmt into a Query.
1225 * Note: previously transformed sub-queries don't affect the parsing
1226 * of this sub-query, because they are not in the toplevel pstate's
1229 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1232 * Check for bogus references to Vars on the current query level (but
1233 * upper-level references are okay). Normally this can't happen
1234 * because the namespace will be empty, but it could happen if we are
1237 if (pstate->p_relnamespace || pstate->p_varnamespace)
1239 if (contain_vars_of_level((Node *) selectQuery, 1))
1241 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1242 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
1246 * Make the leaf query be a subquery in the top-level rangetable.
1248 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1249 list_length(pstate->p_rtable) + 1);
1250 rte = addRangeTableEntryForSubquery(pstate,
1252 makeAlias(selectName, NIL),
1256 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1258 rtr = makeNode(RangeTblRef);
1259 /* assume new rte is at end */
1260 rtr->rtindex = list_length(pstate->p_rtable);
1261 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1262 return (Node *) rtr;
1266 /* Process an internal node (set operation node) */
1267 SetOperationStmt *op = makeNode(SetOperationStmt);
1276 const char *context;
1278 context = (stmt->op == SETOP_UNION ? "UNION" :
1279 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1283 op->all = stmt->all;
1286 * Recursively transform the child nodes.
1288 op->larg = transformSetOperationTree(pstate, stmt->larg);
1289 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
1292 * Verify that the two children have the same number of non-junk
1293 * columns, and determine the types of the merged output columns.
1295 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
1296 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
1297 if (list_length(lcoltypes) != list_length(rcoltypes))
1299 (errcode(ERRCODE_SYNTAX_ERROR),
1300 errmsg("each %s query must have the same number of columns",
1302 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
1303 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
1306 op->colTypmods = NIL;
1307 /* don't have a "foreach4", so chase two of the lists by hand */
1308 lcm = list_head(lcoltypmods);
1309 rcm = list_head(rcoltypmods);
1310 forboth(lct, lcoltypes, rct, rcoltypes)
1312 Oid lcoltype = lfirst_oid(lct);
1313 Oid rcoltype = lfirst_oid(rct);
1314 int32 lcoltypmod = lfirst_int(lcm);
1315 int32 rcoltypmod = lfirst_int(rcm);
1319 /* select common type, same as CASE et al */
1320 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
1322 /* if same type and same typmod, use typmod; else default */
1323 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1324 rescoltypmod = lcoltypmod;
1327 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1328 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1340 * Get output column types/typmods of an (already transformed) set-op node
1343 getSetColTypes(ParseState *pstate, Node *node,
1344 List **colTypes, List **colTypmods)
1348 if (IsA(node, RangeTblRef))
1350 RangeTblRef *rtr = (RangeTblRef *) node;
1351 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
1352 Query *selectQuery = rte->subquery;
1355 Assert(selectQuery != NULL);
1356 /* Get types of non-junk columns */
1357 foreach(tl, selectQuery->targetList)
1359 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1363 *colTypes = lappend_oid(*colTypes,
1364 exprType((Node *) tle->expr));
1365 *colTypmods = lappend_int(*colTypmods,
1366 exprTypmod((Node *) tle->expr));
1369 else if (IsA(node, SetOperationStmt))
1371 SetOperationStmt *op = (SetOperationStmt *) node;
1373 /* Result already computed during transformation of node */
1374 Assert(op->colTypes != NIL);
1375 *colTypes = op->colTypes;
1376 *colTypmods = op->colTypmods;
1379 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
1383 * Attach column names from a ColumnDef list to a TargetEntry list
1384 * (for CREATE TABLE AS)
1387 applyColumnNames(List *dst, List *src)
1392 src_item = list_head(src);
1394 foreach(dst_item, dst)
1396 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1399 /* junk targets don't count */
1403 /* fewer ColumnDefs than target entries is OK */
1404 if (src_item == NULL)
1407 s = (ColumnDef *) lfirst(src_item);
1408 src_item = lnext(src_item);
1410 d->resname = pstrdup(s->colname);
1413 /* more ColumnDefs than target entries is not OK */
1414 if (src_item != NULL)
1416 (errcode(ERRCODE_SYNTAX_ERROR),
1417 errmsg("CREATE TABLE AS specifies too many column names")));
1422 * transformUpdateStmt -
1423 * transforms an update statement
1426 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1428 Query *qry = makeNode(Query);
1430 ListCell *origTargetList;
1433 qry->commandType = CMD_UPDATE;
1434 pstate->p_is_update = true;
1436 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1437 interpretInhOption(stmt->relation->inhOpt),
1442 * the FROM clause is non-standard SQL syntax. We used to be able to do
1443 * this with REPLACE in POSTQUEL so we keep the feature.
1445 transformFromClause(pstate, stmt->fromClause);
1447 qry->targetList = transformTargetList(pstate, stmt->targetList);
1449 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1451 qry->returningList = transformReturningList(pstate, stmt->returningList);
1453 qry->rtable = pstate->p_rtable;
1454 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1456 qry->hasSubLinks = pstate->p_hasSubLinks;
1459 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1460 * an implementation point of view, this is forced because the implicit
1461 * ctid reference would otherwise be an ungrouped variable.)
1463 if (pstate->p_hasAggs)
1465 (errcode(ERRCODE_GROUPING_ERROR),
1466 errmsg("cannot use aggregate function in UPDATE")));
1469 * Now we are done with SELECT-like processing, and can get on with
1470 * transforming the target list to match the UPDATE target columns.
1473 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1474 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1475 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1477 /* Prepare non-junk columns for assignment to target table */
1478 origTargetList = list_head(stmt->targetList);
1480 foreach(tl, qry->targetList)
1482 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1483 ResTarget *origTarget;
1489 * Resjunk nodes need no additional processing, but be sure they
1490 * have resnos that do not match any target columns; else rewriter
1491 * or planner might get confused. They don't need a resname
1494 tle->resno = (AttrNumber) pstate->p_next_resno++;
1495 tle->resname = NULL;
1498 if (origTargetList == NULL)
1499 elog(ERROR, "UPDATE target count mismatch --- internal error");
1500 origTarget = (ResTarget *) lfirst(origTargetList);
1501 Assert(IsA(origTarget, ResTarget));
1503 attrno = attnameAttNum(pstate->p_target_relation,
1504 origTarget->name, true);
1505 if (attrno == InvalidAttrNumber)
1507 (errcode(ERRCODE_UNDEFINED_COLUMN),
1508 errmsg("column \"%s\" of relation \"%s\" does not exist",
1510 RelationGetRelationName(pstate->p_target_relation)),
1511 parser_errposition(pstate, origTarget->location)));
1513 updateTargetListEntry(pstate, tle, origTarget->name,
1515 origTarget->indirection,
1516 origTarget->location);
1518 origTargetList = lnext(origTargetList);
1520 if (origTargetList != NULL)
1521 elog(ERROR, "UPDATE target count mismatch --- internal error");
1527 * transformReturningList -
1528 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1531 transformReturningList(ParseState *pstate, List *returningList)
1534 int save_next_resno;
1538 if (returningList == NIL)
1539 return NIL; /* nothing to do */
1542 * We need to assign resnos starting at one in the RETURNING list. Save
1543 * and restore the main tlist's value of p_next_resno, just in case
1544 * someone looks at it later (probably won't happen).
1546 save_next_resno = pstate->p_next_resno;
1547 pstate->p_next_resno = 1;
1549 /* save other state so that we can detect disallowed stuff */
1550 save_hasAggs = pstate->p_hasAggs;
1551 pstate->p_hasAggs = false;
1552 length_rtable = list_length(pstate->p_rtable);
1554 /* transform RETURNING identically to a SELECT targetlist */
1555 rlist = transformTargetList(pstate, returningList);
1557 /* check for disallowed stuff */
1559 /* aggregates not allowed (but subselects are okay) */
1560 if (pstate->p_hasAggs)
1562 (errcode(ERRCODE_GROUPING_ERROR),
1563 errmsg("cannot use aggregate function in RETURNING")));
1565 /* no new relation references please */
1566 if (list_length(pstate->p_rtable) != length_rtable)
1568 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1569 errmsg("RETURNING cannot contain references to other relations")));
1571 /* mark column origins */
1572 markTargetListOrigins(pstate, rlist);
1575 pstate->p_next_resno = save_next_resno;
1576 pstate->p_hasAggs = save_hasAggs;
1583 * transformDeclareCursorStmt -
1584 * transform a DECLARE CURSOR Statement
1586 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1587 * significantly different from a SELECT) as far as parsing/rewriting/planning
1588 * are concerned, but it's not passed to the executor and so in that sense is
1589 * a utility statement. We transform it into a Query exactly as if it were
1590 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1591 * field to carry the cursor name and options.
1594 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1599 * Don't allow both SCROLL and NO SCROLL to be specified
1601 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1602 (stmt->options & CURSOR_OPT_NO_SCROLL))
1604 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1605 errmsg("cannot specify both SCROLL and NO SCROLL")));
1607 result = transformStmt(pstate, stmt->query);
1609 if (!IsA(result, Query) ||
1610 result->commandType != CMD_SELECT ||
1611 result->utilityStmt != NULL)
1612 elog(ERROR, "unexpected non-SELECT command in cursor statement");
1614 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1615 if (result->intoClause)
1617 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1618 errmsg("DECLARE CURSOR cannot specify INTO")));
1620 /* FOR UPDATE and WITH HOLD are not compatible */
1621 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1623 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1624 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1625 errdetail("Holdable cursors must be READ ONLY.")));
1627 /* FOR UPDATE and SCROLL are not compatible */
1628 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1630 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1631 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1632 errdetail("Scrollable cursors must be READ ONLY.")));
1634 /* FOR UPDATE and INSENSITIVE are not compatible */
1635 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1637 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1638 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1639 errdetail("Insensitive cursors must be READ ONLY.")));
1641 /* We won't need the raw querytree any more */
1644 result->utilityStmt = (Node *) stmt;
1651 * transformExplainStmt -
1652 * transform an EXPLAIN Statement
1654 * EXPLAIN is just like other utility statements in that we emit it as a
1655 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1656 * However, if p_variableparams is set, it could be that the client is
1657 * expecting us to resolve parameter types in something like
1658 * EXPLAIN SELECT * FROM tab WHERE col = $1
1659 * To deal with such cases, we run parse analysis and throw away the result;
1660 * this is a bit grotty but not worth contorting the rest of the system for.
1661 * (The approach we use for DECLARE CURSOR won't work because the statement
1662 * being explained isn't necessarily a SELECT, and in particular might rewrite
1663 * to multiple parsetrees.)
1666 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1670 if (pstate->p_variableparams)
1672 /* Since parse analysis scribbles on its input, copy the tree first! */
1673 (void) transformStmt(pstate, copyObject(stmt->query));
1676 /* Now return the untransformed command as a utility Query */
1677 result = makeNode(Query);
1678 result->commandType = CMD_UTILITY;
1679 result->utilityStmt = (Node *) stmt;
1685 /* exported so planner can check again after rewriting, query pullup, etc */
1687 CheckSelectLocking(Query *qry)
1689 if (qry->setOperations)
1691 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1692 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1693 if (qry->distinctClause != NIL)
1695 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1696 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1697 if (qry->groupClause != NIL)
1699 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1700 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1701 if (qry->havingQual != NULL)
1703 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1704 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1707 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1708 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1712 * Transform a FOR UPDATE/SHARE clause
1714 * This basically involves replacing names by integer relids.
1716 * NB: if you need to change this, see also markQueryForLocking()
1717 * in rewriteHandler.c.
1720 transformLockingClause(Query *qry, LockingClause *lc)
1722 List *lockedRels = lc->lockedRels;
1726 LockingClause *allrels;
1728 CheckSelectLocking(qry);
1730 /* make a clause we can pass down to subqueries to select all rels */
1731 allrels = makeNode(LockingClause);
1732 allrels->lockedRels = NIL; /* indicates all rels */
1733 allrels->forUpdate = lc->forUpdate;
1734 allrels->noWait = lc->noWait;
1736 if (lockedRels == NIL)
1738 /* all regular tables used in query */
1740 foreach(rt, qry->rtable)
1742 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1745 switch (rte->rtekind)
1748 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1749 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1754 * FOR UPDATE/SHARE of subquery is propagated to all of
1757 transformLockingClause(rte->subquery, allrels);
1760 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
1767 /* just the named tables */
1768 foreach(l, lockedRels)
1770 char *relname = strVal(lfirst(l));
1773 foreach(rt, qry->rtable)
1775 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1778 if (strcmp(rte->eref->aliasname, relname) == 0)
1780 switch (rte->rtekind)
1783 applyLockingClause(qry, i,
1784 lc->forUpdate, lc->noWait);
1785 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1790 * FOR UPDATE/SHARE of subquery is propagated to
1791 * all of subquery's rels
1793 transformLockingClause(rte->subquery, allrels);
1797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1798 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
1802 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1803 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
1807 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1808 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
1812 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1813 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1816 elog(ERROR, "unrecognized RTE type: %d",
1817 (int) rte->rtekind);
1820 break; /* out of foreach loop */
1825 (errcode(ERRCODE_UNDEFINED_TABLE),
1826 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
1833 * Record locking info for a single rangetable item
1836 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
1840 /* Check for pre-existing entry for same rtindex */
1841 if ((rc = get_rowmark(qry, rtindex)) != NULL)
1844 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
1845 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
1846 * and exclusive lock at the same time; it'll end up being exclusive
1849 * We also consider that NOWAIT wins if it's specified both ways. This
1850 * is a bit more debatable but raising an error doesn't seem helpful.
1851 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
1852 * internally contains a plain FOR UPDATE spec.)
1854 rc->forUpdate |= forUpdate;
1855 rc->noWait |= noWait;
1859 /* Make a new RowMarkClause */
1860 rc = makeNode(RowMarkClause);
1862 rc->forUpdate = forUpdate;
1863 rc->noWait = noWait;
1864 qry->rowMarks = lappend(qry->rowMarks, rc);
1869 * Traverse a fully-analyzed tree to verify that parameter symbols
1870 * match their types. We need this because some Params might still
1871 * be UNKNOWN, if there wasn't anything to force their coercion,
1872 * and yet other instances seen later might have gotten coerced.
1875 check_parameter_resolution_walker(Node *node,
1876 check_parameter_resolution_context *context)
1880 if (IsA(node, Param))
1882 Param *param = (Param *) node;
1884 if (param->paramkind == PARAM_EXTERN)
1886 int paramno = param->paramid;
1888 if (paramno <= 0 || /* shouldn't happen, but... */
1889 paramno > context->numParams)
1891 (errcode(ERRCODE_UNDEFINED_PARAMETER),
1892 errmsg("there is no parameter $%d", paramno)));
1894 if (param->paramtype != context->paramTypes[paramno - 1])
1896 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1897 errmsg("could not determine data type of parameter $%d",
1902 if (IsA(node, Query))
1904 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1905 return query_tree_walker((Query *) node,
1906 check_parameter_resolution_walker,
1907 (void *) context, 0);
1909 return expression_tree_walker(node, check_parameter_resolution_walker,