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