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.376 2008/08/07 01:11:51 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_oper.h"
37 #include "parser/parse_relation.h"
38 #include "parser/parse_target.h"
39 #include "parser/parsetree.h"
40 #include "utils/rel.h"
47 } check_parameter_resolution_context;
50 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
51 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
52 static List *transformInsertRow(ParseState *pstate, List *exprlist,
53 List *stmtcols, List *icolumns, List *attrnos);
54 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
55 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
56 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
57 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
58 static void getSetColTypes(ParseState *pstate, Node *node,
59 List **colTypes, List **colTypmods);
60 static void applyColumnNames(List *dst, List *src);
61 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
62 static List *transformReturningList(ParseState *pstate, List *returningList);
63 static Query *transformDeclareCursorStmt(ParseState *pstate,
64 DeclareCursorStmt *stmt);
65 static Query *transformExplainStmt(ParseState *pstate,
67 static void transformLockingClause(Query *qry, LockingClause *lc);
68 static bool check_parameter_resolution_walker(Node *node,
69 check_parameter_resolution_context *context);
74 * Analyze a raw parse tree and transform it to Query form.
76 * Optionally, information about $n parameter types can be supplied.
77 * References to $n indexes not defined by paramTypes[] are disallowed.
79 * The result is a Query node. Optimizable statements require considerable
80 * transformation, while utility-type statements are simply hung off
81 * a dummy CMD_UTILITY Query node.
84 parse_analyze(Node *parseTree, const char *sourceText,
85 Oid *paramTypes, int numParams)
87 ParseState *pstate = make_parsestate(NULL);
90 Assert(sourceText != NULL); /* required as of 8.4 */
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 Assert(sourceText != NULL); /* required as of 8.4 */
120 pstate->p_sourcetext = sourceText;
121 pstate->p_paramtypes = *paramTypes;
122 pstate->p_numparams = *numParams;
123 pstate->p_variableparams = true;
125 query = transformStmt(pstate, parseTree);
127 *paramTypes = pstate->p_paramtypes;
128 *numParams = pstate->p_numparams;
130 free_parsestate(pstate);
132 /* make sure all is well with parameter types */
135 check_parameter_resolution_context context;
137 context.paramTypes = *paramTypes;
138 context.numParams = *numParams;
139 check_parameter_resolution_walker((Node *) query, &context);
147 * Entry point for recursively analyzing a sub-statement.
150 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
152 ParseState *pstate = make_parsestate(parentParseState);
155 query = transformStmt(pstate, parseTree);
157 free_parsestate(pstate);
164 * transform a Parse tree into a Query tree.
167 transformStmt(ParseState *pstate, Node *parseTree)
171 switch (nodeTag(parseTree))
174 * Optimizable statements
177 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
181 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
185 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
190 SelectStmt *n = (SelectStmt *) parseTree;
193 result = transformValuesClause(pstate, n);
194 else if (n->op == SETOP_NONE)
195 result = transformSelectStmt(pstate, n);
197 result = transformSetOperationStmt(pstate, n);
204 case T_DeclareCursorStmt:
205 result = transformDeclareCursorStmt(pstate,
206 (DeclareCursorStmt *) parseTree);
210 result = transformExplainStmt(pstate,
211 (ExplainStmt *) parseTree);
217 * other statements don't require any transformation; just return
218 * the original parsetree with a Query node plastered on top.
220 result = makeNode(Query);
221 result->commandType = CMD_UTILITY;
222 result->utilityStmt = (Node *) parseTree;
226 /* Mark as original query until we learn differently */
227 result->querySource = QSRC_ORIGINAL;
228 result->canSetTag = true;
234 * transformDeleteStmt -
235 * transforms a Delete Statement
238 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
240 Query *qry = makeNode(Query);
243 qry->commandType = CMD_DELETE;
245 /* set up range table with just the result rel */
246 qry->resultRelation = setTargetTable(pstate, stmt->relation,
247 interpretInhOption(stmt->relation->inhOpt),
251 qry->distinctClause = NIL;
254 * The USING clause is non-standard SQL syntax, and is equivalent in
255 * functionality to the FROM list that can be specified for UPDATE. The
256 * USING keyword is used rather than FROM because FROM is already a
257 * keyword in the DELETE syntax.
259 transformFromClause(pstate, stmt->usingClause);
261 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
263 qry->returningList = transformReturningList(pstate, stmt->returningList);
265 /* done building the range table and jointree */
266 qry->rtable = pstate->p_rtable;
267 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
269 qry->hasSubLinks = pstate->p_hasSubLinks;
270 qry->hasAggs = pstate->p_hasAggs;
271 if (pstate->p_hasAggs)
272 parseCheckAggregates(pstate, qry);
278 * transformInsertStmt -
279 * transform an Insert Statement
282 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
284 Query *qry = makeNode(Query);
285 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
286 List *exprList = NIL;
287 bool isGeneralSelect;
289 List *sub_relnamespace;
290 List *sub_varnamespace;
299 qry->commandType = CMD_INSERT;
300 pstate->p_is_insert = true;
303 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
304 * VALUES list, or general SELECT input. We special-case VALUES, both for
305 * efficiency and so we can handle DEFAULT specifications.
307 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
310 * If a non-nil rangetable/namespace was passed in, and we are doing
311 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
312 * SELECT. This can only happen if we are inside a CREATE RULE, and in
313 * that case we want the rule's OLD and NEW rtable entries to appear as
314 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
315 * The SELECT's joinlist is not affected however. We must do this before
316 * adding the target table to the INSERT's rtable.
320 sub_rtable = pstate->p_rtable;
321 pstate->p_rtable = NIL;
322 sub_relnamespace = pstate->p_relnamespace;
323 pstate->p_relnamespace = NIL;
324 sub_varnamespace = pstate->p_varnamespace;
325 pstate->p_varnamespace = NIL;
329 sub_rtable = NIL; /* not used, but keep compiler quiet */
330 sub_relnamespace = NIL;
331 sub_varnamespace = NIL;
335 * Must get write lock on INSERT target table before scanning SELECT, else
336 * we will grab the wrong kind of initial lock if the target table is also
337 * mentioned in the SELECT part. Note that the target table is not added
338 * to the joinlist or namespace.
340 qry->resultRelation = setTargetTable(pstate, stmt->relation,
341 false, false, ACL_INSERT);
343 /* Validate stmt->cols list, or build default list if no list given */
344 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
345 Assert(list_length(icolumns) == list_length(attrnos));
348 * Determine which variant of INSERT we have.
350 if (selectStmt == NULL)
353 * We have INSERT ... DEFAULT VALUES. We can handle this case by
354 * emitting an empty targetlist --- all columns will be defaulted when
355 * the planner expands the targetlist.
359 else if (isGeneralSelect)
362 * We make the sub-pstate a child of the outer pstate so that it can
363 * see any Param definitions supplied from above. Since the outer
364 * pstate's rtable and namespace are presently empty, there are no
365 * side-effects of exposing names the sub-SELECT shouldn't be able to
368 ParseState *sub_pstate = make_parsestate(pstate);
372 * Process the source SELECT.
374 * It is important that this be handled just like a standalone SELECT;
375 * otherwise the behavior of SELECT within INSERT might be different
376 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
377 * bugs of just that nature...)
379 sub_pstate->p_rtable = sub_rtable;
380 sub_pstate->p_relnamespace = sub_relnamespace;
381 sub_pstate->p_varnamespace = sub_varnamespace;
383 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
385 free_parsestate(sub_pstate);
387 /* The grammar should have produced a SELECT, but it might have INTO */
388 Assert(IsA(selectQuery, Query));
389 Assert(selectQuery->commandType == CMD_SELECT);
390 Assert(selectQuery->utilityStmt == NULL);
391 if (selectQuery->intoClause)
393 (errcode(ERRCODE_SYNTAX_ERROR),
394 errmsg("INSERT ... SELECT cannot specify INTO")));
397 * Make the source be a subquery in the INSERT's rangetable, and add
398 * it to the INSERT's joinlist.
400 rte = addRangeTableEntryForSubquery(pstate,
402 makeAlias("*SELECT*", NIL),
404 rtr = makeNode(RangeTblRef);
405 /* assume new rte is at end */
406 rtr->rtindex = list_length(pstate->p_rtable);
407 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
408 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
411 * Generate an expression list for the INSERT that selects all the
412 * non-resjunk columns from the subquery. (INSERT's tlist must be
413 * separate from the subquery's tlist because we may add columns,
414 * insert datatype coercions, etc.)
416 * HACK: unknown-type constants and params in the SELECT's targetlist
417 * are copied up as-is rather than being referenced as subquery
418 * outputs. This is to ensure that when we try to coerce them to
419 * the target column's datatype, the right things happen (see
420 * special cases in coerce_type). Otherwise, this fails:
421 * INSERT INTO foo SELECT 'bar', ... FROM baz
425 foreach(lc, selectQuery->targetList)
427 TargetEntry *tle = (TargetEntry *) lfirst(lc);
433 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
434 exprType((Node *) tle->expr) == UNKNOWNOID)
437 expr = (Expr *) makeVar(rtr->rtindex,
439 exprType((Node *) tle->expr),
440 exprTypmod((Node *) tle->expr),
442 exprList = lappend(exprList, expr);
445 /* Prepare row for assignment to target table */
446 exprList = transformInsertRow(pstate, exprList,
450 else if (list_length(selectStmt->valuesLists) > 1)
453 * Process INSERT ... VALUES with multiple VALUES sublists. We
454 * generate a VALUES RTE holding the transformed expression lists, and
455 * build up a targetlist containing Vars that reference the VALUES
458 List *exprsLists = NIL;
459 int sublist_length = -1;
461 foreach(lc, selectStmt->valuesLists)
463 List *sublist = (List *) lfirst(lc);
465 /* Do basic expression transformation (same as a ROW() expr) */
466 sublist = transformExpressionList(pstate, sublist);
469 * All the sublists must be the same length, *after*
470 * transformation (which might expand '*' into multiple items).
471 * The VALUES RTE can't handle anything different.
473 if (sublist_length < 0)
475 /* Remember post-transformation length of first sublist */
476 sublist_length = list_length(sublist);
478 else if (sublist_length != list_length(sublist))
481 (errcode(ERRCODE_SYNTAX_ERROR),
482 errmsg("VALUES lists must all be the same length")));
485 /* Prepare row for assignment to target table */
486 sublist = transformInsertRow(pstate, sublist,
490 exprsLists = lappend(exprsLists, sublist);
494 * There mustn't have been any table references in the expressions,
495 * else strange things would happen, like Cartesian products of those
496 * tables with the VALUES list ...
498 if (pstate->p_joinlist != NIL)
500 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
501 errmsg("VALUES must not contain table references")));
504 * Another thing we can't currently support is NEW/OLD references in
505 * rules --- seems we'd need something like SQL99's LATERAL construct
506 * to ensure that the values would be available while evaluating the
507 * VALUES RTE. This is a shame. FIXME
509 if (list_length(pstate->p_rtable) != 1 &&
510 contain_vars_of_level((Node *) exprsLists, 0))
512 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513 errmsg("VALUES must not contain OLD or NEW references"),
514 errhint("Use SELECT ... UNION ALL ... instead.")));
517 * Generate the VALUES RTE
519 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
520 rtr = makeNode(RangeTblRef);
521 /* assume new rte is at end */
522 rtr->rtindex = list_length(pstate->p_rtable);
523 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
524 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
527 * Generate list of Vars referencing the RTE
529 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
534 * Process INSERT ... VALUES with a single VALUES sublist.
535 * We treat this separately for efficiency and for historical
536 * compatibility --- specifically, allowing table references,
538 * INSERT INTO foo VALUES(bar.*)
540 * The sublist is just computed directly as the Query's targetlist,
541 * with no VALUES RTE. So it works just like SELECT without FROM.
544 List *valuesLists = selectStmt->valuesLists;
546 Assert(list_length(valuesLists) == 1);
548 /* Do basic expression transformation (same as a ROW() expr) */
549 exprList = transformExpressionList(pstate,
550 (List *) linitial(valuesLists));
552 /* Prepare row for assignment to target table */
553 exprList = transformInsertRow(pstate, exprList,
559 * Generate query's target list using the computed list of expressions.
561 qry->targetList = NIL;
562 icols = list_head(icolumns);
563 attnos = list_head(attrnos);
564 foreach(lc, exprList)
566 Expr *expr = (Expr *) lfirst(lc);
570 col = (ResTarget *) lfirst(icols);
571 Assert(IsA(col, ResTarget));
573 tle = makeTargetEntry(expr,
574 (AttrNumber) lfirst_int(attnos),
577 qry->targetList = lappend(qry->targetList, tle);
579 icols = lnext(icols);
580 attnos = lnext(attnos);
584 * If we have a RETURNING clause, we need to add the target relation to
585 * the query namespace before processing it, so that Var references in
586 * RETURNING will work. Also, remove any namespace entries added in a
587 * sub-SELECT or VALUES list.
589 if (stmt->returningList)
591 pstate->p_relnamespace = NIL;
592 pstate->p_varnamespace = NIL;
593 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
595 qry->returningList = transformReturningList(pstate,
596 stmt->returningList);
599 /* done building the range table and jointree */
600 qry->rtable = pstate->p_rtable;
601 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
603 qry->hasSubLinks = pstate->p_hasSubLinks;
604 /* aggregates not allowed (but subselects are okay) */
605 if (pstate->p_hasAggs)
607 (errcode(ERRCODE_GROUPING_ERROR),
608 errmsg("cannot use aggregate function in VALUES")));
614 * Prepare an INSERT row for assignment to the target table.
616 * The row might be either a VALUES row, or variables referencing a
620 transformInsertRow(ParseState *pstate, List *exprlist,
621 List *stmtcols, List *icolumns, List *attrnos)
629 * Check length of expr list. It must not have more expressions than
630 * there are target columns. We allow fewer, but only if no explicit
631 * columns list was given (the remaining columns are implicitly
632 * defaulted). Note we must check this *after* transformation because
633 * that could expand '*' into multiple items.
635 if (list_length(exprlist) > list_length(icolumns))
637 (errcode(ERRCODE_SYNTAX_ERROR),
638 errmsg("INSERT has more expressions than target columns")));
639 if (stmtcols != NIL &&
640 list_length(exprlist) < list_length(icolumns))
642 (errcode(ERRCODE_SYNTAX_ERROR),
643 errmsg("INSERT has more target columns than expressions")));
646 * Prepare columns for assignment to target table.
649 icols = list_head(icolumns);
650 attnos = list_head(attrnos);
651 foreach(lc, exprlist)
653 Expr *expr = (Expr *) lfirst(lc);
656 col = (ResTarget *) lfirst(icols);
657 Assert(IsA(col, ResTarget));
659 expr = transformAssignedExpr(pstate, expr,
665 result = lappend(result, expr);
667 icols = lnext(icols);
668 attnos = lnext(attnos);
676 * transformSelectStmt -
677 * transforms a Select Statement
679 * Note: this covers only cases with no set operations and no VALUES lists;
680 * see below for the other cases.
683 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
685 Query *qry = makeNode(Query);
689 qry->commandType = CMD_SELECT;
691 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
692 pstate->p_locking_clause = stmt->lockingClause;
694 /* process the FROM clause */
695 transformFromClause(pstate, stmt->fromClause);
697 /* transform targetlist */
698 qry->targetList = transformTargetList(pstate, stmt->targetList);
700 /* mark column origins */
701 markTargetListOrigins(pstate, qry->targetList);
703 /* transform WHERE */
704 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
707 * Initial processing of HAVING clause is just like WHERE clause.
709 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
713 * Transform sorting/grouping stuff. Do ORDER BY first because both
714 * transformGroupClause and transformDistinctClause need the results.
715 * Note that these functions can also change the targetList, so it's
716 * passed to them by reference.
718 qry->sortClause = transformSortClause(pstate,
721 true /* fix unknowns */ );
723 qry->groupClause = transformGroupClause(pstate,
728 if (stmt->distinctClause == NIL)
730 qry->distinctClause = NIL;
731 qry->hasDistinctOn = false;
733 else if (linitial(stmt->distinctClause) == NULL)
735 /* We had SELECT DISTINCT */
736 qry->distinctClause = transformDistinctClause(pstate,
739 qry->hasDistinctOn = false;
743 /* We had SELECT DISTINCT ON */
744 qry->distinctClause = transformDistinctOnClause(pstate,
745 stmt->distinctClause,
748 qry->hasDistinctOn = true;
751 /* transform LIMIT */
752 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
754 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
757 /* handle any SELECT INTO/CREATE TABLE AS spec */
758 if (stmt->intoClause)
760 qry->intoClause = stmt->intoClause;
761 if (stmt->intoClause->colNames)
762 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
765 qry->rtable = pstate->p_rtable;
766 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
768 qry->hasSubLinks = pstate->p_hasSubLinks;
769 qry->hasAggs = pstate->p_hasAggs;
770 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
771 parseCheckAggregates(pstate, qry);
773 foreach(l, stmt->lockingClause)
775 transformLockingClause(qry, (LockingClause *) lfirst(l));
782 * transformValuesClause -
783 * transforms a VALUES clause that's being used as a standalone SELECT
785 * We build a Query containing a VALUES RTE, rather as if one had written
786 * SELECT * FROM (VALUES ...)
789 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
791 Query *qry = makeNode(Query);
792 List *exprsLists = NIL;
793 List **coltype_lists = NULL;
794 Oid *coltypes = NULL;
795 int sublist_length = -1;
803 qry->commandType = CMD_SELECT;
805 /* Most SELECT stuff doesn't apply in a VALUES clause */
806 Assert(stmt->distinctClause == NIL);
807 Assert(stmt->targetList == NIL);
808 Assert(stmt->fromClause == NIL);
809 Assert(stmt->whereClause == NULL);
810 Assert(stmt->groupClause == NIL);
811 Assert(stmt->havingClause == NULL);
812 Assert(stmt->op == SETOP_NONE);
815 * For each row of VALUES, transform the raw expressions and gather type
816 * information. This is also a handy place to reject DEFAULT nodes, which
817 * the grammar allows for simplicity.
819 foreach(lc, stmt->valuesLists)
821 List *sublist = (List *) lfirst(lc);
823 /* Do basic expression transformation (same as a ROW() expr) */
824 sublist = transformExpressionList(pstate, sublist);
827 * All the sublists must be the same length, *after* transformation
828 * (which might expand '*' into multiple items). The VALUES RTE can't
829 * handle anything different.
831 if (sublist_length < 0)
833 /* Remember post-transformation length of first sublist */
834 sublist_length = list_length(sublist);
835 /* and allocate arrays for column-type info */
836 coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
837 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
839 else if (sublist_length != list_length(sublist))
842 (errcode(ERRCODE_SYNTAX_ERROR),
843 errmsg("VALUES lists must all be the same length")));
846 exprsLists = lappend(exprsLists, sublist);
849 foreach(lc2, sublist)
851 Node *col = (Node *) lfirst(lc2);
853 if (IsA(col, SetToDefault))
855 (errcode(ERRCODE_SYNTAX_ERROR),
856 errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
857 coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
863 * Now resolve the common types of the columns, and coerce everything to
866 for (i = 0; i < sublist_length; i++)
868 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
872 foreach(lc, exprsLists)
874 List *sublist = (List *) lfirst(lc);
875 List *newsublist = NIL;
878 foreach(lc2, sublist)
880 Node *col = (Node *) lfirst(lc2);
882 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
883 newsublist = lappend(newsublist, col);
887 newExprsLists = lappend(newExprsLists, newsublist);
891 * Generate the VALUES RTE
893 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
894 rtr = makeNode(RangeTblRef);
895 /* assume new rte is at end */
896 rtr->rtindex = list_length(pstate->p_rtable);
897 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
898 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
899 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
902 * Generate a targetlist as though expanding "*"
904 Assert(pstate->p_next_resno == 1);
905 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
908 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
911 qry->sortClause = transformSortClause(pstate,
914 true /* fix unknowns */ );
916 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
918 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
921 if (stmt->lockingClause)
923 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
924 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
926 /* handle any CREATE TABLE AS spec */
927 if (stmt->intoClause)
929 qry->intoClause = stmt->intoClause;
930 if (stmt->intoClause->colNames)
931 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
935 * There mustn't have been any table references in the expressions, else
936 * strange things would happen, like Cartesian products of those tables
937 * with the VALUES list. We have to check this after parsing ORDER BY et
938 * al since those could insert more junk.
940 if (list_length(pstate->p_joinlist) != 1)
942 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
943 errmsg("VALUES must not contain table references")));
946 * Another thing we can't currently support is NEW/OLD references in rules
947 * --- seems we'd need something like SQL99's LATERAL construct to ensure
948 * that the values would be available while evaluating the VALUES RTE.
949 * This is a shame. FIXME
951 if (list_length(pstate->p_rtable) != 1 &&
952 contain_vars_of_level((Node *) newExprsLists, 0))
954 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
955 errmsg("VALUES must not contain OLD or NEW references"),
956 errhint("Use SELECT ... UNION ALL ... instead.")));
958 qry->rtable = pstate->p_rtable;
959 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
961 qry->hasSubLinks = pstate->p_hasSubLinks;
962 /* aggregates not allowed (but subselects are okay) */
963 if (pstate->p_hasAggs)
965 (errcode(ERRCODE_GROUPING_ERROR),
966 errmsg("cannot use aggregate function in VALUES")));
972 * transformSetOperationStmt -
973 * transforms a set-operations tree
975 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
976 * structure to it. We must transform each leaf SELECT and build up a top-
977 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
978 * The tree of set operations is converted into the setOperations field of
979 * the top-level Query.
982 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
984 Query *qry = makeNode(Query);
985 SelectStmt *leftmostSelect;
987 Query *leftmostQuery;
988 SetOperationStmt *sostmt;
989 List *intoColNames = NIL;
995 ListCell *left_tlist,
1004 RangeTblEntry *jrte;
1007 qry->commandType = CMD_SELECT;
1010 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1011 * and from the top-level node.
1013 leftmostSelect = stmt->larg;
1014 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1015 leftmostSelect = leftmostSelect->larg;
1016 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1017 leftmostSelect->larg == NULL);
1018 if (leftmostSelect->intoClause)
1020 qry->intoClause = leftmostSelect->intoClause;
1021 intoColNames = leftmostSelect->intoClause->colNames;
1024 /* clear this to prevent complaints in transformSetOperationTree() */
1025 leftmostSelect->intoClause = NULL;
1028 * These are not one-time, exactly, but we want to process them here and
1029 * not let transformSetOperationTree() see them --- else it'll just
1030 * recurse right back here!
1032 sortClause = stmt->sortClause;
1033 limitOffset = stmt->limitOffset;
1034 limitCount = stmt->limitCount;
1035 lockingClause = stmt->lockingClause;
1037 stmt->sortClause = NIL;
1038 stmt->limitOffset = NULL;
1039 stmt->limitCount = NULL;
1040 stmt->lockingClause = NIL;
1042 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1045 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1046 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1049 * Recursively transform the components of the tree.
1051 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1052 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1053 qry->setOperations = (Node *) sostmt;
1056 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1058 node = sostmt->larg;
1059 while (node && IsA(node, SetOperationStmt))
1060 node = ((SetOperationStmt *) node)->larg;
1061 Assert(node && IsA(node, RangeTblRef));
1062 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1063 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1064 Assert(leftmostQuery != NULL);
1067 * Generate dummy targetlist for outer query using column names of
1068 * leftmost select and common datatypes of topmost set operation. Also
1069 * make lists of the dummy vars and their names for use in parsing ORDER
1072 * Note: we use leftmostRTI as the varno of the dummy variables. It
1073 * shouldn't matter too much which RT index they have, as long as they
1074 * have one that corresponds to a real RT entry; else funny things may
1075 * happen when the tree is mashed by rule rewriting.
1077 qry->targetList = NIL;
1080 left_tlist = list_head(leftmostQuery->targetList);
1082 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1084 Oid colType = lfirst_oid(lct);
1085 int32 colTypmod = lfirst_int(lcm);
1086 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1091 Assert(!lefttle->resjunk);
1092 colName = pstrdup(lefttle->resname);
1093 expr = (Expr *) makeVar(leftmostRTI,
1098 tle = makeTargetEntry(expr,
1099 (AttrNumber) pstate->p_next_resno++,
1102 qry->targetList = lappend(qry->targetList, tle);
1103 targetvars = lappend(targetvars, expr);
1104 targetnames = lappend(targetnames, makeString(colName));
1105 left_tlist = lnext(left_tlist);
1109 * As a first step towards supporting sort clauses that are expressions
1110 * using the output columns, generate a varnamespace entry that makes the
1111 * output columns visible. A Join RTE node is handy for this, since we
1112 * can easily control the Vars generated upon matches.
1114 * Note: we don't yet do anything useful with such cases, but at least
1115 * "ORDER BY upper(foo)" will draw the right error message rather than
1118 jrte = addRangeTableEntryForJoin(NULL,
1125 sv_rtable = pstate->p_rtable;
1126 pstate->p_rtable = list_make1(jrte);
1128 sv_relnamespace = pstate->p_relnamespace;
1129 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1131 sv_varnamespace = pstate->p_varnamespace;
1132 pstate->p_varnamespace = list_make1(jrte);
1135 * For now, we don't support resjunk sort clauses on the output of a
1136 * setOperation tree --- you can only use the SQL92-spec options of
1137 * selecting an output column by name or number. Enforce by checking that
1138 * transformSortClause doesn't add any items to tlist.
1140 tllen = list_length(qry->targetList);
1142 qry->sortClause = transformSortClause(pstate,
1145 false /* no unknowns expected */ );
1147 pstate->p_rtable = sv_rtable;
1148 pstate->p_relnamespace = sv_relnamespace;
1149 pstate->p_varnamespace = sv_varnamespace;
1151 if (tllen != list_length(qry->targetList))
1153 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1154 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1155 errdetail("Only result column names can be used, not expressions or functions."),
1156 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
1158 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1160 qry->limitCount = transformLimitClause(pstate, limitCount,
1164 * Handle SELECT INTO/CREATE TABLE AS.
1166 * Any column names from CREATE TABLE AS need to be attached to both the
1167 * top level and the leftmost subquery. We do not do this earlier because
1168 * we do *not* want sortClause processing to be affected.
1172 applyColumnNames(qry->targetList, intoColNames);
1173 applyColumnNames(leftmostQuery->targetList, intoColNames);
1176 qry->rtable = pstate->p_rtable;
1177 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1179 qry->hasSubLinks = pstate->p_hasSubLinks;
1180 qry->hasAggs = pstate->p_hasAggs;
1181 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1182 parseCheckAggregates(pstate, qry);
1184 foreach(l, lockingClause)
1186 transformLockingClause(qry, (LockingClause *) lfirst(l));
1193 * transformSetOperationTree
1194 * Recursively transform leaves and internal nodes of a set-op tree
1197 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
1201 Assert(stmt && IsA(stmt, SelectStmt));
1204 * Validity-check both leaf and internal SELECTs for disallowed ops.
1206 if (stmt->intoClause)
1208 (errcode(ERRCODE_SYNTAX_ERROR),
1209 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
1210 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1211 if (stmt->lockingClause)
1213 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1214 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1217 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1218 * clauses attached, we need to treat it like a leaf node to generate an
1219 * independent sub-Query tree. Otherwise, it can be represented by a
1220 * SetOperationStmt node underneath the parent Query.
1222 if (stmt->op == SETOP_NONE)
1224 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1229 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1230 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1231 stmt->lockingClause)
1239 /* Process leaf SELECT */
1241 char selectName[32];
1246 * Transform SelectStmt into a Query.
1248 * Note: previously transformed sub-queries don't affect the parsing
1249 * of this sub-query, because they are not in the toplevel pstate's
1252 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1255 * Check for bogus references to Vars on the current query level (but
1256 * upper-level references are okay). Normally this can't happen
1257 * because the namespace will be empty, but it could happen if we are
1260 if (pstate->p_relnamespace || pstate->p_varnamespace)
1262 if (contain_vars_of_level((Node *) selectQuery, 1))
1264 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1265 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
1269 * Make the leaf query be a subquery in the top-level rangetable.
1271 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1272 list_length(pstate->p_rtable) + 1);
1273 rte = addRangeTableEntryForSubquery(pstate,
1275 makeAlias(selectName, NIL),
1279 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1281 rtr = makeNode(RangeTblRef);
1282 /* assume new rte is at end */
1283 rtr->rtindex = list_length(pstate->p_rtable);
1284 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1285 return (Node *) rtr;
1289 /* Process an internal node (set operation node) */
1290 SetOperationStmt *op = makeNode(SetOperationStmt);
1299 const char *context;
1301 context = (stmt->op == SETOP_UNION ? "UNION" :
1302 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1306 op->all = stmt->all;
1309 * Recursively transform the child nodes.
1311 op->larg = transformSetOperationTree(pstate, stmt->larg);
1312 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
1315 * Verify that the two children have the same number of non-junk
1316 * columns, and determine the types of the merged output columns.
1318 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
1319 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
1320 if (list_length(lcoltypes) != list_length(rcoltypes))
1322 (errcode(ERRCODE_SYNTAX_ERROR),
1323 errmsg("each %s query must have the same number of columns",
1325 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
1326 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
1329 op->colTypmods = NIL;
1330 op->groupClauses = NIL;
1331 /* don't have a "foreach4", so chase two of the lists by hand */
1332 lcm = list_head(lcoltypmods);
1333 rcm = list_head(rcoltypmods);
1334 forboth(lct, lcoltypes, rct, rcoltypes)
1336 Oid lcoltype = lfirst_oid(lct);
1337 Oid rcoltype = lfirst_oid(rct);
1338 int32 lcoltypmod = lfirst_int(lcm);
1339 int32 rcoltypmod = lfirst_int(rcm);
1343 /* select common type, same as CASE et al */
1344 rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
1346 /* if same type and same typmod, use typmod; else default */
1347 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1348 rescoltypmod = lcoltypmod;
1351 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1352 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1355 * For all cases except UNION ALL, identify the grouping operators
1356 * (and, if available, sorting operators) that will be used to
1357 * eliminate duplicates.
1359 if (op->op != SETOP_UNION || !op->all)
1361 SortGroupClause *grpcl = makeNode(SortGroupClause);
1365 /* determine the eqop and optional sortop */
1366 get_sort_group_operators(rescoltype,
1368 &sortop, &eqop, NULL);
1370 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1371 grpcl->tleSortGroupRef = 0;
1373 grpcl->sortop = sortop;
1374 grpcl->nulls_first = false; /* OK with or without sortop */
1376 op->groupClauses = lappend(op->groupClauses, grpcl);
1389 * Get output column types/typmods of an (already transformed) set-op node
1392 getSetColTypes(ParseState *pstate, Node *node,
1393 List **colTypes, List **colTypmods)
1397 if (IsA(node, RangeTblRef))
1399 RangeTblRef *rtr = (RangeTblRef *) node;
1400 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
1401 Query *selectQuery = rte->subquery;
1404 Assert(selectQuery != NULL);
1405 /* Get types of non-junk columns */
1406 foreach(tl, selectQuery->targetList)
1408 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1412 *colTypes = lappend_oid(*colTypes,
1413 exprType((Node *) tle->expr));
1414 *colTypmods = lappend_int(*colTypmods,
1415 exprTypmod((Node *) tle->expr));
1418 else if (IsA(node, SetOperationStmt))
1420 SetOperationStmt *op = (SetOperationStmt *) node;
1422 /* Result already computed during transformation of node */
1423 Assert(op->colTypes != NIL);
1424 *colTypes = op->colTypes;
1425 *colTypmods = op->colTypmods;
1428 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
1432 * Attach column names from a ColumnDef list to a TargetEntry list
1433 * (for CREATE TABLE AS)
1436 applyColumnNames(List *dst, List *src)
1441 src_item = list_head(src);
1443 foreach(dst_item, dst)
1445 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1448 /* junk targets don't count */
1452 /* fewer ColumnDefs than target entries is OK */
1453 if (src_item == NULL)
1456 s = (ColumnDef *) lfirst(src_item);
1457 src_item = lnext(src_item);
1459 d->resname = pstrdup(s->colname);
1462 /* more ColumnDefs than target entries is not OK */
1463 if (src_item != NULL)
1465 (errcode(ERRCODE_SYNTAX_ERROR),
1466 errmsg("CREATE TABLE AS specifies too many column names")));
1471 * transformUpdateStmt -
1472 * transforms an update statement
1475 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1477 Query *qry = makeNode(Query);
1479 ListCell *origTargetList;
1482 qry->commandType = CMD_UPDATE;
1483 pstate->p_is_update = true;
1485 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1486 interpretInhOption(stmt->relation->inhOpt),
1491 * the FROM clause is non-standard SQL syntax. We used to be able to do
1492 * this with REPLACE in POSTQUEL so we keep the feature.
1494 transformFromClause(pstate, stmt->fromClause);
1496 qry->targetList = transformTargetList(pstate, stmt->targetList);
1498 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1500 qry->returningList = transformReturningList(pstate, stmt->returningList);
1502 qry->rtable = pstate->p_rtable;
1503 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1505 qry->hasSubLinks = pstate->p_hasSubLinks;
1508 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1509 * an implementation point of view, this is forced because the implicit
1510 * ctid reference would otherwise be an ungrouped variable.)
1512 if (pstate->p_hasAggs)
1514 (errcode(ERRCODE_GROUPING_ERROR),
1515 errmsg("cannot use aggregate function in UPDATE")));
1518 * Now we are done with SELECT-like processing, and can get on with
1519 * transforming the target list to match the UPDATE target columns.
1522 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1523 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1524 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1526 /* Prepare non-junk columns for assignment to target table */
1527 origTargetList = list_head(stmt->targetList);
1529 foreach(tl, qry->targetList)
1531 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1532 ResTarget *origTarget;
1538 * Resjunk nodes need no additional processing, but be sure they
1539 * have resnos that do not match any target columns; else rewriter
1540 * or planner might get confused. They don't need a resname
1543 tle->resno = (AttrNumber) pstate->p_next_resno++;
1544 tle->resname = NULL;
1547 if (origTargetList == NULL)
1548 elog(ERROR, "UPDATE target count mismatch --- internal error");
1549 origTarget = (ResTarget *) lfirst(origTargetList);
1550 Assert(IsA(origTarget, ResTarget));
1552 attrno = attnameAttNum(pstate->p_target_relation,
1553 origTarget->name, true);
1554 if (attrno == InvalidAttrNumber)
1556 (errcode(ERRCODE_UNDEFINED_COLUMN),
1557 errmsg("column \"%s\" of relation \"%s\" does not exist",
1559 RelationGetRelationName(pstate->p_target_relation)),
1560 parser_errposition(pstate, origTarget->location)));
1562 updateTargetListEntry(pstate, tle, origTarget->name,
1564 origTarget->indirection,
1565 origTarget->location);
1567 origTargetList = lnext(origTargetList);
1569 if (origTargetList != NULL)
1570 elog(ERROR, "UPDATE target count mismatch --- internal error");
1576 * transformReturningList -
1577 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1580 transformReturningList(ParseState *pstate, List *returningList)
1583 int save_next_resno;
1587 if (returningList == NIL)
1588 return NIL; /* nothing to do */
1591 * We need to assign resnos starting at one in the RETURNING list. Save
1592 * and restore the main tlist's value of p_next_resno, just in case
1593 * someone looks at it later (probably won't happen).
1595 save_next_resno = pstate->p_next_resno;
1596 pstate->p_next_resno = 1;
1598 /* save other state so that we can detect disallowed stuff */
1599 save_hasAggs = pstate->p_hasAggs;
1600 pstate->p_hasAggs = false;
1601 length_rtable = list_length(pstate->p_rtable);
1603 /* transform RETURNING identically to a SELECT targetlist */
1604 rlist = transformTargetList(pstate, returningList);
1606 /* check for disallowed stuff */
1608 /* aggregates not allowed (but subselects are okay) */
1609 if (pstate->p_hasAggs)
1611 (errcode(ERRCODE_GROUPING_ERROR),
1612 errmsg("cannot use aggregate function in RETURNING")));
1614 /* no new relation references please */
1615 if (list_length(pstate->p_rtable) != length_rtable)
1617 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1618 errmsg("RETURNING cannot contain references to other relations")));
1620 /* mark column origins */
1621 markTargetListOrigins(pstate, rlist);
1624 pstate->p_next_resno = save_next_resno;
1625 pstate->p_hasAggs = save_hasAggs;
1632 * transformDeclareCursorStmt -
1633 * transform a DECLARE CURSOR Statement
1635 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1636 * significantly different from a SELECT) as far as parsing/rewriting/planning
1637 * are concerned, but it's not passed to the executor and so in that sense is
1638 * a utility statement. We transform it into a Query exactly as if it were
1639 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1640 * field to carry the cursor name and options.
1643 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1648 * Don't allow both SCROLL and NO SCROLL to be specified
1650 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1651 (stmt->options & CURSOR_OPT_NO_SCROLL))
1653 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1654 errmsg("cannot specify both SCROLL and NO SCROLL")));
1656 result = transformStmt(pstate, stmt->query);
1658 if (!IsA(result, Query) ||
1659 result->commandType != CMD_SELECT ||
1660 result->utilityStmt != NULL)
1661 elog(ERROR, "unexpected non-SELECT command in cursor statement");
1663 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1664 if (result->intoClause)
1666 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1667 errmsg("DECLARE CURSOR cannot specify INTO")));
1669 /* FOR UPDATE and WITH HOLD are not compatible */
1670 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1672 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1673 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1674 errdetail("Holdable cursors must be READ ONLY.")));
1676 /* FOR UPDATE and SCROLL are not compatible */
1677 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1679 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1680 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1681 errdetail("Scrollable cursors must be READ ONLY.")));
1683 /* FOR UPDATE and INSENSITIVE are not compatible */
1684 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1686 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1687 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1688 errdetail("Insensitive cursors must be READ ONLY.")));
1690 /* We won't need the raw querytree any more */
1693 result->utilityStmt = (Node *) stmt;
1700 * transformExplainStmt -
1701 * transform an EXPLAIN Statement
1703 * EXPLAIN is just like other utility statements in that we emit it as a
1704 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1705 * However, if p_variableparams is set, it could be that the client is
1706 * expecting us to resolve parameter types in something like
1707 * EXPLAIN SELECT * FROM tab WHERE col = $1
1708 * To deal with such cases, we run parse analysis and throw away the result;
1709 * this is a bit grotty but not worth contorting the rest of the system for.
1710 * (The approach we use for DECLARE CURSOR won't work because the statement
1711 * being explained isn't necessarily a SELECT, and in particular might rewrite
1712 * to multiple parsetrees.)
1715 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1719 if (pstate->p_variableparams)
1721 /* Since parse analysis scribbles on its input, copy the tree first! */
1722 (void) transformStmt(pstate, copyObject(stmt->query));
1725 /* Now return the untransformed command as a utility Query */
1726 result = makeNode(Query);
1727 result->commandType = CMD_UTILITY;
1728 result->utilityStmt = (Node *) stmt;
1734 /* exported so planner can check again after rewriting, query pullup, etc */
1736 CheckSelectLocking(Query *qry)
1738 if (qry->setOperations)
1740 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1741 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1742 if (qry->distinctClause != NIL)
1744 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1745 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1746 if (qry->groupClause != NIL)
1748 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1749 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1750 if (qry->havingQual != NULL)
1752 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1753 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1756 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1757 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1761 * Transform a FOR UPDATE/SHARE clause
1763 * This basically involves replacing names by integer relids.
1765 * NB: if you need to change this, see also markQueryForLocking()
1766 * in rewriteHandler.c.
1769 transformLockingClause(Query *qry, LockingClause *lc)
1771 List *lockedRels = lc->lockedRels;
1775 LockingClause *allrels;
1777 CheckSelectLocking(qry);
1779 /* make a clause we can pass down to subqueries to select all rels */
1780 allrels = makeNode(LockingClause);
1781 allrels->lockedRels = NIL; /* indicates all rels */
1782 allrels->forUpdate = lc->forUpdate;
1783 allrels->noWait = lc->noWait;
1785 if (lockedRels == NIL)
1787 /* all regular tables used in query */
1789 foreach(rt, qry->rtable)
1791 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1794 switch (rte->rtekind)
1797 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1798 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1803 * FOR UPDATE/SHARE of subquery is propagated to all of
1806 transformLockingClause(rte->subquery, allrels);
1809 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
1816 /* just the named tables */
1817 foreach(l, lockedRels)
1819 char *relname = strVal(lfirst(l));
1822 foreach(rt, qry->rtable)
1824 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1827 if (strcmp(rte->eref->aliasname, relname) == 0)
1829 switch (rte->rtekind)
1832 applyLockingClause(qry, i,
1833 lc->forUpdate, lc->noWait);
1834 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1839 * FOR UPDATE/SHARE of subquery is propagated to
1840 * all of subquery's rels
1842 transformLockingClause(rte->subquery, allrels);
1846 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1847 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
1851 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1852 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
1856 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1857 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
1861 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1862 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1865 elog(ERROR, "unrecognized RTE type: %d",
1866 (int) rte->rtekind);
1869 break; /* out of foreach loop */
1874 (errcode(ERRCODE_UNDEFINED_TABLE),
1875 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
1882 * Record locking info for a single rangetable item
1885 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
1889 /* Check for pre-existing entry for same rtindex */
1890 if ((rc = get_rowmark(qry, rtindex)) != NULL)
1893 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
1894 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
1895 * and exclusive lock at the same time; it'll end up being exclusive
1898 * We also consider that NOWAIT wins if it's specified both ways. This
1899 * is a bit more debatable but raising an error doesn't seem helpful.
1900 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
1901 * internally contains a plain FOR UPDATE spec.)
1903 rc->forUpdate |= forUpdate;
1904 rc->noWait |= noWait;
1908 /* Make a new RowMarkClause */
1909 rc = makeNode(RowMarkClause);
1911 rc->forUpdate = forUpdate;
1912 rc->noWait = noWait;
1913 qry->rowMarks = lappend(qry->rowMarks, rc);
1918 * Traverse a fully-analyzed tree to verify that parameter symbols
1919 * match their types. We need this because some Params might still
1920 * be UNKNOWN, if there wasn't anything to force their coercion,
1921 * and yet other instances seen later might have gotten coerced.
1924 check_parameter_resolution_walker(Node *node,
1925 check_parameter_resolution_context *context)
1929 if (IsA(node, Param))
1931 Param *param = (Param *) node;
1933 if (param->paramkind == PARAM_EXTERN)
1935 int paramno = param->paramid;
1937 if (paramno <= 0 || /* shouldn't happen, but... */
1938 paramno > context->numParams)
1940 (errcode(ERRCODE_UNDEFINED_PARAMETER),
1941 errmsg("there is no parameter $%d", paramno)));
1943 if (param->paramtype != context->paramTypes[paramno - 1])
1945 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
1946 errmsg("could not determine data type of parameter $%d",
1951 if (IsA(node, Query))
1953 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1954 return query_tree_walker((Query *) node,
1955 check_parameter_resolution_walker,
1956 (void *) context, 0);
1958 return expression_tree_walker(node, check_parameter_resolution_walker,