Fix failure to ensure that a snapshot is available to datatype input functions
[PostgreSQL.git] / src / backend / parser / analyze.c
blobabd486185a69962b9651f490e58696caa5a7149d
1 /*-------------------------------------------------------------------------
3 * analyze.c
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$
22 *-------------------------------------------------------------------------
25 #include "postgres.h"
27 #include "catalog/pg_type.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/var.h"
31 #include "parser/analyze.h"
32 #include "parser/parse_agg.h"
33 #include "parser/parse_clause.h"
34 #include "parser/parse_coerce.h"
35 #include "parser/parse_cte.h"
36 #include "parser/parse_oper.h"
37 #include "parser/parse_relation.h"
38 #include "parser/parse_target.h"
39 #include "parser/parsetree.h"
40 #include "rewrite/rewriteManip.h"
41 #include "utils/rel.h"
44 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
45 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
46 static List *transformInsertRow(ParseState *pstate, List *exprlist,
47 List *stmtcols, List *icolumns, List *attrnos);
48 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
49 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
50 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
51 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
52 List **colInfo);
53 static void applyColumnNames(List *dst, List *src);
54 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
55 static List *transformReturningList(ParseState *pstate, List *returningList);
56 static Query *transformDeclareCursorStmt(ParseState *pstate,
57 DeclareCursorStmt *stmt);
58 static Query *transformExplainStmt(ParseState *pstate,
59 ExplainStmt *stmt);
60 static void transformLockingClause(ParseState *pstate,
61 Query *qry, LockingClause *lc);
62 static bool check_parameter_resolution_walker(Node *node, ParseState *pstate);
66 * parse_analyze
67 * Analyze a raw parse tree and transform it to Query form.
69 * Optionally, information about $n parameter types can be supplied.
70 * References to $n indexes not defined by paramTypes[] are disallowed.
72 * The result is a Query node. Optimizable statements require considerable
73 * transformation, while utility-type statements are simply hung off
74 * a dummy CMD_UTILITY Query node.
76 Query *
77 parse_analyze(Node *parseTree, const char *sourceText,
78 Oid *paramTypes, int numParams)
80 ParseState *pstate = make_parsestate(NULL);
81 Query *query;
83 Assert(sourceText != NULL); /* required as of 8.4 */
85 pstate->p_sourcetext = sourceText;
86 pstate->p_paramtypes = paramTypes;
87 pstate->p_numparams = numParams;
88 pstate->p_variableparams = false;
90 query = transformStmt(pstate, parseTree);
92 free_parsestate(pstate);
94 return query;
98 * parse_analyze_varparams
100 * This variant is used when it's okay to deduce information about $n
101 * symbol datatypes from context. The passed-in paramTypes[] array can
102 * be modified or enlarged (via repalloc).
104 Query *
105 parse_analyze_varparams(Node *parseTree, const char *sourceText,
106 Oid **paramTypes, int *numParams)
108 ParseState *pstate = make_parsestate(NULL);
109 Query *query;
111 Assert(sourceText != NULL); /* required as of 8.4 */
113 pstate->p_sourcetext = sourceText;
114 pstate->p_paramtypes = *paramTypes;
115 pstate->p_numparams = *numParams;
116 pstate->p_variableparams = true;
118 query = transformStmt(pstate, parseTree);
120 /* make sure all is well with parameter types */
121 if (pstate->p_numparams > 0)
122 check_parameter_resolution_walker((Node *) query, pstate);
124 *paramTypes = pstate->p_paramtypes;
125 *numParams = pstate->p_numparams;
127 free_parsestate(pstate);
129 return query;
133 * parse_sub_analyze
134 * Entry point for recursively analyzing a sub-statement.
136 Query *
137 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
139 ParseState *pstate = make_parsestate(parentParseState);
140 Query *query;
142 query = transformStmt(pstate, parseTree);
144 free_parsestate(pstate);
146 return query;
150 * transformStmt -
151 * transform a Parse tree into a Query tree.
153 Query *
154 transformStmt(ParseState *pstate, Node *parseTree)
156 Query *result;
158 switch (nodeTag(parseTree))
161 * Optimizable statements
163 case T_InsertStmt:
164 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
165 break;
167 case T_DeleteStmt:
168 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
169 break;
171 case T_UpdateStmt:
172 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
173 break;
175 case T_SelectStmt:
177 SelectStmt *n = (SelectStmt *) parseTree;
179 if (n->valuesLists)
180 result = transformValuesClause(pstate, n);
181 else if (n->op == SETOP_NONE)
182 result = transformSelectStmt(pstate, n);
183 else
184 result = transformSetOperationStmt(pstate, n);
186 break;
189 * Special cases
191 case T_DeclareCursorStmt:
192 result = transformDeclareCursorStmt(pstate,
193 (DeclareCursorStmt *) parseTree);
194 break;
196 case T_ExplainStmt:
197 result = transformExplainStmt(pstate,
198 (ExplainStmt *) parseTree);
199 break;
201 default:
204 * other statements don't require any transformation; just return
205 * the original parsetree with a Query node plastered on top.
207 result = makeNode(Query);
208 result->commandType = CMD_UTILITY;
209 result->utilityStmt = (Node *) parseTree;
210 break;
213 /* Mark as original query until we learn differently */
214 result->querySource = QSRC_ORIGINAL;
215 result->canSetTag = true;
217 return result;
221 * analyze_requires_snapshot
222 * Returns true if a snapshot must be set before doing parse analysis
223 * on the given raw parse tree.
225 * Classification here should match transformStmt().
227 bool
228 analyze_requires_snapshot(Node *parseTree)
230 bool result;
232 switch (nodeTag(parseTree))
235 * Optimizable statements
237 case T_InsertStmt:
238 case T_DeleteStmt:
239 case T_UpdateStmt:
240 case T_SelectStmt:
241 result = true;
242 break;
245 * Special cases
247 case T_DeclareCursorStmt:
248 /* yes, because it's analyzed just like SELECT */
249 result = true;
250 break;
252 case T_ExplainStmt:
254 * We only need a snapshot in varparams case, but it doesn't seem
255 * worth complicating this function's API to distinguish that.
257 result = true;
258 break;
260 default:
261 /* utility statements don't have any active parse analysis */
262 result = false;
263 break;
266 return result;
270 * transformDeleteStmt -
271 * transforms a Delete Statement
273 static Query *
274 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
276 Query *qry = makeNode(Query);
277 Node *qual;
279 qry->commandType = CMD_DELETE;
281 /* set up range table with just the result rel */
282 qry->resultRelation = setTargetTable(pstate, stmt->relation,
283 interpretInhOption(stmt->relation->inhOpt),
284 true,
285 ACL_DELETE);
287 qry->distinctClause = NIL;
290 * The USING clause is non-standard SQL syntax, and is equivalent in
291 * functionality to the FROM list that can be specified for UPDATE. The
292 * USING keyword is used rather than FROM because FROM is already a
293 * keyword in the DELETE syntax.
295 transformFromClause(pstate, stmt->usingClause);
297 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
299 qry->returningList = transformReturningList(pstate, stmt->returningList);
301 /* done building the range table and jointree */
302 qry->rtable = pstate->p_rtable;
303 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
305 qry->hasSubLinks = pstate->p_hasSubLinks;
306 qry->hasAggs = pstate->p_hasAggs;
307 if (pstate->p_hasAggs)
308 parseCheckAggregates(pstate, qry);
310 return qry;
314 * transformInsertStmt -
315 * transform an Insert Statement
317 static Query *
318 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
320 Query *qry = makeNode(Query);
321 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
322 List *exprList = NIL;
323 bool isGeneralSelect;
324 List *sub_rtable;
325 List *sub_relnamespace;
326 List *sub_varnamespace;
327 List *icolumns;
328 List *attrnos;
329 RangeTblEntry *rte;
330 RangeTblRef *rtr;
331 ListCell *icols;
332 ListCell *attnos;
333 ListCell *lc;
335 qry->commandType = CMD_INSERT;
336 pstate->p_is_insert = true;
339 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
340 * VALUES list, or general SELECT input. We special-case VALUES, both for
341 * efficiency and so we can handle DEFAULT specifications.
343 isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
346 * If a non-nil rangetable/namespace was passed in, and we are doing
347 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
348 * SELECT. This can only happen if we are inside a CREATE RULE, and in
349 * that case we want the rule's OLD and NEW rtable entries to appear as
350 * part of the SELECT's rtable, not as outer references for it. (Kluge!)
351 * The SELECT's joinlist is not affected however. We must do this before
352 * adding the target table to the INSERT's rtable.
354 if (isGeneralSelect)
356 sub_rtable = pstate->p_rtable;
357 pstate->p_rtable = NIL;
358 sub_relnamespace = pstate->p_relnamespace;
359 pstate->p_relnamespace = NIL;
360 sub_varnamespace = pstate->p_varnamespace;
361 pstate->p_varnamespace = NIL;
362 /* There can't be any outer WITH to worry about */
363 Assert(pstate->p_ctenamespace == NIL);
365 else
367 sub_rtable = NIL; /* not used, but keep compiler quiet */
368 sub_relnamespace = NIL;
369 sub_varnamespace = NIL;
373 * Must get write lock on INSERT target table before scanning SELECT, else
374 * we will grab the wrong kind of initial lock if the target table is also
375 * mentioned in the SELECT part. Note that the target table is not added
376 * to the joinlist or namespace.
378 qry->resultRelation = setTargetTable(pstate, stmt->relation,
379 false, false, ACL_INSERT);
381 /* Validate stmt->cols list, or build default list if no list given */
382 icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
383 Assert(list_length(icolumns) == list_length(attrnos));
386 * Determine which variant of INSERT we have.
388 if (selectStmt == NULL)
391 * We have INSERT ... DEFAULT VALUES. We can handle this case by
392 * emitting an empty targetlist --- all columns will be defaulted when
393 * the planner expands the targetlist.
395 exprList = NIL;
397 else if (isGeneralSelect)
400 * We make the sub-pstate a child of the outer pstate so that it can
401 * see any Param definitions supplied from above. Since the outer
402 * pstate's rtable and namespace are presently empty, there are no
403 * side-effects of exposing names the sub-SELECT shouldn't be able to
404 * see.
406 ParseState *sub_pstate = make_parsestate(pstate);
407 Query *selectQuery;
410 * Process the source SELECT.
412 * It is important that this be handled just like a standalone SELECT;
413 * otherwise the behavior of SELECT within INSERT might be different
414 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
415 * bugs of just that nature...)
417 sub_pstate->p_rtable = sub_rtable;
418 sub_pstate->p_relnamespace = sub_relnamespace;
419 sub_pstate->p_varnamespace = sub_varnamespace;
421 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
423 free_parsestate(sub_pstate);
425 /* The grammar should have produced a SELECT, but it might have INTO */
426 if (!IsA(selectQuery, Query) ||
427 selectQuery->commandType != CMD_SELECT ||
428 selectQuery->utilityStmt != NULL)
429 elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
430 if (selectQuery->intoClause)
431 ereport(ERROR,
432 (errcode(ERRCODE_SYNTAX_ERROR),
433 errmsg("INSERT ... SELECT cannot specify INTO"),
434 parser_errposition(pstate,
435 exprLocation((Node *) selectQuery->intoClause))));
438 * Make the source be a subquery in the INSERT's rangetable, and add
439 * it to the INSERT's joinlist.
441 rte = addRangeTableEntryForSubquery(pstate,
442 selectQuery,
443 makeAlias("*SELECT*", NIL),
444 false);
445 rtr = makeNode(RangeTblRef);
446 /* assume new rte is at end */
447 rtr->rtindex = list_length(pstate->p_rtable);
448 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
449 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
451 /*----------
452 * Generate an expression list for the INSERT that selects all the
453 * non-resjunk columns from the subquery. (INSERT's tlist must be
454 * separate from the subquery's tlist because we may add columns,
455 * insert datatype coercions, etc.)
457 * HACK: unknown-type constants and params in the SELECT's targetlist
458 * are copied up as-is rather than being referenced as subquery
459 * outputs. This is to ensure that when we try to coerce them to
460 * the target column's datatype, the right things happen (see
461 * special cases in coerce_type). Otherwise, this fails:
462 * INSERT INTO foo SELECT 'bar', ... FROM baz
463 *----------
465 exprList = NIL;
466 foreach(lc, selectQuery->targetList)
468 TargetEntry *tle = (TargetEntry *) lfirst(lc);
469 Expr *expr;
471 if (tle->resjunk)
472 continue;
473 if (tle->expr &&
474 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
475 exprType((Node *) tle->expr) == UNKNOWNOID)
476 expr = tle->expr;
477 else
479 Var *var = makeVar(rtr->rtindex,
480 tle->resno,
481 exprType((Node *) tle->expr),
482 exprTypmod((Node *) tle->expr),
484 var->location = exprLocation((Node *) tle->expr);
485 expr = (Expr *) var;
487 exprList = lappend(exprList, expr);
490 /* Prepare row for assignment to target table */
491 exprList = transformInsertRow(pstate, exprList,
492 stmt->cols,
493 icolumns, attrnos);
495 else if (list_length(selectStmt->valuesLists) > 1)
498 * Process INSERT ... VALUES with multiple VALUES sublists. We
499 * generate a VALUES RTE holding the transformed expression lists, and
500 * build up a targetlist containing Vars that reference the VALUES
501 * RTE.
503 List *exprsLists = NIL;
504 int sublist_length = -1;
506 /* process the WITH clause */
507 if (selectStmt->withClause)
509 qry->hasRecursive = selectStmt->withClause->recursive;
510 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
513 foreach(lc, selectStmt->valuesLists)
515 List *sublist = (List *) lfirst(lc);
517 /* Do basic expression transformation (same as a ROW() expr) */
518 sublist = transformExpressionList(pstate, sublist);
521 * All the sublists must be the same length, *after*
522 * transformation (which might expand '*' into multiple items).
523 * The VALUES RTE can't handle anything different.
525 if (sublist_length < 0)
527 /* Remember post-transformation length of first sublist */
528 sublist_length = list_length(sublist);
530 else if (sublist_length != list_length(sublist))
532 ereport(ERROR,
533 (errcode(ERRCODE_SYNTAX_ERROR),
534 errmsg("VALUES lists must all be the same length"),
535 parser_errposition(pstate,
536 exprLocation((Node *) sublist))));
539 /* Prepare row for assignment to target table */
540 sublist = transformInsertRow(pstate, sublist,
541 stmt->cols,
542 icolumns, attrnos);
544 exprsLists = lappend(exprsLists, sublist);
548 * There mustn't have been any table references in the expressions,
549 * else strange things would happen, like Cartesian products of those
550 * tables with the VALUES list ...
552 if (pstate->p_joinlist != NIL)
553 ereport(ERROR,
554 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
555 errmsg("VALUES must not contain table references"),
556 parser_errposition(pstate,
557 locate_var_of_level((Node *) exprsLists, 0))));
560 * Another thing we can't currently support is NEW/OLD references in
561 * rules --- seems we'd need something like SQL99's LATERAL construct
562 * to ensure that the values would be available while evaluating the
563 * VALUES RTE. This is a shame. FIXME
565 if (list_length(pstate->p_rtable) != 1 &&
566 contain_vars_of_level((Node *) exprsLists, 0))
567 ereport(ERROR,
568 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
569 errmsg("VALUES must not contain OLD or NEW references"),
570 errhint("Use SELECT ... UNION ALL ... instead."),
571 parser_errposition(pstate,
572 locate_var_of_level((Node *) exprsLists, 0))));
575 * Generate the VALUES RTE
577 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
578 rtr = makeNode(RangeTblRef);
579 /* assume new rte is at end */
580 rtr->rtindex = list_length(pstate->p_rtable);
581 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
582 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
585 * Generate list of Vars referencing the RTE
587 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
589 else
591 /*----------
592 * Process INSERT ... VALUES with a single VALUES sublist.
593 * We treat this separately for efficiency and for historical
594 * compatibility --- specifically, allowing table references,
595 * such as
596 * INSERT INTO foo VALUES(bar.*)
598 * The sublist is just computed directly as the Query's targetlist,
599 * with no VALUES RTE. So it works just like SELECT without FROM.
600 *----------
602 List *valuesLists = selectStmt->valuesLists;
604 Assert(list_length(valuesLists) == 1);
606 /* process the WITH clause */
607 if (selectStmt->withClause)
609 qry->hasRecursive = selectStmt->withClause->recursive;
610 qry->cteList = transformWithClause(pstate, selectStmt->withClause);
613 /* Do basic expression transformation (same as a ROW() expr) */
614 exprList = transformExpressionList(pstate,
615 (List *) linitial(valuesLists));
617 /* Prepare row for assignment to target table */
618 exprList = transformInsertRow(pstate, exprList,
619 stmt->cols,
620 icolumns, attrnos);
624 * Generate query's target list using the computed list of expressions.
626 qry->targetList = NIL;
627 icols = list_head(icolumns);
628 attnos = list_head(attrnos);
629 foreach(lc, exprList)
631 Expr *expr = (Expr *) lfirst(lc);
632 ResTarget *col;
633 TargetEntry *tle;
635 col = (ResTarget *) lfirst(icols);
636 Assert(IsA(col, ResTarget));
638 tle = makeTargetEntry(expr,
639 (AttrNumber) lfirst_int(attnos),
640 col->name,
641 false);
642 qry->targetList = lappend(qry->targetList, tle);
644 icols = lnext(icols);
645 attnos = lnext(attnos);
649 * If we have a RETURNING clause, we need to add the target relation to
650 * the query namespace before processing it, so that Var references in
651 * RETURNING will work. Also, remove any namespace entries added in a
652 * sub-SELECT or VALUES list.
654 if (stmt->returningList)
656 pstate->p_relnamespace = NIL;
657 pstate->p_varnamespace = NIL;
658 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
659 false, true, true);
660 qry->returningList = transformReturningList(pstate,
661 stmt->returningList);
664 /* done building the range table and jointree */
665 qry->rtable = pstate->p_rtable;
666 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
668 qry->hasSubLinks = pstate->p_hasSubLinks;
669 /* aggregates not allowed (but subselects are okay) */
670 if (pstate->p_hasAggs)
671 ereport(ERROR,
672 (errcode(ERRCODE_GROUPING_ERROR),
673 errmsg("cannot use aggregate function in VALUES"),
674 parser_errposition(pstate,
675 locate_agg_of_level((Node *) qry, 0))));
677 return qry;
681 * Prepare an INSERT row for assignment to the target table.
683 * The row might be either a VALUES row, or variables referencing a
684 * sub-SELECT output.
686 static List *
687 transformInsertRow(ParseState *pstate, List *exprlist,
688 List *stmtcols, List *icolumns, List *attrnos)
690 List *result;
691 ListCell *lc;
692 ListCell *icols;
693 ListCell *attnos;
696 * Check length of expr list. It must not have more expressions than
697 * there are target columns. We allow fewer, but only if no explicit
698 * columns list was given (the remaining columns are implicitly
699 * defaulted). Note we must check this *after* transformation because
700 * that could expand '*' into multiple items.
702 if (list_length(exprlist) > list_length(icolumns))
703 ereport(ERROR,
704 (errcode(ERRCODE_SYNTAX_ERROR),
705 errmsg("INSERT has more expressions than target columns"),
706 parser_errposition(pstate,
707 exprLocation(list_nth(exprlist,
708 list_length(icolumns))))));
709 if (stmtcols != NIL &&
710 list_length(exprlist) < list_length(icolumns))
711 ereport(ERROR,
712 (errcode(ERRCODE_SYNTAX_ERROR),
713 errmsg("INSERT has more target columns than expressions"),
714 parser_errposition(pstate,
715 exprLocation(list_nth(icolumns,
716 list_length(exprlist))))));
719 * Prepare columns for assignment to target table.
721 result = NIL;
722 icols = list_head(icolumns);
723 attnos = list_head(attrnos);
724 foreach(lc, exprlist)
726 Expr *expr = (Expr *) lfirst(lc);
727 ResTarget *col;
729 col = (ResTarget *) lfirst(icols);
730 Assert(IsA(col, ResTarget));
732 expr = transformAssignedExpr(pstate, expr,
733 col->name,
734 lfirst_int(attnos),
735 col->indirection,
736 col->location);
738 result = lappend(result, expr);
740 icols = lnext(icols);
741 attnos = lnext(attnos);
744 return result;
749 * transformSelectStmt -
750 * transforms a Select Statement
752 * Note: this covers only cases with no set operations and no VALUES lists;
753 * see below for the other cases.
755 static Query *
756 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
758 Query *qry = makeNode(Query);
759 Node *qual;
760 ListCell *l;
762 qry->commandType = CMD_SELECT;
764 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
765 pstate->p_locking_clause = stmt->lockingClause;
767 /* process the WITH clause */
768 if (stmt->withClause)
770 qry->hasRecursive = stmt->withClause->recursive;
771 qry->cteList = transformWithClause(pstate, stmt->withClause);
774 /* process the FROM clause */
775 transformFromClause(pstate, stmt->fromClause);
777 /* transform targetlist */
778 qry->targetList = transformTargetList(pstate, stmt->targetList);
780 /* mark column origins */
781 markTargetListOrigins(pstate, qry->targetList);
783 /* transform WHERE */
784 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
787 * Initial processing of HAVING clause is just like WHERE clause.
789 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
790 "HAVING");
793 * Transform sorting/grouping stuff. Do ORDER BY first because both
794 * transformGroupClause and transformDistinctClause need the results.
795 * Note that these functions can also change the targetList, so it's
796 * passed to them by reference.
798 qry->sortClause = transformSortClause(pstate,
799 stmt->sortClause,
800 &qry->targetList,
801 true /* fix unknowns */ );
803 qry->groupClause = transformGroupClause(pstate,
804 stmt->groupClause,
805 &qry->targetList,
806 qry->sortClause);
808 if (stmt->distinctClause == NIL)
810 qry->distinctClause = NIL;
811 qry->hasDistinctOn = false;
813 else if (linitial(stmt->distinctClause) == NULL)
815 /* We had SELECT DISTINCT */
816 qry->distinctClause = transformDistinctClause(pstate,
817 &qry->targetList,
818 qry->sortClause);
819 qry->hasDistinctOn = false;
821 else
823 /* We had SELECT DISTINCT ON */
824 qry->distinctClause = transformDistinctOnClause(pstate,
825 stmt->distinctClause,
826 &qry->targetList,
827 qry->sortClause);
828 qry->hasDistinctOn = true;
831 /* transform LIMIT */
832 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
833 "OFFSET");
834 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
835 "LIMIT");
837 /* handle any SELECT INTO/CREATE TABLE AS spec */
838 if (stmt->intoClause)
840 qry->intoClause = stmt->intoClause;
841 if (stmt->intoClause->colNames)
842 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
845 qry->rtable = pstate->p_rtable;
846 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
848 qry->hasSubLinks = pstate->p_hasSubLinks;
849 qry->hasAggs = pstate->p_hasAggs;
850 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
851 parseCheckAggregates(pstate, qry);
853 foreach(l, stmt->lockingClause)
855 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
858 return qry;
862 * transformValuesClause -
863 * transforms a VALUES clause that's being used as a standalone SELECT
865 * We build a Query containing a VALUES RTE, rather as if one had written
866 * SELECT * FROM (VALUES ...)
868 static Query *
869 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
871 Query *qry = makeNode(Query);
872 List *exprsLists = NIL;
873 List **colexprs = NULL;
874 Oid *coltypes = NULL;
875 int sublist_length = -1;
876 List *newExprsLists;
877 RangeTblEntry *rte;
878 RangeTblRef *rtr;
879 ListCell *lc;
880 ListCell *lc2;
881 int i;
883 qry->commandType = CMD_SELECT;
885 /* Most SELECT stuff doesn't apply in a VALUES clause */
886 Assert(stmt->distinctClause == NIL);
887 Assert(stmt->targetList == NIL);
888 Assert(stmt->fromClause == NIL);
889 Assert(stmt->whereClause == NULL);
890 Assert(stmt->groupClause == NIL);
891 Assert(stmt->havingClause == NULL);
892 Assert(stmt->op == SETOP_NONE);
894 /* process the WITH clause */
895 if (stmt->withClause)
897 qry->hasRecursive = stmt->withClause->recursive;
898 qry->cteList = transformWithClause(pstate, stmt->withClause);
902 * For each row of VALUES, transform the raw expressions and gather type
903 * information. This is also a handy place to reject DEFAULT nodes, which
904 * the grammar allows for simplicity.
906 foreach(lc, stmt->valuesLists)
908 List *sublist = (List *) lfirst(lc);
910 /* Do basic expression transformation (same as a ROW() expr) */
911 sublist = transformExpressionList(pstate, sublist);
914 * All the sublists must be the same length, *after* transformation
915 * (which might expand '*' into multiple items). The VALUES RTE can't
916 * handle anything different.
918 if (sublist_length < 0)
920 /* Remember post-transformation length of first sublist */
921 sublist_length = list_length(sublist);
922 /* and allocate arrays for per-column info */
923 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
924 coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
926 else if (sublist_length != list_length(sublist))
928 ereport(ERROR,
929 (errcode(ERRCODE_SYNTAX_ERROR),
930 errmsg("VALUES lists must all be the same length"),
931 parser_errposition(pstate,
932 exprLocation((Node *) sublist))));
935 exprsLists = lappend(exprsLists, sublist);
937 /* Check for DEFAULT and build per-column expression lists */
938 i = 0;
939 foreach(lc2, sublist)
941 Node *col = (Node *) lfirst(lc2);
943 if (IsA(col, SetToDefault))
944 ereport(ERROR,
945 (errcode(ERRCODE_SYNTAX_ERROR),
946 errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
947 parser_errposition(pstate, exprLocation(col))));
948 colexprs[i] = lappend(colexprs[i], col);
949 i++;
954 * Now resolve the common types of the columns, and coerce everything to
955 * those types.
957 for (i = 0; i < sublist_length; i++)
959 coltypes[i] = select_common_type(pstate, colexprs[i], "VALUES", NULL);
962 newExprsLists = NIL;
963 foreach(lc, exprsLists)
965 List *sublist = (List *) lfirst(lc);
966 List *newsublist = NIL;
968 i = 0;
969 foreach(lc2, sublist)
971 Node *col = (Node *) lfirst(lc2);
973 col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
974 newsublist = lappend(newsublist, col);
975 i++;
978 newExprsLists = lappend(newExprsLists, newsublist);
982 * Generate the VALUES RTE
984 rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
985 rtr = makeNode(RangeTblRef);
986 /* assume new rte is at end */
987 rtr->rtindex = list_length(pstate->p_rtable);
988 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
989 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
990 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
993 * Generate a targetlist as though expanding "*"
995 Assert(pstate->p_next_resno == 1);
996 qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
999 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1000 * VALUES, so cope.
1002 qry->sortClause = transformSortClause(pstate,
1003 stmt->sortClause,
1004 &qry->targetList,
1005 true /* fix unknowns */ );
1007 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1008 "OFFSET");
1009 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1010 "LIMIT");
1012 if (stmt->lockingClause)
1013 ereport(ERROR,
1014 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1015 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1017 /* handle any CREATE TABLE AS spec */
1018 if (stmt->intoClause)
1020 qry->intoClause = stmt->intoClause;
1021 if (stmt->intoClause->colNames)
1022 applyColumnNames(qry->targetList, stmt->intoClause->colNames);
1026 * There mustn't have been any table references in the expressions, else
1027 * strange things would happen, like Cartesian products of those tables
1028 * with the VALUES list. We have to check this after parsing ORDER BY et
1029 * al since those could insert more junk.
1031 if (list_length(pstate->p_joinlist) != 1)
1032 ereport(ERROR,
1033 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1034 errmsg("VALUES must not contain table references"),
1035 parser_errposition(pstate,
1036 locate_var_of_level((Node *) newExprsLists, 0))));
1039 * Another thing we can't currently support is NEW/OLD references in rules
1040 * --- seems we'd need something like SQL99's LATERAL construct to ensure
1041 * that the values would be available while evaluating the VALUES RTE.
1042 * This is a shame. FIXME
1044 if (list_length(pstate->p_rtable) != 1 &&
1045 contain_vars_of_level((Node *) newExprsLists, 0))
1046 ereport(ERROR,
1047 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1048 errmsg("VALUES must not contain OLD or NEW references"),
1049 errhint("Use SELECT ... UNION ALL ... instead."),
1050 parser_errposition(pstate,
1051 locate_var_of_level((Node *) newExprsLists, 0))));
1053 qry->rtable = pstate->p_rtable;
1054 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1056 qry->hasSubLinks = pstate->p_hasSubLinks;
1057 /* aggregates not allowed (but subselects are okay) */
1058 if (pstate->p_hasAggs)
1059 ereport(ERROR,
1060 (errcode(ERRCODE_GROUPING_ERROR),
1061 errmsg("cannot use aggregate function in VALUES"),
1062 parser_errposition(pstate,
1063 locate_agg_of_level((Node *) newExprsLists, 0))));
1065 return qry;
1069 * transformSetOperationStmt -
1070 * transforms a set-operations tree
1072 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1073 * structure to it. We must transform each leaf SELECT and build up a top-
1074 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1075 * The tree of set operations is converted into the setOperations field of
1076 * the top-level Query.
1078 static Query *
1079 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1081 Query *qry = makeNode(Query);
1082 SelectStmt *leftmostSelect;
1083 int leftmostRTI;
1084 Query *leftmostQuery;
1085 SetOperationStmt *sostmt;
1086 List *socolinfo;
1087 List *intoColNames = NIL;
1088 List *sortClause;
1089 Node *limitOffset;
1090 Node *limitCount;
1091 List *lockingClause;
1092 Node *node;
1093 ListCell *left_tlist,
1094 *lct,
1095 *lcm,
1097 List *targetvars,
1098 *targetnames,
1099 *sv_relnamespace,
1100 *sv_varnamespace,
1101 *sv_rtable;
1102 RangeTblEntry *jrte;
1103 int tllen;
1105 qry->commandType = CMD_SELECT;
1108 * Find leftmost leaf SelectStmt; extract the one-time-only items from it
1109 * and from the top-level node.
1111 leftmostSelect = stmt->larg;
1112 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1113 leftmostSelect = leftmostSelect->larg;
1114 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1115 leftmostSelect->larg == NULL);
1116 if (leftmostSelect->intoClause)
1118 qry->intoClause = leftmostSelect->intoClause;
1119 intoColNames = leftmostSelect->intoClause->colNames;
1122 /* clear this to prevent complaints in transformSetOperationTree() */
1123 leftmostSelect->intoClause = NULL;
1126 * These are not one-time, exactly, but we want to process them here and
1127 * not let transformSetOperationTree() see them --- else it'll just
1128 * recurse right back here!
1130 sortClause = stmt->sortClause;
1131 limitOffset = stmt->limitOffset;
1132 limitCount = stmt->limitCount;
1133 lockingClause = stmt->lockingClause;
1135 stmt->sortClause = NIL;
1136 stmt->limitOffset = NULL;
1137 stmt->limitCount = NULL;
1138 stmt->lockingClause = NIL;
1140 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1141 if (lockingClause)
1142 ereport(ERROR,
1143 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1144 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1146 /* process the WITH clause */
1147 if (stmt->withClause)
1149 qry->hasRecursive = stmt->withClause->recursive;
1150 qry->cteList = transformWithClause(pstate, stmt->withClause);
1154 * Recursively transform the components of the tree.
1156 sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1157 &socolinfo);
1158 Assert(sostmt && IsA(sostmt, SetOperationStmt));
1159 qry->setOperations = (Node *) sostmt;
1162 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1164 node = sostmt->larg;
1165 while (node && IsA(node, SetOperationStmt))
1166 node = ((SetOperationStmt *) node)->larg;
1167 Assert(node && IsA(node, RangeTblRef));
1168 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1169 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1170 Assert(leftmostQuery != NULL);
1173 * Generate dummy targetlist for outer query using column names of
1174 * leftmost select and common datatypes of topmost set operation. Also
1175 * make lists of the dummy vars and their names for use in parsing ORDER
1176 * BY.
1178 * Note: we use leftmostRTI as the varno of the dummy variables. It
1179 * shouldn't matter too much which RT index they have, as long as they
1180 * have one that corresponds to a real RT entry; else funny things may
1181 * happen when the tree is mashed by rule rewriting.
1183 qry->targetList = NIL;
1184 targetvars = NIL;
1185 targetnames = NIL;
1186 left_tlist = list_head(leftmostQuery->targetList);
1188 forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
1190 Oid colType = lfirst_oid(lct);
1191 int32 colTypmod = lfirst_int(lcm);
1192 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1193 char *colName;
1194 TargetEntry *tle;
1195 Var *var;
1197 Assert(!lefttle->resjunk);
1198 colName = pstrdup(lefttle->resname);
1199 var = makeVar(leftmostRTI,
1200 lefttle->resno,
1201 colType,
1202 colTypmod,
1204 var->location = exprLocation((Node *) lefttle->expr);
1205 tle = makeTargetEntry((Expr *) var,
1206 (AttrNumber) pstate->p_next_resno++,
1207 colName,
1208 false);
1209 qry->targetList = lappend(qry->targetList, tle);
1210 targetvars = lappend(targetvars, var);
1211 targetnames = lappend(targetnames, makeString(colName));
1212 left_tlist = lnext(left_tlist);
1216 * As a first step towards supporting sort clauses that are expressions
1217 * using the output columns, generate a varnamespace entry that makes the
1218 * output columns visible. A Join RTE node is handy for this, since we
1219 * can easily control the Vars generated upon matches.
1221 * Note: we don't yet do anything useful with such cases, but at least
1222 * "ORDER BY upper(foo)" will draw the right error message rather than
1223 * "foo not found".
1225 jrte = addRangeTableEntryForJoin(NULL,
1226 targetnames,
1227 JOIN_INNER,
1228 targetvars,
1229 NULL,
1230 false);
1232 sv_rtable = pstate->p_rtable;
1233 pstate->p_rtable = list_make1(jrte);
1235 sv_relnamespace = pstate->p_relnamespace;
1236 pstate->p_relnamespace = NIL; /* no qualified names allowed */
1238 sv_varnamespace = pstate->p_varnamespace;
1239 pstate->p_varnamespace = list_make1(jrte);
1242 * For now, we don't support resjunk sort clauses on the output of a
1243 * setOperation tree --- you can only use the SQL92-spec options of
1244 * selecting an output column by name or number. Enforce by checking that
1245 * transformSortClause doesn't add any items to tlist.
1247 tllen = list_length(qry->targetList);
1249 qry->sortClause = transformSortClause(pstate,
1250 sortClause,
1251 &qry->targetList,
1252 false /* no unknowns expected */ );
1254 pstate->p_rtable = sv_rtable;
1255 pstate->p_relnamespace = sv_relnamespace;
1256 pstate->p_varnamespace = sv_varnamespace;
1258 if (tllen != list_length(qry->targetList))
1259 ereport(ERROR,
1260 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1261 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1262 errdetail("Only result column names can be used, not expressions or functions."),
1263 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1264 parser_errposition(pstate,
1265 exprLocation(list_nth(qry->targetList, tllen)))));
1267 qry->limitOffset = transformLimitClause(pstate, limitOffset,
1268 "OFFSET");
1269 qry->limitCount = transformLimitClause(pstate, limitCount,
1270 "LIMIT");
1273 * Handle SELECT INTO/CREATE TABLE AS.
1275 * Any column names from CREATE TABLE AS need to be attached to both the
1276 * top level and the leftmost subquery. We do not do this earlier because
1277 * we do *not* want sortClause processing to be affected.
1279 if (intoColNames)
1281 applyColumnNames(qry->targetList, intoColNames);
1282 applyColumnNames(leftmostQuery->targetList, intoColNames);
1285 qry->rtable = pstate->p_rtable;
1286 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1288 qry->hasSubLinks = pstate->p_hasSubLinks;
1289 qry->hasAggs = pstate->p_hasAggs;
1290 if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1291 parseCheckAggregates(pstate, qry);
1293 foreach(l, lockingClause)
1295 transformLockingClause(pstate, qry, (LockingClause *) lfirst(l));
1298 return qry;
1302 * transformSetOperationTree
1303 * Recursively transform leaves and internal nodes of a set-op tree
1305 * In addition to returning the transformed node, we return a list of
1306 * expression nodes showing the type, typmod, and location (for error messages)
1307 * of each output column of the set-op node. This is used only during the
1308 * internal recursion of this function. At the upper levels we use
1309 * SetToDefault nodes for this purpose, since they carry exactly the fields
1310 * needed, but any other expression node type would do as well.
1312 static Node *
1313 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1314 List **colInfo)
1316 bool isLeaf;
1318 Assert(stmt && IsA(stmt, SelectStmt));
1321 * Validity-check both leaf and internal SELECTs for disallowed ops.
1323 if (stmt->intoClause)
1324 ereport(ERROR,
1325 (errcode(ERRCODE_SYNTAX_ERROR),
1326 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1327 parser_errposition(pstate,
1328 exprLocation((Node *) stmt->intoClause))));
1330 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1331 if (stmt->lockingClause)
1332 ereport(ERROR,
1333 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1334 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1337 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
1338 * clauses attached, we need to treat it like a leaf node to generate an
1339 * independent sub-Query tree. Otherwise, it can be represented by a
1340 * SetOperationStmt node underneath the parent Query.
1342 if (stmt->op == SETOP_NONE)
1344 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1345 isLeaf = true;
1347 else
1349 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1350 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1351 stmt->lockingClause)
1352 isLeaf = true;
1353 else
1354 isLeaf = false;
1357 if (isLeaf)
1359 /* Process leaf SELECT */
1360 Query *selectQuery;
1361 char selectName[32];
1362 RangeTblEntry *rte;
1363 RangeTblRef *rtr;
1364 ListCell *tl;
1367 * Transform SelectStmt into a Query.
1369 * Note: previously transformed sub-queries don't affect the parsing
1370 * of this sub-query, because they are not in the toplevel pstate's
1371 * namespace list.
1373 selectQuery = parse_sub_analyze((Node *) stmt, pstate);
1376 * Check for bogus references to Vars on the current query level (but
1377 * upper-level references are okay). Normally this can't happen
1378 * because the namespace will be empty, but it could happen if we are
1379 * inside a rule.
1381 if (pstate->p_relnamespace || pstate->p_varnamespace)
1383 if (contain_vars_of_level((Node *) selectQuery, 1))
1384 ereport(ERROR,
1385 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1386 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1387 parser_errposition(pstate,
1388 locate_var_of_level((Node *) selectQuery, 1))));
1392 * Extract a list of the result expressions for upper-level checking.
1394 *colInfo = NIL;
1395 foreach(tl, selectQuery->targetList)
1397 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1399 if (!tle->resjunk)
1400 *colInfo = lappend(*colInfo, tle->expr);
1404 * Make the leaf query be a subquery in the top-level rangetable.
1406 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1407 list_length(pstate->p_rtable) + 1);
1408 rte = addRangeTableEntryForSubquery(pstate,
1409 selectQuery,
1410 makeAlias(selectName, NIL),
1411 false);
1414 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1416 rtr = makeNode(RangeTblRef);
1417 /* assume new rte is at end */
1418 rtr->rtindex = list_length(pstate->p_rtable);
1419 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1420 return (Node *) rtr;
1422 else
1424 /* Process an internal node (set operation node) */
1425 SetOperationStmt *op = makeNode(SetOperationStmt);
1426 List *lcolinfo;
1427 List *rcolinfo;
1428 ListCell *lci;
1429 ListCell *rci;
1430 const char *context;
1432 context = (stmt->op == SETOP_UNION ? "UNION" :
1433 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1434 "EXCEPT"));
1436 op->op = stmt->op;
1437 op->all = stmt->all;
1440 * Recursively transform the child nodes.
1442 op->larg = transformSetOperationTree(pstate, stmt->larg,
1443 &lcolinfo);
1444 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1445 &rcolinfo);
1448 * Verify that the two children have the same number of non-junk
1449 * columns, and determine the types of the merged output columns.
1451 if (list_length(lcolinfo) != list_length(rcolinfo))
1452 ereport(ERROR,
1453 (errcode(ERRCODE_SYNTAX_ERROR),
1454 errmsg("each %s query must have the same number of columns",
1455 context),
1456 parser_errposition(pstate,
1457 exprLocation((Node *) rcolinfo))));
1459 *colInfo = NIL;
1460 op->colTypes = NIL;
1461 op->colTypmods = NIL;
1462 op->groupClauses = NIL;
1463 forboth(lci, lcolinfo, rci, rcolinfo)
1465 Node *lcolinfo = (Node *) lfirst(lci);
1466 Node *rcolinfo = (Node *) lfirst(rci);
1467 Oid lcoltype = exprType(lcolinfo);
1468 Oid rcoltype = exprType(rcolinfo);
1469 int32 lcoltypmod = exprTypmod(lcolinfo);
1470 int32 rcoltypmod = exprTypmod(rcolinfo);
1471 Node *bestexpr;
1472 SetToDefault *rescolinfo;
1473 Oid rescoltype;
1474 int32 rescoltypmod;
1476 /* select common type, same as CASE et al */
1477 rescoltype = select_common_type(pstate,
1478 list_make2(lcolinfo, rcolinfo),
1479 context,
1480 &bestexpr);
1481 /* if same type and same typmod, use typmod; else default */
1482 if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1483 rescoltypmod = lcoltypmod;
1484 else
1485 rescoltypmod = -1;
1487 /* verify the coercions are actually possible */
1488 (void) coerce_to_common_type(pstate, lcolinfo,
1489 rescoltype, context);
1490 (void) coerce_to_common_type(pstate, rcolinfo,
1491 rescoltype, context);
1493 /* emit results */
1494 rescolinfo = makeNode(SetToDefault);
1495 rescolinfo->typeId = rescoltype;
1496 rescolinfo->typeMod = rescoltypmod;
1497 rescolinfo->location = exprLocation(bestexpr);
1498 *colInfo = lappend(*colInfo, rescolinfo);
1500 op->colTypes = lappend_oid(op->colTypes, rescoltype);
1501 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1504 * For all cases except UNION ALL, identify the grouping operators
1505 * (and, if available, sorting operators) that will be used to
1506 * eliminate duplicates.
1508 if (op->op != SETOP_UNION || !op->all)
1510 SortGroupClause *grpcl = makeNode(SortGroupClause);
1511 Oid sortop;
1512 Oid eqop;
1513 ParseCallbackState pcbstate;
1515 setup_parser_errposition_callback(&pcbstate, pstate,
1516 rescolinfo->location);
1518 /* determine the eqop and optional sortop */
1519 get_sort_group_operators(rescoltype,
1520 false, true, false,
1521 &sortop, &eqop, NULL);
1523 cancel_parser_errposition_callback(&pcbstate);
1525 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1526 grpcl->tleSortGroupRef = 0;
1527 grpcl->eqop = eqop;
1528 grpcl->sortop = sortop;
1529 grpcl->nulls_first = false; /* OK with or without sortop */
1531 op->groupClauses = lappend(op->groupClauses, grpcl);
1535 return (Node *) op;
1540 * Attach column names from a ColumnDef list to a TargetEntry list
1541 * (for CREATE TABLE AS)
1543 static void
1544 applyColumnNames(List *dst, List *src)
1546 ListCell *dst_item;
1547 ListCell *src_item;
1549 src_item = list_head(src);
1551 foreach(dst_item, dst)
1553 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
1554 ColumnDef *s;
1556 /* junk targets don't count */
1557 if (d->resjunk)
1558 continue;
1560 /* fewer ColumnDefs than target entries is OK */
1561 if (src_item == NULL)
1562 break;
1564 s = (ColumnDef *) lfirst(src_item);
1565 src_item = lnext(src_item);
1567 d->resname = pstrdup(s->colname);
1570 /* more ColumnDefs than target entries is not OK */
1571 if (src_item != NULL)
1572 ereport(ERROR,
1573 (errcode(ERRCODE_SYNTAX_ERROR),
1574 errmsg("CREATE TABLE AS specifies too many column names")));
1579 * transformUpdateStmt -
1580 * transforms an update statement
1582 static Query *
1583 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1585 Query *qry = makeNode(Query);
1586 Node *qual;
1587 ListCell *origTargetList;
1588 ListCell *tl;
1590 qry->commandType = CMD_UPDATE;
1591 pstate->p_is_update = true;
1593 qry->resultRelation = setTargetTable(pstate, stmt->relation,
1594 interpretInhOption(stmt->relation->inhOpt),
1595 true,
1596 ACL_UPDATE);
1599 * the FROM clause is non-standard SQL syntax. We used to be able to do
1600 * this with REPLACE in POSTQUEL so we keep the feature.
1602 transformFromClause(pstate, stmt->fromClause);
1604 qry->targetList = transformTargetList(pstate, stmt->targetList);
1606 qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1608 qry->returningList = transformReturningList(pstate, stmt->returningList);
1610 qry->rtable = pstate->p_rtable;
1611 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1613 qry->hasSubLinks = pstate->p_hasSubLinks;
1616 * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1617 * an implementation point of view, this is forced because the implicit
1618 * ctid reference would otherwise be an ungrouped variable.)
1620 if (pstate->p_hasAggs)
1621 ereport(ERROR,
1622 (errcode(ERRCODE_GROUPING_ERROR),
1623 errmsg("cannot use aggregate function in UPDATE"),
1624 parser_errposition(pstate,
1625 locate_agg_of_level((Node *) qry, 0))));
1628 * Now we are done with SELECT-like processing, and can get on with
1629 * transforming the target list to match the UPDATE target columns.
1632 /* Prepare to assign non-conflicting resnos to resjunk attributes */
1633 if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
1634 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
1636 /* Prepare non-junk columns for assignment to target table */
1637 origTargetList = list_head(stmt->targetList);
1639 foreach(tl, qry->targetList)
1641 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1642 ResTarget *origTarget;
1643 int attrno;
1645 if (tle->resjunk)
1648 * Resjunk nodes need no additional processing, but be sure they
1649 * have resnos that do not match any target columns; else rewriter
1650 * or planner might get confused. They don't need a resname
1651 * either.
1653 tle->resno = (AttrNumber) pstate->p_next_resno++;
1654 tle->resname = NULL;
1655 continue;
1657 if (origTargetList == NULL)
1658 elog(ERROR, "UPDATE target count mismatch --- internal error");
1659 origTarget = (ResTarget *) lfirst(origTargetList);
1660 Assert(IsA(origTarget, ResTarget));
1662 attrno = attnameAttNum(pstate->p_target_relation,
1663 origTarget->name, true);
1664 if (attrno == InvalidAttrNumber)
1665 ereport(ERROR,
1666 (errcode(ERRCODE_UNDEFINED_COLUMN),
1667 errmsg("column \"%s\" of relation \"%s\" does not exist",
1668 origTarget->name,
1669 RelationGetRelationName(pstate->p_target_relation)),
1670 parser_errposition(pstate, origTarget->location)));
1672 updateTargetListEntry(pstate, tle, origTarget->name,
1673 attrno,
1674 origTarget->indirection,
1675 origTarget->location);
1677 origTargetList = lnext(origTargetList);
1679 if (origTargetList != NULL)
1680 elog(ERROR, "UPDATE target count mismatch --- internal error");
1682 return qry;
1686 * transformReturningList -
1687 * handle a RETURNING clause in INSERT/UPDATE/DELETE
1689 static List *
1690 transformReturningList(ParseState *pstate, List *returningList)
1692 List *rlist;
1693 int save_next_resno;
1694 bool save_hasAggs;
1695 int length_rtable;
1697 if (returningList == NIL)
1698 return NIL; /* nothing to do */
1701 * We need to assign resnos starting at one in the RETURNING list. Save
1702 * and restore the main tlist's value of p_next_resno, just in case
1703 * someone looks at it later (probably won't happen).
1705 save_next_resno = pstate->p_next_resno;
1706 pstate->p_next_resno = 1;
1708 /* save other state so that we can detect disallowed stuff */
1709 save_hasAggs = pstate->p_hasAggs;
1710 pstate->p_hasAggs = false;
1711 length_rtable = list_length(pstate->p_rtable);
1713 /* transform RETURNING identically to a SELECT targetlist */
1714 rlist = transformTargetList(pstate, returningList);
1716 /* check for disallowed stuff */
1718 /* aggregates not allowed (but subselects are okay) */
1719 if (pstate->p_hasAggs)
1720 ereport(ERROR,
1721 (errcode(ERRCODE_GROUPING_ERROR),
1722 errmsg("cannot use aggregate function in RETURNING"),
1723 parser_errposition(pstate,
1724 locate_agg_of_level((Node *) rlist, 0))));
1726 /* no new relation references please */
1727 if (list_length(pstate->p_rtable) != length_rtable)
1729 int vlocation = -1;
1730 int relid;
1732 /* try to locate such a reference to point to */
1733 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
1735 vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
1736 if (vlocation >= 0)
1737 break;
1739 ereport(ERROR,
1740 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1741 errmsg("RETURNING cannot contain references to other relations"),
1742 parser_errposition(pstate, vlocation)));
1745 /* mark column origins */
1746 markTargetListOrigins(pstate, rlist);
1748 /* restore state */
1749 pstate->p_next_resno = save_next_resno;
1750 pstate->p_hasAggs = save_hasAggs;
1752 return rlist;
1757 * transformDeclareCursorStmt -
1758 * transform a DECLARE CURSOR Statement
1760 * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
1761 * significantly different from a SELECT) as far as parsing/rewriting/planning
1762 * are concerned, but it's not passed to the executor and so in that sense is
1763 * a utility statement. We transform it into a Query exactly as if it were
1764 * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
1765 * field to carry the cursor name and options.
1767 static Query *
1768 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
1770 Query *result;
1773 * Don't allow both SCROLL and NO SCROLL to be specified
1775 if ((stmt->options & CURSOR_OPT_SCROLL) &&
1776 (stmt->options & CURSOR_OPT_NO_SCROLL))
1777 ereport(ERROR,
1778 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1779 errmsg("cannot specify both SCROLL and NO SCROLL")));
1781 result = transformStmt(pstate, stmt->query);
1783 /* Grammar should not have allowed anything but SELECT */
1784 if (!IsA(result, Query) ||
1785 result->commandType != CMD_SELECT ||
1786 result->utilityStmt != NULL)
1787 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
1789 /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
1790 if (result->intoClause)
1791 ereport(ERROR,
1792 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1793 errmsg("DECLARE CURSOR cannot specify INTO"),
1794 parser_errposition(pstate,
1795 exprLocation((Node *) result->intoClause))));
1797 /* FOR UPDATE and WITH HOLD are not compatible */
1798 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
1799 ereport(ERROR,
1800 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1801 errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
1802 errdetail("Holdable cursors must be READ ONLY.")));
1804 /* FOR UPDATE and SCROLL are not compatible */
1805 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
1806 ereport(ERROR,
1807 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1808 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1809 errdetail("Scrollable cursors must be READ ONLY.")));
1811 /* FOR UPDATE and INSENSITIVE are not compatible */
1812 if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
1813 ereport(ERROR,
1814 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1815 errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
1816 errdetail("Insensitive cursors must be READ ONLY.")));
1818 /* We won't need the raw querytree any more */
1819 stmt->query = NULL;
1821 result->utilityStmt = (Node *) stmt;
1823 return result;
1828 * transformExplainStmt -
1829 * transform an EXPLAIN Statement
1831 * EXPLAIN is just like other utility statements in that we emit it as a
1832 * CMD_UTILITY Query node with no transformation of the raw parse tree.
1833 * However, if p_variableparams is set, it could be that the client is
1834 * expecting us to resolve parameter types in something like
1835 * EXPLAIN SELECT * FROM tab WHERE col = $1
1836 * To deal with such cases, we run parse analysis and throw away the result;
1837 * this is a bit grotty but not worth contorting the rest of the system for.
1838 * (The approach we use for DECLARE CURSOR won't work because the statement
1839 * being explained isn't necessarily a SELECT, and in particular might rewrite
1840 * to multiple parsetrees.)
1842 static Query *
1843 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
1845 Query *result;
1847 if (pstate->p_variableparams)
1849 /* Since parse analysis scribbles on its input, copy the tree first! */
1850 (void) transformStmt(pstate, copyObject(stmt->query));
1853 /* Now return the untransformed command as a utility Query */
1854 result = makeNode(Query);
1855 result->commandType = CMD_UTILITY;
1856 result->utilityStmt = (Node *) stmt;
1858 return result;
1862 /* exported so planner can check again after rewriting, query pullup, etc */
1863 void
1864 CheckSelectLocking(Query *qry)
1866 if (qry->setOperations)
1867 ereport(ERROR,
1868 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1869 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1870 if (qry->distinctClause != NIL)
1871 ereport(ERROR,
1872 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1873 errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
1874 if (qry->groupClause != NIL)
1875 ereport(ERROR,
1876 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1877 errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
1878 if (qry->havingQual != NULL)
1879 ereport(ERROR,
1880 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1881 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
1882 if (qry->hasAggs)
1883 ereport(ERROR,
1884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1885 errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
1889 * Transform a FOR UPDATE/SHARE clause
1891 * This basically involves replacing names by integer relids.
1893 * NB: if you need to change this, see also markQueryForLocking()
1894 * in rewriteHandler.c, and isLockedRel() in parse_relation.c.
1896 static void
1897 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc)
1899 List *lockedRels = lc->lockedRels;
1900 ListCell *l;
1901 ListCell *rt;
1902 Index i;
1903 LockingClause *allrels;
1905 CheckSelectLocking(qry);
1907 /* make a clause we can pass down to subqueries to select all rels */
1908 allrels = makeNode(LockingClause);
1909 allrels->lockedRels = NIL; /* indicates all rels */
1910 allrels->forUpdate = lc->forUpdate;
1911 allrels->noWait = lc->noWait;
1913 if (lockedRels == NIL)
1915 /* all regular tables used in query */
1916 i = 0;
1917 foreach(rt, qry->rtable)
1919 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1921 ++i;
1922 switch (rte->rtekind)
1924 case RTE_RELATION:
1925 applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
1926 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1927 break;
1928 case RTE_SUBQUERY:
1931 * FOR UPDATE/SHARE of subquery is propagated to all of
1932 * subquery's rels
1934 transformLockingClause(pstate, rte->subquery, allrels);
1935 break;
1936 case RTE_CTE:
1939 * We allow FOR UPDATE/SHARE of a WITH query to be
1940 * propagated into the WITH, but it doesn't seem
1941 * very sane to allow this for a reference to an
1942 * outer-level WITH. And it definitely wouldn't
1943 * work for a self-reference, since we're not done
1944 * analyzing the CTE anyway.
1946 CommonTableExpr *cte;
1948 if (rte->ctelevelsup > 0 || rte->self_reference)
1949 ereport(ERROR,
1950 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1951 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query")));
1952 cte = GetCTEForRTE(pstate, rte, -1);
1953 /* should be analyzed by now */
1954 Assert(IsA(cte->ctequery, Query));
1955 transformLockingClause(pstate,
1956 (Query *) cte->ctequery,
1957 allrels);
1959 break;
1960 default:
1961 /* ignore JOIN, SPECIAL, FUNCTION RTEs */
1962 break;
1966 else
1968 /* just the named tables */
1969 foreach(l, lockedRels)
1971 RangeVar *thisrel = (RangeVar *) lfirst(l);
1973 /* For simplicity we insist on unqualified alias names here */
1974 if (thisrel->catalogname || thisrel->schemaname)
1975 ereport(ERROR,
1976 (errcode(ERRCODE_SYNTAX_ERROR),
1977 errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
1978 parser_errposition(pstate, thisrel->location)));
1980 i = 0;
1981 foreach(rt, qry->rtable)
1983 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1985 ++i;
1986 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
1988 switch (rte->rtekind)
1990 case RTE_RELATION:
1991 applyLockingClause(qry, i,
1992 lc->forUpdate, lc->noWait);
1993 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1994 break;
1995 case RTE_SUBQUERY:
1998 * FOR UPDATE/SHARE of subquery is propagated to
1999 * all of subquery's rels
2001 transformLockingClause(pstate, rte->subquery, allrels);
2002 break;
2003 case RTE_JOIN:
2004 ereport(ERROR,
2005 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2006 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2007 parser_errposition(pstate, thisrel->location)));
2008 break;
2009 case RTE_SPECIAL:
2010 ereport(ERROR,
2011 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2012 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD"),
2013 parser_errposition(pstate, thisrel->location)));
2014 break;
2015 case RTE_FUNCTION:
2016 ereport(ERROR,
2017 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2018 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2019 parser_errposition(pstate, thisrel->location)));
2020 break;
2021 case RTE_VALUES:
2022 ereport(ERROR,
2023 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2024 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2025 parser_errposition(pstate, thisrel->location)));
2026 break;
2027 case RTE_CTE:
2030 * We allow FOR UPDATE/SHARE of a WITH query
2031 * to be propagated into the WITH, but it
2032 * doesn't seem very sane to allow this for a
2033 * reference to an outer-level WITH. And it
2034 * definitely wouldn't work for a
2035 * self-reference, since we're not done
2036 * analyzing the CTE anyway.
2038 CommonTableExpr *cte;
2040 if (rte->ctelevelsup > 0 || rte->self_reference)
2041 ereport(ERROR,
2042 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2043 errmsg("SELECT FOR UPDATE/SHARE cannot be applied to an outer-level WITH query"),
2044 parser_errposition(pstate, thisrel->location)));
2045 cte = GetCTEForRTE(pstate, rte, -1);
2046 /* should be analyzed by now */
2047 Assert(IsA(cte->ctequery, Query));
2048 transformLockingClause(pstate,
2049 (Query *) cte->ctequery,
2050 allrels);
2052 break;
2053 default:
2054 elog(ERROR, "unrecognized RTE type: %d",
2055 (int) rte->rtekind);
2056 break;
2058 break; /* out of foreach loop */
2061 if (rt == NULL)
2062 ereport(ERROR,
2063 (errcode(ERRCODE_UNDEFINED_TABLE),
2064 errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2065 thisrel->relname),
2066 parser_errposition(pstate, thisrel->location)));
2072 * Record locking info for a single rangetable item
2074 void
2075 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
2077 RowMarkClause *rc;
2079 /* Check for pre-existing entry for same rtindex */
2080 if ((rc = get_rowmark(qry, rtindex)) != NULL)
2083 * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2084 * it as FOR UPDATE. (Reasonable, since you can't take both a shared
2085 * and exclusive lock at the same time; it'll end up being exclusive
2086 * anyway.)
2088 * We also consider that NOWAIT wins if it's specified both ways. This
2089 * is a bit more debatable but raising an error doesn't seem helpful.
2090 * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2091 * internally contains a plain FOR UPDATE spec.)
2093 rc->forUpdate |= forUpdate;
2094 rc->noWait |= noWait;
2095 return;
2098 /* Make a new RowMarkClause */
2099 rc = makeNode(RowMarkClause);
2100 rc->rti = rtindex;
2101 rc->prti = rtindex;
2102 rc->forUpdate = forUpdate;
2103 rc->noWait = noWait;
2104 rc->isParent = false;
2105 qry->rowMarks = lappend(qry->rowMarks, rc);
2110 * Traverse a fully-analyzed tree to verify that parameter symbols
2111 * match their types. We need this because some Params might still
2112 * be UNKNOWN, if there wasn't anything to force their coercion,
2113 * and yet other instances seen later might have gotten coerced.
2115 static bool
2116 check_parameter_resolution_walker(Node *node, ParseState *pstate)
2118 if (node == NULL)
2119 return false;
2120 if (IsA(node, Param))
2122 Param *param = (Param *) node;
2124 if (param->paramkind == PARAM_EXTERN)
2126 int paramno = param->paramid;
2128 if (paramno <= 0 || /* shouldn't happen, but... */
2129 paramno > pstate->p_numparams)
2130 ereport(ERROR,
2131 (errcode(ERRCODE_UNDEFINED_PARAMETER),
2132 errmsg("there is no parameter $%d", paramno),
2133 parser_errposition(pstate, param->location)));
2135 if (param->paramtype != pstate->p_paramtypes[paramno - 1])
2136 ereport(ERROR,
2137 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
2138 errmsg("could not determine data type of parameter $%d",
2139 paramno),
2140 parser_errposition(pstate, param->location)));
2142 return false;
2144 if (IsA(node, Query))
2146 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2147 return query_tree_walker((Query *) node,
2148 check_parameter_resolution_walker,
2149 (void *) pstate, 0);
2151 return expression_tree_walker(node, check_parameter_resolution_walker,
2152 (void *) pstate);