Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * analyze.c
4 : * transform the raw parse tree into a query tree
5 : *
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, EXPLAIN, and CREATE TABLE AS are exceptions because they
14 : * contain optimizable statements, which we should transform.
15 : *
16 : *
17 : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
18 : * Portions Copyright (c) 1994, Regents of the University of California
19 : *
20 : * src/backend/parser/analyze.c
21 : *
22 : *-------------------------------------------------------------------------
23 : */
24 :
25 : #include "postgres.h"
26 :
27 : #include "access/stratnum.h"
28 : #include "access/sysattr.h"
29 : #include "catalog/dependency.h"
30 : #include "catalog/pg_am.h"
31 : #include "catalog/pg_operator.h"
32 : #include "catalog/pg_proc.h"
33 : #include "catalog/pg_type.h"
34 : #include "commands/defrem.h"
35 : #include "miscadmin.h"
36 : #include "nodes/makefuncs.h"
37 : #include "nodes/nodeFuncs.h"
38 : #include "nodes/queryjumble.h"
39 : #include "optimizer/optimizer.h"
40 : #include "parser/analyze.h"
41 : #include "parser/parse_agg.h"
42 : #include "parser/parse_clause.h"
43 : #include "parser/parse_coerce.h"
44 : #include "parser/parse_collate.h"
45 : #include "parser/parse_cte.h"
46 : #include "parser/parse_expr.h"
47 : #include "parser/parse_func.h"
48 : #include "parser/parse_merge.h"
49 : #include "parser/parse_oper.h"
50 : #include "parser/parse_param.h"
51 : #include "parser/parse_relation.h"
52 : #include "parser/parse_target.h"
53 : #include "parser/parse_type.h"
54 : #include "parser/parsetree.h"
55 : #include "utils/backend_status.h"
56 : #include "utils/builtins.h"
57 : #include "utils/fmgroids.h"
58 : #include "utils/guc.h"
59 : #include "utils/lsyscache.h"
60 : #include "utils/rangetypes.h"
61 : #include "utils/rel.h"
62 : #include "utils/syscache.h"
63 :
64 :
65 : /* Passthrough data for transformPLAssignStmtTarget */
66 : typedef struct SelectStmtPassthrough
67 : {
68 : PLAssignStmt *stmt; /* the assignment statement */
69 : Node *target; /* node representing the target variable */
70 : List *indirection; /* indirection yet to be applied to target */
71 : } SelectStmtPassthrough;
72 :
73 : /* Hook for plugins to get control at end of parse analysis */
74 : post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
75 :
76 : static Query *transformOptionalSelectInto(ParseState *pstate, Node *parseTree);
77 : static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
78 : static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
79 : static OnConflictExpr *transformOnConflictClause(ParseState *pstate,
80 : OnConflictClause *onConflictClause);
81 : static ForPortionOfExpr *transformForPortionOfClause(ParseState *pstate,
82 : int rtindex,
83 : const ForPortionOfClause *forPortionOf,
84 : bool isUpdate);
85 : static int count_rowexpr_columns(ParseState *pstate, Node *expr);
86 : static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
87 : SelectStmtPassthrough *passthru);
88 : static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
89 : static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
90 : static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
91 : bool isTopLevel, List **targetlist);
92 : static void determineRecursiveColTypes(ParseState *pstate,
93 : Node *larg, List *nrtargetlist);
94 : static Query *transformReturnStmt(ParseState *pstate, ReturnStmt *stmt);
95 : static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
96 : static Query *transformPLAssignStmt(ParseState *pstate,
97 : PLAssignStmt *stmt);
98 : static List *transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
99 : SelectStmtPassthrough *passthru);
100 : static Query *transformDeclareCursorStmt(ParseState *pstate,
101 : DeclareCursorStmt *stmt);
102 : static Query *transformExplainStmt(ParseState *pstate,
103 : ExplainStmt *stmt);
104 : static Query *transformCreateTableAsStmt(ParseState *pstate,
105 : CreateTableAsStmt *stmt);
106 : static Query *transformCallStmt(ParseState *pstate,
107 : CallStmt *stmt);
108 : static void transformLockingClause(ParseState *pstate, Query *qry,
109 : LockingClause *lc, bool pushedDown);
110 : #ifdef DEBUG_NODE_TESTS_ENABLED
111 : static bool test_raw_expression_coverage(Node *node, void *context);
112 : #endif
113 :
114 :
115 : /*
116 : * parse_analyze_fixedparams
117 : * Analyze a raw parse tree and transform it to Query form.
118 : *
119 : * Optionally, information about $n parameter types can be supplied.
120 : * References to $n indexes not defined by paramTypes[] are disallowed.
121 : *
122 : * The result is a Query node. Optimizable statements require considerable
123 : * transformation, while utility-type statements are simply hung off
124 : * a dummy CMD_UTILITY Query node.
125 : */
126 : Query *
127 494549 : parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
128 : const Oid *paramTypes, int numParams,
129 : QueryEnvironment *queryEnv)
130 : {
131 494549 : ParseState *pstate = make_parsestate(NULL);
132 : Query *query;
133 494549 : JumbleState *jstate = NULL;
134 :
135 : Assert(sourceText != NULL); /* required as of 8.4 */
136 :
137 494549 : pstate->p_sourcetext = sourceText;
138 :
139 494549 : if (numParams > 0)
140 1649 : setup_parse_fixed_parameters(pstate, paramTypes, numParams);
141 :
142 494549 : pstate->p_queryEnv = queryEnv;
143 :
144 494549 : query = transformTopLevelStmt(pstate, parseTree);
145 :
146 488750 : if (IsQueryIdEnabled())
147 75722 : jstate = JumbleQuery(query);
148 :
149 488750 : if (post_parse_analyze_hook)
150 75549 : (*post_parse_analyze_hook) (pstate, query, jstate);
151 :
152 488750 : free_parsestate(pstate);
153 :
154 488750 : pgstat_report_query_id(query->queryId, false);
155 :
156 488750 : return query;
157 : }
158 :
159 : /*
160 : * parse_analyze_varparams
161 : *
162 : * This variant is used when it's okay to deduce information about $n
163 : * symbol datatypes from context. The passed-in paramTypes[] array can
164 : * be modified or enlarged (via repalloc).
165 : */
166 : Query *
167 7018 : parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
168 : Oid **paramTypes, int *numParams,
169 : QueryEnvironment *queryEnv)
170 : {
171 7018 : ParseState *pstate = make_parsestate(NULL);
172 : Query *query;
173 7018 : JumbleState *jstate = NULL;
174 :
175 : Assert(sourceText != NULL); /* required as of 8.4 */
176 :
177 7018 : pstate->p_sourcetext = sourceText;
178 :
179 7018 : setup_parse_variable_parameters(pstate, paramTypes, numParams);
180 :
181 7018 : pstate->p_queryEnv = queryEnv;
182 :
183 7018 : query = transformTopLevelStmt(pstate, parseTree);
184 :
185 : /* make sure all is well with parameter types */
186 7009 : check_variable_parameters(pstate, query);
187 :
188 7009 : if (IsQueryIdEnabled())
189 288 : jstate = JumbleQuery(query);
190 :
191 7009 : if (post_parse_analyze_hook)
192 288 : (*post_parse_analyze_hook) (pstate, query, jstate);
193 :
194 7009 : free_parsestate(pstate);
195 :
196 7009 : pgstat_report_query_id(query->queryId, false);
197 :
198 7009 : return query;
199 : }
200 :
201 : /*
202 : * parse_analyze_withcb
203 : *
204 : * This variant is used when the caller supplies their own parser callback to
205 : * resolve parameters and possibly other things.
206 : */
207 : Query *
208 24805 : parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
209 : ParserSetupHook parserSetup,
210 : void *parserSetupArg,
211 : QueryEnvironment *queryEnv)
212 : {
213 24805 : ParseState *pstate = make_parsestate(NULL);
214 : Query *query;
215 24805 : JumbleState *jstate = NULL;
216 :
217 : Assert(sourceText != NULL); /* required as of 8.4 */
218 :
219 24805 : pstate->p_sourcetext = sourceText;
220 24805 : pstate->p_queryEnv = queryEnv;
221 24805 : (*parserSetup) (pstate, parserSetupArg);
222 :
223 24805 : query = transformTopLevelStmt(pstate, parseTree);
224 :
225 24730 : if (IsQueryIdEnabled())
226 4179 : jstate = JumbleQuery(query);
227 :
228 24730 : if (post_parse_analyze_hook)
229 4171 : (*post_parse_analyze_hook) (pstate, query, jstate);
230 :
231 24730 : free_parsestate(pstate);
232 :
233 24730 : pgstat_report_query_id(query->queryId, false);
234 :
235 24730 : return query;
236 : }
237 :
238 :
239 : /*
240 : * parse_sub_analyze
241 : * Entry point for recursively analyzing a sub-statement.
242 : */
243 : Query *
244 72064 : parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
245 : CommonTableExpr *parentCTE,
246 : bool locked_from_parent,
247 : bool resolve_unknowns)
248 : {
249 72064 : ParseState *pstate = make_parsestate(parentParseState);
250 : Query *query;
251 :
252 72064 : pstate->p_parent_cte = parentCTE;
253 72064 : pstate->p_locked_from_parent = locked_from_parent;
254 72064 : pstate->p_resolve_unknowns = resolve_unknowns;
255 :
256 72064 : query = transformStmt(pstate, parseTree);
257 :
258 71923 : free_parsestate(pstate);
259 :
260 71923 : return query;
261 : }
262 :
263 : /*
264 : * transformTopLevelStmt -
265 : * transform a Parse tree into a Query tree.
266 : *
267 : * This function is just responsible for transferring statement location data
268 : * from the RawStmt into the finished Query.
269 : */
270 : Query *
271 528769 : transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
272 : {
273 : Query *result;
274 :
275 : /* We're at top level, so allow SELECT INTO */
276 528769 : result = transformOptionalSelectInto(pstate, parseTree->stmt);
277 :
278 522882 : result->stmt_location = parseTree->stmt_location;
279 522882 : result->stmt_len = parseTree->stmt_len;
280 :
281 522882 : return result;
282 : }
283 :
284 : /*
285 : * transformOptionalSelectInto -
286 : * If SELECT has INTO, convert it to CREATE TABLE AS.
287 : *
288 : * The only thing we do here that we don't do in transformStmt() is to
289 : * convert SELECT ... INTO into CREATE TABLE AS. Since utility statements
290 : * aren't allowed within larger statements, this is only allowed at the top
291 : * of the parse tree, and so we only try it before entering the recursive
292 : * transformStmt() processing.
293 : */
294 : static Query *
295 545287 : transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
296 : {
297 545287 : if (IsA(parseTree, SelectStmt))
298 : {
299 238893 : SelectStmt *stmt = (SelectStmt *) parseTree;
300 :
301 : /* If it's a set-operation tree, drill down to leftmost SelectStmt */
302 246158 : while (stmt && stmt->op != SETOP_NONE)
303 7265 : stmt = stmt->larg;
304 : Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
305 :
306 238893 : if (stmt->intoClause)
307 : {
308 71 : CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
309 :
310 71 : ctas->query = parseTree;
311 71 : ctas->into = stmt->intoClause;
312 71 : ctas->objtype = OBJECT_TABLE;
313 71 : ctas->is_select_into = true;
314 :
315 : /*
316 : * Remove the intoClause from the SelectStmt. This makes it safe
317 : * for transformSelectStmt to complain if it finds intoClause set
318 : * (implying that the INTO appeared in a disallowed place).
319 : */
320 71 : stmt->intoClause = NULL;
321 :
322 71 : parseTree = (Node *) ctas;
323 : }
324 : }
325 :
326 545287 : return transformStmt(pstate, parseTree);
327 : }
328 :
329 : /*
330 : * transformStmt -
331 : * recursively transform a Parse tree into a Query tree.
332 : */
333 : Query *
334 629908 : transformStmt(ParseState *pstate, Node *parseTree)
335 : {
336 : Query *result;
337 :
338 : #ifdef DEBUG_NODE_TESTS_ENABLED
339 :
340 : /*
341 : * We apply debug_raw_expression_coverage_test testing to basic DML
342 : * statements; we can't just run it on everything because
343 : * raw_expression_tree_walker() doesn't claim to handle utility
344 : * statements.
345 : */
346 629908 : if (Debug_raw_expression_coverage_test)
347 : {
348 629908 : switch (nodeTag(parseTree))
349 : {
350 378963 : case T_SelectStmt:
351 : case T_InsertStmt:
352 : case T_UpdateStmt:
353 : case T_DeleteStmt:
354 : case T_MergeStmt:
355 378963 : (void) test_raw_expression_coverage(parseTree, NULL);
356 378963 : break;
357 250945 : default:
358 250945 : break;
359 : }
360 : }
361 : #endif /* DEBUG_NODE_TESTS_ENABLED */
362 :
363 : /*
364 : * Caution: when changing the set of statement types that have non-default
365 : * processing here, see also stmt_requires_parse_analysis() and
366 : * analyze_requires_snapshot().
367 : */
368 629908 : switch (nodeTag(parseTree))
369 : {
370 : /*
371 : * Optimizable statements
372 : */
373 45245 : case T_InsertStmt:
374 45245 : result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
375 44250 : break;
376 :
377 3346 : case T_DeleteStmt:
378 3346 : result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
379 3249 : break;
380 :
381 9280 : case T_UpdateStmt:
382 9280 : result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
383 9138 : break;
384 :
385 1383 : case T_MergeStmt:
386 1383 : result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
387 1339 : break;
388 :
389 319709 : case T_SelectStmt:
390 : {
391 319709 : SelectStmt *n = (SelectStmt *) parseTree;
392 :
393 319709 : if (n->valuesLists)
394 5801 : result = transformValuesClause(pstate, n);
395 313908 : else if (n->op == SETOP_NONE)
396 305315 : result = transformSelectStmt(pstate, n, NULL);
397 : else
398 8593 : result = transformSetOperationStmt(pstate, n);
399 : }
400 314989 : break;
401 :
402 2776 : case T_ReturnStmt:
403 2776 : result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
404 2772 : break;
405 :
406 3354 : case T_PLAssignStmt:
407 3354 : result = transformPLAssignStmt(pstate,
408 : (PLAssignStmt *) parseTree);
409 3341 : break;
410 :
411 : /*
412 : * Special cases
413 : */
414 2743 : case T_DeclareCursorStmt:
415 2743 : result = transformDeclareCursorStmt(pstate,
416 : (DeclareCursorStmt *) parseTree);
417 2730 : break;
418 :
419 16518 : case T_ExplainStmt:
420 16518 : result = transformExplainStmt(pstate,
421 : (ExplainStmt *) parseTree);
422 16509 : break;
423 :
424 1316 : case T_CreateTableAsStmt:
425 1316 : result = transformCreateTableAsStmt(pstate,
426 : (CreateTableAsStmt *) parseTree);
427 1306 : break;
428 :
429 312 : case T_CallStmt:
430 312 : result = transformCallStmt(pstate,
431 : (CallStmt *) parseTree);
432 291 : break;
433 :
434 223926 : default:
435 :
436 : /*
437 : * other statements don't require any transformation; just return
438 : * the original parsetree with a Query node plastered on top.
439 : */
440 223926 : result = makeNode(Query);
441 223926 : result->commandType = CMD_UTILITY;
442 223926 : result->utilityStmt = parseTree;
443 223926 : break;
444 : }
445 :
446 : /* Mark as original query until we learn differently */
447 623840 : result->querySource = QSRC_ORIGINAL;
448 623840 : result->canSetTag = true;
449 :
450 623840 : return result;
451 : }
452 :
453 : /*
454 : * stmt_requires_parse_analysis
455 : * Returns true if parse analysis will do anything non-trivial
456 : * with the given raw parse tree.
457 : *
458 : * Generally, this should return true for any statement type for which
459 : * transformStmt() does more than wrap a CMD_UTILITY Query around it.
460 : * When it returns false, the caller can assume that there is no situation
461 : * in which parse analysis of the raw statement could need to be re-done.
462 : *
463 : * Currently, since the rewriter and planner do nothing for CMD_UTILITY
464 : * Queries, a false result means that the entire parse analysis/rewrite/plan
465 : * pipeline will never need to be re-done. If that ever changes, callers
466 : * will likely need adjustment.
467 : */
468 : bool
469 19743095 : stmt_requires_parse_analysis(RawStmt *parseTree)
470 : {
471 : bool result;
472 :
473 19743095 : switch (nodeTag(parseTree->stmt))
474 : {
475 : /*
476 : * Optimizable statements
477 : */
478 19211068 : case T_InsertStmt:
479 : case T_DeleteStmt:
480 : case T_UpdateStmt:
481 : case T_MergeStmt:
482 : case T_SelectStmt:
483 : case T_ReturnStmt:
484 : case T_PLAssignStmt:
485 19211068 : result = true;
486 19211068 : break;
487 :
488 : /*
489 : * Special cases
490 : */
491 32221 : case T_DeclareCursorStmt:
492 : case T_ExplainStmt:
493 : case T_CreateTableAsStmt:
494 : case T_CallStmt:
495 32221 : result = true;
496 32221 : break;
497 :
498 499806 : default:
499 : /* all other statements just get wrapped in a CMD_UTILITY Query */
500 499806 : result = false;
501 499806 : break;
502 : }
503 :
504 19743095 : return result;
505 : }
506 :
507 : /*
508 : * analyze_requires_snapshot
509 : * Returns true if a snapshot must be set before doing parse analysis
510 : * on the given raw parse tree.
511 : */
512 : bool
513 464002 : analyze_requires_snapshot(RawStmt *parseTree)
514 : {
515 : /*
516 : * Currently, this should return true in exactly the same cases that
517 : * stmt_requires_parse_analysis() does, so we just invoke that function
518 : * rather than duplicating it. We keep the two entry points separate for
519 : * clarity of callers, since from the callers' standpoint these are
520 : * different conditions.
521 : *
522 : * While there may someday be a statement type for which transformStmt()
523 : * does something nontrivial and yet no snapshot is needed for that
524 : * processing, it seems likely that making such a choice would be fragile.
525 : * If you want to install an exception, document the reasoning for it in a
526 : * comment.
527 : */
528 464002 : return stmt_requires_parse_analysis(parseTree);
529 : }
530 :
531 : /*
532 : * query_requires_rewrite_plan()
533 : * Returns true if rewriting or planning is non-trivial for this Query.
534 : *
535 : * This is much like stmt_requires_parse_analysis(), but applies one step
536 : * further down the pipeline.
537 : *
538 : * We do not provide an equivalent of analyze_requires_snapshot(): callers
539 : * can assume that any rewriting or planning activity needs a snapshot.
540 : */
541 : bool
542 385231 : query_requires_rewrite_plan(Query *query)
543 : {
544 : bool result;
545 :
546 385231 : if (query->commandType != CMD_UTILITY)
547 : {
548 : /* All optimizable statements require rewriting/planning */
549 385231 : result = true;
550 : }
551 : else
552 : {
553 : /* This list should match stmt_requires_parse_analysis() */
554 0 : switch (nodeTag(query->utilityStmt))
555 : {
556 0 : case T_DeclareCursorStmt:
557 : case T_ExplainStmt:
558 : case T_CreateTableAsStmt:
559 : case T_CallStmt:
560 0 : result = true;
561 0 : break;
562 0 : default:
563 0 : result = false;
564 0 : break;
565 : }
566 : }
567 385231 : return result;
568 : }
569 :
570 : /*
571 : * transformDeleteStmt -
572 : * transforms a Delete Statement
573 : */
574 : static Query *
575 3346 : transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
576 : {
577 3346 : Query *qry = makeNode(Query);
578 : ParseNamespaceItem *nsitem;
579 : Node *qual;
580 :
581 3346 : qry->commandType = CMD_DELETE;
582 :
583 : /* process the WITH clause independently of all else */
584 3346 : if (stmt->withClause)
585 : {
586 20 : qry->hasRecursive = stmt->withClause->recursive;
587 20 : qry->cteList = transformWithClause(pstate, stmt->withClause);
588 20 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
589 : }
590 :
591 : /* set up range table with just the result rel */
592 6688 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
593 3346 : stmt->relation->inh,
594 : true,
595 : ACL_DELETE);
596 3342 : nsitem = pstate->p_target_nsitem;
597 :
598 : /* disallow DELETE ... WHERE CURRENT OF on a view */
599 3342 : if (stmt->whereClause &&
600 2264 : IsA(stmt->whereClause, CurrentOfExpr) &&
601 76 : pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
602 4 : ereport(ERROR,
603 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
604 : errmsg("WHERE CURRENT OF on a view is not implemented"));
605 :
606 : /* there's no DISTINCT in DELETE */
607 3338 : qry->distinctClause = NIL;
608 :
609 : /* subqueries in USING cannot access the result relation */
610 3338 : nsitem->p_lateral_only = true;
611 3338 : nsitem->p_lateral_ok = false;
612 :
613 : /*
614 : * The USING clause is non-standard SQL syntax, and is equivalent in
615 : * functionality to the FROM list that can be specified for UPDATE. The
616 : * USING keyword is used rather than FROM because FROM is already a
617 : * keyword in the DELETE syntax.
618 : */
619 3338 : transformFromClause(pstate, stmt->usingClause);
620 :
621 : /* remaining clauses can reference the result relation normally */
622 3326 : nsitem->p_lateral_only = false;
623 3326 : nsitem->p_lateral_ok = true;
624 :
625 3326 : if (stmt->forPortionOf)
626 380 : qry->forPortionOf = transformForPortionOfClause(pstate,
627 : qry->resultRelation,
628 437 : stmt->forPortionOf,
629 : false);
630 :
631 3269 : qual = transformWhereClause(pstate, stmt->whereClause,
632 : EXPR_KIND_WHERE, "WHERE");
633 :
634 3253 : transformReturningClause(pstate, qry, stmt->returningClause,
635 : EXPR_KIND_RETURNING);
636 :
637 : /* done building the range table and jointree */
638 3249 : qry->rtable = pstate->p_rtable;
639 3249 : qry->rteperminfos = pstate->p_rteperminfos;
640 3249 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
641 :
642 3249 : qry->hasSubLinks = pstate->p_hasSubLinks;
643 3249 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
644 3249 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
645 3249 : qry->hasAggs = pstate->p_hasAggs;
646 :
647 3249 : assign_query_collations(pstate, qry);
648 :
649 : /* this must be done after collations, for reliable comparison of exprs */
650 3249 : if (pstate->p_hasAggs)
651 0 : parseCheckAggregates(pstate, qry);
652 :
653 3249 : return qry;
654 : }
655 :
656 : /*
657 : * transformInsertStmt -
658 : * transform an Insert Statement
659 : */
660 : static Query *
661 45245 : transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
662 : {
663 45245 : Query *qry = makeNode(Query);
664 45245 : SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
665 45245 : List *exprList = NIL;
666 : bool isGeneralSelect;
667 : List *sub_rtable;
668 : List *sub_rteperminfos;
669 : List *sub_namespace;
670 : List *icolumns;
671 : List *attrnos;
672 : ParseNamespaceItem *nsitem;
673 : RTEPermissionInfo *perminfo;
674 : ListCell *icols;
675 : ListCell *attnos;
676 : ListCell *lc;
677 : bool requiresUpdatePerm;
678 : AclMode targetPerms;
679 :
680 : /* There can't be any outer WITH to worry about */
681 : Assert(pstate->p_ctenamespace == NIL);
682 :
683 45245 : qry->commandType = CMD_INSERT;
684 :
685 : /* process the WITH clause independently of all else */
686 45245 : if (stmt->withClause)
687 : {
688 189 : qry->hasRecursive = stmt->withClause->recursive;
689 189 : qry->cteList = transformWithClause(pstate, stmt->withClause);
690 189 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
691 : }
692 :
693 45245 : qry->override = stmt->override;
694 :
695 : /*
696 : * ON CONFLICT DO UPDATE and ON CONFLICT DO SELECT FOR UPDATE/SHARE
697 : * require UPDATE permission on the target relation.
698 : */
699 46804 : requiresUpdatePerm = (stmt->onConflictClause &&
700 1559 : (stmt->onConflictClause->action == ONCONFLICT_UPDATE ||
701 626 : (stmt->onConflictClause->action == ONCONFLICT_SELECT &&
702 240 : stmt->onConflictClause->lockStrength != LCS_NONE)));
703 :
704 : /*
705 : * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
706 : * VALUES list, or general SELECT input. We special-case VALUES, both for
707 : * efficiency and so we can handle DEFAULT specifications.
708 : *
709 : * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
710 : * VALUES clause. If we have any of those, treat it as a general SELECT;
711 : * so it will work, but you can't use DEFAULT items together with those.
712 : */
713 80515 : isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
714 35270 : selectStmt->sortClause != NIL ||
715 35270 : selectStmt->limitOffset != NULL ||
716 35270 : selectStmt->limitCount != NULL ||
717 35270 : selectStmt->lockingClause != NIL ||
718 35270 : selectStmt->withClause != NULL));
719 :
720 : /*
721 : * If a non-nil rangetable/namespace was passed in, and we are doing
722 : * INSERT/SELECT, arrange to pass the rangetable/rteperminfos/namespace
723 : * down to the SELECT. This can only happen if we are inside a CREATE
724 : * RULE, and in that case we want the rule's OLD and NEW rtable entries to
725 : * appear as part of the SELECT's rtable, not as outer references for it.
726 : * (Kluge!) The SELECT's joinlist is not affected however. We must do
727 : * this before adding the target table to the INSERT's rtable.
728 : */
729 45245 : if (isGeneralSelect)
730 : {
731 4445 : sub_rtable = pstate->p_rtable;
732 4445 : pstate->p_rtable = NIL;
733 4445 : sub_rteperminfos = pstate->p_rteperminfos;
734 4445 : pstate->p_rteperminfos = NIL;
735 4445 : sub_namespace = pstate->p_namespace;
736 4445 : pstate->p_namespace = NIL;
737 : }
738 : else
739 : {
740 40800 : sub_rtable = NIL; /* not used, but keep compiler quiet */
741 40800 : sub_rteperminfos = NIL;
742 40800 : sub_namespace = NIL;
743 : }
744 :
745 : /*
746 : * Must get write lock on INSERT target table before scanning SELECT, else
747 : * we will grab the wrong kind of initial lock if the target table is also
748 : * mentioned in the SELECT part. Note that the target table is not added
749 : * to the joinlist or namespace.
750 : */
751 45245 : targetPerms = ACL_INSERT;
752 45245 : if (requiresUpdatePerm)
753 1011 : targetPerms |= ACL_UPDATE;
754 45245 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
755 : false, false, targetPerms);
756 :
757 : /* Validate stmt->cols list, or build default list if no list given */
758 45229 : icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
759 : Assert(list_length(icolumns) == list_length(attrnos));
760 :
761 : /*
762 : * Determine which variant of INSERT we have.
763 : */
764 45197 : if (selectStmt == NULL)
765 : {
766 : /*
767 : * We have INSERT ... DEFAULT VALUES. We can handle this case by
768 : * emitting an empty targetlist --- all columns will be defaulted when
769 : * the planner expands the targetlist.
770 : */
771 5530 : exprList = NIL;
772 : }
773 39667 : else if (isGeneralSelect)
774 : {
775 : /*
776 : * We make the sub-pstate a child of the outer pstate so that it can
777 : * see any Param definitions supplied from above. Since the outer
778 : * pstate's rtable and namespace are presently empty, there are no
779 : * side-effects of exposing names the sub-SELECT shouldn't be able to
780 : * see.
781 : */
782 4445 : ParseState *sub_pstate = make_parsestate(pstate);
783 : Query *selectQuery;
784 :
785 : /*
786 : * Process the source SELECT.
787 : *
788 : * It is important that this be handled just like a standalone SELECT;
789 : * otherwise the behavior of SELECT within INSERT might be different
790 : * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
791 : * bugs of just that nature...)
792 : *
793 : * The sole exception is that we prevent resolving unknown-type
794 : * outputs as TEXT. This does not change the semantics since if the
795 : * column type matters semantically, it would have been resolved to
796 : * something else anyway. Doing this lets us resolve such outputs as
797 : * the target column's type, which we handle below.
798 : */
799 4445 : sub_pstate->p_rtable = sub_rtable;
800 4445 : sub_pstate->p_rteperminfos = sub_rteperminfos;
801 4445 : sub_pstate->p_joinexprs = NIL; /* sub_rtable has no joins */
802 4445 : sub_pstate->p_nullingrels = NIL;
803 4445 : sub_pstate->p_namespace = sub_namespace;
804 4445 : sub_pstate->p_resolve_unknowns = false;
805 :
806 4445 : selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
807 :
808 4441 : free_parsestate(sub_pstate);
809 :
810 : /* The grammar should have produced a SELECT */
811 4441 : if (!IsA(selectQuery, Query) ||
812 4441 : selectQuery->commandType != CMD_SELECT)
813 0 : elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
814 :
815 : /*
816 : * Make the source be a subquery in the INSERT's rangetable, and add
817 : * it to the INSERT's joinlist (but not the namespace).
818 : */
819 4441 : nsitem = addRangeTableEntryForSubquery(pstate,
820 : selectQuery,
821 : NULL,
822 : false,
823 : false);
824 4441 : addNSItemToQuery(pstate, nsitem, true, false, false);
825 :
826 : /*----------
827 : * Generate an expression list for the INSERT that selects all the
828 : * non-resjunk columns from the subquery. (INSERT's tlist must be
829 : * separate from the subquery's tlist because we may add columns,
830 : * insert datatype coercions, etc.)
831 : *
832 : * HACK: unknown-type constants and params in the SELECT's targetlist
833 : * are copied up as-is rather than being referenced as subquery
834 : * outputs. This is to ensure that when we try to coerce them to
835 : * the target column's datatype, the right things happen (see
836 : * special cases in coerce_type). Otherwise, this fails:
837 : * INSERT INTO foo SELECT 'bar', ... FROM baz
838 : *----------
839 : */
840 4441 : exprList = NIL;
841 15639 : foreach(lc, selectQuery->targetList)
842 : {
843 11198 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
844 : Expr *expr;
845 :
846 11198 : if (tle->resjunk)
847 64 : continue;
848 11134 : if (tle->expr &&
849 13814 : (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
850 2680 : exprType((Node *) tle->expr) == UNKNOWNOID)
851 836 : expr = tle->expr;
852 : else
853 : {
854 10298 : Var *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
855 :
856 10298 : var->location = exprLocation((Node *) tle->expr);
857 10298 : expr = (Expr *) var;
858 : }
859 11134 : exprList = lappend(exprList, expr);
860 : }
861 :
862 : /* Prepare row for assignment to target table */
863 4441 : exprList = transformInsertRow(pstate, exprList,
864 : stmt->cols,
865 : icolumns, attrnos,
866 : false);
867 : }
868 35222 : else if (list_length(selectStmt->valuesLists) > 1)
869 : {
870 : /*
871 : * Process INSERT ... VALUES with multiple VALUES sublists. We
872 : * generate a VALUES RTE holding the transformed expression lists, and
873 : * build up a targetlist containing Vars that reference the VALUES
874 : * RTE.
875 : */
876 3363 : List *exprsLists = NIL;
877 3363 : List *coltypes = NIL;
878 3363 : List *coltypmods = NIL;
879 3363 : List *colcollations = NIL;
880 3363 : int sublist_length = -1;
881 3363 : bool lateral = false;
882 :
883 : Assert(selectStmt->intoClause == NULL);
884 :
885 14806 : foreach(lc, selectStmt->valuesLists)
886 : {
887 11443 : List *sublist = (List *) lfirst(lc);
888 :
889 : /*
890 : * Do basic expression transformation (same as a ROW() expr, but
891 : * allow SetToDefault at top level)
892 : */
893 11443 : sublist = transformExpressionList(pstate, sublist,
894 : EXPR_KIND_VALUES, true);
895 :
896 : /*
897 : * All the sublists must be the same length, *after*
898 : * transformation (which might expand '*' into multiple items).
899 : * The VALUES RTE can't handle anything different.
900 : */
901 11443 : if (sublist_length < 0)
902 : {
903 : /* Remember post-transformation length of first sublist */
904 3363 : sublist_length = list_length(sublist);
905 : }
906 8080 : else if (sublist_length != list_length(sublist))
907 : {
908 0 : ereport(ERROR,
909 : (errcode(ERRCODE_SYNTAX_ERROR),
910 : errmsg("VALUES lists must all be the same length"),
911 : parser_errposition(pstate,
912 : exprLocation((Node *) sublist))));
913 : }
914 :
915 : /*
916 : * Prepare row for assignment to target table. We process any
917 : * indirection on the target column specs normally but then strip
918 : * off the resulting field/array assignment nodes, since we don't
919 : * want the parsed statement to contain copies of those in each
920 : * VALUES row. (It's annoying to have to transform the
921 : * indirection specs over and over like this, but avoiding it
922 : * would take some really messy refactoring of
923 : * transformAssignmentIndirection.)
924 : */
925 11443 : sublist = transformInsertRow(pstate, sublist,
926 : stmt->cols,
927 : icolumns, attrnos,
928 : true);
929 :
930 : /*
931 : * We must assign collations now because assign_query_collations
932 : * doesn't process rangetable entries. We just assign all the
933 : * collations independently in each row, and don't worry about
934 : * whether they are consistent vertically. The outer INSERT query
935 : * isn't going to care about the collations of the VALUES columns,
936 : * so it's not worth the effort to identify a common collation for
937 : * each one here. (But note this does have one user-visible
938 : * consequence: INSERT ... VALUES won't complain about conflicting
939 : * explicit COLLATEs in a column, whereas the same VALUES
940 : * construct in another context would complain.)
941 : */
942 11443 : assign_list_collations(pstate, sublist);
943 :
944 11443 : exprsLists = lappend(exprsLists, sublist);
945 : }
946 :
947 : /*
948 : * Construct column type/typmod/collation lists for the VALUES RTE.
949 : * Every expression in each column has been coerced to the type/typmod
950 : * of the corresponding target column or subfield, so it's sufficient
951 : * to look at the exprType/exprTypmod of the first row. We don't care
952 : * about the collation labeling, so just fill in InvalidOid for that.
953 : */
954 9753 : foreach(lc, (List *) linitial(exprsLists))
955 : {
956 6390 : Node *val = (Node *) lfirst(lc);
957 :
958 6390 : coltypes = lappend_oid(coltypes, exprType(val));
959 6390 : coltypmods = lappend_int(coltypmods, exprTypmod(val));
960 6390 : colcollations = lappend_oid(colcollations, InvalidOid);
961 : }
962 :
963 : /*
964 : * Ordinarily there can't be any current-level Vars in the expression
965 : * lists, because the namespace was empty ... but if we're inside
966 : * CREATE RULE, then NEW/OLD references might appear. In that case we
967 : * have to mark the VALUES RTE as LATERAL.
968 : */
969 3381 : if (list_length(pstate->p_rtable) != 1 &&
970 18 : contain_vars_of_level((Node *) exprsLists, 0))
971 18 : lateral = true;
972 :
973 : /*
974 : * Generate the VALUES RTE
975 : */
976 3363 : nsitem = addRangeTableEntryForValues(pstate, exprsLists,
977 : coltypes, coltypmods, colcollations,
978 : NULL, lateral, true);
979 3363 : addNSItemToQuery(pstate, nsitem, true, false, false);
980 :
981 : /*
982 : * Generate list of Vars referencing the RTE
983 : */
984 3363 : exprList = expandNSItemVars(pstate, nsitem, 0, -1, NULL);
985 :
986 : /*
987 : * Re-apply any indirection on the target column specs to the Vars
988 : */
989 3363 : exprList = transformInsertRow(pstate, exprList,
990 : stmt->cols,
991 : icolumns, attrnos,
992 : false);
993 : }
994 : else
995 : {
996 : /*
997 : * Process INSERT ... VALUES with a single VALUES sublist. We treat
998 : * this case separately for efficiency. The sublist is just computed
999 : * directly as the Query's targetlist, with no VALUES RTE. So it
1000 : * works just like a SELECT without any FROM.
1001 : */
1002 31859 : List *valuesLists = selectStmt->valuesLists;
1003 :
1004 : Assert(list_length(valuesLists) == 1);
1005 : Assert(selectStmt->intoClause == NULL);
1006 :
1007 : /*
1008 : * Do basic expression transformation (same as a ROW() expr, but allow
1009 : * SetToDefault at top level)
1010 : */
1011 31859 : exprList = transformExpressionList(pstate,
1012 31859 : (List *) linitial(valuesLists),
1013 : EXPR_KIND_VALUES_SINGLE,
1014 : true);
1015 :
1016 : /* Prepare row for assignment to target table */
1017 31843 : exprList = transformInsertRow(pstate, exprList,
1018 : stmt->cols,
1019 : icolumns, attrnos,
1020 : false);
1021 : }
1022 :
1023 : /*
1024 : * Generate query's target list using the computed list of expressions.
1025 : * Also, mark all the target columns as needing insert permissions.
1026 : */
1027 44326 : perminfo = pstate->p_target_nsitem->p_perminfo;
1028 44326 : qry->targetList = NIL;
1029 : Assert(list_length(exprList) <= list_length(icolumns));
1030 130758 : forthree(lc, exprList, icols, icolumns, attnos, attrnos)
1031 : {
1032 86432 : Expr *expr = (Expr *) lfirst(lc);
1033 86432 : ResTarget *col = lfirst_node(ResTarget, icols);
1034 86432 : AttrNumber attr_num = (AttrNumber) lfirst_int(attnos);
1035 : TargetEntry *tle;
1036 :
1037 86432 : tle = makeTargetEntry(expr,
1038 : attr_num,
1039 : col->name,
1040 : false);
1041 86432 : qry->targetList = lappend(qry->targetList, tle);
1042 :
1043 86432 : perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
1044 : attr_num - FirstLowInvalidHeapAttributeNumber);
1045 : }
1046 :
1047 : /*
1048 : * If we have any clauses yet to process, set the query namespace to
1049 : * contain only the target relation, removing any entries added in a
1050 : * sub-SELECT or VALUES list.
1051 : */
1052 44326 : if (stmt->onConflictClause || stmt->returningClause)
1053 : {
1054 2202 : pstate->p_namespace = NIL;
1055 2202 : addNSItemToQuery(pstate, pstate->p_target_nsitem,
1056 : false, true, true);
1057 : }
1058 :
1059 : /* ON CONFLICT DO SELECT requires a RETURNING clause */
1060 44326 : if (stmt->onConflictClause &&
1061 1559 : stmt->onConflictClause->action == ONCONFLICT_SELECT &&
1062 240 : !stmt->returningClause)
1063 4 : ereport(ERROR,
1064 : errcode(ERRCODE_SYNTAX_ERROR),
1065 : errmsg("ON CONFLICT DO SELECT requires a RETURNING clause"),
1066 : parser_errposition(pstate, stmt->onConflictClause->location));
1067 :
1068 : /* Process ON CONFLICT, if any. */
1069 44322 : if (stmt->onConflictClause)
1070 1555 : qry->onConflict = transformOnConflictClause(pstate,
1071 : stmt->onConflictClause);
1072 :
1073 : /* Process RETURNING, if any. */
1074 44282 : if (stmt->returningClause)
1075 1094 : transformReturningClause(pstate, qry, stmt->returningClause,
1076 : EXPR_KIND_RETURNING);
1077 :
1078 : /* done building the range table and jointree */
1079 44250 : qry->rtable = pstate->p_rtable;
1080 44250 : qry->rteperminfos = pstate->p_rteperminfos;
1081 44250 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1082 :
1083 44250 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1084 44250 : qry->hasSubLinks = pstate->p_hasSubLinks;
1085 :
1086 44250 : assign_query_collations(pstate, qry);
1087 :
1088 44250 : return qry;
1089 : }
1090 :
1091 : /*
1092 : * Prepare an INSERT row for assignment to the target table.
1093 : *
1094 : * exprlist: transformed expressions for source values; these might come from
1095 : * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
1096 : * stmtcols: original target-columns spec for INSERT (we just test for NIL)
1097 : * icolumns: effective target-columns spec (list of ResTarget)
1098 : * attrnos: integer column numbers (must be same length as icolumns)
1099 : * strip_indirection: if true, remove any field/array assignment nodes
1100 : */
1101 : List *
1102 51746 : transformInsertRow(ParseState *pstate, List *exprlist,
1103 : List *stmtcols, List *icolumns, List *attrnos,
1104 : bool strip_indirection)
1105 : {
1106 : List *result;
1107 : ListCell *lc;
1108 : ListCell *icols;
1109 : ListCell *attnos;
1110 :
1111 : /*
1112 : * Check length of expr list. It must not have more expressions than
1113 : * there are target columns. We allow fewer, but only if no explicit
1114 : * columns list was given (the remaining columns are implicitly
1115 : * defaulted). Note we must check this *after* transformation because
1116 : * that could expand '*' into multiple items.
1117 : */
1118 51746 : if (list_length(exprlist) > list_length(icolumns))
1119 17 : ereport(ERROR,
1120 : (errcode(ERRCODE_SYNTAX_ERROR),
1121 : errmsg("INSERT has more expressions than target columns"),
1122 : parser_errposition(pstate,
1123 : exprLocation(list_nth(exprlist,
1124 : list_length(icolumns))))));
1125 62649 : if (stmtcols != NIL &&
1126 10920 : list_length(exprlist) < list_length(icolumns))
1127 : {
1128 : /*
1129 : * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1130 : * where the user accidentally created a RowExpr instead of separate
1131 : * columns. Add a suitable hint if that seems to be the problem,
1132 : * because the main error message is quite misleading for this case.
1133 : * (If there's no stmtcols, you'll get something about data type
1134 : * mismatch, which is less misleading so we don't worry about giving a
1135 : * hint in that case.)
1136 : */
1137 8 : ereport(ERROR,
1138 : (errcode(ERRCODE_SYNTAX_ERROR),
1139 : errmsg("INSERT has more target columns than expressions"),
1140 : ((list_length(exprlist) == 1 &&
1141 : count_rowexpr_columns(pstate, linitial(exprlist)) ==
1142 : list_length(icolumns)) ?
1143 : errhint("The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?") : 0),
1144 : parser_errposition(pstate,
1145 : exprLocation(list_nth(icolumns,
1146 : list_length(exprlist))))));
1147 : }
1148 :
1149 : /*
1150 : * Prepare columns for assignment to target table.
1151 : */
1152 51721 : result = NIL;
1153 164648 : forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1154 : {
1155 113753 : Expr *expr = (Expr *) lfirst(lc);
1156 113753 : ResTarget *col = lfirst_node(ResTarget, icols);
1157 113753 : int attno = lfirst_int(attnos);
1158 :
1159 113753 : expr = transformAssignedExpr(pstate, expr,
1160 : EXPR_KIND_INSERT_TARGET,
1161 113753 : col->name,
1162 : attno,
1163 : col->indirection,
1164 : col->location);
1165 :
1166 112927 : if (strip_indirection)
1167 : {
1168 : /*
1169 : * We need to remove top-level FieldStores and SubscriptingRefs,
1170 : * as well as any CoerceToDomain appearing above one of those ---
1171 : * but not a CoerceToDomain that isn't above one of those.
1172 : */
1173 25351 : while (expr)
1174 : {
1175 25351 : Expr *subexpr = expr;
1176 :
1177 25527 : while (IsA(subexpr, CoerceToDomain))
1178 : {
1179 176 : subexpr = ((CoerceToDomain *) subexpr)->arg;
1180 : }
1181 25351 : if (IsA(subexpr, FieldStore))
1182 : {
1183 144 : FieldStore *fstore = (FieldStore *) subexpr;
1184 :
1185 144 : expr = (Expr *) linitial(fstore->newvals);
1186 : }
1187 25207 : else if (IsA(subexpr, SubscriptingRef))
1188 : {
1189 232 : SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1190 :
1191 232 : if (sbsref->refassgnexpr == NULL)
1192 0 : break;
1193 :
1194 232 : expr = sbsref->refassgnexpr;
1195 : }
1196 : else
1197 24975 : break;
1198 : }
1199 : }
1200 :
1201 112927 : result = lappend(result, expr);
1202 : }
1203 :
1204 50895 : return result;
1205 : }
1206 :
1207 : /*
1208 : * transformOnConflictClause -
1209 : * transforms an OnConflictClause in an INSERT
1210 : */
1211 : static OnConflictExpr *
1212 1555 : transformOnConflictClause(ParseState *pstate,
1213 : OnConflictClause *onConflictClause)
1214 : {
1215 1555 : ParseNamespaceItem *exclNSItem = NULL;
1216 : List *arbiterElems;
1217 : Node *arbiterWhere;
1218 : Oid arbiterConstraint;
1219 1555 : List *onConflictSet = NIL;
1220 1555 : Node *onConflictWhere = NULL;
1221 1555 : int exclRelIndex = 0;
1222 1555 : List *exclRelTlist = NIL;
1223 : OnConflictExpr *result;
1224 :
1225 : /*
1226 : * If this is ON CONFLICT DO SELECT/UPDATE, first create the range table
1227 : * entry for the EXCLUDED pseudo relation, so that that will be present
1228 : * while processing arbiter expressions. (You can't actually reference it
1229 : * from there, but this provides a useful error message if you try.)
1230 : */
1231 1555 : if (onConflictClause->action == ONCONFLICT_UPDATE ||
1232 622 : onConflictClause->action == ONCONFLICT_SELECT)
1233 : {
1234 1169 : Relation targetrel = pstate->p_target_relation;
1235 : RangeTblEntry *exclRte;
1236 :
1237 1169 : exclNSItem = addRangeTableEntryForRelation(pstate,
1238 : targetrel,
1239 : RowExclusiveLock,
1240 : makeAlias("excluded", NIL),
1241 : false, false);
1242 1169 : exclRte = exclNSItem->p_rte;
1243 1169 : exclRelIndex = exclNSItem->p_rtindex;
1244 :
1245 : /*
1246 : * relkind is set to composite to signal that we're not dealing with
1247 : * an actual relation, and no permission checks are required on it.
1248 : * (We'll check the actual target relation, instead.)
1249 : */
1250 1169 : exclRte->relkind = RELKIND_COMPOSITE_TYPE;
1251 :
1252 : /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1253 1169 : exclRelTlist = BuildOnConflictExcludedTargetlist(targetrel,
1254 : exclRelIndex);
1255 : }
1256 :
1257 : /* Process the arbiter clause, ON CONFLICT ON (...) */
1258 1555 : transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1259 : &arbiterWhere, &arbiterConstraint);
1260 :
1261 : /* Process DO SELECT/UPDATE */
1262 1535 : if (onConflictClause->action == ONCONFLICT_UPDATE ||
1263 610 : onConflictClause->action == ONCONFLICT_SELECT)
1264 : {
1265 : /*
1266 : * Add the EXCLUDED pseudo relation to the query namespace, making it
1267 : * available in SET and WHERE subexpressions.
1268 : */
1269 1161 : addNSItemToQuery(pstate, exclNSItem, false, true, true);
1270 :
1271 : /* Process the UPDATE SET clause */
1272 1161 : if (onConflictClause->action == ONCONFLICT_UPDATE)
1273 : onConflictSet =
1274 925 : transformUpdateTargetList(pstate, onConflictClause->targetList, NULL);
1275 :
1276 : /* Process the SELECT/UPDATE WHERE clause */
1277 1141 : onConflictWhere = transformWhereClause(pstate,
1278 : onConflictClause->whereClause,
1279 : EXPR_KIND_WHERE, "WHERE");
1280 :
1281 : /*
1282 : * Remove the EXCLUDED pseudo relation from the query namespace, since
1283 : * it's not supposed to be available in RETURNING. (Maybe someday we
1284 : * could allow that, and drop this step.)
1285 : */
1286 : Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem);
1287 1141 : pstate->p_namespace = list_delete_last(pstate->p_namespace);
1288 : }
1289 :
1290 : /* Finally, build ON CONFLICT DO [NOTHING | SELECT | UPDATE] expression */
1291 1515 : result = makeNode(OnConflictExpr);
1292 :
1293 1515 : result->action = onConflictClause->action;
1294 1515 : result->arbiterElems = arbiterElems;
1295 1515 : result->arbiterWhere = arbiterWhere;
1296 1515 : result->constraint = arbiterConstraint;
1297 1515 : result->lockStrength = onConflictClause->lockStrength;
1298 1515 : result->onConflictSet = onConflictSet;
1299 1515 : result->onConflictWhere = onConflictWhere;
1300 1515 : result->exclRelIndex = exclRelIndex;
1301 1515 : result->exclRelTlist = exclRelTlist;
1302 :
1303 1515 : return result;
1304 : }
1305 :
1306 : /*
1307 : * transformForPortionOfClause
1308 : *
1309 : * Transforms a ForPortionOfClause in an UPDATE/DELETE statement.
1310 : *
1311 : * - Look up the range/period requested.
1312 : * - Build a compatible range value from the FROM and TO expressions.
1313 : * - Build an "overlaps" expression for filtering, used later by the
1314 : * rewriter.
1315 : * - For UPDATEs, build an "intersects" expression the rewriter can add
1316 : * to the targetList to change the temporal bounds.
1317 : */
1318 : static ForPortionOfExpr *
1319 1013 : transformForPortionOfClause(ParseState *pstate,
1320 : int rtindex,
1321 : const ForPortionOfClause *forPortionOf,
1322 : bool isUpdate)
1323 : {
1324 1013 : Relation targetrel = pstate->p_target_relation;
1325 1013 : int range_attno = InvalidAttrNumber;
1326 : Form_pg_attribute attr;
1327 : Oid attbasetype;
1328 : Oid opclass;
1329 : Oid opfamily;
1330 : Oid opcintype;
1331 1013 : Oid funcid = InvalidOid;
1332 : StrategyNumber strat;
1333 : Oid opid;
1334 : OpExpr *op;
1335 : ForPortionOfExpr *result;
1336 : Var *rangeVar;
1337 :
1338 : /* We don't support FOR PORTION OF FDW queries. */
1339 1013 : if (targetrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1340 2 : ereport(ERROR,
1341 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1342 : errmsg("foreign tables don't support FOR PORTION OF")));
1343 :
1344 1011 : result = makeNode(ForPortionOfExpr);
1345 :
1346 : /* Look up the FOR PORTION OF name requested. */
1347 1011 : range_attno = attnameAttNum(targetrel, forPortionOf->range_name, false);
1348 1011 : if (range_attno == InvalidAttrNumber)
1349 8 : ereport(ERROR,
1350 : (errcode(ERRCODE_UNDEFINED_COLUMN),
1351 : errmsg("column \"%s\" of relation \"%s\" does not exist",
1352 : forPortionOf->range_name,
1353 : RelationGetRelationName(targetrel)),
1354 : parser_errposition(pstate, forPortionOf->location)));
1355 1003 : attr = TupleDescAttr(targetrel->rd_att, range_attno - 1);
1356 :
1357 1003 : attbasetype = getBaseType(attr->atttypid);
1358 :
1359 1003 : rangeVar = makeVar(rtindex,
1360 : range_attno,
1361 : attr->atttypid,
1362 : attr->atttypmod,
1363 : attr->attcollation,
1364 : 0);
1365 1003 : rangeVar->location = forPortionOf->location;
1366 1003 : result->rangeVar = rangeVar;
1367 :
1368 : /* Require SELECT privilege on the application-time column. */
1369 1003 : markVarForSelectPriv(pstate, rangeVar);
1370 :
1371 : /*
1372 : * Use the basetype for the target, which shouldn't be required to follow
1373 : * domain rules. The table's column type is in the Var if we need it.
1374 : */
1375 1003 : result->rangeType = attbasetype;
1376 1003 : result->isDomain = attbasetype != attr->atttypid;
1377 :
1378 1003 : if (forPortionOf->target)
1379 : {
1380 200 : Oid declared_target_type = attbasetype;
1381 : Oid actual_target_type;
1382 :
1383 : /*
1384 : * We were already given an expression for the target, so we don't
1385 : * have to build anything. We still have to make sure we got the right
1386 : * type. NULL will be caught be the executor.
1387 : */
1388 :
1389 400 : result->targetRange = transformExpr(pstate,
1390 200 : forPortionOf->target,
1391 : EXPR_KIND_FOR_PORTION);
1392 :
1393 200 : actual_target_type = exprType(result->targetRange);
1394 :
1395 200 : if (!can_coerce_type(1, &actual_target_type, &declared_target_type, COERCION_IMPLICIT))
1396 32 : ereport(ERROR,
1397 : (errcode(ERRCODE_DATATYPE_MISMATCH),
1398 : errmsg("could not coerce FOR PORTION OF target from %s to %s",
1399 : format_type_be(actual_target_type),
1400 : format_type_be(declared_target_type)),
1401 : parser_errposition(pstate, exprLocation(forPortionOf->target))));
1402 :
1403 168 : result->targetRange = coerce_type(pstate,
1404 : result->targetRange,
1405 : actual_target_type,
1406 : declared_target_type,
1407 : -1,
1408 : COERCION_IMPLICIT,
1409 : COERCE_IMPLICIT_CAST,
1410 168 : exprLocation(forPortionOf->target));
1411 :
1412 : /*
1413 : * XXX: For now we only support ranges and multiranges, so we fail on
1414 : * anything else.
1415 : */
1416 168 : if (!type_is_range(attbasetype) && !type_is_multirange(attbasetype))
1417 24 : ereport(ERROR,
1418 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1419 : errmsg("column \"%s\" of relation \"%s\" is not a range or multirange type",
1420 : forPortionOf->range_name,
1421 : RelationGetRelationName(targetrel)),
1422 : parser_errposition(pstate, forPortionOf->location)));
1423 :
1424 : }
1425 : else
1426 : {
1427 : Oid rngsubtype;
1428 : Oid declared_arg_types[2];
1429 : Oid actual_arg_types[2];
1430 : List *args;
1431 :
1432 : /*
1433 : * Make sure it's a range column. XXX: We could support this syntax on
1434 : * multirange columns too, if we just built a one-range multirange
1435 : * from the FROM/TO phrases.
1436 : */
1437 803 : if (!type_is_range(attbasetype))
1438 8 : ereport(ERROR,
1439 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1440 : errmsg("column \"%s\" of relation \"%s\" is not a range type",
1441 : forPortionOf->range_name,
1442 : RelationGetRelationName(targetrel)),
1443 : parser_errposition(pstate, forPortionOf->location)));
1444 :
1445 795 : rngsubtype = get_range_subtype(attbasetype);
1446 795 : declared_arg_types[0] = rngsubtype;
1447 795 : declared_arg_types[1] = rngsubtype;
1448 :
1449 : /*
1450 : * Build a range from the FROM ... TO ... bounds. This should give a
1451 : * constant result, so we accept functions like NOW() but not column
1452 : * references, subqueries, etc.
1453 : */
1454 1574 : result->targetFrom = transformExpr(pstate,
1455 795 : forPortionOf->target_start,
1456 : EXPR_KIND_FOR_PORTION);
1457 1558 : result->targetTo = transformExpr(pstate,
1458 779 : forPortionOf->target_end,
1459 : EXPR_KIND_FOR_PORTION);
1460 779 : actual_arg_types[0] = exprType(result->targetFrom);
1461 779 : actual_arg_types[1] = exprType(result->targetTo);
1462 779 : args = list_make2(copyObject(result->targetFrom),
1463 : copyObject(result->targetTo));
1464 :
1465 : /*
1466 : * Check the bound types separately, for better error message and
1467 : * location
1468 : */
1469 779 : if (!can_coerce_type(1, actual_arg_types, declared_arg_types, COERCION_IMPLICIT))
1470 8 : ereport(ERROR,
1471 : (errcode(ERRCODE_DATATYPE_MISMATCH),
1472 : errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
1473 : "FROM",
1474 : format_type_be(actual_arg_types[0]),
1475 : format_type_be(declared_arg_types[0])),
1476 : parser_errposition(pstate, exprLocation(forPortionOf->target_start))));
1477 771 : if (!can_coerce_type(1, &actual_arg_types[1], &declared_arg_types[1], COERCION_IMPLICIT))
1478 8 : ereport(ERROR,
1479 : (errcode(ERRCODE_DATATYPE_MISMATCH),
1480 : errmsg("could not coerce FOR PORTION OF %s bound from %s to %s",
1481 : "TO",
1482 : format_type_be(actual_arg_types[1]),
1483 : format_type_be(declared_arg_types[1])),
1484 : parser_errposition(pstate, exprLocation(forPortionOf->target_end))));
1485 :
1486 763 : make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
1487 763 : result->targetRange = (Node *) makeFuncExpr(get_range_constructor2(attbasetype),
1488 : attbasetype,
1489 : args,
1490 : InvalidOid, InvalidOid, COERCE_EXPLICIT_CALL);
1491 : }
1492 907 : if (contain_volatile_functions_after_planning((Expr *) result->targetRange))
1493 8 : ereport(ERROR,
1494 : (errmsg("FOR PORTION OF bounds cannot contain volatile functions")));
1495 :
1496 : /*
1497 : * Build overlapsExpr to use as an extra qual. This means we only hit rows
1498 : * matching the FROM & TO bounds. We must look up the overlaps operator
1499 : * (usually "&&").
1500 : */
1501 891 : opclass = GetDefaultOpClass(attr->atttypid, GIST_AM_OID);
1502 891 : if (!OidIsValid(opclass))
1503 0 : ereport(ERROR,
1504 : (errcode(ERRCODE_UNDEFINED_OBJECT),
1505 : errmsg("data type %s has no default operator class for access method \"%s\"",
1506 : format_type_be(attr->atttypid), "gist"),
1507 : errhint("You must define a default operator class for the data type.")));
1508 :
1509 : /* Look up the operators and functions we need. */
1510 891 : GetOperatorFromCompareType(opclass, InvalidOid, COMPARE_OVERLAP, &opid, &strat);
1511 891 : op = makeNode(OpExpr);
1512 891 : op->opno = opid;
1513 891 : op->opfuncid = get_opcode(opid);
1514 891 : op->opresulttype = BOOLOID;
1515 891 : op->args = list_make2(copyObject(rangeVar), copyObject(result->targetRange));
1516 891 : result->overlapsExpr = (Node *) op;
1517 :
1518 : /*
1519 : * Look up the without_portion func. This computes the bounds of temporal
1520 : * leftovers.
1521 : *
1522 : * XXX: Find a more extensible way to look up the function, permitting
1523 : * user-defined types. An opclass support function doesn't make sense,
1524 : * since there is no index involved. Perhaps a type support function.
1525 : */
1526 891 : if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
1527 891 : switch (opcintype)
1528 : {
1529 803 : case ANYRANGEOID:
1530 803 : result->withoutPortionProc = F_RANGE_MINUS_MULTI;
1531 803 : break;
1532 88 : case ANYMULTIRANGEOID:
1533 88 : result->withoutPortionProc = F_MULTIRANGE_MINUS_MULTI;
1534 88 : break;
1535 0 : default:
1536 0 : elog(ERROR, "unexpected opcintype: %u", opcintype);
1537 : }
1538 : else
1539 0 : elog(ERROR, "unexpected opclass: %u", opclass);
1540 :
1541 891 : if (isUpdate)
1542 : {
1543 : /*
1544 : * Now make sure we update the start/end time of the record. For a
1545 : * range col (r) this is `r = r * targetRange` (where * is the
1546 : * intersect operator).
1547 : */
1548 : Oid intersectoperoid;
1549 : List *funcArgs;
1550 : Node *rangeTLEExpr;
1551 : TargetEntry *tle;
1552 511 : RTEPermissionInfo *target_perminfo = pstate->p_target_nsitem->p_perminfo;
1553 :
1554 : /*
1555 : * Whatever operator is used for intersect by temporal foreign keys,
1556 : * we can use its backing procedure for intersects in FOR PORTION OF.
1557 : * XXX: Share code with FindFKPeriodOpers?
1558 : */
1559 511 : switch (opcintype)
1560 : {
1561 463 : case ANYRANGEOID:
1562 463 : intersectoperoid = OID_RANGE_INTERSECT_RANGE_OP;
1563 463 : break;
1564 48 : case ANYMULTIRANGEOID:
1565 48 : intersectoperoid = OID_MULTIRANGE_INTERSECT_MULTIRANGE_OP;
1566 48 : break;
1567 0 : default:
1568 0 : elog(ERROR, "unexpected opcintype: %u", opcintype);
1569 : }
1570 511 : funcid = get_opcode(intersectoperoid);
1571 511 : if (!OidIsValid(funcid))
1572 0 : ereport(ERROR,
1573 : errcode(ERRCODE_UNDEFINED_OBJECT),
1574 : errmsg("could not identify an intersect function for type %s",
1575 : format_type_be(opcintype)));
1576 :
1577 511 : funcArgs = list_make2(copyObject(rangeVar),
1578 : copyObject(result->targetRange));
1579 511 : rangeTLEExpr = (Node *) makeFuncExpr(funcid, attbasetype, funcArgs,
1580 : InvalidOid, InvalidOid,
1581 : COERCE_EXPLICIT_CALL);
1582 :
1583 : /*
1584 : * Coerce to domain if necessary. If we skip this, we will allow
1585 : * updating to forbidden values.
1586 : */
1587 511 : rangeTLEExpr = coerce_type(pstate,
1588 : rangeTLEExpr,
1589 : attbasetype,
1590 : attr->atttypid,
1591 : -1,
1592 : COERCION_IMPLICIT,
1593 : COERCE_IMPLICIT_CAST,
1594 511 : exprLocation(forPortionOf->target));
1595 :
1596 : /* Make a TLE to set the range column */
1597 511 : result->rangeTargetList = NIL;
1598 511 : tle = makeTargetEntry((Expr *) rangeTLEExpr, range_attno,
1599 511 : forPortionOf->range_name, false);
1600 511 : result->rangeTargetList = lappend(result->rangeTargetList, tle);
1601 :
1602 : /* Mark the range column as requiring update permissions */
1603 511 : target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
1604 : range_attno - FirstLowInvalidHeapAttributeNumber);
1605 : }
1606 : else
1607 380 : result->rangeTargetList = NIL;
1608 :
1609 891 : result->range_name = forPortionOf->range_name;
1610 891 : result->location = forPortionOf->location;
1611 891 : result->targetLocation = forPortionOf->target_location;
1612 :
1613 891 : return result;
1614 : }
1615 :
1616 : /*
1617 : * BuildOnConflictExcludedTargetlist
1618 : * Create target list for the EXCLUDED pseudo-relation of ON CONFLICT,
1619 : * representing the columns of targetrel with varno exclRelIndex.
1620 : *
1621 : * Note: Exported for use in the rewriter.
1622 : */
1623 : List *
1624 1317 : BuildOnConflictExcludedTargetlist(Relation targetrel,
1625 : Index exclRelIndex)
1626 : {
1627 1317 : List *result = NIL;
1628 : int attno;
1629 : Var *var;
1630 : TargetEntry *te;
1631 :
1632 : /*
1633 : * Note that resnos of the tlist must correspond to attnos of the
1634 : * underlying relation, hence we need entries for dropped columns too.
1635 : */
1636 4722 : for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1637 : {
1638 3405 : Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1639 : char *name;
1640 :
1641 3405 : if (attr->attisdropped)
1642 : {
1643 : /*
1644 : * can't use atttypid here, but it doesn't really matter what type
1645 : * the Const claims to be.
1646 : */
1647 74 : var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1648 74 : name = NULL;
1649 : }
1650 : else
1651 : {
1652 3331 : var = makeVar(exclRelIndex, attno + 1,
1653 : attr->atttypid, attr->atttypmod,
1654 : attr->attcollation,
1655 : 0);
1656 3331 : name = pstrdup(NameStr(attr->attname));
1657 : }
1658 :
1659 3405 : te = makeTargetEntry((Expr *) var,
1660 3405 : attno + 1,
1661 : name,
1662 : false);
1663 :
1664 3405 : result = lappend(result, te);
1665 : }
1666 :
1667 : /*
1668 : * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1669 : * the other entries in the EXCLUDED tlist, its resno must match the Var's
1670 : * varattno, else the wrong things happen while resolving references in
1671 : * setrefs.c. This is against normal conventions for targetlists, but
1672 : * it's okay since we don't use this as a real tlist.
1673 : */
1674 1317 : var = makeVar(exclRelIndex, InvalidAttrNumber,
1675 1317 : targetrel->rd_rel->reltype,
1676 : -1, InvalidOid, 0);
1677 1317 : te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1678 1317 : result = lappend(result, te);
1679 :
1680 1317 : return result;
1681 : }
1682 :
1683 :
1684 : /*
1685 : * count_rowexpr_columns -
1686 : * get number of columns contained in a ROW() expression;
1687 : * return -1 if expression isn't a RowExpr or a Var referencing one.
1688 : *
1689 : * This is currently used only for hint purposes, so we aren't terribly
1690 : * tense about recognizing all possible cases. The Var case is interesting
1691 : * because that's what we'll get in the INSERT ... SELECT (...) case.
1692 : */
1693 : static int
1694 0 : count_rowexpr_columns(ParseState *pstate, Node *expr)
1695 : {
1696 0 : if (expr == NULL)
1697 0 : return -1;
1698 0 : if (IsA(expr, RowExpr))
1699 0 : return list_length(((RowExpr *) expr)->args);
1700 0 : if (IsA(expr, Var))
1701 : {
1702 0 : Var *var = (Var *) expr;
1703 0 : AttrNumber attnum = var->varattno;
1704 :
1705 0 : if (attnum > 0 && var->vartype == RECORDOID)
1706 : {
1707 : RangeTblEntry *rte;
1708 :
1709 0 : rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1710 0 : if (rte->rtekind == RTE_SUBQUERY)
1711 : {
1712 : /* Subselect-in-FROM: examine sub-select's output expr */
1713 0 : TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
1714 : attnum);
1715 :
1716 0 : if (ste == NULL || ste->resjunk)
1717 0 : return -1;
1718 0 : expr = (Node *) ste->expr;
1719 0 : if (IsA(expr, RowExpr))
1720 0 : return list_length(((RowExpr *) expr)->args);
1721 : }
1722 : }
1723 : }
1724 0 : return -1;
1725 : }
1726 :
1727 :
1728 : /*
1729 : * transformSelectStmt -
1730 : * transforms a Select Statement
1731 : *
1732 : * This function is also used to transform the source expression of a
1733 : * PLAssignStmt. In that usage, passthru is non-NULL and we need to
1734 : * call transformPLAssignStmtTarget after the initial transformation of the
1735 : * SELECT's targetlist. (We could generalize this into an arbitrary callback
1736 : * function, but for now that would just be more notation with no benefit.)
1737 : * All the rest is the same as a regular SelectStmt.
1738 : *
1739 : * Note: this covers only cases with no set operations and no VALUES lists;
1740 : * see below for the other cases.
1741 : */
1742 : static Query *
1743 308663 : transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
1744 : SelectStmtPassthrough *passthru)
1745 : {
1746 308663 : Query *qry = makeNode(Query);
1747 : Node *qual;
1748 : ListCell *l;
1749 :
1750 308663 : qry->commandType = CMD_SELECT;
1751 :
1752 : /* process the WITH clause independently of all else */
1753 308663 : if (stmt->withClause)
1754 : {
1755 1712 : qry->hasRecursive = stmt->withClause->recursive;
1756 1712 : qry->cteList = transformWithClause(pstate, stmt->withClause);
1757 1515 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1758 : }
1759 :
1760 : /* Complain if we get called from someplace where INTO is not allowed */
1761 308466 : if (stmt->intoClause)
1762 12 : ereport(ERROR,
1763 : (errcode(ERRCODE_SYNTAX_ERROR),
1764 : errmsg("SELECT ... INTO is not allowed here"),
1765 : parser_errposition(pstate,
1766 : exprLocation((Node *) stmt->intoClause))));
1767 :
1768 : /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1769 308454 : pstate->p_locking_clause = stmt->lockingClause;
1770 :
1771 : /* make WINDOW info available for window functions, too */
1772 308454 : pstate->p_windowdefs = stmt->windowClause;
1773 :
1774 : /* process the FROM clause */
1775 308454 : transformFromClause(pstate, stmt->fromClause);
1776 :
1777 : /* transform targetlist */
1778 307963 : qry->targetList = transformTargetList(pstate, stmt->targetList,
1779 : EXPR_KIND_SELECT_TARGET);
1780 :
1781 : /*
1782 : * If we're within a PLAssignStmt, do further transformation of the
1783 : * targetlist; that has to happen before we consider sorting or grouping.
1784 : * Otherwise, mark column origins (which are useless in a PLAssignStmt).
1785 : */
1786 304311 : if (passthru)
1787 3348 : qry->targetList = transformPLAssignStmtTarget(pstate, qry->targetList,
1788 : passthru);
1789 : else
1790 300963 : markTargetListOrigins(pstate, qry->targetList);
1791 :
1792 : /* transform WHERE */
1793 304304 : qual = transformWhereClause(pstate, stmt->whereClause,
1794 : EXPR_KIND_WHERE, "WHERE");
1795 :
1796 : /* initial processing of HAVING clause is much like WHERE clause */
1797 304233 : qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1798 : EXPR_KIND_HAVING, "HAVING");
1799 :
1800 : /*
1801 : * Transform sorting/grouping stuff. Do ORDER BY first because both
1802 : * transformGroupClause and transformDistinctClause need the results. Note
1803 : * that these functions can also change the targetList, so it's passed to
1804 : * them by reference.
1805 : */
1806 304229 : qry->sortClause = transformSortClause(pstate,
1807 : stmt->sortClause,
1808 : &qry->targetList,
1809 : EXPR_KIND_ORDER_BY,
1810 : false /* allow SQL92 rules */ );
1811 :
1812 608402 : qry->groupClause = transformGroupClause(pstate,
1813 : stmt->groupClause,
1814 304209 : stmt->groupByAll,
1815 : &qry->groupingSets,
1816 : &qry->targetList,
1817 : qry->sortClause,
1818 : EXPR_KIND_GROUP_BY,
1819 : false /* allow SQL92 rules */ );
1820 304193 : qry->groupDistinct = stmt->groupDistinct;
1821 304193 : qry->groupByAll = stmt->groupByAll;
1822 :
1823 304193 : if (stmt->distinctClause == NIL)
1824 : {
1825 301664 : qry->distinctClause = NIL;
1826 301664 : qry->hasDistinctOn = false;
1827 : }
1828 2529 : else if (linitial(stmt->distinctClause) == NULL)
1829 : {
1830 : /* We had SELECT DISTINCT */
1831 2362 : qry->distinctClause = transformDistinctClause(pstate,
1832 : &qry->targetList,
1833 : qry->sortClause,
1834 : false);
1835 2362 : qry->hasDistinctOn = false;
1836 : }
1837 : else
1838 : {
1839 : /* We had SELECT DISTINCT ON */
1840 167 : qry->distinctClause = transformDistinctOnClause(pstate,
1841 : stmt->distinctClause,
1842 : &qry->targetList,
1843 : qry->sortClause);
1844 159 : qry->hasDistinctOn = true;
1845 : }
1846 :
1847 : /* transform LIMIT */
1848 304185 : qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1849 : EXPR_KIND_OFFSET, "OFFSET",
1850 : stmt->limitOption);
1851 304185 : qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1852 : EXPR_KIND_LIMIT, "LIMIT",
1853 : stmt->limitOption);
1854 304177 : qry->limitOption = stmt->limitOption;
1855 :
1856 : /* transform window clauses after we have seen all window functions */
1857 304177 : qry->windowClause = transformWindowDefinitions(pstate,
1858 : pstate->p_windowdefs,
1859 : &qry->targetList);
1860 :
1861 : /* resolve any still-unresolved output columns as being type text */
1862 304133 : if (pstate->p_resolve_unknowns)
1863 276949 : resolveTargetListUnknowns(pstate, qry->targetList);
1864 :
1865 304133 : qry->rtable = pstate->p_rtable;
1866 304133 : qry->rteperminfos = pstate->p_rteperminfos;
1867 304133 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1868 :
1869 304133 : qry->hasSubLinks = pstate->p_hasSubLinks;
1870 304133 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1871 304133 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1872 304133 : qry->hasAggs = pstate->p_hasAggs;
1873 :
1874 309127 : foreach(l, stmt->lockingClause)
1875 : {
1876 5022 : transformLockingClause(pstate, qry,
1877 5022 : (LockingClause *) lfirst(l), false);
1878 : }
1879 :
1880 304105 : assign_query_collations(pstate, qry);
1881 :
1882 : /* this must be done after collations, for reliable comparison of exprs */
1883 304077 : if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1884 27732 : parseCheckAggregates(pstate, qry);
1885 :
1886 304001 : return qry;
1887 : }
1888 :
1889 : /*
1890 : * transformValuesClause -
1891 : * transforms a VALUES clause that's being used as a standalone SELECT
1892 : *
1893 : * We build a Query containing a VALUES RTE, rather as if one had written
1894 : * SELECT * FROM (VALUES ...) AS "*VALUES*"
1895 : */
1896 : static Query *
1897 5801 : transformValuesClause(ParseState *pstate, SelectStmt *stmt)
1898 : {
1899 5801 : Query *qry = makeNode(Query);
1900 5801 : List *exprsLists = NIL;
1901 5801 : List *coltypes = NIL;
1902 5801 : List *coltypmods = NIL;
1903 5801 : List *colcollations = NIL;
1904 5801 : List **colexprs = NULL;
1905 5801 : int sublist_length = -1;
1906 5801 : bool lateral = false;
1907 : ParseNamespaceItem *nsitem;
1908 : ListCell *lc;
1909 : ListCell *lc2;
1910 : int i;
1911 :
1912 5801 : qry->commandType = CMD_SELECT;
1913 :
1914 : /* Most SELECT stuff doesn't apply in a VALUES clause */
1915 : Assert(stmt->distinctClause == NIL);
1916 : Assert(stmt->intoClause == NULL);
1917 : Assert(stmt->targetList == NIL);
1918 : Assert(stmt->fromClause == NIL);
1919 : Assert(stmt->whereClause == NULL);
1920 : Assert(stmt->groupClause == NIL);
1921 : Assert(stmt->havingClause == NULL);
1922 : Assert(stmt->windowClause == NIL);
1923 : Assert(stmt->op == SETOP_NONE);
1924 :
1925 : /* process the WITH clause independently of all else */
1926 5801 : if (stmt->withClause)
1927 : {
1928 40 : qry->hasRecursive = stmt->withClause->recursive;
1929 40 : qry->cteList = transformWithClause(pstate, stmt->withClause);
1930 36 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1931 : }
1932 :
1933 : /*
1934 : * For each row of VALUES, transform the raw expressions.
1935 : *
1936 : * Note that the intermediate representation we build is column-organized
1937 : * not row-organized. That simplifies the type and collation processing
1938 : * below.
1939 : */
1940 21550 : foreach(lc, stmt->valuesLists)
1941 : {
1942 15758 : List *sublist = (List *) lfirst(lc);
1943 :
1944 : /*
1945 : * Do basic expression transformation (same as a ROW() expr, but here
1946 : * we disallow SetToDefault)
1947 : */
1948 15758 : sublist = transformExpressionList(pstate, sublist,
1949 : EXPR_KIND_VALUES, false);
1950 :
1951 : /*
1952 : * All the sublists must be the same length, *after* transformation
1953 : * (which might expand '*' into multiple items). The VALUES RTE can't
1954 : * handle anything different.
1955 : */
1956 15753 : if (sublist_length < 0)
1957 : {
1958 : /* Remember post-transformation length of first sublist */
1959 5792 : sublist_length = list_length(sublist);
1960 : /* and allocate array for per-column lists */
1961 5792 : colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1962 : }
1963 9961 : else if (sublist_length != list_length(sublist))
1964 : {
1965 0 : ereport(ERROR,
1966 : (errcode(ERRCODE_SYNTAX_ERROR),
1967 : errmsg("VALUES lists must all be the same length"),
1968 : parser_errposition(pstate,
1969 : exprLocation((Node *) sublist))));
1970 : }
1971 :
1972 : /* Build per-column expression lists */
1973 15753 : i = 0;
1974 37526 : foreach(lc2, sublist)
1975 : {
1976 21773 : Node *col = (Node *) lfirst(lc2);
1977 :
1978 21773 : colexprs[i] = lappend(colexprs[i], col);
1979 21773 : i++;
1980 : }
1981 :
1982 : /* Release sub-list's cells to save memory */
1983 15753 : list_free(sublist);
1984 :
1985 : /* Prepare an exprsLists element for this row */
1986 15753 : exprsLists = lappend(exprsLists, NIL);
1987 : }
1988 :
1989 : /*
1990 : * Now resolve the common types of the columns, and coerce everything to
1991 : * those types. Then identify the common typmod and common collation, if
1992 : * any, of each column.
1993 : *
1994 : * We must do collation processing now because (1) assign_query_collations
1995 : * doesn't process rangetable entries, and (2) we need to label the VALUES
1996 : * RTE with column collations for use in the outer query. We don't
1997 : * consider conflict of implicit collations to be an error here; instead
1998 : * the column will just show InvalidOid as its collation, and you'll get a
1999 : * failure later if that results in failure to resolve a collation.
2000 : *
2001 : * Note we modify the per-column expression lists in-place.
2002 : */
2003 13325 : for (i = 0; i < sublist_length; i++)
2004 : {
2005 : Oid coltype;
2006 : int32 coltypmod;
2007 : Oid colcoll;
2008 :
2009 7533 : coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
2010 :
2011 29306 : foreach(lc, colexprs[i])
2012 : {
2013 21773 : Node *col = (Node *) lfirst(lc);
2014 :
2015 21773 : col = coerce_to_common_type(pstate, col, coltype, "VALUES");
2016 21773 : lfirst(lc) = col;
2017 : }
2018 :
2019 7533 : coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
2020 7533 : colcoll = select_common_collation(pstate, colexprs[i], true);
2021 :
2022 7533 : coltypes = lappend_oid(coltypes, coltype);
2023 7533 : coltypmods = lappend_int(coltypmods, coltypmod);
2024 7533 : colcollations = lappend_oid(colcollations, colcoll);
2025 : }
2026 :
2027 : /*
2028 : * Finally, rearrange the coerced expressions into row-organized lists.
2029 : */
2030 13325 : for (i = 0; i < sublist_length; i++)
2031 : {
2032 29306 : forboth(lc, colexprs[i], lc2, exprsLists)
2033 : {
2034 21773 : Node *col = (Node *) lfirst(lc);
2035 21773 : List *sublist = lfirst(lc2);
2036 :
2037 21773 : sublist = lappend(sublist, col);
2038 21773 : lfirst(lc2) = sublist;
2039 : }
2040 7533 : list_free(colexprs[i]);
2041 : }
2042 :
2043 : /*
2044 : * Ordinarily there can't be any current-level Vars in the expression
2045 : * lists, because the namespace was empty ... but if we're inside CREATE
2046 : * RULE, then NEW/OLD references might appear. In that case we have to
2047 : * mark the VALUES RTE as LATERAL.
2048 : */
2049 5797 : if (pstate->p_rtable != NIL &&
2050 5 : contain_vars_of_level((Node *) exprsLists, 0))
2051 5 : lateral = true;
2052 :
2053 : /*
2054 : * Generate the VALUES RTE
2055 : */
2056 5792 : nsitem = addRangeTableEntryForValues(pstate, exprsLists,
2057 : coltypes, coltypmods, colcollations,
2058 : NULL, lateral, true);
2059 5792 : addNSItemToQuery(pstate, nsitem, true, true, true);
2060 :
2061 : /*
2062 : * Generate a targetlist as though expanding "*"
2063 : */
2064 : Assert(pstate->p_next_resno == 1);
2065 5792 : qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
2066 :
2067 : /*
2068 : * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2069 : * VALUES, so cope.
2070 : */
2071 5792 : qry->sortClause = transformSortClause(pstate,
2072 : stmt->sortClause,
2073 : &qry->targetList,
2074 : EXPR_KIND_ORDER_BY,
2075 : false /* allow SQL92 rules */ );
2076 :
2077 5792 : qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2078 : EXPR_KIND_OFFSET, "OFFSET",
2079 : stmt->limitOption);
2080 5792 : qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2081 : EXPR_KIND_LIMIT, "LIMIT",
2082 : stmt->limitOption);
2083 5792 : qry->limitOption = stmt->limitOption;
2084 :
2085 5792 : if (stmt->lockingClause)
2086 0 : ereport(ERROR,
2087 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2088 : /*------
2089 : translator: %s is a SQL row locking clause such as FOR UPDATE */
2090 : errmsg("%s cannot be applied to VALUES",
2091 : LCS_asString(((LockingClause *)
2092 : linitial(stmt->lockingClause))->strength))));
2093 :
2094 5792 : qry->rtable = pstate->p_rtable;
2095 5792 : qry->rteperminfos = pstate->p_rteperminfos;
2096 5792 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2097 :
2098 5792 : qry->hasSubLinks = pstate->p_hasSubLinks;
2099 :
2100 5792 : assign_query_collations(pstate, qry);
2101 :
2102 5792 : return qry;
2103 : }
2104 :
2105 : /*
2106 : * transformSetOperationStmt -
2107 : * transforms a set-operations tree
2108 : *
2109 : * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
2110 : * structure to it. We must transform each leaf SELECT and build up a top-
2111 : * level Query that contains the leaf SELECTs as subqueries in its rangetable.
2112 : * The tree of set operations is converted into the setOperations field of
2113 : * the top-level Query.
2114 : */
2115 : static Query *
2116 8593 : transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
2117 : {
2118 8593 : Query *qry = makeNode(Query);
2119 : SelectStmt *leftmostSelect;
2120 : int leftmostRTI;
2121 : Query *leftmostQuery;
2122 : SetOperationStmt *sostmt;
2123 : List *sortClause;
2124 : Node *limitOffset;
2125 : Node *limitCount;
2126 : List *lockingClause;
2127 : WithClause *withClause;
2128 : Node *node;
2129 : ListCell *left_tlist,
2130 : *lct,
2131 : *lcm,
2132 : *lcc,
2133 : *l;
2134 : List *targetvars,
2135 : *targetnames,
2136 : *sv_namespace;
2137 : int sv_rtable_length;
2138 : ParseNamespaceItem *jnsitem;
2139 : ParseNamespaceColumn *sortnscolumns;
2140 : int sortcolindex;
2141 : int tllen;
2142 :
2143 8593 : qry->commandType = CMD_SELECT;
2144 :
2145 : /*
2146 : * Find leftmost leaf SelectStmt. We currently only need to do this in
2147 : * order to deliver a suitable error message if there's an INTO clause
2148 : * there, implying the set-op tree is in a context that doesn't allow
2149 : * INTO. (transformSetOperationTree would throw error anyway, but it
2150 : * seems worth the trouble to throw a different error for non-leftmost
2151 : * INTO, so we produce that error in transformSetOperationTree.)
2152 : */
2153 8593 : leftmostSelect = stmt->larg;
2154 13018 : while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2155 4425 : leftmostSelect = leftmostSelect->larg;
2156 : Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
2157 : leftmostSelect->larg == NULL);
2158 8593 : if (leftmostSelect->intoClause)
2159 0 : ereport(ERROR,
2160 : (errcode(ERRCODE_SYNTAX_ERROR),
2161 : errmsg("SELECT ... INTO is not allowed here"),
2162 : parser_errposition(pstate,
2163 : exprLocation((Node *) leftmostSelect->intoClause))));
2164 :
2165 : /*
2166 : * We need to extract ORDER BY and other top-level clauses here and not
2167 : * let transformSetOperationTree() see them --- else it'll just recurse
2168 : * right back here!
2169 : */
2170 8593 : sortClause = stmt->sortClause;
2171 8593 : limitOffset = stmt->limitOffset;
2172 8593 : limitCount = stmt->limitCount;
2173 8593 : lockingClause = stmt->lockingClause;
2174 8593 : withClause = stmt->withClause;
2175 :
2176 8593 : stmt->sortClause = NIL;
2177 8593 : stmt->limitOffset = NULL;
2178 8593 : stmt->limitCount = NULL;
2179 8593 : stmt->lockingClause = NIL;
2180 8593 : stmt->withClause = NULL;
2181 :
2182 : /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2183 8593 : if (lockingClause)
2184 4 : ereport(ERROR,
2185 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2186 : /*------
2187 : translator: %s is a SQL row locking clause such as FOR UPDATE */
2188 : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2189 : LCS_asString(((LockingClause *)
2190 : linitial(lockingClause))->strength))));
2191 :
2192 : /* Process the WITH clause independently of all else */
2193 8589 : if (withClause)
2194 : {
2195 170 : qry->hasRecursive = withClause->recursive;
2196 170 : qry->cteList = transformWithClause(pstate, withClause);
2197 170 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2198 : }
2199 :
2200 : /*
2201 : * Recursively transform the components of the tree.
2202 : */
2203 8589 : sostmt = castNode(SetOperationStmt,
2204 : transformSetOperationTree(pstate, stmt, true, NULL));
2205 : Assert(sostmt);
2206 8541 : qry->setOperations = (Node *) sostmt;
2207 :
2208 : /*
2209 : * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2210 : */
2211 8541 : node = sostmt->larg;
2212 12954 : while (node && IsA(node, SetOperationStmt))
2213 4413 : node = ((SetOperationStmt *) node)->larg;
2214 : Assert(node && IsA(node, RangeTblRef));
2215 8541 : leftmostRTI = ((RangeTblRef *) node)->rtindex;
2216 8541 : leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2217 : Assert(leftmostQuery != NULL);
2218 :
2219 : /*
2220 : * Generate dummy targetlist for outer query using column names of
2221 : * leftmost select and common datatypes/collations of topmost set
2222 : * operation. Also make lists of the dummy vars and their names for use
2223 : * in parsing ORDER BY.
2224 : *
2225 : * Note: we use leftmostRTI as the varno of the dummy variables. It
2226 : * shouldn't matter too much which RT index they have, as long as they
2227 : * have one that corresponds to a real RT entry; else funny things may
2228 : * happen when the tree is mashed by rule rewriting.
2229 : */
2230 8541 : qry->targetList = NIL;
2231 8541 : targetvars = NIL;
2232 8541 : targetnames = NIL;
2233 : sortnscolumns = (ParseNamespaceColumn *)
2234 8541 : palloc0(list_length(sostmt->colTypes) * sizeof(ParseNamespaceColumn));
2235 8541 : sortcolindex = 0;
2236 :
2237 29483 : forfour(lct, sostmt->colTypes,
2238 : lcm, sostmt->colTypmods,
2239 : lcc, sostmt->colCollations,
2240 : left_tlist, leftmostQuery->targetList)
2241 : {
2242 20942 : Oid colType = lfirst_oid(lct);
2243 20942 : int32 colTypmod = lfirst_int(lcm);
2244 20942 : Oid colCollation = lfirst_oid(lcc);
2245 20942 : TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2246 : char *colName;
2247 : TargetEntry *tle;
2248 : Var *var;
2249 :
2250 : Assert(!lefttle->resjunk);
2251 20942 : colName = pstrdup(lefttle->resname);
2252 20942 : var = makeVar(leftmostRTI,
2253 20942 : lefttle->resno,
2254 : colType,
2255 : colTypmod,
2256 : colCollation,
2257 : 0);
2258 20942 : var->location = exprLocation((Node *) lefttle->expr);
2259 20942 : tle = makeTargetEntry((Expr *) var,
2260 20942 : (AttrNumber) pstate->p_next_resno++,
2261 : colName,
2262 : false);
2263 20942 : qry->targetList = lappend(qry->targetList, tle);
2264 20942 : targetvars = lappend(targetvars, var);
2265 20942 : targetnames = lappend(targetnames, makeString(colName));
2266 20942 : sortnscolumns[sortcolindex].p_varno = leftmostRTI;
2267 20942 : sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
2268 20942 : sortnscolumns[sortcolindex].p_vartype = colType;
2269 20942 : sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
2270 20942 : sortnscolumns[sortcolindex].p_varcollid = colCollation;
2271 20942 : sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
2272 20942 : sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
2273 20942 : sortcolindex++;
2274 : }
2275 :
2276 : /*
2277 : * As a first step towards supporting sort clauses that are expressions
2278 : * using the output columns, generate a namespace entry that makes the
2279 : * output columns visible. A Join RTE node is handy for this, since we
2280 : * can easily control the Vars generated upon matches.
2281 : *
2282 : * Note: we don't yet do anything useful with such cases, but at least
2283 : * "ORDER BY upper(foo)" will draw the right error message rather than
2284 : * "foo not found".
2285 : */
2286 8541 : sv_rtable_length = list_length(pstate->p_rtable);
2287 :
2288 8541 : jnsitem = addRangeTableEntryForJoin(pstate,
2289 : targetnames,
2290 : sortnscolumns,
2291 : JOIN_INNER,
2292 : 0,
2293 : targetvars,
2294 : NIL,
2295 : NIL,
2296 : NULL,
2297 : NULL,
2298 : false);
2299 :
2300 8541 : sv_namespace = pstate->p_namespace;
2301 8541 : pstate->p_namespace = NIL;
2302 :
2303 : /* add jnsitem to column namespace only */
2304 8541 : addNSItemToQuery(pstate, jnsitem, false, false, true);
2305 :
2306 : /*
2307 : * For now, we don't support resjunk sort clauses on the output of a
2308 : * setOperation tree --- you can only use the SQL92-spec options of
2309 : * selecting an output column by name or number. Enforce by checking that
2310 : * transformSortClause doesn't add any items to tlist. Note, if changing
2311 : * this, add_setop_child_rel_equivalences() will need to be updated.
2312 : */
2313 8541 : tllen = list_length(qry->targetList);
2314 :
2315 8541 : qry->sortClause = transformSortClause(pstate,
2316 : sortClause,
2317 : &qry->targetList,
2318 : EXPR_KIND_ORDER_BY,
2319 : false /* allow SQL92 rules */ );
2320 :
2321 : /* restore namespace, remove join RTE from rtable */
2322 8537 : pstate->p_namespace = sv_namespace;
2323 8537 : pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
2324 :
2325 8537 : if (tllen != list_length(qry->targetList))
2326 0 : ereport(ERROR,
2327 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2328 : errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2329 : errdetail("Only result column names can be used, not expressions or functions."),
2330 : errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
2331 : parser_errposition(pstate,
2332 : exprLocation(list_nth(qry->targetList, tllen)))));
2333 :
2334 8537 : qry->limitOffset = transformLimitClause(pstate, limitOffset,
2335 : EXPR_KIND_OFFSET, "OFFSET",
2336 : stmt->limitOption);
2337 8537 : qry->limitCount = transformLimitClause(pstate, limitCount,
2338 : EXPR_KIND_LIMIT, "LIMIT",
2339 : stmt->limitOption);
2340 8537 : qry->limitOption = stmt->limitOption;
2341 :
2342 8537 : qry->rtable = pstate->p_rtable;
2343 8537 : qry->rteperminfos = pstate->p_rteperminfos;
2344 8537 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2345 :
2346 8537 : qry->hasSubLinks = pstate->p_hasSubLinks;
2347 8537 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2348 8537 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2349 8537 : qry->hasAggs = pstate->p_hasAggs;
2350 :
2351 8537 : foreach(l, lockingClause)
2352 : {
2353 0 : transformLockingClause(pstate, qry,
2354 0 : (LockingClause *) lfirst(l), false);
2355 : }
2356 :
2357 8537 : assign_query_collations(pstate, qry);
2358 :
2359 : /* this must be done after collations, for reliable comparison of exprs */
2360 8537 : if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2361 0 : parseCheckAggregates(pstate, qry);
2362 :
2363 8537 : return qry;
2364 : }
2365 :
2366 : /*
2367 : * Make a SortGroupClause node for a SetOperationStmt's groupClauses
2368 : *
2369 : * If require_hash is true, the caller is indicating that they need hash
2370 : * support or they will fail. So look extra hard for hash support.
2371 : */
2372 : SortGroupClause *
2373 17573 : makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
2374 : {
2375 17573 : SortGroupClause *grpcl = makeNode(SortGroupClause);
2376 : Oid sortop;
2377 : Oid eqop;
2378 : bool hashable;
2379 :
2380 : /* determine the eqop and optional sortop */
2381 17573 : get_sort_group_operators(rescoltype,
2382 : false, true, false,
2383 : &sortop, &eqop, NULL,
2384 : &hashable);
2385 :
2386 : /*
2387 : * The type cache doesn't believe that record is hashable (see
2388 : * cache_record_field_properties()), but if the caller really needs hash
2389 : * support, we can assume it does. Worst case, if any components of the
2390 : * record don't support hashing, we will fail at execution.
2391 : */
2392 17573 : if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
2393 16 : hashable = true;
2394 :
2395 : /* we don't have a tlist yet, so can't assign sortgrouprefs */
2396 17573 : grpcl->tleSortGroupRef = 0;
2397 17573 : grpcl->eqop = eqop;
2398 17573 : grpcl->sortop = sortop;
2399 17573 : grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2400 17573 : grpcl->nulls_first = false; /* OK with or without sortop */
2401 17573 : grpcl->hashable = hashable;
2402 :
2403 17573 : return grpcl;
2404 : }
2405 :
2406 : /*
2407 : * transformSetOperationTree
2408 : * Recursively transform leaves and internal nodes of a set-op tree
2409 : *
2410 : * In addition to returning the transformed node, if targetlist isn't NULL
2411 : * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
2412 : * set-op node these are the actual targetlist entries; otherwise they are
2413 : * dummy entries created to carry the type, typmod, collation, and location
2414 : * (for error messages) of each output column of the set-op node. This info
2415 : * is needed only during the internal recursion of this function, so outside
2416 : * callers pass NULL for targetlist. Note: the reason for passing the
2417 : * actual targetlist entries of a leaf node is so that upper levels can
2418 : * replace UNKNOWN Consts with properly-coerced constants.
2419 : */
2420 : static Node *
2421 34693 : transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
2422 : bool isTopLevel, List **targetlist)
2423 : {
2424 : bool isLeaf;
2425 :
2426 : Assert(stmt && IsA(stmt, SelectStmt));
2427 :
2428 : /* Guard against stack overflow due to overly complex set-expressions */
2429 34693 : check_stack_depth();
2430 :
2431 : /*
2432 : * Validity-check both leaf and internal SELECTs for disallowed ops.
2433 : */
2434 34693 : if (stmt->intoClause)
2435 0 : ereport(ERROR,
2436 : (errcode(ERRCODE_SYNTAX_ERROR),
2437 : errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
2438 : parser_errposition(pstate,
2439 : exprLocation((Node *) stmt->intoClause))));
2440 :
2441 : /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2442 34693 : if (stmt->lockingClause)
2443 0 : ereport(ERROR,
2444 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2445 : /*------
2446 : translator: %s is a SQL row locking clause such as FOR UPDATE */
2447 : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2448 : LCS_asString(((LockingClause *)
2449 : linitial(stmt->lockingClause))->strength))));
2450 :
2451 : /*
2452 : * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
2453 : * or WITH clauses attached, we need to treat it like a leaf node to
2454 : * generate an independent sub-Query tree. Otherwise, it can be
2455 : * represented by a SetOperationStmt node underneath the parent Query.
2456 : */
2457 34693 : if (stmt->op == SETOP_NONE)
2458 : {
2459 : Assert(stmt->larg == NULL && stmt->rarg == NULL);
2460 21599 : isLeaf = true;
2461 : }
2462 : else
2463 : {
2464 : Assert(stmt->larg != NULL && stmt->rarg != NULL);
2465 13094 : if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2466 13078 : stmt->lockingClause || stmt->withClause)
2467 40 : isLeaf = true;
2468 : else
2469 13054 : isLeaf = false;
2470 : }
2471 :
2472 34693 : if (isLeaf)
2473 : {
2474 : /* Process leaf SELECT */
2475 : Query *selectQuery;
2476 : ParseNamespaceItem *nsitem;
2477 : RangeTblRef *rtr;
2478 :
2479 : /*
2480 : * Transform SelectStmt into a Query.
2481 : *
2482 : * This works the same as SELECT transformation normally would, except
2483 : * that we prevent resolving unknown-type outputs as TEXT. This does
2484 : * not change the subquery's semantics since if the column type
2485 : * matters semantically, it would have been resolved to something else
2486 : * anyway. Doing this lets us resolve such outputs using
2487 : * select_common_type(), below.
2488 : *
2489 : * Note: previously transformed sub-queries don't affect the parsing
2490 : * of this sub-query, because they are not in the toplevel pstate's
2491 : * namespace list.
2492 : */
2493 21639 : selectQuery = parse_sub_analyze((Node *) stmt, pstate,
2494 : NULL, false, false);
2495 :
2496 : /*
2497 : * Check for bogus references to Vars on the current query level (but
2498 : * upper-level references are okay). Normally this can't happen
2499 : * because the namespace will be empty, but it could happen if we are
2500 : * inside a rule.
2501 : */
2502 21619 : if (pstate->p_namespace)
2503 : {
2504 0 : if (contain_vars_of_level((Node *) selectQuery, 1))
2505 0 : ereport(ERROR,
2506 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2507 : errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2508 : parser_errposition(pstate,
2509 : locate_var_of_level((Node *) selectQuery, 1))));
2510 : }
2511 :
2512 : /*
2513 : * Extract a list of the non-junk TLEs for upper-level processing.
2514 : */
2515 21619 : if (targetlist)
2516 : {
2517 : ListCell *tl;
2518 :
2519 21619 : *targetlist = NIL;
2520 82906 : foreach(tl, selectQuery->targetList)
2521 : {
2522 61287 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2523 :
2524 61287 : if (!tle->resjunk)
2525 61279 : *targetlist = lappend(*targetlist, tle);
2526 : }
2527 : }
2528 :
2529 : /*
2530 : * Make the leaf query be a subquery in the top-level rangetable.
2531 : */
2532 21619 : nsitem = addRangeTableEntryForSubquery(pstate,
2533 : selectQuery,
2534 : NULL,
2535 : false,
2536 : false);
2537 :
2538 : /*
2539 : * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2540 : */
2541 21619 : rtr = makeNode(RangeTblRef);
2542 21619 : rtr->rtindex = nsitem->p_rtindex;
2543 21619 : return (Node *) rtr;
2544 : }
2545 : else
2546 : {
2547 : /* Process an internal node (set operation node) */
2548 13054 : SetOperationStmt *op = makeNode(SetOperationStmt);
2549 : List *ltargetlist;
2550 : List *rtargetlist;
2551 : const char *context;
2552 13859 : bool recursive = (pstate->p_parent_cte &&
2553 805 : pstate->p_parent_cte->cterecursive);
2554 :
2555 13550 : context = (stmt->op == SETOP_UNION ? "UNION" :
2556 496 : (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2557 : "EXCEPT"));
2558 :
2559 13054 : op->op = stmt->op;
2560 13054 : op->all = stmt->all;
2561 :
2562 : /*
2563 : * Recursively transform the left child node.
2564 : */
2565 13054 : op->larg = transformSetOperationTree(pstate, stmt->larg,
2566 : false,
2567 : <argetlist);
2568 :
2569 : /*
2570 : * If we are processing a recursive union query, now is the time to
2571 : * examine the non-recursive term's output columns and mark the
2572 : * containing CTE as having those result columns. We should do this
2573 : * only at the topmost setop of the CTE, of course.
2574 : */
2575 13050 : if (isTopLevel && recursive)
2576 709 : determineRecursiveColTypes(pstate, op->larg, ltargetlist);
2577 :
2578 : /*
2579 : * Recursively transform the right child node.
2580 : */
2581 13050 : op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2582 : false,
2583 : &rtargetlist);
2584 :
2585 13034 : constructSetOpTargetlist(pstate, op, ltargetlist, rtargetlist, targetlist,
2586 : context, recursive);
2587 :
2588 13006 : return (Node *) op;
2589 : }
2590 : }
2591 :
2592 : /*
2593 : * constructSetOpTargetlist
2594 : * Compute the types, typmods and collations of the columns in the target
2595 : * list of the given set operation.
2596 : *
2597 : * For every pair of columns in the targetlists of the children, compute the
2598 : * common type, typmod, and collation representing the output (UNION) column.
2599 : * If targetlist is not NULL, also build the dummy output targetlist
2600 : * containing non-resjunk output columns. The values are stored into the
2601 : * given SetOperationStmt node. context is a string for error messages
2602 : * ("UNION" etc.). recursive is true if it is a recursive union.
2603 : */
2604 : void
2605 13440 : constructSetOpTargetlist(ParseState *pstate, SetOperationStmt *op,
2606 : const List *ltargetlist, const List *rtargetlist,
2607 : List **targetlist, const char *context, bool recursive)
2608 : {
2609 : ListCell *ltl;
2610 : ListCell *rtl;
2611 :
2612 : /*
2613 : * Verify that the two children have the same number of non-junk columns,
2614 : * and determine the types of the merged output columns.
2615 : */
2616 13440 : if (list_length(ltargetlist) != list_length(rtargetlist))
2617 0 : ereport(ERROR,
2618 : (errcode(ERRCODE_SYNTAX_ERROR),
2619 : errmsg("each %s query must have the same number of columns",
2620 : context),
2621 : parser_errposition(pstate,
2622 : exprLocation((const Node *) rtargetlist))));
2623 :
2624 13440 : if (targetlist)
2625 4737 : *targetlist = NIL;
2626 13440 : op->colTypes = NIL;
2627 13440 : op->colTypmods = NIL;
2628 13440 : op->colCollations = NIL;
2629 13440 : op->groupClauses = NIL;
2630 :
2631 54716 : forboth(ltl, ltargetlist, rtl, rtargetlist)
2632 : {
2633 41304 : TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
2634 41304 : TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
2635 41304 : Node *lcolnode = (Node *) ltle->expr;
2636 41304 : Node *rcolnode = (Node *) rtle->expr;
2637 41304 : Oid lcoltype = exprType(lcolnode);
2638 41304 : Oid rcoltype = exprType(rcolnode);
2639 : Node *bestexpr;
2640 : int bestlocation;
2641 : Oid rescoltype;
2642 : int32 rescoltypmod;
2643 : Oid rescolcoll;
2644 :
2645 : /* select common type, same as CASE et al */
2646 41304 : rescoltype = select_common_type(pstate,
2647 : list_make2(lcolnode, rcolnode),
2648 : context,
2649 : &bestexpr);
2650 41304 : bestlocation = exprLocation(bestexpr);
2651 :
2652 : /*
2653 : * Verify the coercions are actually possible. If not, we'd fail
2654 : * later anyway, but we want to fail now while we have sufficient
2655 : * context to produce an error cursor position.
2656 : *
2657 : * For all non-UNKNOWN-type cases, we verify coercibility but we don't
2658 : * modify the child's expression, for fear of changing the child
2659 : * query's semantics.
2660 : *
2661 : * If a child expression is an UNKNOWN-type Const or Param, we want to
2662 : * replace it with the coerced expression. This can only happen when
2663 : * the child is a leaf set-op node. It's safe to replace the
2664 : * expression because if the child query's semantics depended on the
2665 : * type of this output column, it'd have already coerced the UNKNOWN
2666 : * to something else. We want to do this because (a) we want to
2667 : * verify that a Const is valid for the target type, or resolve the
2668 : * actual type of an UNKNOWN Param, and (b) we want to avoid
2669 : * unnecessary discrepancies between the output type of the child
2670 : * query and the resolved target type. Such a discrepancy would
2671 : * disable optimization in the planner.
2672 : *
2673 : * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2674 : * (knowing that coerce_to_common_type would fail). The planner is
2675 : * sometimes able to fold an UNKNOWN Var to a constant before it has
2676 : * to coerce the type, so failing now would just break cases that
2677 : * might work.
2678 : */
2679 41304 : if (lcoltype != UNKNOWNOID)
2680 36995 : lcolnode = coerce_to_common_type(pstate, lcolnode,
2681 : rescoltype, context);
2682 4309 : else if (IsA(lcolnode, Const) ||
2683 0 : IsA(lcolnode, Param))
2684 : {
2685 4309 : lcolnode = coerce_to_common_type(pstate, lcolnode,
2686 : rescoltype, context);
2687 4309 : ltle->expr = (Expr *) lcolnode;
2688 : }
2689 :
2690 41304 : if (rcoltype != UNKNOWNOID)
2691 36451 : rcolnode = coerce_to_common_type(pstate, rcolnode,
2692 : rescoltype, context);
2693 4853 : else if (IsA(rcolnode, Const) ||
2694 0 : IsA(rcolnode, Param))
2695 : {
2696 4853 : rcolnode = coerce_to_common_type(pstate, rcolnode,
2697 : rescoltype, context);
2698 4849 : rtle->expr = (Expr *) rcolnode;
2699 : }
2700 :
2701 41300 : rescoltypmod = select_common_typmod(pstate,
2702 : list_make2(lcolnode, rcolnode),
2703 : rescoltype);
2704 :
2705 : /*
2706 : * Select common collation. A common collation is required for all
2707 : * set operators except UNION ALL; see SQL:2008 7.13 <query
2708 : * expression> Syntax Rule 15c. (If we fail to identify a common
2709 : * collation for a UNION ALL column, the colCollations element will be
2710 : * set to InvalidOid, which may result in a runtime error if something
2711 : * at a higher query level wants to use the column's collation.)
2712 : */
2713 41300 : rescolcoll = select_common_collation(pstate,
2714 : list_make2(lcolnode, rcolnode),
2715 41300 : (op->op == SETOP_UNION && op->all));
2716 :
2717 : /* emit results */
2718 41276 : op->colTypes = lappend_oid(op->colTypes, rescoltype);
2719 41276 : op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2720 41276 : op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2721 :
2722 : /*
2723 : * For all cases except UNION ALL, identify the grouping operators
2724 : * (and, if available, sorting operators) that will be used to
2725 : * eliminate duplicates.
2726 : */
2727 41276 : if (op->op != SETOP_UNION || !op->all)
2728 : {
2729 : ParseCallbackState pcbstate;
2730 :
2731 17557 : setup_parser_errposition_callback(&pcbstate, pstate,
2732 : bestlocation);
2733 :
2734 : /* If it's a recursive union, we need to require hashing support. */
2735 17557 : op->groupClauses = lappend(op->groupClauses,
2736 17557 : makeSortGroupClauseForSetOp(rescoltype, recursive));
2737 :
2738 17557 : cancel_parser_errposition_callback(&pcbstate);
2739 : }
2740 :
2741 : /*
2742 : * Construct a dummy tlist entry to return. We use a SetToDefault
2743 : * node for the expression, since it carries exactly the fields
2744 : * needed, but any other expression node type would do as well.
2745 : */
2746 41276 : if (targetlist)
2747 : {
2748 19955 : SetToDefault *rescolnode = makeNode(SetToDefault);
2749 : TargetEntry *restle;
2750 :
2751 19955 : rescolnode->typeId = rescoltype;
2752 19955 : rescolnode->typeMod = rescoltypmod;
2753 19955 : rescolnode->collation = rescolcoll;
2754 19955 : rescolnode->location = bestlocation;
2755 19955 : restle = makeTargetEntry((Expr *) rescolnode,
2756 : 0, /* no need to set resno */
2757 : NULL,
2758 : false);
2759 19955 : *targetlist = lappend(*targetlist, restle);
2760 : }
2761 : }
2762 13412 : }
2763 :
2764 : /*
2765 : * Process the outputs of the non-recursive term of a recursive union
2766 : * to set up the parent CTE's columns
2767 : */
2768 : static void
2769 709 : determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
2770 : {
2771 : Node *node;
2772 : int leftmostRTI;
2773 : Query *leftmostQuery;
2774 : List *targetList;
2775 : ListCell *left_tlist;
2776 : ListCell *nrtl;
2777 : int next_resno;
2778 :
2779 : /*
2780 : * Find leftmost leaf SELECT
2781 : */
2782 709 : node = larg;
2783 713 : while (node && IsA(node, SetOperationStmt))
2784 4 : node = ((SetOperationStmt *) node)->larg;
2785 : Assert(node && IsA(node, RangeTblRef));
2786 709 : leftmostRTI = ((RangeTblRef *) node)->rtindex;
2787 709 : leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2788 : Assert(leftmostQuery != NULL);
2789 :
2790 : /*
2791 : * Generate dummy targetlist using column names of leftmost select and
2792 : * dummy result expressions of the non-recursive term.
2793 : */
2794 709 : targetList = NIL;
2795 709 : next_resno = 1;
2796 :
2797 2256 : forboth(nrtl, nrtargetlist, left_tlist, leftmostQuery->targetList)
2798 : {
2799 1547 : TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
2800 1547 : TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2801 : char *colName;
2802 : TargetEntry *tle;
2803 :
2804 : Assert(!lefttle->resjunk);
2805 1547 : colName = pstrdup(lefttle->resname);
2806 1547 : tle = makeTargetEntry(nrtle->expr,
2807 1547 : next_resno++,
2808 : colName,
2809 : false);
2810 1547 : targetList = lappend(targetList, tle);
2811 : }
2812 :
2813 : /* Now build CTE's output column info using dummy targetlist */
2814 709 : analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2815 709 : }
2816 :
2817 :
2818 : /*
2819 : * transformReturnStmt -
2820 : * transforms a return statement
2821 : */
2822 : static Query *
2823 2776 : transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
2824 : {
2825 2776 : Query *qry = makeNode(Query);
2826 :
2827 2776 : qry->commandType = CMD_SELECT;
2828 2776 : qry->isReturn = true;
2829 :
2830 2776 : qry->targetList = list_make1(makeTargetEntry((Expr *) transformExpr(pstate, stmt->returnval, EXPR_KIND_SELECT_TARGET),
2831 : 1, NULL, false));
2832 :
2833 2772 : if (pstate->p_resolve_unknowns)
2834 2772 : resolveTargetListUnknowns(pstate, qry->targetList);
2835 2772 : qry->rtable = pstate->p_rtable;
2836 2772 : qry->rteperminfos = pstate->p_rteperminfos;
2837 2772 : qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2838 2772 : qry->hasSubLinks = pstate->p_hasSubLinks;
2839 2772 : qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2840 2772 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2841 2772 : qry->hasAggs = pstate->p_hasAggs;
2842 :
2843 2772 : assign_query_collations(pstate, qry);
2844 :
2845 2772 : return qry;
2846 : }
2847 :
2848 :
2849 : /*
2850 : * transformUpdateStmt -
2851 : * transforms an update statement
2852 : */
2853 : static Query *
2854 9280 : transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2855 : {
2856 9280 : Query *qry = makeNode(Query);
2857 : ParseNamespaceItem *nsitem;
2858 : Node *qual;
2859 :
2860 9280 : qry->commandType = CMD_UPDATE;
2861 :
2862 : /* process the WITH clause independently of all else */
2863 9280 : if (stmt->withClause)
2864 : {
2865 55 : qry->hasRecursive = stmt->withClause->recursive;
2866 55 : qry->cteList = transformWithClause(pstate, stmt->withClause);
2867 55 : qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2868 : }
2869 :
2870 18559 : qry->resultRelation = setTargetTable(pstate, stmt->relation,
2871 9280 : stmt->relation->inh,
2872 : true,
2873 : ACL_UPDATE);
2874 :
2875 : /* disallow UPDATE ... WHERE CURRENT OF on a view */
2876 9279 : if (stmt->whereClause &&
2877 6963 : IsA(stmt->whereClause, CurrentOfExpr) &&
2878 104 : pstate->p_target_relation->rd_rel->relkind == RELKIND_VIEW)
2879 4 : ereport(ERROR,
2880 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2881 : errmsg("WHERE CURRENT OF on a view is not implemented"));
2882 :
2883 9275 : if (stmt->forPortionOf)
2884 511 : qry->forPortionOf = transformForPortionOfClause(pstate,
2885 : qry->resultRelation,
2886 576 : stmt->forPortionOf,
2887 : true);
2888 :
2889 9210 : nsitem = pstate->p_target_nsitem;
2890 :
2891 : /* subqueries in FROM cannot access the result relation */
2892 9210 : nsitem->p_lateral_only = true;
2893 9210 : nsitem->p_lateral_ok = false;
2894 :
2895 : /*
2896 : * the FROM clause is non-standard SQL syntax. We used to be able to do
2897 : * this with REPLACE in POSTQUEL so we keep the feature.
2898 : */
2899 9210 : transformFromClause(pstate, stmt->fromClause);
2900 :
2901 : /* remaining clauses can reference the result relation normally */
2902 9194 : nsitem->p_lateral_only = false;
2903 9194 : nsitem->p_lateral_ok = true;
2904 :
2905 9194 : qual = transformWhereClause(pstate, stmt->whereClause,
2906 : EXPR_KIND_WHERE, "WHERE");
2907 :
2908 9186 : transformReturningClause(pstate, qry, stmt->returningClause,
2909 : EXPR_KIND_RETURNING);
2910 :
2911 : /*
2912 : * Now we are done with SELECT-like processing, and can get on with
2913 : * transforming the target list to match the UPDATE target columns.
2914 : */
2915 9174 : qry->targetList = transformUpdateTargetList(pstate, stmt->targetList,
2916 : qry->forPortionOf);
2917 :
2918 9138 : qry->rtable = pstate->p_rtable;
2919 9138 : qry->rteperminfos = pstate->p_rteperminfos;
2920 9138 : qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2921 :
2922 9138 : qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2923 9138 : qry->hasSubLinks = pstate->p_hasSubLinks;
2924 :
2925 9138 : assign_query_collations(pstate, qry);
2926 :
2927 9138 : return qry;
2928 : }
2929 :
2930 : /*
2931 : * transformUpdateTargetList -
2932 : * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2933 : */
2934 : List *
2935 11077 : transformUpdateTargetList(ParseState *pstate, List *origTlist, ForPortionOfExpr *forPortionOf)
2936 : {
2937 11077 : List *tlist = NIL;
2938 : RTEPermissionInfo *target_perminfo;
2939 : ListCell *orig_tl;
2940 : ListCell *tl;
2941 :
2942 11077 : tlist = transformTargetList(pstate, origTlist,
2943 : EXPR_KIND_UPDATE_SOURCE);
2944 :
2945 : /* Prepare to assign non-conflicting resnos to resjunk attributes */
2946 11045 : if (pstate->p_next_resno <= RelationGetNumberOfAttributes(pstate->p_target_relation))
2947 9386 : pstate->p_next_resno = RelationGetNumberOfAttributes(pstate->p_target_relation) + 1;
2948 :
2949 : /* Prepare non-junk columns for assignment to target table */
2950 11045 : target_perminfo = pstate->p_target_nsitem->p_perminfo;
2951 11045 : orig_tl = list_head(origTlist);
2952 :
2953 24722 : foreach(tl, tlist)
2954 : {
2955 13705 : TargetEntry *tle = (TargetEntry *) lfirst(tl);
2956 : ResTarget *origTarget;
2957 : int attrno;
2958 :
2959 13705 : if (tle->resjunk)
2960 : {
2961 : /*
2962 : * Resjunk nodes need no additional processing, but be sure they
2963 : * have resnos that do not match any target columns; else rewriter
2964 : * or planner might get confused. They don't need a resname
2965 : * either.
2966 : */
2967 91 : tle->resno = (AttrNumber) pstate->p_next_resno++;
2968 91 : tle->resname = NULL;
2969 91 : continue;
2970 : }
2971 13614 : if (orig_tl == NULL)
2972 0 : elog(ERROR, "UPDATE target count mismatch --- internal error");
2973 13614 : origTarget = lfirst_node(ResTarget, orig_tl);
2974 :
2975 13614 : attrno = attnameAttNum(pstate->p_target_relation,
2976 13614 : origTarget->name, true);
2977 13614 : if (attrno == InvalidAttrNumber)
2978 16 : ereport(ERROR,
2979 : (errcode(ERRCODE_UNDEFINED_COLUMN),
2980 : errmsg("column \"%s\" of relation \"%s\" does not exist",
2981 : origTarget->name,
2982 : RelationGetRelationName(pstate->p_target_relation)),
2983 : (origTarget->indirection != NIL &&
2984 : strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2985 : errhint("SET target columns cannot be qualified with the relation name.") : 0,
2986 : parser_errposition(pstate, origTarget->location)));
2987 :
2988 : /*
2989 : * If this is a FOR PORTION OF update, forbid directly setting the
2990 : * range column, since that would conflict with the implicit updates.
2991 : */
2992 13598 : if (forPortionOf != NULL)
2993 : {
2994 524 : if (attrno == forPortionOf->rangeVar->varattno)
2995 4 : ereport(ERROR,
2996 : (errcode(ERRCODE_SYNTAX_ERROR),
2997 : errmsg("cannot update column \"%s\" because it is used in FOR PORTION OF",
2998 : origTarget->name),
2999 : parser_errposition(pstate, origTarget->location)));
3000 : }
3001 :
3002 13594 : updateTargetListEntry(pstate, tle, origTarget->name,
3003 : attrno,
3004 : origTarget->indirection,
3005 : origTarget->location);
3006 :
3007 : /* Mark the target column as requiring update permissions */
3008 13586 : target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
3009 : attrno - FirstLowInvalidHeapAttributeNumber);
3010 :
3011 13586 : orig_tl = lnext(origTlist, orig_tl);
3012 : }
3013 11017 : if (orig_tl != NULL)
3014 0 : elog(ERROR, "UPDATE target count mismatch --- internal error");
3015 :
3016 11017 : return tlist;
3017 : }
3018 :
3019 : /*
3020 : * addNSItemForReturning -
3021 : * add a ParseNamespaceItem for the OLD or NEW alias in RETURNING.
3022 : */
3023 : static void
3024 4576 : addNSItemForReturning(ParseState *pstate, const char *aliasname,
3025 : VarReturningType returning_type)
3026 : {
3027 : List *colnames;
3028 : int numattrs;
3029 : ParseNamespaceColumn *nscolumns;
3030 : ParseNamespaceItem *nsitem;
3031 :
3032 : /* copy per-column data from the target relation */
3033 4576 : colnames = pstate->p_target_nsitem->p_rte->eref->colnames;
3034 4576 : numattrs = list_length(colnames);
3035 :
3036 4576 : nscolumns = palloc_array(ParseNamespaceColumn, numattrs);
3037 :
3038 4576 : memcpy(nscolumns, pstate->p_target_nsitem->p_nscolumns,
3039 : numattrs * sizeof(ParseNamespaceColumn));
3040 :
3041 : /* mark all columns as returning OLD/NEW */
3042 17954 : for (int i = 0; i < numattrs; i++)
3043 13378 : nscolumns[i].p_varreturningtype = returning_type;
3044 :
3045 : /* build the nsitem, copying most fields from the target relation */
3046 4576 : nsitem = palloc_object(ParseNamespaceItem);
3047 4576 : nsitem->p_names = makeAlias(aliasname, colnames);
3048 4576 : nsitem->p_rte = pstate->p_target_nsitem->p_rte;
3049 4576 : nsitem->p_rtindex = pstate->p_target_nsitem->p_rtindex;
3050 4576 : nsitem->p_perminfo = pstate->p_target_nsitem->p_perminfo;
3051 4576 : nsitem->p_nscolumns = nscolumns;
3052 4576 : nsitem->p_returning_type = returning_type;
3053 :
3054 : /* add it to the query namespace as a table-only item */
3055 4576 : addNSItemToQuery(pstate, nsitem, false, true, false);
3056 4576 : }
3057 :
3058 : /*
3059 : * transformReturningClause -
3060 : * handle a RETURNING clause in INSERT/UPDATE/DELETE/MERGE
3061 : */
3062 : void
3063 14896 : transformReturningClause(ParseState *pstate, Query *qry,
3064 : ReturningClause *returningClause,
3065 : ParseExprKind exprKind)
3066 : {
3067 14896 : int save_nslen = list_length(pstate->p_namespace);
3068 : int save_next_resno;
3069 :
3070 14896 : if (returningClause == NULL)
3071 12562 : return; /* nothing to do */
3072 :
3073 : /*
3074 : * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
3075 : * there is any conflict with existing relations.
3076 : */
3077 4716 : foreach_node(ReturningOption, option, returningClause->options)
3078 : {
3079 80 : switch (option->option)
3080 : {
3081 36 : case RETURNING_OPTION_OLD:
3082 36 : if (qry->returningOldAlias != NULL)
3083 4 : ereport(ERROR,
3084 : errcode(ERRCODE_SYNTAX_ERROR),
3085 : /* translator: %s is OLD or NEW */
3086 : errmsg("%s cannot be specified multiple times", "OLD"),
3087 : parser_errposition(pstate, option->location));
3088 32 : qry->returningOldAlias = option->value;
3089 32 : break;
3090 :
3091 44 : case RETURNING_OPTION_NEW:
3092 44 : if (qry->returningNewAlias != NULL)
3093 4 : ereport(ERROR,
3094 : errcode(ERRCODE_SYNTAX_ERROR),
3095 : /* translator: %s is OLD or NEW */
3096 : errmsg("%s cannot be specified multiple times", "NEW"),
3097 : parser_errposition(pstate, option->location));
3098 40 : qry->returningNewAlias = option->value;
3099 40 : break;
3100 :
3101 0 : default:
3102 0 : elog(ERROR, "unrecognized returning option: %d", option->option);
3103 : }
3104 :
3105 72 : if (refnameNamespaceItem(pstate, NULL, option->value, -1, NULL) != NULL)
3106 8 : ereport(ERROR,
3107 : errcode(ERRCODE_DUPLICATE_ALIAS),
3108 : errmsg("table name \"%s\" specified more than once",
3109 : option->value),
3110 : parser_errposition(pstate, option->location));
3111 :
3112 64 : addNSItemForReturning(pstate, option->value,
3113 64 : option->option == RETURNING_OPTION_OLD ?
3114 : VAR_RETURNING_OLD : VAR_RETURNING_NEW);
3115 : }
3116 :
3117 : /*
3118 : * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
3119 : * unless masked by existing relations.
3120 : */
3121 4616 : if (qry->returningOldAlias == NULL &&
3122 2298 : refnameNamespaceItem(pstate, NULL, "old", -1, NULL) == NULL)
3123 : {
3124 2258 : qry->returningOldAlias = "old";
3125 2258 : addNSItemForReturning(pstate, "old", VAR_RETURNING_OLD);
3126 : }
3127 4612 : if (qry->returningNewAlias == NULL &&
3128 2294 : refnameNamespaceItem(pstate, NULL, "new", -1, NULL) == NULL)
3129 : {
3130 2254 : qry->returningNewAlias = "new";
3131 2254 : addNSItemForReturning(pstate, "new", VAR_RETURNING_NEW);
3132 : }
3133 :
3134 : /*
3135 : * We need to assign resnos starting at one in the RETURNING list. Save
3136 : * and restore the main tlist's value of p_next_resno, just in case
3137 : * someone looks at it later (probably won't happen).
3138 : */
3139 2318 : save_next_resno = pstate->p_next_resno;
3140 2318 : pstate->p_next_resno = 1;
3141 :
3142 : /* transform RETURNING expressions identically to a SELECT targetlist */
3143 2318 : qry->returningList = transformTargetList(pstate,
3144 : returningClause->exprs,
3145 : exprKind);
3146 :
3147 : /*
3148 : * Complain if the nonempty tlist expanded to nothing (which is possible
3149 : * if it contains only a star-expansion of a zero-column table). If we
3150 : * allow this, the parsed Query will look like it didn't have RETURNING,
3151 : * with results that would probably surprise the user.
3152 : */
3153 2290 : if (qry->returningList == NIL)
3154 4 : ereport(ERROR,
3155 : (errcode(ERRCODE_SYNTAX_ERROR),
3156 : errmsg("RETURNING must have at least one column"),
3157 : parser_errposition(pstate,
3158 : exprLocation(linitial(returningClause->exprs)))));
3159 :
3160 : /* mark column origins */
3161 2286 : markTargetListOrigins(pstate, qry->returningList);
3162 :
3163 : /* resolve any still-unresolved output columns as being type text */
3164 2286 : if (pstate->p_resolve_unknowns)
3165 2286 : resolveTargetListUnknowns(pstate, qry->returningList);
3166 :
3167 : /* restore state */
3168 2286 : pstate->p_namespace = list_truncate(pstate->p_namespace, save_nslen);
3169 2286 : pstate->p_next_resno = save_next_resno;
3170 : }
3171 :
3172 :
3173 : /*
3174 : * transformPLAssignStmt -
3175 : * transform a PL/pgSQL assignment statement
3176 : *
3177 : * If there is no opt_indirection, the transformed statement looks like
3178 : * "SELECT a_expr ...", except the expression has been cast to the type of
3179 : * the target. With indirection, it's still a SELECT, but the expression will
3180 : * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
3181 : * new value for a container-type variable represented by the target. The
3182 : * expression references the target as the container source.
3183 : */
3184 : static Query *
3185 3354 : transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
3186 : {
3187 : Query *qry;
3188 3354 : ColumnRef *cref = makeNode(ColumnRef);
3189 3354 : List *indirection = stmt->indirection;
3190 3354 : int nnames = stmt->nnames;
3191 : Node *target;
3192 : SelectStmtPassthrough passthru;
3193 : bool save_resolve_unknowns;
3194 :
3195 : /*
3196 : * First, construct a ColumnRef for the target variable. If the target
3197 : * has more than one dotted name, we have to pull the extra names out of
3198 : * the indirection list.
3199 : */
3200 3354 : cref->fields = list_make1(makeString(stmt->name));
3201 3354 : cref->location = stmt->location;
3202 3354 : if (nnames > 1)
3203 : {
3204 : /* avoid munging the raw parsetree */
3205 253 : indirection = list_copy(indirection);
3206 513 : while (--nnames > 0 && indirection != NIL)
3207 : {
3208 260 : Node *ind = (Node *) linitial(indirection);
3209 :
3210 260 : if (!IsA(ind, String))
3211 0 : elog(ERROR, "invalid name count in PLAssignStmt");
3212 260 : cref->fields = lappend(cref->fields, ind);
3213 260 : indirection = list_delete_first(indirection);
3214 : }
3215 : }
3216 :
3217 : /*
3218 : * Transform the target reference. Typically we will get back a Param
3219 : * node, but there's no reason to be too picky about its type. (Note that
3220 : * we must do this before calling transformSelectStmt. It's tempting to
3221 : * do it inside transformPLAssignStmtTarget, but we need to do it before
3222 : * adding any FROM tables to the pstate's namespace, else we might wrongly
3223 : * resolve the target as a table column.)
3224 : */
3225 3354 : target = transformExpr(pstate, (Node *) cref,
3226 : EXPR_KIND_UPDATE_TARGET);
3227 :
3228 : /* Set up passthrough data for transformPLAssignStmtTarget */
3229 3348 : passthru.stmt = stmt;
3230 3348 : passthru.target = target;
3231 3348 : passthru.indirection = indirection;
3232 :
3233 : /*
3234 : * To avoid duplicating a lot of code, we use transformSelectStmt to do
3235 : * almost all of the work. However, we need to do additional processing
3236 : * on the SELECT's targetlist after it's been transformed, but before
3237 : * possible addition of targetlist items for ORDER BY or GROUP BY.
3238 : * transformSelectStmt knows it should call transformPLAssignStmtTarget if
3239 : * it's passed a passthru argument.
3240 : *
3241 : * Also, disable resolution of unknown-type tlist items; PL/pgSQL wants to
3242 : * deal with that itself.
3243 : */
3244 3348 : save_resolve_unknowns = pstate->p_resolve_unknowns;
3245 3348 : pstate->p_resolve_unknowns = false;
3246 3348 : qry = transformSelectStmt(pstate, stmt->val, &passthru);
3247 3341 : pstate->p_resolve_unknowns = save_resolve_unknowns;
3248 :
3249 3341 : return qry;
3250 : }
3251 :
3252 : /*
3253 : * Callback function to adjust a SELECT's tlist to make the output suitable
3254 : * for assignment to a PLAssignStmt's target variable.
3255 : *
3256 : * Note: we actually modify the tle->expr in-place, but the function's API
3257 : * is set up to not presume that.
3258 : */
3259 : static List *
3260 3348 : transformPLAssignStmtTarget(ParseState *pstate, List *tlist,
3261 : SelectStmtPassthrough *passthru)
3262 : {
3263 3348 : PLAssignStmt *stmt = passthru->stmt;
3264 3348 : Node *target = passthru->target;
3265 3348 : List *indirection = passthru->indirection;
3266 : Oid targettype;
3267 : int32 targettypmod;
3268 : Oid targetcollation;
3269 : TargetEntry *tle;
3270 : Oid type_id;
3271 :
3272 3348 : targettype = exprType(target);
3273 3348 : targettypmod = exprTypmod(target);
3274 3348 : targetcollation = exprCollation(target);
3275 :
3276 : /* we should have exactly one targetlist item */
3277 3348 : if (list_length(tlist) != 1)
3278 2 : ereport(ERROR,
3279 : (errcode(ERRCODE_SYNTAX_ERROR),
3280 : errmsg_plural("assignment source returned %d column",
3281 : "assignment source returned %d columns",
3282 : list_length(tlist),
3283 : list_length(tlist))));
3284 :
3285 3346 : tle = linitial_node(TargetEntry, tlist);
3286 :
3287 : /*
3288 : * This next bit is similar to transformAssignedExpr; the key difference
3289 : * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
3290 : */
3291 3346 : type_id = exprType((Node *) tle->expr);
3292 :
3293 3346 : pstate->p_expr_kind = EXPR_KIND_UPDATE_TARGET;
3294 :
3295 3346 : if (indirection)
3296 : {
3297 60 : tle->expr = (Expr *)
3298 65 : transformAssignmentIndirection(pstate,
3299 : target,
3300 65 : stmt->name,
3301 : false,
3302 : targettype,
3303 : targettypmod,
3304 : targetcollation,
3305 : indirection,
3306 : list_head(indirection),
3307 65 : (Node *) tle->expr,
3308 : COERCION_PLPGSQL,
3309 : exprLocation(target));
3310 : }
3311 3281 : else if (targettype != type_id &&
3312 902 : (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
3313 226 : (type_id == RECORDOID || ISCOMPLEX(type_id)))
3314 : {
3315 : /*
3316 : * Hack: do not let coerce_to_target_type() deal with inconsistent
3317 : * composite types. Just pass the expression result through as-is,
3318 : * and let the PL/pgSQL executor do the conversion its way. This is
3319 : * rather bogus, but it's needed for backwards compatibility.
3320 : */
3321 : }
3322 : else
3323 : {
3324 : /*
3325 : * For normal non-qualified target column, do type checking and
3326 : * coercion.
3327 : */
3328 3093 : Node *orig_expr = (Node *) tle->expr;
3329 :
3330 3093 : tle->expr = (Expr *)
3331 3093 : coerce_to_target_type(pstate,
3332 : orig_expr, type_id,
3333 : targettype, targettypmod,
3334 : COERCION_PLPGSQL,
3335 : COERCE_IMPLICIT_CAST,
3336 : -1);
3337 : /* With COERCION_PLPGSQL, this error is probably unreachable */
3338 3093 : if (tle->expr == NULL)
3339 0 : ereport(ERROR,
3340 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3341 : errmsg("variable \"%s\" is of type %s"
3342 : " but expression is of type %s",
3343 : stmt->name,
3344 : format_type_be(targettype),
3345 : format_type_be(type_id)),
3346 : errhint("You will need to rewrite or cast the expression."),
3347 : parser_errposition(pstate, exprLocation(orig_expr))));
3348 : }
3349 :
3350 3341 : pstate->p_expr_kind = EXPR_KIND_NONE;
3351 :
3352 3341 : return list_make1(tle);
3353 : }
3354 :
3355 :
3356 : /*
3357 : * transformDeclareCursorStmt -
3358 : * transform a DECLARE CURSOR Statement
3359 : *
3360 : * DECLARE CURSOR is like other utility statements in that we emit it as a
3361 : * CMD_UTILITY Query node; however, we must first transform the contained
3362 : * query. We used to postpone that until execution, but it's really necessary
3363 : * to do it during the normal parse analysis phase to ensure that side effects
3364 : * of parser hooks happen at the expected time.
3365 : */
3366 : static Query *
3367 2743 : transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
3368 : {
3369 : Query *result;
3370 : Query *query;
3371 :
3372 2743 : if ((stmt->options & CURSOR_OPT_SCROLL) &&
3373 160 : (stmt->options & CURSOR_OPT_NO_SCROLL))
3374 0 : ereport(ERROR,
3375 : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3376 : /* translator: %s is a SQL keyword */
3377 : errmsg("cannot specify both %s and %s",
3378 : "SCROLL", "NO SCROLL")));
3379 :
3380 2743 : if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
3381 0 : (stmt->options & CURSOR_OPT_INSENSITIVE))
3382 0 : ereport(ERROR,
3383 : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3384 : /* translator: %s is a SQL keyword */
3385 : errmsg("cannot specify both %s and %s",
3386 : "ASENSITIVE", "INSENSITIVE")));
3387 :
3388 : /* Transform contained query, not allowing SELECT INTO */
3389 2743 : query = transformStmt(pstate, stmt->query);
3390 2730 : stmt->query = (Node *) query;
3391 :
3392 : /* Grammar should not have allowed anything but SELECT */
3393 2730 : if (!IsA(query, Query) ||
3394 2730 : query->commandType != CMD_SELECT)
3395 0 : elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
3396 :
3397 : /*
3398 : * We also disallow data-modifying WITH in a cursor. (This could be
3399 : * allowed, but the semantics of when the updates occur might be
3400 : * surprising.)
3401 : */
3402 2730 : if (query->hasModifyingCTE)
3403 0 : ereport(ERROR,
3404 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3405 : errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
3406 :
3407 : /* FOR UPDATE and WITH HOLD are not compatible */
3408 2730 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
3409 0 : ereport(ERROR,
3410 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3411 : /*------
3412 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3413 : errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
3414 : LCS_asString(((RowMarkClause *)
3415 : linitial(query->rowMarks))->strength)),
3416 : errdetail("Holdable cursors must be READ ONLY.")));
3417 :
3418 : /* FOR UPDATE and SCROLL are not compatible */
3419 2730 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
3420 0 : ereport(ERROR,
3421 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3422 : /*------
3423 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3424 : errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
3425 : LCS_asString(((RowMarkClause *)
3426 : linitial(query->rowMarks))->strength)),
3427 : errdetail("Scrollable cursors must be READ ONLY.")));
3428 :
3429 : /* FOR UPDATE and INSENSITIVE are not compatible */
3430 2730 : if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
3431 0 : ereport(ERROR,
3432 : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3433 : /*------
3434 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3435 : errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
3436 : LCS_asString(((RowMarkClause *)
3437 : linitial(query->rowMarks))->strength)),
3438 : errdetail("Insensitive cursors must be READ ONLY.")));
3439 :
3440 : /* represent the command as a utility Query */
3441 2730 : result = makeNode(Query);
3442 2730 : result->commandType = CMD_UTILITY;
3443 2730 : result->utilityStmt = (Node *) stmt;
3444 :
3445 2730 : return result;
3446 : }
3447 :
3448 :
3449 : /*
3450 : * transformExplainStmt -
3451 : * transform an EXPLAIN Statement
3452 : *
3453 : * EXPLAIN is like other utility statements in that we emit it as a
3454 : * CMD_UTILITY Query node; however, we must first transform the contained
3455 : * query. We used to postpone that until execution, but it's really necessary
3456 : * to do it during the normal parse analysis phase to ensure that side effects
3457 : * of parser hooks happen at the expected time.
3458 : */
3459 : static Query *
3460 16518 : transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
3461 : {
3462 : Query *result;
3463 16518 : bool generic_plan = false;
3464 16518 : Oid *paramTypes = NULL;
3465 16518 : int numParams = 0;
3466 :
3467 : /*
3468 : * If we have no external source of parameter definitions, and the
3469 : * GENERIC_PLAN option is specified, then accept variable parameter
3470 : * definitions (similarly to PREPARE, for example).
3471 : */
3472 16518 : if (pstate->p_paramref_hook == NULL)
3473 : {
3474 : ListCell *lc;
3475 :
3476 32810 : foreach(lc, stmt->options)
3477 : {
3478 16304 : DefElem *opt = (DefElem *) lfirst(lc);
3479 :
3480 16304 : if (strcmp(opt->defname, "generic_plan") == 0)
3481 12 : generic_plan = defGetBoolean(opt);
3482 : /* don't "break", as we want the last value */
3483 : }
3484 16506 : if (generic_plan)
3485 12 : setup_parse_variable_parameters(pstate, ¶mTypes, &numParams);
3486 : }
3487 :
3488 : /* transform contained query, allowing SELECT INTO */
3489 16518 : stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
3490 :
3491 : /* make sure all is well with parameter types */
3492 16509 : if (generic_plan)
3493 12 : check_variable_parameters(pstate, (Query *) stmt->query);
3494 :
3495 : /* represent the command as a utility Query */
3496 16509 : result = makeNode(Query);
3497 16509 : result->commandType = CMD_UTILITY;
3498 16509 : result->utilityStmt = (Node *) stmt;
3499 :
3500 16509 : return result;
3501 : }
3502 :
3503 :
3504 : /*
3505 : * transformCreateTableAsStmt -
3506 : * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
3507 : * Statement
3508 : *
3509 : * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
3510 : */
3511 : static Query *
3512 1316 : transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
3513 : {
3514 : Query *result;
3515 : Query *query;
3516 :
3517 : /* transform contained query, not allowing SELECT INTO */
3518 1316 : query = transformStmt(pstate, stmt->query);
3519 1314 : stmt->query = (Node *) query;
3520 :
3521 : /* additional work needed for CREATE MATERIALIZED VIEW */
3522 1314 : if (stmt->objtype == OBJECT_MATVIEW)
3523 : {
3524 : ObjectAddress temp_object;
3525 :
3526 : /*
3527 : * Prohibit a data-modifying CTE in the query used to create a
3528 : * materialized view. It's not sufficiently clear what the user would
3529 : * want to happen if the MV is refreshed or incrementally maintained.
3530 : */
3531 356 : if (query->hasModifyingCTE)
3532 0 : ereport(ERROR,
3533 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3534 : errmsg("materialized views must not use data-modifying statements in WITH")));
3535 :
3536 : /*
3537 : * Check whether any temporary database objects are used in the
3538 : * creation query. It would be hard to refresh data or incrementally
3539 : * maintain it if a source disappeared.
3540 : */
3541 356 : if (query_uses_temp_object(query, &temp_object))
3542 4 : ereport(ERROR,
3543 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3544 : errmsg("materialized views must not use temporary objects"),
3545 : errdetail("This view depends on temporary %s.",
3546 : getObjectDescription(&temp_object, false))));
3547 :
3548 : /*
3549 : * A materialized view would either need to save parameters for use in
3550 : * maintaining/loading the data or prohibit them entirely. The latter
3551 : * seems safer and more sane.
3552 : */
3553 348 : if (query_contains_extern_params(query))
3554 0 : ereport(ERROR,
3555 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3556 : errmsg("materialized views may not be defined using bound parameters")));
3557 :
3558 : /*
3559 : * For now, we disallow unlogged materialized views, because it seems
3560 : * like a bad idea for them to just go to empty after a crash. (If we
3561 : * could mark them as unpopulated, that would be better, but that
3562 : * requires catalog changes which crash recovery can't presently
3563 : * handle.)
3564 : */
3565 348 : if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
3566 0 : ereport(ERROR,
3567 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3568 : errmsg("materialized views cannot be unlogged")));
3569 :
3570 : /*
3571 : * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
3572 : * for purposes of creating the view's ON SELECT rule. We stash that
3573 : * in the IntoClause because that's where intorel_startup() can
3574 : * conveniently get it from.
3575 : */
3576 348 : stmt->into->viewQuery = copyObject(query);
3577 : }
3578 :
3579 : /* represent the command as a utility Query */
3580 1306 : result = makeNode(Query);
3581 1306 : result->commandType = CMD_UTILITY;
3582 1306 : result->utilityStmt = (Node *) stmt;
3583 :
3584 1306 : return result;
3585 : }
3586 :
3587 : /*
3588 : * transform a CallStmt
3589 : */
3590 : static Query *
3591 312 : transformCallStmt(ParseState *pstate, CallStmt *stmt)
3592 : {
3593 : List *targs;
3594 : ListCell *lc;
3595 : Node *node;
3596 : FuncExpr *fexpr;
3597 : HeapTuple proctup;
3598 : Datum proargmodes;
3599 : bool isNull;
3600 312 : List *outargs = NIL;
3601 : Query *result;
3602 :
3603 : /*
3604 : * First, do standard parse analysis on the procedure call and its
3605 : * arguments, allowing us to identify the called procedure.
3606 : */
3607 312 : targs = NIL;
3608 764 : foreach(lc, stmt->funccall->args)
3609 : {
3610 452 : targs = lappend(targs, transformExpr(pstate,
3611 452 : (Node *) lfirst(lc),
3612 : EXPR_KIND_CALL_ARGUMENT));
3613 : }
3614 :
3615 312 : node = ParseFuncOrColumn(pstate,
3616 312 : stmt->funccall->funcname,
3617 : targs,
3618 : pstate->p_last_srf,
3619 : stmt->funccall,
3620 : true,
3621 312 : stmt->funccall->location);
3622 :
3623 291 : assign_expr_collations(pstate, node);
3624 :
3625 291 : fexpr = castNode(FuncExpr, node);
3626 :
3627 291 : proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
3628 291 : if (!HeapTupleIsValid(proctup))
3629 0 : elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3630 :
3631 : /*
3632 : * Expand the argument list to deal with named-argument notation and
3633 : * default arguments. For ordinary FuncExprs this'd be done during
3634 : * planning, but a CallStmt doesn't go through planning, and there seems
3635 : * no good reason not to do it here.
3636 : */
3637 291 : fexpr->args = expand_function_arguments(fexpr->args,
3638 : true,
3639 : fexpr->funcresulttype,
3640 : proctup);
3641 :
3642 : /* Fetch proargmodes; if it's null, there are no output args */
3643 291 : proargmodes = SysCacheGetAttr(PROCOID, proctup,
3644 : Anum_pg_proc_proargmodes,
3645 : &isNull);
3646 291 : if (!isNull)
3647 : {
3648 : /*
3649 : * Split the list into input arguments in fexpr->args and output
3650 : * arguments in stmt->outargs. INOUT arguments appear in both lists.
3651 : */
3652 : ArrayType *arr;
3653 : int numargs;
3654 : char *argmodes;
3655 : List *inargs;
3656 : int i;
3657 :
3658 119 : arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
3659 119 : numargs = list_length(fexpr->args);
3660 119 : if (ARR_NDIM(arr) != 1 ||
3661 119 : ARR_DIMS(arr)[0] != numargs ||
3662 119 : ARR_HASNULL(arr) ||
3663 119 : ARR_ELEMTYPE(arr) != CHAROID)
3664 0 : elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3665 : numargs);
3666 119 : argmodes = (char *) ARR_DATA_PTR(arr);
3667 :
3668 119 : inargs = NIL;
3669 119 : i = 0;
3670 395 : foreach(lc, fexpr->args)
3671 : {
3672 276 : Node *n = lfirst(lc);
3673 :
3674 276 : switch (argmodes[i])
3675 : {
3676 91 : case PROARGMODE_IN:
3677 : case PROARGMODE_VARIADIC:
3678 91 : inargs = lappend(inargs, n);
3679 91 : break;
3680 72 : case PROARGMODE_OUT:
3681 72 : outargs = lappend(outargs, n);
3682 72 : break;
3683 113 : case PROARGMODE_INOUT:
3684 113 : inargs = lappend(inargs, n);
3685 113 : outargs = lappend(outargs, copyObject(n));
3686 113 : break;
3687 0 : default:
3688 : /* note we don't support PROARGMODE_TABLE */
3689 0 : elog(ERROR, "invalid argmode %c for procedure",
3690 : argmodes[i]);
3691 : break;
3692 : }
3693 276 : i++;
3694 : }
3695 119 : fexpr->args = inargs;
3696 : }
3697 :
3698 291 : stmt->funcexpr = fexpr;
3699 291 : stmt->outargs = outargs;
3700 :
3701 291 : ReleaseSysCache(proctup);
3702 :
3703 : /* represent the command as a utility Query */
3704 291 : result = makeNode(Query);
3705 291 : result->commandType = CMD_UTILITY;
3706 291 : result->utilityStmt = (Node *) stmt;
3707 :
3708 291 : return result;
3709 : }
3710 :
3711 : /*
3712 : * Produce a string representation of a LockClauseStrength value.
3713 : * This should only be applied to valid values (not LCS_NONE).
3714 : */
3715 : const char *
3716 32 : LCS_asString(LockClauseStrength strength)
3717 : {
3718 32 : switch (strength)
3719 : {
3720 0 : case LCS_NONE:
3721 : Assert(false);
3722 0 : break;
3723 0 : case LCS_FORKEYSHARE:
3724 0 : return "FOR KEY SHARE";
3725 0 : case LCS_FORSHARE:
3726 0 : return "FOR SHARE";
3727 4 : case LCS_FORNOKEYUPDATE:
3728 4 : return "FOR NO KEY UPDATE";
3729 28 : case LCS_FORUPDATE:
3730 28 : return "FOR UPDATE";
3731 : }
3732 0 : return "FOR some"; /* shouldn't happen */
3733 : }
3734 :
3735 : /*
3736 : * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
3737 : *
3738 : * exported so planner can check again after rewriting, query pullup, etc
3739 : */
3740 : void
3741 11592 : CheckSelectLocking(Query *qry, LockClauseStrength strength)
3742 : {
3743 : Assert(strength != LCS_NONE); /* else caller error */
3744 :
3745 11592 : if (qry->setOperations)
3746 0 : ereport(ERROR,
3747 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3748 : /*------
3749 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3750 : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3751 : LCS_asString(strength))));
3752 11592 : if (qry->distinctClause != NIL)
3753 0 : ereport(ERROR,
3754 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3755 : /*------
3756 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3757 : errmsg("%s is not allowed with DISTINCT clause",
3758 : LCS_asString(strength))));
3759 11592 : if (qry->groupClause != NIL || qry->groupingSets != NIL)
3760 8 : ereport(ERROR,
3761 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3762 : /*------
3763 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3764 : errmsg("%s is not allowed with GROUP BY clause",
3765 : LCS_asString(strength))));
3766 11584 : if (qry->havingQual != NULL)
3767 0 : ereport(ERROR,
3768 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3769 : /*------
3770 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3771 : errmsg("%s is not allowed with HAVING clause",
3772 : LCS_asString(strength))));
3773 11584 : if (qry->hasAggs)
3774 4 : ereport(ERROR,
3775 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3776 : /*------
3777 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3778 : errmsg("%s is not allowed with aggregate functions",
3779 : LCS_asString(strength))));
3780 11580 : if (qry->hasWindowFuncs)
3781 0 : ereport(ERROR,
3782 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3783 : /*------
3784 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3785 : errmsg("%s is not allowed with window functions",
3786 : LCS_asString(strength))));
3787 11580 : if (qry->hasTargetSRFs)
3788 0 : ereport(ERROR,
3789 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3790 : /*------
3791 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3792 : errmsg("%s is not allowed with set-returning functions in the target list",
3793 : LCS_asString(strength))));
3794 11580 : }
3795 :
3796 : /*
3797 : * Transform a FOR [KEY] UPDATE/SHARE clause
3798 : *
3799 : * This basically involves replacing names by integer relids.
3800 : *
3801 : * NB: if you need to change this, see also markQueryForLocking()
3802 : * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
3803 : */
3804 : static void
3805 5028 : transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc,
3806 : bool pushedDown)
3807 : {
3808 5028 : List *lockedRels = lc->lockedRels;
3809 : ListCell *l;
3810 : ListCell *rt;
3811 : Index i;
3812 : LockingClause *allrels;
3813 :
3814 5028 : CheckSelectLocking(qry, lc->strength);
3815 :
3816 : /* make a clause we can pass down to subqueries to select all rels */
3817 5016 : allrels = makeNode(LockingClause);
3818 5016 : allrels->lockedRels = NIL; /* indicates all rels */
3819 5016 : allrels->strength = lc->strength;
3820 5016 : allrels->waitPolicy = lc->waitPolicy;
3821 :
3822 5016 : if (lockedRels == NIL)
3823 : {
3824 : /*
3825 : * Lock all regular tables used in query and its subqueries. We
3826 : * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3827 : * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3828 : * it's convenient. We can't rely on the namespace mechanism that has
3829 : * largely replaced inFromCl, since for example we need to lock
3830 : * base-relation RTEs even if they are masked by upper joins.
3831 : */
3832 3798 : i = 0;
3833 7646 : foreach(rt, qry->rtable)
3834 : {
3835 3848 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3836 :
3837 3848 : ++i;
3838 3848 : if (!rte->inFromCl)
3839 8 : continue;
3840 3840 : switch (rte->rtekind)
3841 : {
3842 3824 : case RTE_RELATION:
3843 : {
3844 : RTEPermissionInfo *perminfo;
3845 :
3846 3824 : applyLockingClause(qry, i,
3847 : lc->strength,
3848 : lc->waitPolicy,
3849 : pushedDown);
3850 3824 : perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3851 3824 : perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3852 : }
3853 3824 : break;
3854 0 : case RTE_SUBQUERY:
3855 0 : applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3856 : pushedDown);
3857 :
3858 : /*
3859 : * FOR UPDATE/SHARE of subquery is propagated to all of
3860 : * subquery's rels, too. We could do this later (based on
3861 : * the marking of the subquery RTE) but it is convenient
3862 : * to have local knowledge in each query level about which
3863 : * rels need to be opened with RowShareLock.
3864 : */
3865 0 : transformLockingClause(pstate, rte->subquery,
3866 : allrels, true);
3867 0 : break;
3868 16 : default:
3869 : /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3870 16 : break;
3871 : }
3872 : }
3873 : }
3874 : else
3875 : {
3876 : /*
3877 : * Lock just the named tables. As above, we allow locking any base
3878 : * relation regardless of alias-visibility rules, so we need to
3879 : * examine inFromCl to exclude OLD/NEW.
3880 : */
3881 2426 : foreach(l, lockedRels)
3882 : {
3883 1224 : RangeVar *thisrel = (RangeVar *) lfirst(l);
3884 :
3885 : /* For simplicity we insist on unqualified alias names here */
3886 1224 : if (thisrel->catalogname || thisrel->schemaname)
3887 0 : ereport(ERROR,
3888 : (errcode(ERRCODE_SYNTAX_ERROR),
3889 : /*------
3890 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3891 : errmsg("%s must specify unqualified relation names",
3892 : LCS_asString(lc->strength)),
3893 : parser_errposition(pstate, thisrel->location)));
3894 :
3895 1224 : i = 0;
3896 1418 : foreach(rt, qry->rtable)
3897 : {
3898 1410 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3899 1410 : char *rtename = rte->eref->aliasname;
3900 :
3901 1410 : ++i;
3902 1410 : if (!rte->inFromCl)
3903 16 : continue;
3904 :
3905 : /*
3906 : * A join RTE without an alias is not visible as a relation
3907 : * name and needs to be skipped (otherwise it might hide a
3908 : * base relation with the same name), except if it has a USING
3909 : * alias, which *is* visible.
3910 : *
3911 : * Subquery and values RTEs without aliases are never visible
3912 : * as relation names and must always be skipped.
3913 : */
3914 1394 : if (rte->alias == NULL)
3915 : {
3916 109 : if (rte->rtekind == RTE_JOIN)
3917 : {
3918 40 : if (rte->join_using_alias == NULL)
3919 32 : continue;
3920 8 : rtename = rte->join_using_alias->aliasname;
3921 : }
3922 69 : else if (rte->rtekind == RTE_SUBQUERY ||
3923 65 : rte->rtekind == RTE_VALUES)
3924 4 : continue;
3925 : }
3926 :
3927 1358 : if (strcmp(rtename, thisrel->relname) == 0)
3928 : {
3929 1216 : switch (rte->rtekind)
3930 : {
3931 1202 : case RTE_RELATION:
3932 : {
3933 : RTEPermissionInfo *perminfo;
3934 :
3935 1202 : applyLockingClause(qry, i,
3936 : lc->strength,
3937 : lc->waitPolicy,
3938 : pushedDown);
3939 1202 : perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3940 1202 : perminfo->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3941 : }
3942 1202 : break;
3943 6 : case RTE_SUBQUERY:
3944 6 : applyLockingClause(qry, i, lc->strength,
3945 : lc->waitPolicy, pushedDown);
3946 : /* see comment above */
3947 6 : transformLockingClause(pstate, rte->subquery,
3948 : allrels, true);
3949 6 : break;
3950 8 : case RTE_JOIN:
3951 8 : ereport(ERROR,
3952 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3953 : /*------
3954 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3955 : errmsg("%s cannot be applied to a join",
3956 : LCS_asString(lc->strength)),
3957 : parser_errposition(pstate, thisrel->location)));
3958 : break;
3959 0 : case RTE_FUNCTION:
3960 0 : ereport(ERROR,
3961 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3962 : /*------
3963 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3964 : errmsg("%s cannot be applied to a function",
3965 : LCS_asString(lc->strength)),
3966 : parser_errposition(pstate, thisrel->location)));
3967 : break;
3968 0 : case RTE_TABLEFUNC:
3969 0 : ereport(ERROR,
3970 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3971 : /*------
3972 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3973 : errmsg("%s cannot be applied to a table function",
3974 : LCS_asString(lc->strength)),
3975 : parser_errposition(pstate, thisrel->location)));
3976 : break;
3977 0 : case RTE_VALUES:
3978 0 : ereport(ERROR,
3979 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3980 : /*------
3981 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3982 : errmsg("%s cannot be applied to VALUES",
3983 : LCS_asString(lc->strength)),
3984 : parser_errposition(pstate, thisrel->location)));
3985 : break;
3986 0 : case RTE_CTE:
3987 0 : ereport(ERROR,
3988 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3989 : /*------
3990 : translator: %s is a SQL row locking clause such as FOR UPDATE */
3991 : errmsg("%s cannot be applied to a WITH query",
3992 : LCS_asString(lc->strength)),
3993 : parser_errposition(pstate, thisrel->location)));
3994 : break;
3995 0 : case RTE_NAMEDTUPLESTORE:
3996 0 : ereport(ERROR,
3997 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3998 : /*------
3999 : translator: %s is a SQL row locking clause such as FOR UPDATE */
4000 : errmsg("%s cannot be applied to a named tuplestore",
4001 : LCS_asString(lc->strength)),
4002 : parser_errposition(pstate, thisrel->location)));
4003 : break;
4004 :
4005 : /* Shouldn't be possible to see RTE_RESULT here */
4006 :
4007 0 : default:
4008 0 : elog(ERROR, "unrecognized RTE type: %d",
4009 : (int) rte->rtekind);
4010 : break;
4011 : }
4012 1208 : break; /* out of foreach loop */
4013 : }
4014 : }
4015 1216 : if (rt == NULL)
4016 8 : ereport(ERROR,
4017 : (errcode(ERRCODE_UNDEFINED_TABLE),
4018 : /*------
4019 : translator: %s is a SQL row locking clause such as FOR UPDATE */
4020 : errmsg("relation \"%s\" in %s clause not found in FROM clause",
4021 : thisrel->relname,
4022 : LCS_asString(lc->strength)),
4023 : parser_errposition(pstate, thisrel->location)));
4024 : }
4025 : }
4026 5000 : }
4027 :
4028 : /*
4029 : * Record locking info for a single rangetable item
4030 : */
4031 : void
4032 5096 : applyLockingClause(Query *qry, Index rtindex,
4033 : LockClauseStrength strength, LockWaitPolicy waitPolicy,
4034 : bool pushedDown)
4035 : {
4036 : RowMarkClause *rc;
4037 :
4038 : Assert(strength != LCS_NONE); /* else caller error */
4039 :
4040 : /* If it's an explicit clause, make sure hasForUpdate gets set */
4041 5096 : if (!pushedDown)
4042 5030 : qry->hasForUpdate = true;
4043 :
4044 : /* Check for pre-existing entry for same rtindex */
4045 5096 : if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
4046 : {
4047 : /*
4048 : * If the same RTE is specified with more than one locking strength,
4049 : * use the strongest. (Reasonable, since you can't take both a shared
4050 : * and exclusive lock at the same time; it'll end up being exclusive
4051 : * anyway.)
4052 : *
4053 : * Similarly, if the same RTE is specified with more than one lock
4054 : * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
4055 : * turn wins over waiting for the lock (the default). This is a bit
4056 : * more debatable but raising an error doesn't seem helpful. (Consider
4057 : * for instance SELECT FOR UPDATE NOWAIT from a view that internally
4058 : * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
4059 : * LOCKED is reasonable since the former throws an error in case of
4060 : * coming across a locked tuple, which may be undesirable in some
4061 : * cases but it seems better than silently returning inconsistent
4062 : * results.
4063 : *
4064 : * And of course pushedDown becomes false if any clause is explicit.
4065 : */
4066 0 : rc->strength = Max(rc->strength, strength);
4067 0 : rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
4068 0 : rc->pushedDown &= pushedDown;
4069 0 : return;
4070 : }
4071 :
4072 : /* Make a new RowMarkClause */
4073 5096 : rc = makeNode(RowMarkClause);
4074 5096 : rc->rti = rtindex;
4075 5096 : rc->strength = strength;
4076 5096 : rc->waitPolicy = waitPolicy;
4077 5096 : rc->pushedDown = pushedDown;
4078 5096 : qry->rowMarks = lappend(qry->rowMarks, rc);
4079 : }
4080 :
4081 : #ifdef DEBUG_NODE_TESTS_ENABLED
4082 : /*
4083 : * Coverage testing for raw_expression_tree_walker().
4084 : *
4085 : * When enabled, we run raw_expression_tree_walker() over every DML statement
4086 : * submitted to parse analysis. Without this provision, that function is only
4087 : * applied in limited cases involving CTEs, and we don't really want to have
4088 : * to test everything inside as well as outside a CTE.
4089 : */
4090 : static bool
4091 17405148 : test_raw_expression_coverage(Node *node, void *context)
4092 : {
4093 17405148 : if (node == NULL)
4094 9364251 : return false;
4095 8040897 : return raw_expression_tree_walker(node,
4096 : test_raw_expression_coverage,
4097 : context);
4098 : }
4099 : #endif /* DEBUG_NODE_TESTS_ENABLED */
|